VirtualBox

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

Last change on this file since 82018 was 82018, checked in by vboxsync, 5 years ago

VMM/HMVMXR0: Nested VMX: bugref:9180 Unused variable build fix.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 709.4 KB
Line 
1/* $Id: HMVMXR0.cpp 82018 2019-11-20 10:30:36Z vboxsync $ */
2/** @file
3 * HM VMX (Intel VT-x) - Host Context Ring-0.
4 */
5
6/*
7 * Copyright (C) 2012-2019 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)->hm.s.idEnteredCpu == RTMpCpuId(), \
165 ("Illegal migration! Entered on CPU %u Current %u\n", \
166 (a_pVCpu)->hm.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 DECLCALLBACK(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_VIRTXCPT_INFO_ADDR_FULL,
537 VMX_VMCS64_CTRL_VIRTXCPT_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_TSC_MULTIPLIER_FULL,
543 VMX_VMCS64_CTRL_TSC_MULTIPLIER_HIGH,
544
545 /* 64-bit read-only data fields. */
546 VMX_VMCS64_RO_GUEST_PHYS_ADDR_FULL,
547 VMX_VMCS64_RO_GUEST_PHYS_ADDR_HIGH,
548
549 /* 64-bit guest-state fields. */
550 VMX_VMCS64_GUEST_VMCS_LINK_PTR_FULL,
551 VMX_VMCS64_GUEST_VMCS_LINK_PTR_HIGH,
552 VMX_VMCS64_GUEST_DEBUGCTL_FULL,
553 VMX_VMCS64_GUEST_DEBUGCTL_HIGH,
554 VMX_VMCS64_GUEST_PAT_FULL,
555 VMX_VMCS64_GUEST_PAT_HIGH,
556 VMX_VMCS64_GUEST_EFER_FULL,
557 VMX_VMCS64_GUEST_EFER_HIGH,
558 VMX_VMCS64_GUEST_PERF_GLOBAL_CTRL_FULL,
559 VMX_VMCS64_GUEST_PERF_GLOBAL_CTRL_HIGH,
560 VMX_VMCS64_GUEST_PDPTE0_FULL,
561 VMX_VMCS64_GUEST_PDPTE0_HIGH,
562 VMX_VMCS64_GUEST_PDPTE1_FULL,
563 VMX_VMCS64_GUEST_PDPTE1_HIGH,
564 VMX_VMCS64_GUEST_PDPTE2_FULL,
565 VMX_VMCS64_GUEST_PDPTE2_HIGH,
566 VMX_VMCS64_GUEST_PDPTE3_FULL,
567 VMX_VMCS64_GUEST_PDPTE3_HIGH,
568 VMX_VMCS64_GUEST_BNDCFGS_FULL,
569 VMX_VMCS64_GUEST_BNDCFGS_HIGH,
570
571 /* 64-bit host-state fields. */
572 VMX_VMCS64_HOST_PAT_FULL,
573 VMX_VMCS64_HOST_PAT_HIGH,
574 VMX_VMCS64_HOST_EFER_FULL,
575 VMX_VMCS64_HOST_EFER_HIGH,
576 VMX_VMCS64_HOST_PERF_GLOBAL_CTRL_FULL,
577 VMX_VMCS64_HOST_PERF_GLOBAL_CTRL_HIGH,
578
579 /* 32-bit control fields. */
580 VMX_VMCS32_CTRL_PIN_EXEC,
581 VMX_VMCS32_CTRL_PROC_EXEC,
582 VMX_VMCS32_CTRL_EXCEPTION_BITMAP,
583 VMX_VMCS32_CTRL_PAGEFAULT_ERROR_MASK,
584 VMX_VMCS32_CTRL_PAGEFAULT_ERROR_MATCH,
585 VMX_VMCS32_CTRL_CR3_TARGET_COUNT,
586 VMX_VMCS32_CTRL_EXIT,
587 VMX_VMCS32_CTRL_EXIT_MSR_STORE_COUNT,
588 VMX_VMCS32_CTRL_EXIT_MSR_LOAD_COUNT,
589 VMX_VMCS32_CTRL_ENTRY,
590 VMX_VMCS32_CTRL_ENTRY_MSR_LOAD_COUNT,
591 VMX_VMCS32_CTRL_ENTRY_INTERRUPTION_INFO,
592 VMX_VMCS32_CTRL_ENTRY_EXCEPTION_ERRCODE,
593 VMX_VMCS32_CTRL_ENTRY_INSTR_LENGTH,
594 VMX_VMCS32_CTRL_TPR_THRESHOLD,
595 VMX_VMCS32_CTRL_PROC_EXEC2,
596 VMX_VMCS32_CTRL_PLE_GAP,
597 VMX_VMCS32_CTRL_PLE_WINDOW,
598
599 /* 32-bits read-only fields. */
600 VMX_VMCS32_RO_VM_INSTR_ERROR,
601 VMX_VMCS32_RO_EXIT_REASON,
602 VMX_VMCS32_RO_EXIT_INTERRUPTION_INFO,
603 VMX_VMCS32_RO_EXIT_INTERRUPTION_ERROR_CODE,
604 VMX_VMCS32_RO_IDT_VECTORING_INFO,
605 VMX_VMCS32_RO_IDT_VECTORING_ERROR_CODE,
606 VMX_VMCS32_RO_EXIT_INSTR_LENGTH,
607 VMX_VMCS32_RO_EXIT_INSTR_INFO,
608
609 /* 32-bit guest-state fields. */
610 VMX_VMCS32_GUEST_ES_LIMIT,
611 VMX_VMCS32_GUEST_CS_LIMIT,
612 VMX_VMCS32_GUEST_SS_LIMIT,
613 VMX_VMCS32_GUEST_DS_LIMIT,
614 VMX_VMCS32_GUEST_FS_LIMIT,
615 VMX_VMCS32_GUEST_GS_LIMIT,
616 VMX_VMCS32_GUEST_LDTR_LIMIT,
617 VMX_VMCS32_GUEST_TR_LIMIT,
618 VMX_VMCS32_GUEST_GDTR_LIMIT,
619 VMX_VMCS32_GUEST_IDTR_LIMIT,
620 VMX_VMCS32_GUEST_ES_ACCESS_RIGHTS,
621 VMX_VMCS32_GUEST_CS_ACCESS_RIGHTS,
622 VMX_VMCS32_GUEST_SS_ACCESS_RIGHTS,
623 VMX_VMCS32_GUEST_DS_ACCESS_RIGHTS,
624 VMX_VMCS32_GUEST_FS_ACCESS_RIGHTS,
625 VMX_VMCS32_GUEST_GS_ACCESS_RIGHTS,
626 VMX_VMCS32_GUEST_LDTR_ACCESS_RIGHTS,
627 VMX_VMCS32_GUEST_TR_ACCESS_RIGHTS,
628 VMX_VMCS32_GUEST_INT_STATE,
629 VMX_VMCS32_GUEST_ACTIVITY_STATE,
630 VMX_VMCS32_GUEST_SMBASE,
631 VMX_VMCS32_GUEST_SYSENTER_CS,
632 VMX_VMCS32_PREEMPT_TIMER_VALUE,
633
634 /* 32-bit host-state fields. */
635 VMX_VMCS32_HOST_SYSENTER_CS,
636
637 /* Natural-width control fields. */
638 VMX_VMCS_CTRL_CR0_MASK,
639 VMX_VMCS_CTRL_CR4_MASK,
640 VMX_VMCS_CTRL_CR0_READ_SHADOW,
641 VMX_VMCS_CTRL_CR4_READ_SHADOW,
642 VMX_VMCS_CTRL_CR3_TARGET_VAL0,
643 VMX_VMCS_CTRL_CR3_TARGET_VAL1,
644 VMX_VMCS_CTRL_CR3_TARGET_VAL2,
645 VMX_VMCS_CTRL_CR3_TARGET_VAL3,
646
647 /* Natural-width read-only data fields. */
648 VMX_VMCS_RO_EXIT_QUALIFICATION,
649 VMX_VMCS_RO_IO_RCX,
650 VMX_VMCS_RO_IO_RSI,
651 VMX_VMCS_RO_IO_RDI,
652 VMX_VMCS_RO_IO_RIP,
653 VMX_VMCS_RO_GUEST_LINEAR_ADDR,
654
655 /* Natural-width guest-state field */
656 VMX_VMCS_GUEST_CR0,
657 VMX_VMCS_GUEST_CR3,
658 VMX_VMCS_GUEST_CR4,
659 VMX_VMCS_GUEST_ES_BASE,
660 VMX_VMCS_GUEST_CS_BASE,
661 VMX_VMCS_GUEST_SS_BASE,
662 VMX_VMCS_GUEST_DS_BASE,
663 VMX_VMCS_GUEST_FS_BASE,
664 VMX_VMCS_GUEST_GS_BASE,
665 VMX_VMCS_GUEST_LDTR_BASE,
666 VMX_VMCS_GUEST_TR_BASE,
667 VMX_VMCS_GUEST_GDTR_BASE,
668 VMX_VMCS_GUEST_IDTR_BASE,
669 VMX_VMCS_GUEST_DR7,
670 VMX_VMCS_GUEST_RSP,
671 VMX_VMCS_GUEST_RIP,
672 VMX_VMCS_GUEST_RFLAGS,
673 VMX_VMCS_GUEST_PENDING_DEBUG_XCPTS,
674 VMX_VMCS_GUEST_SYSENTER_ESP,
675 VMX_VMCS_GUEST_SYSENTER_EIP,
676
677 /* Natural-width host-state fields */
678 VMX_VMCS_HOST_CR0,
679 VMX_VMCS_HOST_CR3,
680 VMX_VMCS_HOST_CR4,
681 VMX_VMCS_HOST_FS_BASE,
682 VMX_VMCS_HOST_GS_BASE,
683 VMX_VMCS_HOST_TR_BASE,
684 VMX_VMCS_HOST_GDTR_BASE,
685 VMX_VMCS_HOST_IDTR_BASE,
686 VMX_VMCS_HOST_SYSENTER_ESP,
687 VMX_VMCS_HOST_SYSENTER_EIP,
688 VMX_VMCS_HOST_RSP,
689 VMX_VMCS_HOST_RIP
690};
691#endif /* VBOX_WITH_NESTED_HWVIRT_VMX */
692
693static const uint32_t g_aVmcsSegBase[] =
694{
695 VMX_VMCS_GUEST_ES_BASE,
696 VMX_VMCS_GUEST_CS_BASE,
697 VMX_VMCS_GUEST_SS_BASE,
698 VMX_VMCS_GUEST_DS_BASE,
699 VMX_VMCS_GUEST_FS_BASE,
700 VMX_VMCS_GUEST_GS_BASE
701};
702static const uint32_t g_aVmcsSegSel[] =
703{
704 VMX_VMCS16_GUEST_ES_SEL,
705 VMX_VMCS16_GUEST_CS_SEL,
706 VMX_VMCS16_GUEST_SS_SEL,
707 VMX_VMCS16_GUEST_DS_SEL,
708 VMX_VMCS16_GUEST_FS_SEL,
709 VMX_VMCS16_GUEST_GS_SEL
710};
711static const uint32_t g_aVmcsSegLimit[] =
712{
713 VMX_VMCS32_GUEST_ES_LIMIT,
714 VMX_VMCS32_GUEST_CS_LIMIT,
715 VMX_VMCS32_GUEST_SS_LIMIT,
716 VMX_VMCS32_GUEST_DS_LIMIT,
717 VMX_VMCS32_GUEST_FS_LIMIT,
718 VMX_VMCS32_GUEST_GS_LIMIT
719};
720static const uint32_t g_aVmcsSegAttr[] =
721{
722 VMX_VMCS32_GUEST_ES_ACCESS_RIGHTS,
723 VMX_VMCS32_GUEST_CS_ACCESS_RIGHTS,
724 VMX_VMCS32_GUEST_SS_ACCESS_RIGHTS,
725 VMX_VMCS32_GUEST_DS_ACCESS_RIGHTS,
726 VMX_VMCS32_GUEST_FS_ACCESS_RIGHTS,
727 VMX_VMCS32_GUEST_GS_ACCESS_RIGHTS
728};
729AssertCompile(RT_ELEMENTS(g_aVmcsSegSel) == X86_SREG_COUNT);
730AssertCompile(RT_ELEMENTS(g_aVmcsSegLimit) == X86_SREG_COUNT);
731AssertCompile(RT_ELEMENTS(g_aVmcsSegBase) == X86_SREG_COUNT);
732AssertCompile(RT_ELEMENTS(g_aVmcsSegAttr) == X86_SREG_COUNT);
733
734#ifdef HMVMX_USE_FUNCTION_TABLE
735/**
736 * VMX_EXIT dispatch table.
737 */
738static const PFNVMXEXITHANDLER g_apfnVMExitHandlers[VMX_EXIT_MAX + 1] =
739{
740 /* 0 VMX_EXIT_XCPT_OR_NMI */ hmR0VmxExitXcptOrNmi,
741 /* 1 VMX_EXIT_EXT_INT */ hmR0VmxExitExtInt,
742 /* 2 VMX_EXIT_TRIPLE_FAULT */ hmR0VmxExitTripleFault,
743 /* 3 VMX_EXIT_INIT_SIGNAL */ hmR0VmxExitErrUnexpected,
744 /* 4 VMX_EXIT_SIPI */ hmR0VmxExitErrUnexpected,
745 /* 5 VMX_EXIT_IO_SMI */ hmR0VmxExitErrUnexpected,
746 /* 6 VMX_EXIT_SMI */ hmR0VmxExitErrUnexpected,
747 /* 7 VMX_EXIT_INT_WINDOW */ hmR0VmxExitIntWindow,
748 /* 8 VMX_EXIT_NMI_WINDOW */ hmR0VmxExitNmiWindow,
749 /* 9 VMX_EXIT_TASK_SWITCH */ hmR0VmxExitTaskSwitch,
750 /* 10 VMX_EXIT_CPUID */ hmR0VmxExitCpuid,
751 /* 11 VMX_EXIT_GETSEC */ hmR0VmxExitGetsec,
752 /* 12 VMX_EXIT_HLT */ hmR0VmxExitHlt,
753 /* 13 VMX_EXIT_INVD */ hmR0VmxExitInvd,
754 /* 14 VMX_EXIT_INVLPG */ hmR0VmxExitInvlpg,
755 /* 15 VMX_EXIT_RDPMC */ hmR0VmxExitRdpmc,
756 /* 16 VMX_EXIT_RDTSC */ hmR0VmxExitRdtsc,
757 /* 17 VMX_EXIT_RSM */ hmR0VmxExitErrUnexpected,
758 /* 18 VMX_EXIT_VMCALL */ hmR0VmxExitVmcall,
759#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
760 /* 19 VMX_EXIT_VMCLEAR */ hmR0VmxExitVmclear,
761 /* 20 VMX_EXIT_VMLAUNCH */ hmR0VmxExitVmlaunch,
762 /* 21 VMX_EXIT_VMPTRLD */ hmR0VmxExitVmptrld,
763 /* 22 VMX_EXIT_VMPTRST */ hmR0VmxExitVmptrst,
764 /* 23 VMX_EXIT_VMREAD */ hmR0VmxExitVmread,
765 /* 24 VMX_EXIT_VMRESUME */ hmR0VmxExitVmresume,
766 /* 25 VMX_EXIT_VMWRITE */ hmR0VmxExitVmwrite,
767 /* 26 VMX_EXIT_VMXOFF */ hmR0VmxExitVmxoff,
768 /* 27 VMX_EXIT_VMXON */ hmR0VmxExitVmxon,
769#else
770 /* 19 VMX_EXIT_VMCLEAR */ hmR0VmxExitSetPendingXcptUD,
771 /* 20 VMX_EXIT_VMLAUNCH */ hmR0VmxExitSetPendingXcptUD,
772 /* 21 VMX_EXIT_VMPTRLD */ hmR0VmxExitSetPendingXcptUD,
773 /* 22 VMX_EXIT_VMPTRST */ hmR0VmxExitSetPendingXcptUD,
774 /* 23 VMX_EXIT_VMREAD */ hmR0VmxExitSetPendingXcptUD,
775 /* 24 VMX_EXIT_VMRESUME */ hmR0VmxExitSetPendingXcptUD,
776 /* 25 VMX_EXIT_VMWRITE */ hmR0VmxExitSetPendingXcptUD,
777 /* 26 VMX_EXIT_VMXOFF */ hmR0VmxExitSetPendingXcptUD,
778 /* 27 VMX_EXIT_VMXON */ hmR0VmxExitSetPendingXcptUD,
779#endif
780 /* 28 VMX_EXIT_MOV_CRX */ hmR0VmxExitMovCRx,
781 /* 29 VMX_EXIT_MOV_DRX */ hmR0VmxExitMovDRx,
782 /* 30 VMX_EXIT_IO_INSTR */ hmR0VmxExitIoInstr,
783 /* 31 VMX_EXIT_RDMSR */ hmR0VmxExitRdmsr,
784 /* 32 VMX_EXIT_WRMSR */ hmR0VmxExitWrmsr,
785 /* 33 VMX_EXIT_ERR_INVALID_GUEST_STATE */ hmR0VmxExitErrInvalidGuestState,
786 /* 34 VMX_EXIT_ERR_MSR_LOAD */ hmR0VmxExitErrUnexpected,
787 /* 35 UNDEFINED */ hmR0VmxExitErrUnexpected,
788 /* 36 VMX_EXIT_MWAIT */ hmR0VmxExitMwait,
789 /* 37 VMX_EXIT_MTF */ hmR0VmxExitMtf,
790 /* 38 UNDEFINED */ hmR0VmxExitErrUnexpected,
791 /* 39 VMX_EXIT_MONITOR */ hmR0VmxExitMonitor,
792 /* 40 VMX_EXIT_PAUSE */ hmR0VmxExitPause,
793 /* 41 VMX_EXIT_ERR_MACHINE_CHECK */ hmR0VmxExitErrUnexpected,
794 /* 42 UNDEFINED */ hmR0VmxExitErrUnexpected,
795 /* 43 VMX_EXIT_TPR_BELOW_THRESHOLD */ hmR0VmxExitTprBelowThreshold,
796 /* 44 VMX_EXIT_APIC_ACCESS */ hmR0VmxExitApicAccess,
797 /* 45 VMX_EXIT_VIRTUALIZED_EOI */ hmR0VmxExitErrUnexpected,
798 /* 46 VMX_EXIT_GDTR_IDTR_ACCESS */ hmR0VmxExitErrUnexpected,
799 /* 47 VMX_EXIT_LDTR_TR_ACCESS */ hmR0VmxExitErrUnexpected,
800 /* 48 VMX_EXIT_EPT_VIOLATION */ hmR0VmxExitEptViolation,
801 /* 49 VMX_EXIT_EPT_MISCONFIG */ hmR0VmxExitEptMisconfig,
802 /* 50 VMX_EXIT_INVEPT */ hmR0VmxExitSetPendingXcptUD,
803 /* 51 VMX_EXIT_RDTSCP */ hmR0VmxExitRdtscp,
804 /* 52 VMX_EXIT_PREEMPT_TIMER */ hmR0VmxExitPreemptTimer,
805#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
806 /* 53 VMX_EXIT_INVVPID */ hmR0VmxExitInvvpid,
807#else
808 /* 53 VMX_EXIT_INVVPID */ hmR0VmxExitSetPendingXcptUD,
809#endif
810 /* 54 VMX_EXIT_WBINVD */ hmR0VmxExitWbinvd,
811 /* 55 VMX_EXIT_XSETBV */ hmR0VmxExitXsetbv,
812 /* 56 VMX_EXIT_APIC_WRITE */ hmR0VmxExitErrUnexpected,
813 /* 57 VMX_EXIT_RDRAND */ hmR0VmxExitErrUnexpected,
814 /* 58 VMX_EXIT_INVPCID */ hmR0VmxExitInvpcid,
815 /* 59 VMX_EXIT_VMFUNC */ hmR0VmxExitErrUnexpected,
816 /* 60 VMX_EXIT_ENCLS */ hmR0VmxExitErrUnexpected,
817 /* 61 VMX_EXIT_RDSEED */ hmR0VmxExitErrUnexpected,
818 /* 62 VMX_EXIT_PML_FULL */ hmR0VmxExitErrUnexpected,
819 /* 63 VMX_EXIT_XSAVES */ hmR0VmxExitErrUnexpected,
820 /* 64 VMX_EXIT_XRSTORS */ hmR0VmxExitErrUnexpected,
821 /* 65 UNDEFINED */ hmR0VmxExitErrUnexpected,
822 /* 66 VMX_EXIT_SPP_EVENT */ hmR0VmxExitErrUnexpected,
823 /* 67 VMX_EXIT_UMWAIT */ hmR0VmxExitErrUnexpected,
824 /* 68 VMX_EXIT_TPAUSE */ hmR0VmxExitErrUnexpected,
825};
826#endif /* HMVMX_USE_FUNCTION_TABLE */
827
828#if defined(VBOX_STRICT) && defined(LOG_ENABLED)
829static const char * const g_apszVmxInstrErrors[HMVMX_INSTR_ERROR_MAX + 1] =
830{
831 /* 0 */ "(Not Used)",
832 /* 1 */ "VMCALL executed in VMX root operation.",
833 /* 2 */ "VMCLEAR with invalid physical address.",
834 /* 3 */ "VMCLEAR with VMXON pointer.",
835 /* 4 */ "VMLAUNCH with non-clear VMCS.",
836 /* 5 */ "VMRESUME with non-launched VMCS.",
837 /* 6 */ "VMRESUME after VMXOFF",
838 /* 7 */ "VM-entry with invalid control fields.",
839 /* 8 */ "VM-entry with invalid host state fields.",
840 /* 9 */ "VMPTRLD with invalid physical address.",
841 /* 10 */ "VMPTRLD with VMXON pointer.",
842 /* 11 */ "VMPTRLD with incorrect revision identifier.",
843 /* 12 */ "VMREAD/VMWRITE from/to unsupported VMCS component.",
844 /* 13 */ "VMWRITE to read-only VMCS component.",
845 /* 14 */ "(Not Used)",
846 /* 15 */ "VMXON executed in VMX root operation.",
847 /* 16 */ "VM-entry with invalid executive-VMCS pointer.",
848 /* 17 */ "VM-entry with non-launched executing VMCS.",
849 /* 18 */ "VM-entry with executive-VMCS pointer not VMXON pointer.",
850 /* 19 */ "VMCALL with non-clear VMCS.",
851 /* 20 */ "VMCALL with invalid VM-exit control fields.",
852 /* 21 */ "(Not Used)",
853 /* 22 */ "VMCALL with incorrect MSEG revision identifier.",
854 /* 23 */ "VMXOFF under dual monitor treatment of SMIs and SMM.",
855 /* 24 */ "VMCALL with invalid SMM-monitor features.",
856 /* 25 */ "VM-entry with invalid VM-execution control fields in executive VMCS.",
857 /* 26 */ "VM-entry with events blocked by MOV SS.",
858 /* 27 */ "(Not Used)",
859 /* 28 */ "Invalid operand to INVEPT/INVVPID."
860};
861#endif /* VBOX_STRICT && LOG_ENABLED */
862
863
864/**
865 * Gets the CR0 guest/host mask.
866 *
867 * These bits typically does not change through the lifetime of a VM. Any bit set in
868 * this mask is owned by the host/hypervisor and would cause a VM-exit when modified
869 * by the guest.
870 *
871 * @returns The CR0 guest/host mask.
872 * @param pVCpu The cross context virtual CPU structure.
873 */
874static uint64_t hmR0VmxGetFixedCr0Mask(PCVMCPUCC pVCpu)
875{
876 /*
877 * Modifications to CR0 bits that VT-x ignores saving/restoring (CD, ET, NW) and
878 * to CR0 bits that we require for shadow paging (PG) by the guest must cause VM-exits.
879 *
880 * Furthermore, modifications to any bits that are reserved/unspecified currently
881 * by the Intel spec. must also cause a VM-exit. This prevents unpredictable behavior
882 * when future CPUs specify and use currently reserved/unspecified bits.
883 */
884 /** @todo Avoid intercepting CR0.PE with unrestricted guest execution. Fix PGM
885 * enmGuestMode to be in-sync with the current mode. See @bugref{6398}
886 * and @bugref{6944}. */
887 PCVMCC pVM = pVCpu->CTX_SUFF(pVM);
888 return ( X86_CR0_PE
889 | X86_CR0_NE
890 | (pVM->hm.s.fNestedPaging ? 0 : X86_CR0_WP)
891 | X86_CR0_PG
892 | VMX_EXIT_HOST_CR0_IGNORE_MASK);
893}
894
895
896/**
897 * Gets the CR4 guest/host mask.
898 *
899 * These bits typically does not change through the lifetime of a VM. Any bit set in
900 * this mask is owned by the host/hypervisor and would cause a VM-exit when modified
901 * by the guest.
902 *
903 * @returns The CR4 guest/host mask.
904 * @param pVCpu The cross context virtual CPU structure.
905 */
906static uint64_t hmR0VmxGetFixedCr4Mask(PCVMCPUCC pVCpu)
907{
908 /*
909 * We construct a mask of all CR4 bits that the guest can modify without causing
910 * a VM-exit. Then invert this mask to obtain all CR4 bits that should cause
911 * a VM-exit when the guest attempts to modify them when executing using
912 * hardware-assisted VMX.
913 *
914 * When a feature is not exposed to the guest (and may be present on the host),
915 * we want to intercept guest modifications to the bit so we can emulate proper
916 * behavior (e.g., #GP).
917 *
918 * Furthermore, only modifications to those bits that don't require immediate
919 * emulation is allowed. For e.g., PCIDE is excluded because the behavior
920 * depends on CR3 which might not always be the guest value while executing
921 * using hardware-assisted VMX.
922 */
923 PCVMCC pVM = pVCpu->CTX_SUFF(pVM);
924 bool const fFsGsBase = pVM->cpum.ro.GuestFeatures.fFsGsBase;
925 bool const fXSaveRstor = pVM->cpum.ro.GuestFeatures.fXSaveRstor;
926 bool const fFxSaveRstor = pVM->cpum.ro.GuestFeatures.fFxSaveRstor;
927
928 /*
929 * Paranoia.
930 * Ensure features exposed to the guest are present on the host.
931 */
932 Assert(!fFsGsBase || pVM->cpum.ro.HostFeatures.fFsGsBase);
933 Assert(!fXSaveRstor || pVM->cpum.ro.HostFeatures.fXSaveRstor);
934 Assert(!fFxSaveRstor || pVM->cpum.ro.HostFeatures.fFxSaveRstor);
935
936 uint64_t const fGstMask = ( X86_CR4_PVI
937 | X86_CR4_TSD
938 | X86_CR4_DE
939 | X86_CR4_MCE
940 | X86_CR4_PCE
941 | X86_CR4_OSXMMEEXCPT
942 | (fFsGsBase ? X86_CR4_FSGSBASE : 0)
943 | (fXSaveRstor ? X86_CR4_OSXSAVE : 0)
944 | (fFxSaveRstor ? X86_CR4_OSFXSR : 0));
945 return ~fGstMask;
946}
947
948
949/**
950 * Returns whether the the VM-exit MSR-store area differs from the VM-exit MSR-load
951 * area.
952 *
953 * @returns @c true if it's different, @c false otherwise.
954 * @param pVmcsInfo The VMCS info. object.
955 */
956DECL_FORCE_INLINE(bool) hmR0VmxIsSeparateExitMsrStoreAreaVmcs(PCVMXVMCSINFO pVmcsInfo)
957{
958 return RT_BOOL( pVmcsInfo->pvGuestMsrStore != pVmcsInfo->pvGuestMsrLoad
959 && pVmcsInfo->pvGuestMsrStore);
960}
961
962
963/**
964 * Sets the given Processor-based VM-execution controls.
965 *
966 * @param pVmxTransient The VMX-transient structure.
967 * @param uProcCtls The Processor-based VM-execution controls to set.
968 */
969static void hmR0VmxSetProcCtlsVmcs(PVMXTRANSIENT pVmxTransient, uint32_t uProcCtls)
970{
971 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
972 if ((pVmcsInfo->u32ProcCtls & uProcCtls) != uProcCtls)
973 {
974 pVmcsInfo->u32ProcCtls |= uProcCtls;
975 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, pVmcsInfo->u32ProcCtls);
976 AssertRC(rc);
977 }
978}
979
980
981/**
982 * Removes the given Processor-based VM-execution controls.
983 *
984 * @param pVCpu The cross context virtual CPU structure.
985 * @param pVmxTransient The VMX-transient structure.
986 * @param uProcCtls The Processor-based VM-execution controls to remove.
987 *
988 * @remarks When executing a nested-guest, this will not remove any of the specified
989 * controls if the nested hypervisor has set any one of them.
990 */
991static void hmR0VmxRemoveProcCtlsVmcs(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient, uint32_t uProcCtls)
992{
993 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
994 if (pVmcsInfo->u32ProcCtls & uProcCtls)
995 {
996#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
997 bool const fRemoveCtls = !pVmxTransient->fIsNestedGuest
998 ? true
999 : !CPUMIsGuestVmxProcCtlsSet(&pVCpu->cpum.GstCtx, uProcCtls);
1000#else
1001 NOREF(pVCpu);
1002 bool const fRemoveCtls = true;
1003#endif
1004 if (fRemoveCtls)
1005 {
1006 pVmcsInfo->u32ProcCtls &= ~uProcCtls;
1007 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, pVmcsInfo->u32ProcCtls);
1008 AssertRC(rc);
1009 }
1010 }
1011}
1012
1013
1014/**
1015 * Sets the TSC offset for the current VMCS.
1016 *
1017 * @param uTscOffset The TSC offset to set.
1018 * @param pVmcsInfo The VMCS info. object.
1019 */
1020static void hmR0VmxSetTscOffsetVmcs(PVMXVMCSINFO pVmcsInfo, uint64_t uTscOffset)
1021{
1022 if (pVmcsInfo->u64TscOffset != uTscOffset)
1023 {
1024 int rc = VMXWriteVmcs64(VMX_VMCS64_CTRL_TSC_OFFSET_FULL, uTscOffset);
1025 AssertRC(rc);
1026 pVmcsInfo->u64TscOffset = uTscOffset;
1027 }
1028}
1029
1030
1031/**
1032 * Adds one or more exceptions to the exception bitmap and commits it to the current
1033 * VMCS.
1034 *
1035 * @param pVmxTransient The VMX-transient structure.
1036 * @param uXcptMask The exception(s) to add.
1037 */
1038static void hmR0VmxAddXcptInterceptMask(PCVMXTRANSIENT pVmxTransient, uint32_t uXcptMask)
1039{
1040 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
1041 uint32_t uXcptBitmap = pVmcsInfo->u32XcptBitmap;
1042 if ((uXcptBitmap & uXcptMask) != uXcptMask)
1043 {
1044 uXcptBitmap |= uXcptMask;
1045 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_EXCEPTION_BITMAP, uXcptBitmap);
1046 AssertRC(rc);
1047 pVmcsInfo->u32XcptBitmap = uXcptBitmap;
1048 }
1049}
1050
1051
1052/**
1053 * Adds an exception to the exception bitmap and commits it to the current VMCS.
1054 *
1055 * @param pVmxTransient The VMX-transient structure.
1056 * @param uXcpt The exception to add.
1057 */
1058static void hmR0VmxAddXcptIntercept(PCVMXTRANSIENT pVmxTransient, uint8_t uXcpt)
1059{
1060 Assert(uXcpt <= X86_XCPT_LAST);
1061 hmR0VmxAddXcptInterceptMask(pVmxTransient, RT_BIT_32(uXcpt));
1062}
1063
1064
1065/**
1066 * Remove one or more exceptions from the exception bitmap and commits it to the
1067 * current VMCS.
1068 *
1069 * This takes care of not removing the exception intercept if a nested-guest
1070 * requires the exception to be intercepted.
1071 *
1072 * @returns VBox status code.
1073 * @param pVCpu The cross context virtual CPU structure.
1074 * @param pVmxTransient The VMX-transient structure.
1075 * @param uXcptMask The exception(s) to remove.
1076 */
1077static int hmR0VmxRemoveXcptInterceptMask(PVMCPUCC pVCpu, PCVMXTRANSIENT pVmxTransient, uint32_t uXcptMask)
1078{
1079 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
1080 uint32_t u32XcptBitmap = pVmcsInfo->u32XcptBitmap;
1081 if (u32XcptBitmap & uXcptMask)
1082 {
1083#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
1084 if (!pVmxTransient->fIsNestedGuest)
1085 { /* likely */ }
1086 else
1087 {
1088 PCVMXVVMCS pVmcsNstGst = pVCpu->cpum.GstCtx.hwvirt.vmx.CTX_SUFF(pVmcs);
1089 uXcptMask &= ~pVmcsNstGst->u32XcptBitmap;
1090 }
1091#endif
1092#ifdef HMVMX_ALWAYS_TRAP_ALL_XCPTS
1093 uXcptMask &= ~( RT_BIT(X86_XCPT_BP)
1094 | RT_BIT(X86_XCPT_DE)
1095 | RT_BIT(X86_XCPT_NM)
1096 | RT_BIT(X86_XCPT_TS)
1097 | RT_BIT(X86_XCPT_UD)
1098 | RT_BIT(X86_XCPT_NP)
1099 | RT_BIT(X86_XCPT_SS)
1100 | RT_BIT(X86_XCPT_GP)
1101 | RT_BIT(X86_XCPT_PF)
1102 | RT_BIT(X86_XCPT_MF));
1103#elif defined(HMVMX_ALWAYS_TRAP_PF)
1104 uXcptMask &= ~RT_BIT(X86_XCPT_PF);
1105#endif
1106 if (uXcptMask)
1107 {
1108 /* Validate we are not removing any essential exception intercepts. */
1109 Assert(pVCpu->CTX_SUFF(pVM)->hm.s.fNestedPaging || !(uXcptMask & RT_BIT(X86_XCPT_PF)));
1110 NOREF(pVCpu);
1111 Assert(!(uXcptMask & RT_BIT(X86_XCPT_DB)));
1112 Assert(!(uXcptMask & RT_BIT(X86_XCPT_AC)));
1113
1114 /* Remove it from the exception bitmap. */
1115 u32XcptBitmap &= ~uXcptMask;
1116
1117 /* Commit and update the cache if necessary. */
1118 if (pVmcsInfo->u32XcptBitmap != u32XcptBitmap)
1119 {
1120 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_EXCEPTION_BITMAP, u32XcptBitmap);
1121 AssertRC(rc);
1122 pVmcsInfo->u32XcptBitmap = u32XcptBitmap;
1123 }
1124 }
1125 }
1126 return VINF_SUCCESS;
1127}
1128
1129
1130/**
1131 * Remove an exceptions from the exception bitmap and commits it to the current
1132 * VMCS.
1133 *
1134 * @returns VBox status code.
1135 * @param pVCpu The cross context virtual CPU structure.
1136 * @param pVmxTransient The VMX-transient structure.
1137 * @param uXcpt The exception to remove.
1138 */
1139static int hmR0VmxRemoveXcptIntercept(PVMCPUCC pVCpu, PCVMXTRANSIENT pVmxTransient, uint8_t uXcpt)
1140{
1141 return hmR0VmxRemoveXcptInterceptMask(pVCpu, pVmxTransient, RT_BIT(uXcpt));
1142}
1143
1144
1145/**
1146 * Loads the VMCS specified by the VMCS info. object.
1147 *
1148 * @returns VBox status code.
1149 * @param pVmcsInfo The VMCS info. object.
1150 *
1151 * @remarks Can be called with interrupts disabled.
1152 */
1153static int hmR0VmxLoadVmcs(PVMXVMCSINFO pVmcsInfo)
1154{
1155 Assert(pVmcsInfo->HCPhysVmcs != 0 && pVmcsInfo->HCPhysVmcs != NIL_RTHCPHYS);
1156 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
1157
1158 int rc = VMXLoadVmcs(pVmcsInfo->HCPhysVmcs);
1159 if (RT_SUCCESS(rc))
1160 pVmcsInfo->fVmcsState |= VMX_V_VMCS_LAUNCH_STATE_CURRENT;
1161 return rc;
1162}
1163
1164
1165/**
1166 * Clears the VMCS specified by the VMCS info. object.
1167 *
1168 * @returns VBox status code.
1169 * @param pVmcsInfo The VMCS info. object.
1170 *
1171 * @remarks Can be called with interrupts disabled.
1172 */
1173static int hmR0VmxClearVmcs(PVMXVMCSINFO pVmcsInfo)
1174{
1175 Assert(pVmcsInfo->HCPhysVmcs != 0 && pVmcsInfo->HCPhysVmcs != NIL_RTHCPHYS);
1176 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
1177
1178 int rc = VMXClearVmcs(pVmcsInfo->HCPhysVmcs);
1179 if (RT_SUCCESS(rc))
1180 pVmcsInfo->fVmcsState = VMX_V_VMCS_LAUNCH_STATE_CLEAR;
1181 return rc;
1182}
1183
1184
1185#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
1186/**
1187 * Loads the shadow VMCS specified by the VMCS info. object.
1188 *
1189 * @returns VBox status code.
1190 * @param pVmcsInfo The VMCS info. object.
1191 *
1192 * @remarks Can be called with interrupts disabled.
1193 */
1194static int hmR0VmxLoadShadowVmcs(PVMXVMCSINFO pVmcsInfo)
1195{
1196 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
1197 Assert(pVmcsInfo->HCPhysShadowVmcs != 0 && pVmcsInfo->HCPhysShadowVmcs != NIL_RTHCPHYS);
1198
1199 int rc = VMXLoadVmcs(pVmcsInfo->HCPhysShadowVmcs);
1200 if (RT_SUCCESS(rc))
1201 pVmcsInfo->fShadowVmcsState |= VMX_V_VMCS_LAUNCH_STATE_CURRENT;
1202 return rc;
1203}
1204
1205
1206/**
1207 * Clears the shadow VMCS specified by the VMCS info. object.
1208 *
1209 * @returns VBox status code.
1210 * @param pVmcsInfo The VMCS info. object.
1211 *
1212 * @remarks Can be called with interrupts disabled.
1213 */
1214static int hmR0VmxClearShadowVmcs(PVMXVMCSINFO pVmcsInfo)
1215{
1216 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
1217 Assert(pVmcsInfo->HCPhysShadowVmcs != 0 && pVmcsInfo->HCPhysShadowVmcs != NIL_RTHCPHYS);
1218
1219 int rc = VMXClearVmcs(pVmcsInfo->HCPhysShadowVmcs);
1220 if (RT_SUCCESS(rc))
1221 pVmcsInfo->fShadowVmcsState = VMX_V_VMCS_LAUNCH_STATE_CLEAR;
1222 return rc;
1223}
1224
1225
1226/**
1227 * Switches from and to the specified VMCSes.
1228 *
1229 * @returns VBox status code.
1230 * @param pVmcsInfoFrom The VMCS info. object we are switching from.
1231 * @param pVmcsInfoTo The VMCS info. object we are switching to.
1232 *
1233 * @remarks Called with interrupts disabled.
1234 */
1235static int hmR0VmxSwitchVmcs(PVMXVMCSINFO pVmcsInfoFrom, PVMXVMCSINFO pVmcsInfoTo)
1236{
1237 /*
1238 * Clear the VMCS we are switching out if it has not already been cleared.
1239 * This will sync any CPU internal data back to the VMCS.
1240 */
1241 if (pVmcsInfoFrom->fVmcsState != VMX_V_VMCS_LAUNCH_STATE_CLEAR)
1242 {
1243 int rc = hmR0VmxClearVmcs(pVmcsInfoFrom);
1244 if (RT_SUCCESS(rc))
1245 {
1246 /*
1247 * The shadow VMCS, if any, would not be active at this point since we
1248 * would have cleared it while importing the virtual hardware-virtualization
1249 * state as part the VMLAUNCH/VMRESUME VM-exit. Hence, there's no need to
1250 * clear the shadow VMCS here, just assert for safety.
1251 */
1252 Assert(!pVmcsInfoFrom->pvShadowVmcs || pVmcsInfoFrom->fShadowVmcsState == VMX_V_VMCS_LAUNCH_STATE_CLEAR);
1253 }
1254 else
1255 return rc;
1256 }
1257
1258 /*
1259 * Clear the VMCS we are switching to if it has not already been cleared.
1260 * This will initialize the VMCS launch state to "clear" required for loading it.
1261 *
1262 * See Intel spec. 31.6 "Preparation And Launching A Virtual Machine".
1263 */
1264 if (pVmcsInfoTo->fVmcsState != VMX_V_VMCS_LAUNCH_STATE_CLEAR)
1265 {
1266 int rc = hmR0VmxClearVmcs(pVmcsInfoTo);
1267 if (RT_SUCCESS(rc))
1268 { /* likely */ }
1269 else
1270 return rc;
1271 }
1272
1273 /*
1274 * Finally, load the VMCS we are switching to.
1275 */
1276 return hmR0VmxLoadVmcs(pVmcsInfoTo);
1277}
1278
1279
1280/**
1281 * Switches between the guest VMCS and the nested-guest VMCS as specified by the
1282 * caller.
1283 *
1284 * @returns VBox status code.
1285 * @param pVCpu The cross context virtual CPU structure.
1286 * @param fSwitchToNstGstVmcs Whether to switch to the nested-guest VMCS (pass
1287 * true) or guest VMCS (pass false).
1288 */
1289static int hmR0VmxSwitchToGstOrNstGstVmcs(PVMCPUCC pVCpu, bool fSwitchToNstGstVmcs)
1290{
1291 /* Ensure we have synced everything from the guest-CPU context to the VMCS before switching. */
1292 HMVMX_CPUMCTX_ASSERT(pVCpu, HMVMX_CPUMCTX_EXTRN_ALL);
1293
1294 PVMXVMCSINFO pVmcsInfoFrom;
1295 PVMXVMCSINFO pVmcsInfoTo;
1296 if (fSwitchToNstGstVmcs)
1297 {
1298 pVmcsInfoFrom = &pVCpu->hm.s.vmx.VmcsInfo;
1299 pVmcsInfoTo = &pVCpu->hm.s.vmx.VmcsInfoNstGst;
1300 }
1301 else
1302 {
1303 pVmcsInfoFrom = &pVCpu->hm.s.vmx.VmcsInfoNstGst;
1304 pVmcsInfoTo = &pVCpu->hm.s.vmx.VmcsInfo;
1305 }
1306
1307 /*
1308 * Disable interrupts to prevent being preempted while we switch the current VMCS as the
1309 * preemption hook code path acquires the current VMCS.
1310 */
1311 RTCCUINTREG const fEFlags = ASMIntDisableFlags();
1312
1313 int rc = hmR0VmxSwitchVmcs(pVmcsInfoFrom, pVmcsInfoTo);
1314 if (RT_SUCCESS(rc))
1315 {
1316 pVCpu->hm.s.vmx.fSwitchedToNstGstVmcs = fSwitchToNstGstVmcs;
1317
1318 /*
1319 * If we are switching to a VMCS that was executed on a different host CPU or was
1320 * never executed before, flag that we need to export the host state before executing
1321 * guest/nested-guest code using hardware-assisted VMX.
1322 *
1323 * This could probably be done in a preemptible context since the preemption hook
1324 * will flag the necessary change in host context. However, since preemption is
1325 * already disabled and to avoid making assumptions about host specific code in
1326 * RTMpCpuId when called with preemption enabled, we'll do this while preemption is
1327 * disabled.
1328 */
1329 if (pVmcsInfoTo->idHostCpuState == RTMpCpuId())
1330 { /* likely */ }
1331 else
1332 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_HOST_CONTEXT | HM_CHANGED_VMX_HOST_GUEST_SHARED_STATE);
1333
1334 ASMSetFlags(fEFlags);
1335
1336 /*
1337 * We use a different VM-exit MSR-store areas for the guest and nested-guest. Hence,
1338 * flag that we need to update the host MSR values there. Even if we decide in the
1339 * future to share the VM-exit MSR-store area page between the guest and nested-guest,
1340 * if its content differs, we would have to update the host MSRs anyway.
1341 */
1342 pVCpu->hm.s.vmx.fUpdatedHostAutoMsrs = false;
1343 }
1344 else
1345 ASMSetFlags(fEFlags);
1346 return rc;
1347}
1348#endif /* VBOX_WITH_NESTED_HWVIRT_VMX */
1349
1350
1351/**
1352 * Updates the VM's last error record.
1353 *
1354 * If there was a VMX instruction error, reads the error data from the VMCS and
1355 * updates VCPU's last error record as well.
1356 *
1357 * @param pVCpu The cross context virtual CPU structure of the calling EMT.
1358 * Can be NULL if @a rc is not VERR_VMX_UNABLE_TO_START_VM or
1359 * VERR_VMX_INVALID_VMCS_FIELD.
1360 * @param rc The error code.
1361 */
1362static void hmR0VmxUpdateErrorRecord(PVMCPUCC pVCpu, int rc)
1363{
1364 if ( rc == VERR_VMX_INVALID_VMCS_FIELD
1365 || rc == VERR_VMX_UNABLE_TO_START_VM)
1366 {
1367 AssertPtrReturnVoid(pVCpu);
1368 VMXReadVmcs32(VMX_VMCS32_RO_VM_INSTR_ERROR, &pVCpu->hm.s.vmx.LastError.u32InstrError);
1369 }
1370 pVCpu->CTX_SUFF(pVM)->hm.s.rcInit = rc;
1371}
1372
1373
1374#ifdef VBOX_STRICT
1375/**
1376 * Reads the VM-entry interruption-information field from the VMCS into the VMX
1377 * transient structure.
1378 *
1379 * @param pVmxTransient The VMX-transient structure.
1380 */
1381DECLINLINE(void) hmR0VmxReadEntryIntInfoVmcs(PVMXTRANSIENT pVmxTransient)
1382{
1383 int rc = VMXReadVmcs32(VMX_VMCS32_CTRL_ENTRY_INTERRUPTION_INFO, &pVmxTransient->uEntryIntInfo);
1384 AssertRC(rc);
1385}
1386
1387
1388/**
1389 * Reads the VM-entry exception error code field from the VMCS into
1390 * the VMX transient structure.
1391 *
1392 * @param pVmxTransient The VMX-transient structure.
1393 */
1394DECLINLINE(void) hmR0VmxReadEntryXcptErrorCodeVmcs(PVMXTRANSIENT pVmxTransient)
1395{
1396 int rc = VMXReadVmcs32(VMX_VMCS32_CTRL_ENTRY_EXCEPTION_ERRCODE, &pVmxTransient->uEntryXcptErrorCode);
1397 AssertRC(rc);
1398}
1399
1400
1401/**
1402 * Reads the VM-entry exception error code field from the VMCS into
1403 * the VMX transient structure.
1404 *
1405 * @param pVmxTransient The VMX-transient structure.
1406 */
1407DECLINLINE(void) hmR0VmxReadEntryInstrLenVmcs(PVMXTRANSIENT pVmxTransient)
1408{
1409 int rc = VMXReadVmcs32(VMX_VMCS32_CTRL_ENTRY_INSTR_LENGTH, &pVmxTransient->cbEntryInstr);
1410 AssertRC(rc);
1411}
1412#endif /* VBOX_STRICT */
1413
1414
1415/**
1416 * Reads the VM-exit interruption-information field from the VMCS into the VMX
1417 * transient structure.
1418 *
1419 * @param pVmxTransient The VMX-transient structure.
1420 */
1421DECLINLINE(void) hmR0VmxReadExitIntInfoVmcs(PVMXTRANSIENT pVmxTransient)
1422{
1423 if (!(pVmxTransient->fVmcsFieldsRead & HMVMX_READ_EXIT_INTERRUPTION_INFO))
1424 {
1425 int rc = VMXReadVmcs32(VMX_VMCS32_RO_EXIT_INTERRUPTION_INFO, &pVmxTransient->uExitIntInfo);
1426 AssertRC(rc);
1427 pVmxTransient->fVmcsFieldsRead |= HMVMX_READ_EXIT_INTERRUPTION_INFO;
1428 }
1429}
1430
1431
1432/**
1433 * Reads the VM-exit interruption error code from the VMCS into the VMX
1434 * transient structure.
1435 *
1436 * @param pVmxTransient The VMX-transient structure.
1437 */
1438DECLINLINE(void) hmR0VmxReadExitIntErrorCodeVmcs(PVMXTRANSIENT pVmxTransient)
1439{
1440 if (!(pVmxTransient->fVmcsFieldsRead & HMVMX_READ_EXIT_INTERRUPTION_ERROR_CODE))
1441 {
1442 int rc = VMXReadVmcs32(VMX_VMCS32_RO_EXIT_INTERRUPTION_ERROR_CODE, &pVmxTransient->uExitIntErrorCode);
1443 AssertRC(rc);
1444 pVmxTransient->fVmcsFieldsRead |= HMVMX_READ_EXIT_INTERRUPTION_ERROR_CODE;
1445 }
1446}
1447
1448
1449/**
1450 * Reads the VM-exit instruction length field from the VMCS into the VMX
1451 * transient structure.
1452 *
1453 * @param pVmxTransient The VMX-transient structure.
1454 */
1455DECLINLINE(void) hmR0VmxReadExitInstrLenVmcs(PVMXTRANSIENT pVmxTransient)
1456{
1457 if (!(pVmxTransient->fVmcsFieldsRead & HMVMX_READ_EXIT_INSTR_LEN))
1458 {
1459 int rc = VMXReadVmcs32(VMX_VMCS32_RO_EXIT_INSTR_LENGTH, &pVmxTransient->cbExitInstr);
1460 AssertRC(rc);
1461 pVmxTransient->fVmcsFieldsRead |= HMVMX_READ_EXIT_INSTR_LEN;
1462 }
1463}
1464
1465
1466/**
1467 * Reads the VM-exit instruction-information field from the VMCS into
1468 * the VMX transient structure.
1469 *
1470 * @param pVmxTransient The VMX-transient structure.
1471 */
1472DECLINLINE(void) hmR0VmxReadExitInstrInfoVmcs(PVMXTRANSIENT pVmxTransient)
1473{
1474 if (!(pVmxTransient->fVmcsFieldsRead & HMVMX_READ_EXIT_INSTR_INFO))
1475 {
1476 int rc = VMXReadVmcs32(VMX_VMCS32_RO_EXIT_INSTR_INFO, &pVmxTransient->ExitInstrInfo.u);
1477 AssertRC(rc);
1478 pVmxTransient->fVmcsFieldsRead |= HMVMX_READ_EXIT_INSTR_INFO;
1479 }
1480}
1481
1482
1483/**
1484 * Reads the Exit Qualification from the VMCS into the VMX transient structure.
1485 *
1486 * @param pVmxTransient The VMX-transient structure.
1487 */
1488DECLINLINE(void) hmR0VmxReadExitQualVmcs(PVMXTRANSIENT pVmxTransient)
1489{
1490 if (!(pVmxTransient->fVmcsFieldsRead & HMVMX_READ_EXIT_QUALIFICATION))
1491 {
1492 int rc = VMXReadVmcsNw(VMX_VMCS_RO_EXIT_QUALIFICATION, &pVmxTransient->uExitQual);
1493 AssertRC(rc);
1494 pVmxTransient->fVmcsFieldsRead |= HMVMX_READ_EXIT_QUALIFICATION;
1495 }
1496}
1497
1498
1499/**
1500 * Reads the Guest-linear address from the VMCS into the VMX transient structure.
1501 *
1502 * @param pVmxTransient The VMX-transient structure.
1503 */
1504DECLINLINE(void) hmR0VmxReadGuestLinearAddrVmcs(PVMXTRANSIENT pVmxTransient)
1505{
1506 if (!(pVmxTransient->fVmcsFieldsRead & HMVMX_READ_GUEST_LINEAR_ADDR))
1507 {
1508 int rc = VMXReadVmcsNw(VMX_VMCS_RO_GUEST_LINEAR_ADDR, &pVmxTransient->uGuestLinearAddr);
1509 AssertRC(rc);
1510 pVmxTransient->fVmcsFieldsRead |= HMVMX_READ_GUEST_LINEAR_ADDR;
1511 }
1512}
1513
1514
1515/**
1516 * Reads the Guest-physical address from the VMCS into the VMX transient structure.
1517 *
1518 * @param pVmxTransient The VMX-transient structure.
1519 */
1520DECLINLINE(void) hmR0VmxReadGuestPhysicalAddrVmcs(PVMXTRANSIENT pVmxTransient)
1521{
1522 if (!(pVmxTransient->fVmcsFieldsRead & HMVMX_READ_GUEST_PHYSICAL_ADDR))
1523 {
1524 int rc = VMXReadVmcs64(VMX_VMCS64_RO_GUEST_PHYS_ADDR_FULL, &pVmxTransient->uGuestPhysicalAddr);
1525 AssertRC(rc);
1526 pVmxTransient->fVmcsFieldsRead |= HMVMX_READ_GUEST_PHYSICAL_ADDR;
1527 }
1528}
1529
1530#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
1531/**
1532 * Reads the Guest pending-debug exceptions from the VMCS into the VMX transient
1533 * structure.
1534 *
1535 * @param pVmxTransient The VMX-transient structure.
1536 */
1537DECLINLINE(void) hmR0VmxReadGuestPendingDbgXctps(PVMXTRANSIENT pVmxTransient)
1538{
1539 if (!(pVmxTransient->fVmcsFieldsRead & HMVMX_READ_GUEST_PENDING_DBG_XCPTS))
1540 {
1541 int rc = VMXReadVmcsNw(VMX_VMCS_GUEST_PENDING_DEBUG_XCPTS, &pVmxTransient->uGuestPendingDbgXcpts);
1542 AssertRC(rc);
1543 pVmxTransient->fVmcsFieldsRead |= HMVMX_READ_GUEST_PENDING_DBG_XCPTS;
1544 }
1545}
1546#endif
1547
1548/**
1549 * Reads the IDT-vectoring information field from the VMCS into the VMX
1550 * transient structure.
1551 *
1552 * @param pVmxTransient The VMX-transient structure.
1553 *
1554 * @remarks No-long-jump zone!!!
1555 */
1556DECLINLINE(void) hmR0VmxReadIdtVectoringInfoVmcs(PVMXTRANSIENT pVmxTransient)
1557{
1558 if (!(pVmxTransient->fVmcsFieldsRead & HMVMX_READ_IDT_VECTORING_INFO))
1559 {
1560 int rc = VMXReadVmcs32(VMX_VMCS32_RO_IDT_VECTORING_INFO, &pVmxTransient->uIdtVectoringInfo);
1561 AssertRC(rc);
1562 pVmxTransient->fVmcsFieldsRead |= HMVMX_READ_IDT_VECTORING_INFO;
1563 }
1564}
1565
1566
1567/**
1568 * Reads the IDT-vectoring error code from the VMCS into the VMX
1569 * transient structure.
1570 *
1571 * @param pVmxTransient The VMX-transient structure.
1572 */
1573DECLINLINE(void) hmR0VmxReadIdtVectoringErrorCodeVmcs(PVMXTRANSIENT pVmxTransient)
1574{
1575 if (!(pVmxTransient->fVmcsFieldsRead & HMVMX_READ_IDT_VECTORING_ERROR_CODE))
1576 {
1577 int rc = VMXReadVmcs32(VMX_VMCS32_RO_IDT_VECTORING_ERROR_CODE, &pVmxTransient->uIdtVectoringErrorCode);
1578 AssertRC(rc);
1579 pVmxTransient->fVmcsFieldsRead |= HMVMX_READ_IDT_VECTORING_ERROR_CODE;
1580 }
1581}
1582
1583#ifdef HMVMX_ALWAYS_SAVE_RO_GUEST_STATE
1584/**
1585 * Reads all relevant read-only VMCS fields into the VMX transient structure.
1586 *
1587 * @param pVmxTransient The VMX-transient structure.
1588 */
1589static void hmR0VmxReadAllRoFieldsVmcs(PVMXTRANSIENT pVmxTransient)
1590{
1591 int rc = VMXReadVmcsNw(VMX_VMCS_RO_EXIT_QUALIFICATION, &pVmxTransient->uExitQual);
1592 rc |= VMXReadVmcs32(VMX_VMCS32_RO_EXIT_INSTR_LENGTH, &pVmxTransient->cbExitInstr);
1593 rc |= VMXReadVmcs32(VMX_VMCS32_RO_EXIT_INSTR_INFO, &pVmxTransient->ExitInstrInfo.u);
1594 rc |= VMXReadVmcs32(VMX_VMCS32_RO_IDT_VECTORING_INFO, &pVmxTransient->uIdtVectoringInfo);
1595 rc |= VMXReadVmcs32(VMX_VMCS32_RO_IDT_VECTORING_ERROR_CODE, &pVmxTransient->uIdtVectoringErrorCode);
1596 rc |= VMXReadVmcs32(VMX_VMCS32_RO_EXIT_INTERRUPTION_INFO, &pVmxTransient->uExitIntInfo);
1597 rc |= VMXReadVmcs32(VMX_VMCS32_RO_EXIT_INTERRUPTION_ERROR_CODE, &pVmxTransient->uExitIntErrorCode);
1598 rc |= VMXReadVmcsNw(VMX_VMCS_RO_GUEST_LINEAR_ADDR, &pVmxTransient->uGuestLinearAddr);
1599 rc |= VMXReadVmcs64(VMX_VMCS64_RO_GUEST_PHYS_ADDR_FULL, &pVmxTransient->uGuestPhysicalAddr);
1600 AssertRC(rc);
1601 pVmxTransient->fVmcsFieldsRead |= HMVMX_READ_EXIT_QUALIFICATION
1602 | HMVMX_READ_EXIT_INSTR_LEN
1603 | HMVMX_READ_EXIT_INSTR_INFO
1604 | HMVMX_READ_IDT_VECTORING_INFO
1605 | HMVMX_READ_IDT_VECTORING_ERROR_CODE
1606 | HMVMX_READ_EXIT_INTERRUPTION_INFO
1607 | HMVMX_READ_EXIT_INTERRUPTION_ERROR_CODE
1608 | HMVMX_READ_GUEST_LINEAR_ADDR
1609 | HMVMX_READ_GUEST_PHYSICAL_ADDR;
1610}
1611#endif
1612
1613/**
1614 * Enters VMX root mode operation on the current CPU.
1615 *
1616 * @returns VBox status code.
1617 * @param pHostCpu The HM physical-CPU structure.
1618 * @param pVM The cross context VM structure. Can be
1619 * NULL, after a resume.
1620 * @param HCPhysCpuPage Physical address of the VMXON region.
1621 * @param pvCpuPage Pointer to the VMXON region.
1622 */
1623static int hmR0VmxEnterRootMode(PHMPHYSCPU pHostCpu, PVMCC pVM, RTHCPHYS HCPhysCpuPage, void *pvCpuPage)
1624{
1625 Assert(pHostCpu);
1626 Assert(HCPhysCpuPage && HCPhysCpuPage != NIL_RTHCPHYS);
1627 Assert(RT_ALIGN_T(HCPhysCpuPage, _4K, RTHCPHYS) == HCPhysCpuPage);
1628 Assert(pvCpuPage);
1629 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
1630
1631 if (pVM)
1632 {
1633 /* Write the VMCS revision identifier to the VMXON region. */
1634 *(uint32_t *)pvCpuPage = RT_BF_GET(pVM->hm.s.vmx.Msrs.u64Basic, VMX_BF_BASIC_VMCS_ID);
1635 }
1636
1637 /* Paranoid: Disable interrupts as, in theory, interrupt handlers might mess with CR4. */
1638 RTCCUINTREG const fEFlags = ASMIntDisableFlags();
1639
1640 /* Enable the VMX bit in CR4 if necessary. */
1641 RTCCUINTREG const uOldCr4 = SUPR0ChangeCR4(X86_CR4_VMXE, RTCCUINTREG_MAX);
1642
1643 /* Record whether VMXE was already prior to us enabling it above. */
1644 pHostCpu->fVmxeAlreadyEnabled = RT_BOOL(uOldCr4 & X86_CR4_VMXE);
1645
1646 /* Enter VMX root mode. */
1647 int rc = VMXEnable(HCPhysCpuPage);
1648 if (RT_FAILURE(rc))
1649 {
1650 /* Restore CR4.VMXE if it was not set prior to our attempt to set it above. */
1651 if (!pHostCpu->fVmxeAlreadyEnabled)
1652 SUPR0ChangeCR4(0 /* fOrMask */, ~(uint64_t)X86_CR4_VMXE);
1653
1654 if (pVM)
1655 pVM->hm.s.vmx.HCPhysVmxEnableError = HCPhysCpuPage;
1656 }
1657
1658 /* Restore interrupts. */
1659 ASMSetFlags(fEFlags);
1660 return rc;
1661}
1662
1663
1664/**
1665 * Exits VMX root mode operation on the current CPU.
1666 *
1667 * @returns VBox status code.
1668 * @param pHostCpu The HM physical-CPU structure.
1669 */
1670static int hmR0VmxLeaveRootMode(PHMPHYSCPU pHostCpu)
1671{
1672 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
1673
1674 /* Paranoid: Disable interrupts as, in theory, interrupts handlers might mess with CR4. */
1675 RTCCUINTREG const fEFlags = ASMIntDisableFlags();
1676
1677 /* If we're for some reason not in VMX root mode, then don't leave it. */
1678 RTCCUINTREG const uHostCr4 = ASMGetCR4();
1679
1680 int rc;
1681 if (uHostCr4 & X86_CR4_VMXE)
1682 {
1683 /* Exit VMX root mode and clear the VMX bit in CR4. */
1684 VMXDisable();
1685
1686 /* Clear CR4.VMXE only if it was clear prior to use setting it. */
1687 if (!pHostCpu->fVmxeAlreadyEnabled)
1688 SUPR0ChangeCR4(0 /* fOrMask */, ~(uint64_t)X86_CR4_VMXE);
1689
1690 rc = VINF_SUCCESS;
1691 }
1692 else
1693 rc = VERR_VMX_NOT_IN_VMX_ROOT_MODE;
1694
1695 /* Restore interrupts. */
1696 ASMSetFlags(fEFlags);
1697 return rc;
1698}
1699
1700
1701/**
1702 * Allocates pages specified as specified by an array of VMX page allocation info
1703 * objects.
1704 *
1705 * The pages contents are zero'd after allocation.
1706 *
1707 * @returns VBox status code.
1708 * @param hMemObj The ring-0 memory object associated with the allocation.
1709 * @param paAllocInfo The pointer to the first element of the VMX
1710 * page-allocation info object array.
1711 * @param cEntries The number of elements in the @a paAllocInfo array.
1712 */
1713static int hmR0VmxPagesAllocZ(RTR0MEMOBJ hMemObj, PVMXPAGEALLOCINFO paAllocInfo, uint32_t cEntries)
1714{
1715 /* Figure out how many pages to allocate. */
1716 uint32_t cPages = 0;
1717 for (uint32_t iPage = 0; iPage < cEntries; iPage++)
1718 cPages += !!paAllocInfo[iPage].fValid;
1719
1720 /* Allocate the pages. */
1721 if (cPages)
1722 {
1723 size_t const cbPages = cPages << X86_PAGE_4K_SHIFT;
1724 int rc = RTR0MemObjAllocPage(&hMemObj, cbPages, false /* fExecutable */);
1725 if (RT_FAILURE(rc))
1726 return rc;
1727
1728 /* Zero the contents and assign each page to the corresponding VMX page-allocation entry. */
1729 void *pvFirstPage = RTR0MemObjAddress(hMemObj);
1730 ASMMemZero32(pvFirstPage, cbPages);
1731
1732 uint32_t iPage = 0;
1733 for (uint32_t i = 0; i < cEntries; i++)
1734 if (paAllocInfo[i].fValid)
1735 {
1736 RTHCPHYS const HCPhysPage = RTR0MemObjGetPagePhysAddr(hMemObj, iPage);
1737 void *pvPage = (void *)((uintptr_t)pvFirstPage + (iPage << X86_PAGE_4K_SHIFT));
1738 Assert(HCPhysPage && HCPhysPage != NIL_RTHCPHYS);
1739 AssertPtr(pvPage);
1740
1741 Assert(paAllocInfo[iPage].pHCPhys);
1742 Assert(paAllocInfo[iPage].ppVirt);
1743 *paAllocInfo[iPage].pHCPhys = HCPhysPage;
1744 *paAllocInfo[iPage].ppVirt = pvPage;
1745
1746 /* Move to next page. */
1747 ++iPage;
1748 }
1749
1750 /* Make sure all valid (requested) pages have been assigned. */
1751 Assert(iPage == cPages);
1752 }
1753 return VINF_SUCCESS;
1754}
1755
1756
1757/**
1758 * Frees pages allocated using hmR0VmxPagesAllocZ.
1759 *
1760 * @param hMemObj The ring-0 memory object associated with the allocation.
1761 */
1762DECL_FORCE_INLINE(void) hmR0VmxPagesFree(RTR0MEMOBJ hMemObj)
1763{
1764 /* We can cleanup wholesale since it's all one allocation. */
1765 RTR0MemObjFree(hMemObj, true /* fFreeMappings */);
1766}
1767
1768
1769/**
1770 * Initializes a VMCS info. object.
1771 *
1772 * @param pVmcsInfo The VMCS info. object.
1773 */
1774static void hmR0VmxVmcsInfoInit(PVMXVMCSINFO pVmcsInfo)
1775{
1776 memset(pVmcsInfo, 0, sizeof(*pVmcsInfo));
1777
1778 Assert(pVmcsInfo->hMemObj == NIL_RTR0MEMOBJ);
1779 pVmcsInfo->HCPhysVmcs = NIL_RTHCPHYS;
1780 pVmcsInfo->HCPhysShadowVmcs = NIL_RTHCPHYS;
1781 pVmcsInfo->HCPhysMsrBitmap = NIL_RTHCPHYS;
1782 pVmcsInfo->HCPhysGuestMsrLoad = NIL_RTHCPHYS;
1783 pVmcsInfo->HCPhysGuestMsrStore = NIL_RTHCPHYS;
1784 pVmcsInfo->HCPhysHostMsrLoad = NIL_RTHCPHYS;
1785 pVmcsInfo->HCPhysVirtApic = NIL_RTHCPHYS;
1786 pVmcsInfo->HCPhysEPTP = NIL_RTHCPHYS;
1787 pVmcsInfo->u64VmcsLinkPtr = NIL_RTHCPHYS;
1788 pVmcsInfo->idHostCpuState = NIL_RTCPUID;
1789 pVmcsInfo->idHostCpuExec = NIL_RTCPUID;
1790}
1791
1792
1793/**
1794 * Frees the VT-x structures for a VMCS info. object.
1795 *
1796 * @param pVmcsInfo The VMCS info. object.
1797 */
1798static void hmR0VmxVmcsInfoFree(PVMXVMCSINFO pVmcsInfo)
1799{
1800 if (pVmcsInfo->hMemObj != NIL_RTR0MEMOBJ)
1801 {
1802 hmR0VmxPagesFree(pVmcsInfo->hMemObj);
1803 hmR0VmxVmcsInfoInit(pVmcsInfo);
1804 }
1805}
1806
1807
1808/**
1809 * Allocates the VT-x structures for a VMCS info. object.
1810 *
1811 * @returns VBox status code.
1812 * @param pVCpu The cross context virtual CPU structure.
1813 * @param pVmcsInfo The VMCS info. object.
1814 * @param fIsNstGstVmcs Whether this is a nested-guest VMCS.
1815 *
1816 * @remarks The caller is expected to take care of any and all allocation failures.
1817 * This function will not perform any cleanup for failures half-way
1818 * through.
1819 */
1820static int hmR0VmxAllocVmcsInfo(PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo, bool fIsNstGstVmcs)
1821{
1822 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
1823
1824 bool const fMsrBitmaps = RT_BOOL(pVM->hm.s.vmx.Msrs.ProcCtls.n.allowed1 & VMX_PROC_CTLS_USE_MSR_BITMAPS);
1825 bool const fShadowVmcs = !fIsNstGstVmcs ? pVM->hm.s.vmx.fUseVmcsShadowing : pVM->cpum.ro.GuestFeatures.fVmxVmcsShadowing;
1826 Assert(!pVM->cpum.ro.GuestFeatures.fVmxVmcsShadowing); /* VMCS shadowing is not yet exposed to the guest. */
1827 VMXPAGEALLOCINFO aAllocInfo[] = {
1828 { true, 0 /* Unused */, &pVmcsInfo->HCPhysVmcs, &pVmcsInfo->pvVmcs },
1829 { true, 0 /* Unused */, &pVmcsInfo->HCPhysGuestMsrLoad, &pVmcsInfo->pvGuestMsrLoad },
1830 { true, 0 /* Unused */, &pVmcsInfo->HCPhysHostMsrLoad, &pVmcsInfo->pvHostMsrLoad },
1831 { fMsrBitmaps, 0 /* Unused */, &pVmcsInfo->HCPhysMsrBitmap, &pVmcsInfo->pvMsrBitmap },
1832 { fShadowVmcs, 0 /* Unused */, &pVmcsInfo->HCPhysShadowVmcs, &pVmcsInfo->pvShadowVmcs },
1833 };
1834
1835 int rc = hmR0VmxPagesAllocZ(pVmcsInfo->hMemObj, &aAllocInfo[0], RT_ELEMENTS(aAllocInfo));
1836 if (RT_FAILURE(rc))
1837 return rc;
1838
1839 /*
1840 * We use the same page for VM-entry MSR-load and VM-exit MSR store areas.
1841 * Because they contain a symmetric list of guest MSRs to load on VM-entry and store on VM-exit.
1842 */
1843 AssertCompile(RT_ELEMENTS(aAllocInfo) > 0);
1844 Assert(pVmcsInfo->HCPhysGuestMsrLoad != NIL_RTHCPHYS);
1845 pVmcsInfo->pvGuestMsrStore = pVmcsInfo->pvGuestMsrLoad;
1846 pVmcsInfo->HCPhysGuestMsrStore = pVmcsInfo->HCPhysGuestMsrLoad;
1847
1848 /*
1849 * Get the virtual-APIC page rather than allocating them again.
1850 */
1851 if (pVM->hm.s.vmx.Msrs.ProcCtls.n.allowed1 & VMX_PROC_CTLS_USE_TPR_SHADOW)
1852 {
1853 if (!fIsNstGstVmcs)
1854 {
1855 if (PDMHasApic(pVM))
1856 {
1857 rc = APICGetApicPageForCpu(pVCpu, &pVmcsInfo->HCPhysVirtApic, (PRTR0PTR)&pVmcsInfo->pbVirtApic, NULL /*pR3Ptr*/);
1858 if (RT_FAILURE(rc))
1859 return rc;
1860 Assert(pVmcsInfo->pbVirtApic);
1861 Assert(pVmcsInfo->HCPhysVirtApic && pVmcsInfo->HCPhysVirtApic != NIL_RTHCPHYS);
1862 }
1863 }
1864 else
1865 {
1866 pVmcsInfo->pbVirtApic = (uint8_t *)CPUMGetGuestVmxVirtApicPage(&pVCpu->cpum.GstCtx, &pVmcsInfo->HCPhysVirtApic);
1867 Assert(pVmcsInfo->pbVirtApic);
1868 Assert(pVmcsInfo->HCPhysVirtApic && pVmcsInfo->HCPhysVirtApic != NIL_RTHCPHYS);
1869 }
1870 }
1871
1872 return VINF_SUCCESS;
1873}
1874
1875
1876/**
1877 * Free all VT-x structures for the VM.
1878 *
1879 * @returns IPRT status code.
1880 * @param pVM The cross context VM structure.
1881 */
1882static void hmR0VmxStructsFree(PVMCC pVM)
1883{
1884 hmR0VmxPagesFree(pVM->hm.s.vmx.hMemObj);
1885#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
1886 if (pVM->hm.s.vmx.fUseVmcsShadowing)
1887 {
1888 RTMemFree(pVM->hm.s.vmx.paShadowVmcsFields);
1889 RTMemFree(pVM->hm.s.vmx.paShadowVmcsRoFields);
1890 }
1891#endif
1892
1893 for (VMCPUID idCpu = 0; idCpu < pVM->cCpus; idCpu++)
1894 {
1895 PVMCPUCC pVCpu = VMCC_GET_CPU(pVM, idCpu);
1896 hmR0VmxVmcsInfoFree(&pVCpu->hm.s.vmx.VmcsInfo);
1897#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
1898 if (pVM->cpum.ro.GuestFeatures.fVmx)
1899 hmR0VmxVmcsInfoFree(&pVCpu->hm.s.vmx.VmcsInfoNstGst);
1900#endif
1901 }
1902}
1903
1904
1905/**
1906 * Allocate all VT-x structures for the VM.
1907 *
1908 * @returns IPRT status code.
1909 * @param pVM The cross context VM structure.
1910 *
1911 * @remarks This functions will cleanup on memory allocation failures.
1912 */
1913static int hmR0VmxStructsAlloc(PVMCC pVM)
1914{
1915 /*
1916 * Sanity check the VMCS size reported by the CPU as we assume 4KB allocations.
1917 * The VMCS size cannot be more than 4096 bytes.
1918 *
1919 * See Intel spec. Appendix A.1 "Basic VMX Information".
1920 */
1921 uint32_t const cbVmcs = RT_BF_GET(pVM->hm.s.vmx.Msrs.u64Basic, VMX_BF_BASIC_VMCS_SIZE);
1922 if (cbVmcs <= X86_PAGE_4K_SIZE)
1923 { /* likely */ }
1924 else
1925 {
1926 VMCC_GET_CPU_0(pVM)->hm.s.u32HMError = VMX_UFC_INVALID_VMCS_SIZE;
1927 return VERR_HM_UNSUPPORTED_CPU_FEATURE_COMBO;
1928 }
1929
1930 /*
1931 * Allocate per-VM VT-x structures.
1932 */
1933 bool const fVirtApicAccess = RT_BOOL(pVM->hm.s.vmx.Msrs.ProcCtls2.n.allowed1 & VMX_PROC_CTLS2_VIRT_APIC_ACCESS);
1934 bool const fUseVmcsShadowing = pVM->hm.s.vmx.fUseVmcsShadowing;
1935 VMXPAGEALLOCINFO aAllocInfo[] = {
1936 { fVirtApicAccess, 0 /* Unused */, &pVM->hm.s.vmx.HCPhysApicAccess, (PRTR0PTR)&pVM->hm.s.vmx.pbApicAccess },
1937 { fUseVmcsShadowing, 0 /* Unused */, &pVM->hm.s.vmx.HCPhysVmreadBitmap, &pVM->hm.s.vmx.pvVmreadBitmap },
1938 { fUseVmcsShadowing, 0 /* Unused */, &pVM->hm.s.vmx.HCPhysVmwriteBitmap, &pVM->hm.s.vmx.pvVmwriteBitmap },
1939#ifdef VBOX_WITH_CRASHDUMP_MAGIC
1940 { true, 0 /* Unused */, &pVM->hm.s.vmx.HCPhysScratch, &(PRTR0PTR)pVM->hm.s.vmx.pbScratch },
1941#endif
1942 };
1943
1944 int rc = hmR0VmxPagesAllocZ(pVM->hm.s.vmx.hMemObj, &aAllocInfo[0], RT_ELEMENTS(aAllocInfo));
1945 if (RT_FAILURE(rc))
1946 goto cleanup;
1947
1948#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
1949 /* Allocate the shadow VMCS-fields array. */
1950 if (fUseVmcsShadowing)
1951 {
1952 Assert(!pVM->hm.s.vmx.cShadowVmcsFields);
1953 Assert(!pVM->hm.s.vmx.cShadowVmcsRoFields);
1954 pVM->hm.s.vmx.paShadowVmcsFields = (uint32_t *)RTMemAllocZ(sizeof(g_aVmcsFields));
1955 pVM->hm.s.vmx.paShadowVmcsRoFields = (uint32_t *)RTMemAllocZ(sizeof(g_aVmcsFields));
1956 if (RT_LIKELY( pVM->hm.s.vmx.paShadowVmcsFields
1957 && pVM->hm.s.vmx.paShadowVmcsRoFields))
1958 { /* likely */ }
1959 else
1960 {
1961 rc = VERR_NO_MEMORY;
1962 goto cleanup;
1963 }
1964 }
1965#endif
1966
1967 /*
1968 * Allocate per-VCPU VT-x structures.
1969 */
1970 for (VMCPUID idCpu = 0; idCpu < pVM->cCpus; idCpu++)
1971 {
1972 /* Allocate the guest VMCS structures. */
1973 PVMCPUCC pVCpu = VMCC_GET_CPU(pVM, idCpu);
1974 rc = hmR0VmxAllocVmcsInfo(pVCpu, &pVCpu->hm.s.vmx.VmcsInfo, false /* fIsNstGstVmcs */);
1975 if (RT_FAILURE(rc))
1976 goto cleanup;
1977
1978#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
1979 /* Allocate the nested-guest VMCS structures, when the VMX feature is exposed to the guest. */
1980 if (pVM->cpum.ro.GuestFeatures.fVmx)
1981 {
1982 rc = hmR0VmxAllocVmcsInfo(pVCpu, &pVCpu->hm.s.vmx.VmcsInfoNstGst, true /* fIsNstGstVmcs */);
1983 if (RT_FAILURE(rc))
1984 goto cleanup;
1985 }
1986#endif
1987 }
1988
1989 return VINF_SUCCESS;
1990
1991cleanup:
1992 hmR0VmxStructsFree(pVM);
1993 Assert(rc != VINF_SUCCESS);
1994 return rc;
1995}
1996
1997
1998/**
1999 * Pre-initializes non-zero fields in VMX structures that will be allocated.
2000 *
2001 * @param pVM The cross context VM structure.
2002 */
2003static void hmR0VmxStructsInit(PVMCC pVM)
2004{
2005 /* Paranoia. */
2006 Assert(pVM->hm.s.vmx.pbApicAccess == NULL);
2007#ifdef VBOX_WITH_CRASHDUMP_MAGIC
2008 Assert(pVM->hm.s.vmx.pbScratch == NULL);
2009#endif
2010
2011 /*
2012 * Initialize members up-front so we can cleanup en masse on allocation failures.
2013 */
2014#ifdef VBOX_WITH_CRASHDUMP_MAGIC
2015 pVM->hm.s.vmx.HCPhysScratch = NIL_RTHCPHYS;
2016#endif
2017 pVM->hm.s.vmx.HCPhysApicAccess = NIL_RTHCPHYS;
2018 pVM->hm.s.vmx.HCPhysVmreadBitmap = NIL_RTHCPHYS;
2019 pVM->hm.s.vmx.HCPhysVmwriteBitmap = NIL_RTHCPHYS;
2020 for (VMCPUID idCpu = 0; idCpu < pVM->cCpus; idCpu++)
2021 {
2022 PVMCPUCC pVCpu = VMCC_GET_CPU(pVM, idCpu);
2023 hmR0VmxVmcsInfoInit(&pVCpu->hm.s.vmx.VmcsInfo);
2024 hmR0VmxVmcsInfoInit(&pVCpu->hm.s.vmx.VmcsInfoNstGst);
2025 }
2026}
2027
2028#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
2029/**
2030 * Returns whether an MSR at the given MSR-bitmap offset is intercepted or not.
2031 *
2032 * @returns @c true if the MSR is intercepted, @c false otherwise.
2033 * @param pvMsrBitmap The MSR bitmap.
2034 * @param offMsr The MSR byte offset.
2035 * @param iBit The bit offset from the byte offset.
2036 */
2037DECLINLINE(bool) hmR0VmxIsMsrBitSet(const void *pvMsrBitmap, uint16_t offMsr, int32_t iBit)
2038{
2039 uint8_t const * const pbMsrBitmap = (uint8_t const * const)pvMsrBitmap;
2040 Assert(pbMsrBitmap);
2041 Assert(offMsr + (iBit >> 3) <= X86_PAGE_4K_SIZE);
2042 return ASMBitTest(pbMsrBitmap + offMsr, iBit);
2043}
2044#endif
2045
2046/**
2047 * Sets the permission bits for the specified MSR in the given MSR bitmap.
2048 *
2049 * If the passed VMCS is a nested-guest VMCS, this function ensures that the
2050 * read/write intercept is cleared from the MSR bitmap used for hardware-assisted
2051 * VMX execution of the nested-guest, only if nested-guest is also not intercepting
2052 * the read/write access of this MSR.
2053 *
2054 * @param pVCpu The cross context virtual CPU structure.
2055 * @param pVmcsInfo The VMCS info. object.
2056 * @param fIsNstGstVmcs Whether this is a nested-guest VMCS.
2057 * @param idMsr The MSR value.
2058 * @param fMsrpm The MSR permissions (see VMXMSRPM_XXX). This must
2059 * include both a read -and- a write permission!
2060 *
2061 * @sa CPUMGetVmxMsrPermission.
2062 * @remarks Can be called with interrupts disabled.
2063 */
2064static void hmR0VmxSetMsrPermission(PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo, bool fIsNstGstVmcs, uint32_t idMsr, uint32_t fMsrpm)
2065{
2066 uint8_t *pbMsrBitmap = (uint8_t *)pVmcsInfo->pvMsrBitmap;
2067 Assert(pbMsrBitmap);
2068 Assert(VMXMSRPM_IS_FLAG_VALID(fMsrpm));
2069
2070 /*
2071 * MSR-bitmap Layout:
2072 * Byte index MSR range Interpreted as
2073 * 0x000 - 0x3ff 0x00000000 - 0x00001fff Low MSR read bits.
2074 * 0x400 - 0x7ff 0xc0000000 - 0xc0001fff High MSR read bits.
2075 * 0x800 - 0xbff 0x00000000 - 0x00001fff Low MSR write bits.
2076 * 0xc00 - 0xfff 0xc0000000 - 0xc0001fff High MSR write bits.
2077 *
2078 * A bit corresponding to an MSR within the above range causes a VM-exit
2079 * if the bit is 1 on executions of RDMSR/WRMSR. If an MSR falls out of
2080 * the MSR range, it always cause a VM-exit.
2081 *
2082 * See Intel spec. 24.6.9 "MSR-Bitmap Address".
2083 */
2084 uint16_t const offBitmapRead = 0;
2085 uint16_t const offBitmapWrite = 0x800;
2086 uint16_t offMsr;
2087 int32_t iBit;
2088 if (idMsr <= UINT32_C(0x00001fff))
2089 {
2090 offMsr = 0;
2091 iBit = idMsr;
2092 }
2093 else if (idMsr - UINT32_C(0xc0000000) <= UINT32_C(0x00001fff))
2094 {
2095 offMsr = 0x400;
2096 iBit = idMsr - UINT32_C(0xc0000000);
2097 }
2098 else
2099 AssertMsgFailedReturnVoid(("Invalid MSR %#RX32\n", idMsr));
2100
2101 /*
2102 * Set the MSR read permission.
2103 */
2104 uint16_t const offMsrRead = offBitmapRead + offMsr;
2105 Assert(offMsrRead + (iBit >> 3) < offBitmapWrite);
2106 if (fMsrpm & VMXMSRPM_ALLOW_RD)
2107 {
2108#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
2109 bool const fClear = !fIsNstGstVmcs ? true
2110 : !hmR0VmxIsMsrBitSet(pVCpu->cpum.GstCtx.hwvirt.vmx.CTX_SUFF(pvMsrBitmap), offMsrRead, iBit);
2111#else
2112 RT_NOREF2(pVCpu, fIsNstGstVmcs);
2113 bool const fClear = true;
2114#endif
2115 if (fClear)
2116 ASMBitClear(pbMsrBitmap + offMsrRead, iBit);
2117 }
2118 else
2119 ASMBitSet(pbMsrBitmap + offMsrRead, iBit);
2120
2121 /*
2122 * Set the MSR write permission.
2123 */
2124 uint16_t const offMsrWrite = offBitmapWrite + offMsr;
2125 Assert(offMsrWrite + (iBit >> 3) < X86_PAGE_4K_SIZE);
2126 if (fMsrpm & VMXMSRPM_ALLOW_WR)
2127 {
2128#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
2129 bool const fClear = !fIsNstGstVmcs ? true
2130 : !hmR0VmxIsMsrBitSet(pVCpu->cpum.GstCtx.hwvirt.vmx.CTX_SUFF(pvMsrBitmap), offMsrWrite, iBit);
2131#else
2132 RT_NOREF2(pVCpu, fIsNstGstVmcs);
2133 bool const fClear = true;
2134#endif
2135 if (fClear)
2136 ASMBitClear(pbMsrBitmap + offMsrWrite, iBit);
2137 }
2138 else
2139 ASMBitSet(pbMsrBitmap + offMsrWrite, iBit);
2140}
2141
2142
2143/**
2144 * Updates the VMCS with the number of effective MSRs in the auto-load/store MSR
2145 * area.
2146 *
2147 * @returns VBox status code.
2148 * @param pVCpu The cross context virtual CPU structure.
2149 * @param pVmcsInfo The VMCS info. object.
2150 * @param cMsrs The number of MSRs.
2151 */
2152static int hmR0VmxSetAutoLoadStoreMsrCount(PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo, uint32_t cMsrs)
2153{
2154 /* Shouldn't ever happen but there -is- a number. We're well within the recommended 512. */
2155 uint32_t const cMaxSupportedMsrs = VMX_MISC_MAX_MSRS(pVCpu->CTX_SUFF(pVM)->hm.s.vmx.Msrs.u64Misc);
2156 if (RT_LIKELY(cMsrs < cMaxSupportedMsrs))
2157 {
2158 /* Commit the MSR counts to the VMCS and update the cache. */
2159 if (pVmcsInfo->cEntryMsrLoad != cMsrs)
2160 {
2161 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_ENTRY_MSR_LOAD_COUNT, cMsrs); AssertRC(rc);
2162 rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_EXIT_MSR_STORE_COUNT, cMsrs); AssertRC(rc);
2163 rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_EXIT_MSR_LOAD_COUNT, cMsrs); AssertRC(rc);
2164 pVmcsInfo->cEntryMsrLoad = cMsrs;
2165 pVmcsInfo->cExitMsrStore = cMsrs;
2166 pVmcsInfo->cExitMsrLoad = cMsrs;
2167 }
2168 return VINF_SUCCESS;
2169 }
2170
2171 LogRel(("Auto-load/store MSR count exceeded! cMsrs=%u MaxSupported=%u\n", cMsrs, cMaxSupportedMsrs));
2172 pVCpu->hm.s.u32HMError = VMX_UFC_INSUFFICIENT_GUEST_MSR_STORAGE;
2173 return VERR_HM_UNSUPPORTED_CPU_FEATURE_COMBO;
2174}
2175
2176
2177/**
2178 * Adds a new (or updates the value of an existing) guest/host MSR
2179 * pair to be swapped during the world-switch as part of the
2180 * auto-load/store MSR area in the VMCS.
2181 *
2182 * @returns VBox status code.
2183 * @param pVCpu The cross context virtual CPU structure.
2184 * @param pVmxTransient The VMX-transient structure.
2185 * @param idMsr The MSR.
2186 * @param uGuestMsrValue Value of the guest MSR.
2187 * @param fSetReadWrite Whether to set the guest read/write access of this
2188 * MSR (thus not causing a VM-exit).
2189 * @param fUpdateHostMsr Whether to update the value of the host MSR if
2190 * necessary.
2191 */
2192static int hmR0VmxAddAutoLoadStoreMsr(PVMCPUCC pVCpu, PCVMXTRANSIENT pVmxTransient, uint32_t idMsr, uint64_t uGuestMsrValue,
2193 bool fSetReadWrite, bool fUpdateHostMsr)
2194{
2195 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
2196 bool const fIsNstGstVmcs = pVmxTransient->fIsNestedGuest;
2197 PVMXAUTOMSR pGuestMsrLoad = (PVMXAUTOMSR)pVmcsInfo->pvGuestMsrLoad;
2198 uint32_t cMsrs = pVmcsInfo->cEntryMsrLoad;
2199 uint32_t i;
2200
2201 /* Paranoia. */
2202 Assert(pGuestMsrLoad);
2203
2204 LogFlowFunc(("pVCpu=%p idMsr=%#RX32 uGestMsrValue=%#RX64\n", pVCpu, idMsr, uGuestMsrValue));
2205
2206 /* Check if the MSR already exists in the VM-entry MSR-load area. */
2207 for (i = 0; i < cMsrs; i++)
2208 {
2209 if (pGuestMsrLoad[i].u32Msr == idMsr)
2210 break;
2211 }
2212
2213 bool fAdded = false;
2214 if (i == cMsrs)
2215 {
2216 /* The MSR does not exist, bump the MSR count to make room for the new MSR. */
2217 ++cMsrs;
2218 int rc = hmR0VmxSetAutoLoadStoreMsrCount(pVCpu, pVmcsInfo, cMsrs);
2219 AssertMsgRCReturn(rc, ("Insufficient space to add MSR to VM-entry MSR-load/store area %u\n", idMsr), rc);
2220
2221 /* Set the guest to read/write this MSR without causing VM-exits. */
2222 if ( fSetReadWrite
2223 && (pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_USE_MSR_BITMAPS))
2224 hmR0VmxSetMsrPermission(pVCpu, pVmcsInfo, fIsNstGstVmcs, idMsr, VMXMSRPM_ALLOW_RD_WR);
2225
2226 Log4Func(("Added MSR %#RX32, cMsrs=%u\n", idMsr, cMsrs));
2227 fAdded = true;
2228 }
2229
2230 /* Update the MSR value for the newly added or already existing MSR. */
2231 pGuestMsrLoad[i].u32Msr = idMsr;
2232 pGuestMsrLoad[i].u64Value = uGuestMsrValue;
2233
2234 /* Create the corresponding slot in the VM-exit MSR-store area if we use a different page. */
2235 if (hmR0VmxIsSeparateExitMsrStoreAreaVmcs(pVmcsInfo))
2236 {
2237 PVMXAUTOMSR pGuestMsrStore = (PVMXAUTOMSR)pVmcsInfo->pvGuestMsrStore;
2238 pGuestMsrStore[i].u32Msr = idMsr;
2239 pGuestMsrStore[i].u64Value = uGuestMsrValue;
2240 }
2241
2242 /* Update the corresponding slot in the host MSR area. */
2243 PVMXAUTOMSR pHostMsr = (PVMXAUTOMSR)pVmcsInfo->pvHostMsrLoad;
2244 Assert(pHostMsr != pVmcsInfo->pvGuestMsrLoad);
2245 Assert(pHostMsr != pVmcsInfo->pvGuestMsrStore);
2246 pHostMsr[i].u32Msr = idMsr;
2247
2248 /*
2249 * Only if the caller requests to update the host MSR value AND we've newly added the
2250 * MSR to the host MSR area do we actually update the value. Otherwise, it will be
2251 * updated by hmR0VmxUpdateAutoLoadHostMsrs().
2252 *
2253 * We do this for performance reasons since reading MSRs may be quite expensive.
2254 */
2255 if (fAdded)
2256 {
2257 if (fUpdateHostMsr)
2258 {
2259 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
2260 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
2261 pHostMsr[i].u64Value = ASMRdMsr(idMsr);
2262 }
2263 else
2264 {
2265 /* Someone else can do the work. */
2266 pVCpu->hm.s.vmx.fUpdatedHostAutoMsrs = false;
2267 }
2268 }
2269 return VINF_SUCCESS;
2270}
2271
2272
2273/**
2274 * Removes a guest/host MSR pair to be swapped during the world-switch from the
2275 * auto-load/store MSR area in the VMCS.
2276 *
2277 * @returns VBox status code.
2278 * @param pVCpu The cross context virtual CPU structure.
2279 * @param pVmxTransient The VMX-transient structure.
2280 * @param idMsr The MSR.
2281 */
2282static int hmR0VmxRemoveAutoLoadStoreMsr(PVMCPUCC pVCpu, PCVMXTRANSIENT pVmxTransient, uint32_t idMsr)
2283{
2284 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
2285 bool const fIsNstGstVmcs = pVmxTransient->fIsNestedGuest;
2286 PVMXAUTOMSR pGuestMsrLoad = (PVMXAUTOMSR)pVmcsInfo->pvGuestMsrLoad;
2287 uint32_t cMsrs = pVmcsInfo->cEntryMsrLoad;
2288
2289 LogFlowFunc(("pVCpu=%p idMsr=%#RX32\n", pVCpu, idMsr));
2290
2291 for (uint32_t i = 0; i < cMsrs; i++)
2292 {
2293 /* Find the MSR. */
2294 if (pGuestMsrLoad[i].u32Msr == idMsr)
2295 {
2296 /*
2297 * If it's the last MSR, we only need to reduce the MSR count.
2298 * If it's -not- the last MSR, copy the last MSR in place of it and reduce the MSR count.
2299 */
2300 if (i < cMsrs - 1)
2301 {
2302 /* Remove it from the VM-entry MSR-load area. */
2303 pGuestMsrLoad[i].u32Msr = pGuestMsrLoad[cMsrs - 1].u32Msr;
2304 pGuestMsrLoad[i].u64Value = pGuestMsrLoad[cMsrs - 1].u64Value;
2305
2306 /* Remove it from the VM-exit MSR-store area if it's in a different page. */
2307 if (hmR0VmxIsSeparateExitMsrStoreAreaVmcs(pVmcsInfo))
2308 {
2309 PVMXAUTOMSR pGuestMsrStore = (PVMXAUTOMSR)pVmcsInfo->pvGuestMsrStore;
2310 Assert(pGuestMsrStore[i].u32Msr == idMsr);
2311 pGuestMsrStore[i].u32Msr = pGuestMsrStore[cMsrs - 1].u32Msr;
2312 pGuestMsrStore[i].u64Value = pGuestMsrStore[cMsrs - 1].u64Value;
2313 }
2314
2315 /* Remove it from the VM-exit MSR-load area. */
2316 PVMXAUTOMSR pHostMsr = (PVMXAUTOMSR)pVmcsInfo->pvHostMsrLoad;
2317 Assert(pHostMsr[i].u32Msr == idMsr);
2318 pHostMsr[i].u32Msr = pHostMsr[cMsrs - 1].u32Msr;
2319 pHostMsr[i].u64Value = pHostMsr[cMsrs - 1].u64Value;
2320 }
2321
2322 /* Reduce the count to reflect the removed MSR and bail. */
2323 --cMsrs;
2324 break;
2325 }
2326 }
2327
2328 /* Update the VMCS if the count changed (meaning the MSR was found and removed). */
2329 if (cMsrs != pVmcsInfo->cEntryMsrLoad)
2330 {
2331 int rc = hmR0VmxSetAutoLoadStoreMsrCount(pVCpu, pVmcsInfo, cMsrs);
2332 AssertRCReturn(rc, rc);
2333
2334 /* We're no longer swapping MSRs during the world-switch, intercept guest read/writes to them. */
2335 if (pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_USE_MSR_BITMAPS)
2336 hmR0VmxSetMsrPermission(pVCpu, pVmcsInfo, fIsNstGstVmcs, idMsr, VMXMSRPM_EXIT_RD | VMXMSRPM_EXIT_WR);
2337
2338 Log4Func(("Removed MSR %#RX32, cMsrs=%u\n", idMsr, cMsrs));
2339 return VINF_SUCCESS;
2340 }
2341
2342 return VERR_NOT_FOUND;
2343}
2344
2345
2346/**
2347 * Checks if the specified guest MSR is part of the VM-entry MSR-load area.
2348 *
2349 * @returns @c true if found, @c false otherwise.
2350 * @param pVmcsInfo The VMCS info. object.
2351 * @param idMsr The MSR to find.
2352 */
2353static bool hmR0VmxIsAutoLoadGuestMsr(PCVMXVMCSINFO pVmcsInfo, uint32_t idMsr)
2354{
2355 PCVMXAUTOMSR pMsrs = (PCVMXAUTOMSR)pVmcsInfo->pvGuestMsrLoad;
2356 uint32_t const cMsrs = pVmcsInfo->cEntryMsrLoad;
2357 Assert(pMsrs);
2358 Assert(sizeof(*pMsrs) * cMsrs <= X86_PAGE_4K_SIZE);
2359 for (uint32_t i = 0; i < cMsrs; i++)
2360 {
2361 if (pMsrs[i].u32Msr == idMsr)
2362 return true;
2363 }
2364 return false;
2365}
2366
2367
2368/**
2369 * Updates the value of all host MSRs in the VM-exit MSR-load area.
2370 *
2371 * @param pVCpu The cross context virtual CPU structure.
2372 * @param pVmcsInfo The VMCS info. object.
2373 *
2374 * @remarks No-long-jump zone!!!
2375 */
2376static void hmR0VmxUpdateAutoLoadHostMsrs(PCVMCPUCC pVCpu, PCVMXVMCSINFO pVmcsInfo)
2377{
2378 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
2379
2380 PVMXAUTOMSR pHostMsrLoad = (PVMXAUTOMSR)pVmcsInfo->pvHostMsrLoad;
2381 uint32_t const cMsrs = pVmcsInfo->cExitMsrLoad;
2382 Assert(pHostMsrLoad);
2383 Assert(sizeof(*pHostMsrLoad) * cMsrs <= X86_PAGE_4K_SIZE);
2384 LogFlowFunc(("pVCpu=%p cMsrs=%u\n", pVCpu, cMsrs));
2385 for (uint32_t i = 0; i < cMsrs; i++)
2386 {
2387 /*
2388 * Performance hack for the host EFER MSR. We use the cached value rather than re-read it.
2389 * Strict builds will catch mismatches in hmR0VmxCheckAutoLoadStoreMsrs(). See @bugref{7368}.
2390 */
2391 if (pHostMsrLoad[i].u32Msr == MSR_K6_EFER)
2392 pHostMsrLoad[i].u64Value = pVCpu->CTX_SUFF(pVM)->hm.s.vmx.u64HostMsrEfer;
2393 else
2394 pHostMsrLoad[i].u64Value = ASMRdMsr(pHostMsrLoad[i].u32Msr);
2395 }
2396}
2397
2398
2399/**
2400 * Saves a set of host MSRs to allow read/write passthru access to the guest and
2401 * perform lazy restoration of the host MSRs while leaving VT-x.
2402 *
2403 * @param pVCpu The cross context virtual CPU structure.
2404 *
2405 * @remarks No-long-jump zone!!!
2406 */
2407static void hmR0VmxLazySaveHostMsrs(PVMCPUCC pVCpu)
2408{
2409 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
2410
2411 /*
2412 * Note: If you're adding MSRs here, make sure to update the MSR-bitmap accesses in hmR0VmxSetupVmcsProcCtls().
2413 */
2414 if (!(pVCpu->hm.s.vmx.fLazyMsrs & VMX_LAZY_MSRS_SAVED_HOST))
2415 {
2416 Assert(!(pVCpu->hm.s.vmx.fLazyMsrs & VMX_LAZY_MSRS_LOADED_GUEST)); /* Guest MSRs better not be loaded now. */
2417 if (pVCpu->CTX_SUFF(pVM)->hm.s.fAllow64BitGuests)
2418 {
2419 pVCpu->hm.s.vmx.u64HostMsrLStar = ASMRdMsr(MSR_K8_LSTAR);
2420 pVCpu->hm.s.vmx.u64HostMsrStar = ASMRdMsr(MSR_K6_STAR);
2421 pVCpu->hm.s.vmx.u64HostMsrSfMask = ASMRdMsr(MSR_K8_SF_MASK);
2422 pVCpu->hm.s.vmx.u64HostMsrKernelGsBase = ASMRdMsr(MSR_K8_KERNEL_GS_BASE);
2423 }
2424 pVCpu->hm.s.vmx.fLazyMsrs |= VMX_LAZY_MSRS_SAVED_HOST;
2425 }
2426}
2427
2428
2429/**
2430 * Checks whether the MSR belongs to the set of guest MSRs that we restore
2431 * lazily while leaving VT-x.
2432 *
2433 * @returns true if it does, false otherwise.
2434 * @param pVCpu The cross context virtual CPU structure.
2435 * @param idMsr The MSR to check.
2436 */
2437static bool hmR0VmxIsLazyGuestMsr(PCVMCPUCC pVCpu, uint32_t idMsr)
2438{
2439 if (pVCpu->CTX_SUFF(pVM)->hm.s.fAllow64BitGuests)
2440 {
2441 switch (idMsr)
2442 {
2443 case MSR_K8_LSTAR:
2444 case MSR_K6_STAR:
2445 case MSR_K8_SF_MASK:
2446 case MSR_K8_KERNEL_GS_BASE:
2447 return true;
2448 }
2449 }
2450 return false;
2451}
2452
2453
2454/**
2455 * Loads a set of guests MSRs to allow read/passthru to the guest.
2456 *
2457 * The name of this function is slightly confusing. This function does NOT
2458 * postpone loading, but loads the MSR right now. "hmR0VmxLazy" is simply a
2459 * common prefix for functions dealing with "lazy restoration" of the shared
2460 * MSRs.
2461 *
2462 * @param pVCpu The cross context virtual CPU structure.
2463 *
2464 * @remarks No-long-jump zone!!!
2465 */
2466static void hmR0VmxLazyLoadGuestMsrs(PVMCPUCC pVCpu)
2467{
2468 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
2469 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
2470
2471 Assert(pVCpu->hm.s.vmx.fLazyMsrs & VMX_LAZY_MSRS_SAVED_HOST);
2472 if (pVCpu->CTX_SUFF(pVM)->hm.s.fAllow64BitGuests)
2473 {
2474 /*
2475 * If the guest MSRs are not loaded -and- if all the guest MSRs are identical
2476 * to the MSRs on the CPU (which are the saved host MSRs, see assertion above) then
2477 * we can skip a few MSR writes.
2478 *
2479 * Otherwise, it implies either 1. they're not loaded, or 2. they're loaded but the
2480 * guest MSR values in the guest-CPU context might be different to what's currently
2481 * loaded in the CPU. In either case, we need to write the new guest MSR values to the
2482 * CPU, see @bugref{8728}.
2483 */
2484 PCCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
2485 if ( !(pVCpu->hm.s.vmx.fLazyMsrs & VMX_LAZY_MSRS_LOADED_GUEST)
2486 && pCtx->msrKERNELGSBASE == pVCpu->hm.s.vmx.u64HostMsrKernelGsBase
2487 && pCtx->msrLSTAR == pVCpu->hm.s.vmx.u64HostMsrLStar
2488 && pCtx->msrSTAR == pVCpu->hm.s.vmx.u64HostMsrStar
2489 && pCtx->msrSFMASK == pVCpu->hm.s.vmx.u64HostMsrSfMask)
2490 {
2491#ifdef VBOX_STRICT
2492 Assert(ASMRdMsr(MSR_K8_KERNEL_GS_BASE) == pCtx->msrKERNELGSBASE);
2493 Assert(ASMRdMsr(MSR_K8_LSTAR) == pCtx->msrLSTAR);
2494 Assert(ASMRdMsr(MSR_K6_STAR) == pCtx->msrSTAR);
2495 Assert(ASMRdMsr(MSR_K8_SF_MASK) == pCtx->msrSFMASK);
2496#endif
2497 }
2498 else
2499 {
2500 ASMWrMsr(MSR_K8_KERNEL_GS_BASE, pCtx->msrKERNELGSBASE);
2501 ASMWrMsr(MSR_K8_LSTAR, pCtx->msrLSTAR);
2502 ASMWrMsr(MSR_K6_STAR, pCtx->msrSTAR);
2503 ASMWrMsr(MSR_K8_SF_MASK, pCtx->msrSFMASK);
2504 }
2505 }
2506 pVCpu->hm.s.vmx.fLazyMsrs |= VMX_LAZY_MSRS_LOADED_GUEST;
2507}
2508
2509
2510/**
2511 * Performs lazy restoration of the set of host MSRs if they were previously
2512 * loaded with guest MSR values.
2513 *
2514 * @param pVCpu The cross context virtual CPU structure.
2515 *
2516 * @remarks No-long-jump zone!!!
2517 * @remarks The guest MSRs should have been saved back into the guest-CPU
2518 * context by hmR0VmxImportGuestState()!!!
2519 */
2520static void hmR0VmxLazyRestoreHostMsrs(PVMCPUCC pVCpu)
2521{
2522 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
2523 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
2524
2525 if (pVCpu->hm.s.vmx.fLazyMsrs & VMX_LAZY_MSRS_LOADED_GUEST)
2526 {
2527 Assert(pVCpu->hm.s.vmx.fLazyMsrs & VMX_LAZY_MSRS_SAVED_HOST);
2528 if (pVCpu->CTX_SUFF(pVM)->hm.s.fAllow64BitGuests)
2529 {
2530 ASMWrMsr(MSR_K8_LSTAR, pVCpu->hm.s.vmx.u64HostMsrLStar);
2531 ASMWrMsr(MSR_K6_STAR, pVCpu->hm.s.vmx.u64HostMsrStar);
2532 ASMWrMsr(MSR_K8_SF_MASK, pVCpu->hm.s.vmx.u64HostMsrSfMask);
2533 ASMWrMsr(MSR_K8_KERNEL_GS_BASE, pVCpu->hm.s.vmx.u64HostMsrKernelGsBase);
2534 }
2535 }
2536 pVCpu->hm.s.vmx.fLazyMsrs &= ~(VMX_LAZY_MSRS_LOADED_GUEST | VMX_LAZY_MSRS_SAVED_HOST);
2537}
2538
2539
2540/**
2541 * Verifies that our cached values of the VMCS fields are all consistent with
2542 * what's actually present in the VMCS.
2543 *
2544 * @returns VBox status code.
2545 * @retval VINF_SUCCESS if all our caches match their respective VMCS fields.
2546 * @retval VERR_VMX_VMCS_FIELD_CACHE_INVALID if a cache field doesn't match the
2547 * VMCS content. HMCPU error-field is
2548 * updated, see VMX_VCI_XXX.
2549 * @param pVCpu The cross context virtual CPU structure.
2550 * @param pVmcsInfo The VMCS info. object.
2551 * @param fIsNstGstVmcs Whether this is a nested-guest VMCS.
2552 */
2553static int hmR0VmxCheckCachedVmcsCtls(PVMCPUCC pVCpu, PCVMXVMCSINFO pVmcsInfo, bool fIsNstGstVmcs)
2554{
2555 const char * const pcszVmcs = fIsNstGstVmcs ? "Nested-guest VMCS" : "VMCS";
2556
2557 uint32_t u32Val;
2558 int rc = VMXReadVmcs32(VMX_VMCS32_CTRL_ENTRY, &u32Val);
2559 AssertRC(rc);
2560 AssertMsgReturnStmt(pVmcsInfo->u32EntryCtls == u32Val,
2561 ("%s controls mismatch: Cache=%#RX32 VMCS=%#RX32\n", pcszVmcs, pVmcsInfo->u32EntryCtls, u32Val),
2562 pVCpu->hm.s.u32HMError = VMX_VCI_CTRL_ENTRY,
2563 VERR_VMX_VMCS_FIELD_CACHE_INVALID);
2564
2565 rc = VMXReadVmcs32(VMX_VMCS32_CTRL_EXIT, &u32Val);
2566 AssertRC(rc);
2567 AssertMsgReturnStmt(pVmcsInfo->u32ExitCtls == u32Val,
2568 ("%s controls mismatch: Cache=%#RX32 VMCS=%#RX32\n", pcszVmcs, pVmcsInfo->u32ExitCtls, u32Val),
2569 pVCpu->hm.s.u32HMError = VMX_VCI_CTRL_EXIT,
2570 VERR_VMX_VMCS_FIELD_CACHE_INVALID);
2571
2572 rc = VMXReadVmcs32(VMX_VMCS32_CTRL_PIN_EXEC, &u32Val);
2573 AssertRC(rc);
2574 AssertMsgReturnStmt(pVmcsInfo->u32PinCtls == u32Val,
2575 ("%s controls mismatch: Cache=%#RX32 VMCS=%#RX32\n", pcszVmcs, pVmcsInfo->u32PinCtls, u32Val),
2576 pVCpu->hm.s.u32HMError = VMX_VCI_CTRL_PIN_EXEC,
2577 VERR_VMX_VMCS_FIELD_CACHE_INVALID);
2578
2579 rc = VMXReadVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, &u32Val);
2580 AssertRC(rc);
2581 AssertMsgReturnStmt(pVmcsInfo->u32ProcCtls == u32Val,
2582 ("%s controls mismatch: Cache=%#RX32 VMCS=%#RX32\n", pcszVmcs, pVmcsInfo->u32ProcCtls, u32Val),
2583 pVCpu->hm.s.u32HMError = VMX_VCI_CTRL_PROC_EXEC,
2584 VERR_VMX_VMCS_FIELD_CACHE_INVALID);
2585
2586 if (pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_USE_SECONDARY_CTLS)
2587 {
2588 rc = VMXReadVmcs32(VMX_VMCS32_CTRL_PROC_EXEC2, &u32Val);
2589 AssertRC(rc);
2590 AssertMsgReturnStmt(pVmcsInfo->u32ProcCtls2 == u32Val,
2591 ("%s controls mismatch: Cache=%#RX32 VMCS=%#RX32\n", pcszVmcs, pVmcsInfo->u32ProcCtls2, u32Val),
2592 pVCpu->hm.s.u32HMError = VMX_VCI_CTRL_PROC_EXEC2,
2593 VERR_VMX_VMCS_FIELD_CACHE_INVALID);
2594 }
2595
2596 rc = VMXReadVmcs32(VMX_VMCS32_CTRL_EXCEPTION_BITMAP, &u32Val);
2597 AssertRC(rc);
2598 AssertMsgReturnStmt(pVmcsInfo->u32XcptBitmap == u32Val,
2599 ("%s exception bitmap mismatch: Cache=%#RX32 VMCS=%#RX32\n", pcszVmcs, pVmcsInfo->u32XcptBitmap, u32Val),
2600 pVCpu->hm.s.u32HMError = VMX_VCI_CTRL_XCPT_BITMAP,
2601 VERR_VMX_VMCS_FIELD_CACHE_INVALID);
2602
2603 uint64_t u64Val;
2604 rc = VMXReadVmcs64(VMX_VMCS64_CTRL_TSC_OFFSET_FULL, &u64Val);
2605 AssertRC(rc);
2606 AssertMsgReturnStmt(pVmcsInfo->u64TscOffset == u64Val,
2607 ("%s TSC offset mismatch: Cache=%#RX64 VMCS=%#RX64\n", pcszVmcs, pVmcsInfo->u64TscOffset, u64Val),
2608 pVCpu->hm.s.u32HMError = VMX_VCI_CTRL_TSC_OFFSET,
2609 VERR_VMX_VMCS_FIELD_CACHE_INVALID);
2610
2611 NOREF(pcszVmcs);
2612 return VINF_SUCCESS;
2613}
2614
2615
2616#ifdef VBOX_STRICT
2617/**
2618 * Verifies that our cached host EFER MSR value has not changed since we cached it.
2619 *
2620 * @param pVCpu The cross context virtual CPU structure.
2621 * @param pVmcsInfo The VMCS info. object.
2622 */
2623static void hmR0VmxCheckHostEferMsr(PCVMCPUCC pVCpu, PCVMXVMCSINFO pVmcsInfo)
2624{
2625 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
2626
2627 if (pVmcsInfo->u32ExitCtls & VMX_EXIT_CTLS_LOAD_EFER_MSR)
2628 {
2629 uint64_t const uHostEferMsr = ASMRdMsr(MSR_K6_EFER);
2630 uint64_t const uHostEferMsrCache = pVCpu->CTX_SUFF(pVM)->hm.s.vmx.u64HostMsrEfer;
2631 uint64_t uVmcsEferMsrVmcs;
2632 int rc = VMXReadVmcs64(VMX_VMCS64_HOST_EFER_FULL, &uVmcsEferMsrVmcs);
2633 AssertRC(rc);
2634
2635 AssertMsgReturnVoid(uHostEferMsr == uVmcsEferMsrVmcs,
2636 ("EFER Host/VMCS mismatch! host=%#RX64 vmcs=%#RX64\n", uHostEferMsr, uVmcsEferMsrVmcs));
2637 AssertMsgReturnVoid(uHostEferMsr == uHostEferMsrCache,
2638 ("EFER Host/Cache mismatch! host=%#RX64 cache=%#RX64\n", uHostEferMsr, uHostEferMsrCache));
2639 }
2640}
2641
2642
2643/**
2644 * Verifies whether the guest/host MSR pairs in the auto-load/store area in the
2645 * VMCS are correct.
2646 *
2647 * @param pVCpu The cross context virtual CPU structure.
2648 * @param pVmcsInfo The VMCS info. object.
2649 * @param fIsNstGstVmcs Whether this is a nested-guest VMCS.
2650 */
2651static void hmR0VmxCheckAutoLoadStoreMsrs(PVMCPUCC pVCpu, PCVMXVMCSINFO pVmcsInfo, bool fIsNstGstVmcs)
2652{
2653 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
2654
2655 /* Read the various MSR-area counts from the VMCS. */
2656 uint32_t cEntryLoadMsrs;
2657 uint32_t cExitStoreMsrs;
2658 uint32_t cExitLoadMsrs;
2659 int rc = VMXReadVmcs32(VMX_VMCS32_CTRL_ENTRY_MSR_LOAD_COUNT, &cEntryLoadMsrs); AssertRC(rc);
2660 rc = VMXReadVmcs32(VMX_VMCS32_CTRL_EXIT_MSR_STORE_COUNT, &cExitStoreMsrs); AssertRC(rc);
2661 rc = VMXReadVmcs32(VMX_VMCS32_CTRL_EXIT_MSR_LOAD_COUNT, &cExitLoadMsrs); AssertRC(rc);
2662
2663 /* Verify all the MSR counts are the same. */
2664 Assert(cEntryLoadMsrs == cExitStoreMsrs);
2665 Assert(cExitStoreMsrs == cExitLoadMsrs);
2666 uint32_t const cMsrs = cExitLoadMsrs;
2667
2668 /* Verify the MSR counts do not exceed the maximum count supported by the hardware. */
2669 Assert(cMsrs < VMX_MISC_MAX_MSRS(pVCpu->CTX_SUFF(pVM)->hm.s.vmx.Msrs.u64Misc));
2670
2671 /* Verify the MSR counts are within the allocated page size. */
2672 Assert(sizeof(VMXAUTOMSR) * cMsrs <= X86_PAGE_4K_SIZE);
2673
2674 /* Verify the relevant contents of the MSR areas match. */
2675 PCVMXAUTOMSR pGuestMsrLoad = (PCVMXAUTOMSR)pVmcsInfo->pvGuestMsrLoad;
2676 PCVMXAUTOMSR pGuestMsrStore = (PCVMXAUTOMSR)pVmcsInfo->pvGuestMsrStore;
2677 PCVMXAUTOMSR pHostMsrLoad = (PCVMXAUTOMSR)pVmcsInfo->pvHostMsrLoad;
2678 bool const fSeparateExitMsrStorePage = hmR0VmxIsSeparateExitMsrStoreAreaVmcs(pVmcsInfo);
2679 for (uint32_t i = 0; i < cMsrs; i++)
2680 {
2681 /* Verify that the MSRs are paired properly and that the host MSR has the correct value. */
2682 if (fSeparateExitMsrStorePage)
2683 {
2684 AssertMsgReturnVoid(pGuestMsrLoad->u32Msr == pGuestMsrStore->u32Msr,
2685 ("GuestMsrLoad=%#RX32 GuestMsrStore=%#RX32 cMsrs=%u\n",
2686 pGuestMsrLoad->u32Msr, pGuestMsrStore->u32Msr, cMsrs));
2687 }
2688
2689 AssertMsgReturnVoid(pHostMsrLoad->u32Msr == pGuestMsrLoad->u32Msr,
2690 ("HostMsrLoad=%#RX32 GuestMsrLoad=%#RX32 cMsrs=%u\n",
2691 pHostMsrLoad->u32Msr, pGuestMsrLoad->u32Msr, cMsrs));
2692
2693 uint64_t const u64Msr = ASMRdMsr(pHostMsrLoad->u32Msr);
2694 AssertMsgReturnVoid(pHostMsrLoad->u64Value == u64Msr,
2695 ("u32Msr=%#RX32 VMCS Value=%#RX64 ASMRdMsr=%#RX64 cMsrs=%u\n",
2696 pHostMsrLoad->u32Msr, pHostMsrLoad->u64Value, u64Msr, cMsrs));
2697
2698 /* Verify that cached host EFER MSR matches what's loaded the CPU. */
2699 bool const fIsEferMsr = RT_BOOL(pHostMsrLoad->u32Msr == MSR_K6_EFER);
2700 if (fIsEferMsr)
2701 {
2702 AssertMsgReturnVoid(u64Msr == pVCpu->CTX_SUFF(pVM)->hm.s.vmx.u64HostMsrEfer,
2703 ("Cached=%#RX64 ASMRdMsr=%#RX64 cMsrs=%u\n",
2704 pVCpu->CTX_SUFF(pVM)->hm.s.vmx.u64HostMsrEfer, u64Msr, cMsrs));
2705 }
2706
2707 /* Verify that the accesses are as expected in the MSR bitmap for auto-load/store MSRs. */
2708 if (pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_USE_MSR_BITMAPS)
2709 {
2710 uint32_t const fMsrpm = CPUMGetVmxMsrPermission(pVmcsInfo->pvMsrBitmap, pGuestMsrLoad->u32Msr);
2711 if (fIsEferMsr)
2712 {
2713 AssertMsgReturnVoid((fMsrpm & VMXMSRPM_EXIT_RD), ("Passthru read for EFER MSR!?\n"));
2714 AssertMsgReturnVoid((fMsrpm & VMXMSRPM_EXIT_WR), ("Passthru write for EFER MSR!?\n"));
2715 }
2716 else
2717 {
2718 if (!fIsNstGstVmcs)
2719 {
2720 AssertMsgReturnVoid((fMsrpm & VMXMSRPM_ALLOW_RD_WR) == VMXMSRPM_ALLOW_RD_WR,
2721 ("u32Msr=%#RX32 cMsrs=%u No passthru read/write!\n", pGuestMsrLoad->u32Msr, cMsrs));
2722 }
2723 else
2724 {
2725 /*
2726 * A nested-guest VMCS must -also- allow read/write passthrough for the MSR for us to
2727 * execute a nested-guest with MSR passthrough.
2728 *
2729 * Check if the nested-guest MSR bitmap allows passthrough, and if so, assert that we
2730 * allow passthrough too.
2731 */
2732 void const *pvMsrBitmapNstGst = pVCpu->cpum.GstCtx.hwvirt.vmx.CTX_SUFF(pvMsrBitmap);
2733 Assert(pvMsrBitmapNstGst);
2734 uint32_t const fMsrpmNstGst = CPUMGetVmxMsrPermission(pvMsrBitmapNstGst, pGuestMsrLoad->u32Msr);
2735 AssertMsgReturnVoid(fMsrpm == fMsrpmNstGst,
2736 ("u32Msr=%#RX32 cMsrs=%u Permission mismatch fMsrpm=%#x fMsrpmNstGst=%#x!\n",
2737 pGuestMsrLoad->u32Msr, cMsrs, fMsrpm, fMsrpmNstGst));
2738 }
2739 }
2740 }
2741
2742 /* Move to the next MSR. */
2743 pHostMsrLoad++;
2744 pGuestMsrLoad++;
2745 pGuestMsrStore++;
2746 }
2747}
2748#endif /* VBOX_STRICT */
2749
2750
2751/**
2752 * Flushes the TLB using EPT.
2753 *
2754 * @returns VBox status code.
2755 * @param pVCpu The cross context virtual CPU structure of the calling
2756 * EMT. Can be NULL depending on @a enmTlbFlush.
2757 * @param pVmcsInfo The VMCS info. object. Can be NULL depending on @a
2758 * enmTlbFlush.
2759 * @param enmTlbFlush Type of flush.
2760 *
2761 * @remarks Caller is responsible for making sure this function is called only
2762 * when NestedPaging is supported and providing @a enmTlbFlush that is
2763 * supported by the CPU.
2764 * @remarks Can be called with interrupts disabled.
2765 */
2766static void hmR0VmxFlushEpt(PVMCPUCC pVCpu, PCVMXVMCSINFO pVmcsInfo, VMXTLBFLUSHEPT enmTlbFlush)
2767{
2768 uint64_t au64Descriptor[2];
2769 if (enmTlbFlush == VMXTLBFLUSHEPT_ALL_CONTEXTS)
2770 au64Descriptor[0] = 0;
2771 else
2772 {
2773 Assert(pVCpu);
2774 Assert(pVmcsInfo);
2775 au64Descriptor[0] = pVmcsInfo->HCPhysEPTP;
2776 }
2777 au64Descriptor[1] = 0; /* MBZ. Intel spec. 33.3 "VMX Instructions" */
2778
2779 int rc = VMXR0InvEPT(enmTlbFlush, &au64Descriptor[0]);
2780 AssertMsg(rc == VINF_SUCCESS, ("VMXR0InvEPT %#x %#RHp failed. rc=%Rrc\n", enmTlbFlush, au64Descriptor[0], rc));
2781
2782 if ( RT_SUCCESS(rc)
2783 && pVCpu)
2784 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushNestedPaging);
2785}
2786
2787
2788/**
2789 * Flushes the TLB using VPID.
2790 *
2791 * @returns VBox status code.
2792 * @param pVCpu The cross context virtual CPU structure of the calling
2793 * EMT. Can be NULL depending on @a enmTlbFlush.
2794 * @param enmTlbFlush Type of flush.
2795 * @param GCPtr Virtual address of the page to flush (can be 0 depending
2796 * on @a enmTlbFlush).
2797 *
2798 * @remarks Can be called with interrupts disabled.
2799 */
2800static void hmR0VmxFlushVpid(PVMCPUCC pVCpu, VMXTLBFLUSHVPID enmTlbFlush, RTGCPTR GCPtr)
2801{
2802 Assert(pVCpu->CTX_SUFF(pVM)->hm.s.vmx.fVpid);
2803
2804 uint64_t au64Descriptor[2];
2805 if (enmTlbFlush == VMXTLBFLUSHVPID_ALL_CONTEXTS)
2806 {
2807 au64Descriptor[0] = 0;
2808 au64Descriptor[1] = 0;
2809 }
2810 else
2811 {
2812 AssertPtr(pVCpu);
2813 AssertMsg(pVCpu->hm.s.uCurrentAsid != 0, ("VMXR0InvVPID: invalid ASID %lu\n", pVCpu->hm.s.uCurrentAsid));
2814 AssertMsg(pVCpu->hm.s.uCurrentAsid <= UINT16_MAX, ("VMXR0InvVPID: invalid ASID %lu\n", pVCpu->hm.s.uCurrentAsid));
2815 au64Descriptor[0] = pVCpu->hm.s.uCurrentAsid;
2816 au64Descriptor[1] = GCPtr;
2817 }
2818
2819 int rc = VMXR0InvVPID(enmTlbFlush, &au64Descriptor[0]);
2820 AssertMsg(rc == VINF_SUCCESS,
2821 ("VMXR0InvVPID %#x %u %RGv failed with %Rrc\n", enmTlbFlush, pVCpu ? pVCpu->hm.s.uCurrentAsid : 0, GCPtr, rc));
2822
2823 if ( RT_SUCCESS(rc)
2824 && pVCpu)
2825 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushAsid);
2826 NOREF(rc);
2827}
2828
2829
2830/**
2831 * Invalidates a guest page by guest virtual address. Only relevant for EPT/VPID,
2832 * otherwise there is nothing really to invalidate.
2833 *
2834 * @returns VBox status code.
2835 * @param pVCpu The cross context virtual CPU structure.
2836 * @param GCVirt Guest virtual address of the page to invalidate.
2837 */
2838VMMR0DECL(int) VMXR0InvalidatePage(PVMCPUCC pVCpu, RTGCPTR GCVirt)
2839{
2840 AssertPtr(pVCpu);
2841 LogFlowFunc(("pVCpu=%p GCVirt=%RGv\n", pVCpu, GCVirt));
2842
2843 if (!VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_TLB_FLUSH))
2844 {
2845 /*
2846 * We must invalidate the guest TLB entry in either case, we cannot ignore it even for
2847 * the EPT case. See @bugref{6043} and @bugref{6177}.
2848 *
2849 * Set the VMCPU_FF_TLB_FLUSH force flag and flush before VM-entry in hmR0VmxFlushTLB*()
2850 * as this function maybe called in a loop with individual addresses.
2851 */
2852 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
2853 if (pVM->hm.s.vmx.fVpid)
2854 {
2855 bool fVpidFlush = RT_BOOL(pVM->hm.s.vmx.Msrs.u64EptVpidCaps & MSR_IA32_VMX_EPT_VPID_CAP_INVVPID_INDIV_ADDR);
2856 if (fVpidFlush)
2857 {
2858 hmR0VmxFlushVpid(pVCpu, VMXTLBFLUSHVPID_INDIV_ADDR, GCVirt);
2859 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushTlbInvlpgVirt);
2860 }
2861 else
2862 VMCPU_FF_SET(pVCpu, VMCPU_FF_TLB_FLUSH);
2863 }
2864 else if (pVM->hm.s.fNestedPaging)
2865 VMCPU_FF_SET(pVCpu, VMCPU_FF_TLB_FLUSH);
2866 }
2867
2868 return VINF_SUCCESS;
2869}
2870
2871
2872/**
2873 * Dummy placeholder for tagged-TLB flush handling before VM-entry. Used in the
2874 * case where neither EPT nor VPID is supported by the CPU.
2875 *
2876 * @param pHostCpu The HM physical-CPU structure.
2877 * @param pVCpu The cross context virtual CPU structure.
2878 *
2879 * @remarks Called with interrupts disabled.
2880 */
2881static void hmR0VmxFlushTaggedTlbNone(PHMPHYSCPU pHostCpu, PVMCPUCC pVCpu)
2882{
2883 AssertPtr(pVCpu);
2884 AssertPtr(pHostCpu);
2885
2886 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_TLB_FLUSH);
2887
2888 Assert(pHostCpu->idCpu != NIL_RTCPUID);
2889 pVCpu->hm.s.idLastCpu = pHostCpu->idCpu;
2890 pVCpu->hm.s.cTlbFlushes = pHostCpu->cTlbFlushes;
2891 pVCpu->hm.s.fForceTLBFlush = false;
2892 return;
2893}
2894
2895
2896/**
2897 * Flushes the tagged-TLB entries for EPT+VPID CPUs as necessary.
2898 *
2899 * @param pHostCpu The HM physical-CPU structure.
2900 * @param pVCpu The cross context virtual CPU structure.
2901 * @param pVmcsInfo The VMCS info. object.
2902 *
2903 * @remarks All references to "ASID" in this function pertains to "VPID" in Intel's
2904 * nomenclature. The reason is, to avoid confusion in compare statements
2905 * since the host-CPU copies are named "ASID".
2906 *
2907 * @remarks Called with interrupts disabled.
2908 */
2909static void hmR0VmxFlushTaggedTlbBoth(PHMPHYSCPU pHostCpu, PVMCPUCC pVCpu, PCVMXVMCSINFO pVmcsInfo)
2910{
2911#ifdef VBOX_WITH_STATISTICS
2912 bool fTlbFlushed = false;
2913# define HMVMX_SET_TAGGED_TLB_FLUSHED() do { fTlbFlushed = true; } while (0)
2914# define HMVMX_UPDATE_FLUSH_SKIPPED_STAT() do { \
2915 if (!fTlbFlushed) \
2916 STAM_COUNTER_INC(&pVCpu->hm.s.StatNoFlushTlbWorldSwitch); \
2917 } while (0)
2918#else
2919# define HMVMX_SET_TAGGED_TLB_FLUSHED() do { } while (0)
2920# define HMVMX_UPDATE_FLUSH_SKIPPED_STAT() do { } while (0)
2921#endif
2922
2923 AssertPtr(pVCpu);
2924 AssertPtr(pHostCpu);
2925 Assert(pHostCpu->idCpu != NIL_RTCPUID);
2926
2927 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
2928 AssertMsg(pVM->hm.s.fNestedPaging && pVM->hm.s.vmx.fVpid,
2929 ("hmR0VmxFlushTaggedTlbBoth cannot be invoked unless NestedPaging & VPID are enabled."
2930 "fNestedPaging=%RTbool fVpid=%RTbool", pVM->hm.s.fNestedPaging, pVM->hm.s.vmx.fVpid));
2931
2932 /*
2933 * Force a TLB flush for the first world-switch if the current CPU differs from the one we
2934 * ran on last. If the TLB flush count changed, another VM (VCPU rather) has hit the ASID
2935 * limit while flushing the TLB or the host CPU is online after a suspend/resume, so we
2936 * cannot reuse the current ASID anymore.
2937 */
2938 if ( pVCpu->hm.s.idLastCpu != pHostCpu->idCpu
2939 || pVCpu->hm.s.cTlbFlushes != pHostCpu->cTlbFlushes)
2940 {
2941 ++pHostCpu->uCurrentAsid;
2942 if (pHostCpu->uCurrentAsid >= pVM->hm.s.uMaxAsid)
2943 {
2944 pHostCpu->uCurrentAsid = 1; /* Wraparound to 1; host uses 0. */
2945 pHostCpu->cTlbFlushes++; /* All VCPUs that run on this host CPU must use a new VPID. */
2946 pHostCpu->fFlushAsidBeforeUse = true; /* All VCPUs that run on this host CPU must flush their new VPID before use. */
2947 }
2948
2949 pVCpu->hm.s.uCurrentAsid = pHostCpu->uCurrentAsid;
2950 pVCpu->hm.s.idLastCpu = pHostCpu->idCpu;
2951 pVCpu->hm.s.cTlbFlushes = pHostCpu->cTlbFlushes;
2952
2953 /*
2954 * Flush by EPT when we get rescheduled to a new host CPU to ensure EPT-only tagged mappings are also
2955 * invalidated. We don't need to flush-by-VPID here as flushing by EPT covers it. See @bugref{6568}.
2956 */
2957 hmR0VmxFlushEpt(pVCpu, pVmcsInfo, pVM->hm.s.vmx.enmTlbFlushEpt);
2958 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushTlbWorldSwitch);
2959 HMVMX_SET_TAGGED_TLB_FLUSHED();
2960 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_TLB_FLUSH);
2961 }
2962 else if (VMCPU_FF_TEST_AND_CLEAR(pVCpu, VMCPU_FF_TLB_FLUSH)) /* Check for explicit TLB flushes. */
2963 {
2964 /*
2965 * Changes to the EPT paging structure by VMM requires flushing-by-EPT as the CPU
2966 * creates guest-physical (ie. only EPT-tagged) mappings while traversing the EPT
2967 * tables when EPT is in use. Flushing-by-VPID will only flush linear (only
2968 * VPID-tagged) and combined (EPT+VPID tagged) mappings but not guest-physical
2969 * mappings, see @bugref{6568}.
2970 *
2971 * See Intel spec. 28.3.2 "Creating and Using Cached Translation Information".
2972 */
2973 hmR0VmxFlushEpt(pVCpu, pVmcsInfo, pVM->hm.s.vmx.enmTlbFlushEpt);
2974 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushTlb);
2975 HMVMX_SET_TAGGED_TLB_FLUSHED();
2976 }
2977 else if (pVCpu->hm.s.vmx.fSwitchedNstGstFlushTlb)
2978 {
2979 /*
2980 * The nested-guest specifies its own guest-physical address to use as the APIC-access
2981 * address which requires flushing the TLB of EPT cached structures.
2982 *
2983 * See Intel spec. 28.3.3.4 "Guidelines for Use of the INVEPT Instruction".
2984 */
2985 hmR0VmxFlushEpt(pVCpu, pVmcsInfo, pVM->hm.s.vmx.enmTlbFlushEpt);
2986 pVCpu->hm.s.vmx.fSwitchedNstGstFlushTlb = false;
2987 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushTlbNstGst);
2988 HMVMX_SET_TAGGED_TLB_FLUSHED();
2989 }
2990
2991
2992 pVCpu->hm.s.fForceTLBFlush = false;
2993 HMVMX_UPDATE_FLUSH_SKIPPED_STAT();
2994
2995 Assert(pVCpu->hm.s.idLastCpu == pHostCpu->idCpu);
2996 Assert(pVCpu->hm.s.cTlbFlushes == pHostCpu->cTlbFlushes);
2997 AssertMsg(pVCpu->hm.s.cTlbFlushes == pHostCpu->cTlbFlushes,
2998 ("Flush count mismatch for cpu %d (%u vs %u)\n", pHostCpu->idCpu, pVCpu->hm.s.cTlbFlushes, pHostCpu->cTlbFlushes));
2999 AssertMsg(pHostCpu->uCurrentAsid >= 1 && pHostCpu->uCurrentAsid < pVM->hm.s.uMaxAsid,
3000 ("Cpu[%u] uCurrentAsid=%u cTlbFlushes=%u pVCpu->idLastCpu=%u pVCpu->cTlbFlushes=%u\n", pHostCpu->idCpu,
3001 pHostCpu->uCurrentAsid, pHostCpu->cTlbFlushes, pVCpu->hm.s.idLastCpu, pVCpu->hm.s.cTlbFlushes));
3002 AssertMsg(pVCpu->hm.s.uCurrentAsid >= 1 && pVCpu->hm.s.uCurrentAsid < pVM->hm.s.uMaxAsid,
3003 ("Cpu[%u] pVCpu->uCurrentAsid=%u\n", pHostCpu->idCpu, pVCpu->hm.s.uCurrentAsid));
3004
3005 /* Update VMCS with the VPID. */
3006 int rc = VMXWriteVmcs16(VMX_VMCS16_VPID, pVCpu->hm.s.uCurrentAsid);
3007 AssertRC(rc);
3008
3009#undef HMVMX_SET_TAGGED_TLB_FLUSHED
3010}
3011
3012
3013/**
3014 * Flushes the tagged-TLB entries for EPT CPUs as necessary.
3015 *
3016 * @param pHostCpu The HM physical-CPU structure.
3017 * @param pVCpu The cross context virtual CPU structure.
3018 * @param pVmcsInfo The VMCS info. object.
3019 *
3020 * @remarks Called with interrupts disabled.
3021 */
3022static void hmR0VmxFlushTaggedTlbEpt(PHMPHYSCPU pHostCpu, PVMCPUCC pVCpu, PCVMXVMCSINFO pVmcsInfo)
3023{
3024 AssertPtr(pVCpu);
3025 AssertPtr(pHostCpu);
3026 Assert(pHostCpu->idCpu != NIL_RTCPUID);
3027 AssertMsg(pVCpu->CTX_SUFF(pVM)->hm.s.fNestedPaging, ("hmR0VmxFlushTaggedTlbEpt cannot be invoked without NestedPaging."));
3028 AssertMsg(!pVCpu->CTX_SUFF(pVM)->hm.s.vmx.fVpid, ("hmR0VmxFlushTaggedTlbEpt cannot be invoked with VPID."));
3029
3030 /*
3031 * Force a TLB flush for the first world-switch if the current CPU differs from the one we ran on last.
3032 * A change in the TLB flush count implies the host CPU is online after a suspend/resume.
3033 */
3034 if ( pVCpu->hm.s.idLastCpu != pHostCpu->idCpu
3035 || pVCpu->hm.s.cTlbFlushes != pHostCpu->cTlbFlushes)
3036 {
3037 pVCpu->hm.s.fForceTLBFlush = true;
3038 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushTlbWorldSwitch);
3039 }
3040
3041 /* Check for explicit TLB flushes. */
3042 if (VMCPU_FF_TEST_AND_CLEAR(pVCpu, VMCPU_FF_TLB_FLUSH))
3043 {
3044 pVCpu->hm.s.fForceTLBFlush = true;
3045 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushTlb);
3046 }
3047
3048 /* Check for TLB flushes while switching to/from a nested-guest. */
3049 if (pVCpu->hm.s.vmx.fSwitchedNstGstFlushTlb)
3050 {
3051 pVCpu->hm.s.fForceTLBFlush = true;
3052 pVCpu->hm.s.vmx.fSwitchedNstGstFlushTlb = false;
3053 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushTlbNstGst);
3054 }
3055
3056 pVCpu->hm.s.idLastCpu = pHostCpu->idCpu;
3057 pVCpu->hm.s.cTlbFlushes = pHostCpu->cTlbFlushes;
3058
3059 if (pVCpu->hm.s.fForceTLBFlush)
3060 {
3061 hmR0VmxFlushEpt(pVCpu, pVmcsInfo, pVCpu->CTX_SUFF(pVM)->hm.s.vmx.enmTlbFlushEpt);
3062 pVCpu->hm.s.fForceTLBFlush = false;
3063 }
3064}
3065
3066
3067/**
3068 * Flushes the tagged-TLB entries for VPID CPUs as necessary.
3069 *
3070 * @param pHostCpu The HM physical-CPU structure.
3071 * @param pVCpu The cross context virtual CPU structure.
3072 *
3073 * @remarks Called with interrupts disabled.
3074 */
3075static void hmR0VmxFlushTaggedTlbVpid(PHMPHYSCPU pHostCpu, PVMCPUCC pVCpu)
3076{
3077 AssertPtr(pVCpu);
3078 AssertPtr(pHostCpu);
3079 Assert(pHostCpu->idCpu != NIL_RTCPUID);
3080 AssertMsg(pVCpu->CTX_SUFF(pVM)->hm.s.vmx.fVpid, ("hmR0VmxFlushTlbVpid cannot be invoked without VPID."));
3081 AssertMsg(!pVCpu->CTX_SUFF(pVM)->hm.s.fNestedPaging, ("hmR0VmxFlushTlbVpid cannot be invoked with NestedPaging"));
3082
3083 /*
3084 * Force a TLB flush for the first world switch if the current CPU differs from the one we
3085 * ran on last. If the TLB flush count changed, another VM (VCPU rather) has hit the ASID
3086 * limit while flushing the TLB or the host CPU is online after a suspend/resume, so we
3087 * cannot reuse the current ASID anymore.
3088 */
3089 if ( pVCpu->hm.s.idLastCpu != pHostCpu->idCpu
3090 || pVCpu->hm.s.cTlbFlushes != pHostCpu->cTlbFlushes)
3091 {
3092 pVCpu->hm.s.fForceTLBFlush = true;
3093 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushTlbWorldSwitch);
3094 }
3095
3096 /* Check for explicit TLB flushes. */
3097 if (VMCPU_FF_TEST_AND_CLEAR(pVCpu, VMCPU_FF_TLB_FLUSH))
3098 {
3099 /*
3100 * If we ever support VPID flush combinations other than ALL or SINGLE-context (see
3101 * hmR0VmxSetupTaggedTlb()) we would need to explicitly flush in this case (add an
3102 * fExplicitFlush = true here and change the pHostCpu->fFlushAsidBeforeUse check below to
3103 * include fExplicitFlush's too) - an obscure corner case.
3104 */
3105 pVCpu->hm.s.fForceTLBFlush = true;
3106 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushTlb);
3107 }
3108
3109 /* Check for TLB flushes while switching to/from a nested-guest. */
3110 if (pVCpu->hm.s.vmx.fSwitchedNstGstFlushTlb)
3111 {
3112 pVCpu->hm.s.fForceTLBFlush = true;
3113 pVCpu->hm.s.vmx.fSwitchedNstGstFlushTlb = false;
3114 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushTlbNstGst);
3115 }
3116
3117 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
3118 pVCpu->hm.s.idLastCpu = pHostCpu->idCpu;
3119 if (pVCpu->hm.s.fForceTLBFlush)
3120 {
3121 ++pHostCpu->uCurrentAsid;
3122 if (pHostCpu->uCurrentAsid >= pVM->hm.s.uMaxAsid)
3123 {
3124 pHostCpu->uCurrentAsid = 1; /* Wraparound to 1; host uses 0 */
3125 pHostCpu->cTlbFlushes++; /* All VCPUs that run on this host CPU must use a new VPID. */
3126 pHostCpu->fFlushAsidBeforeUse = true; /* All VCPUs that run on this host CPU must flush their new VPID before use. */
3127 }
3128
3129 pVCpu->hm.s.fForceTLBFlush = false;
3130 pVCpu->hm.s.cTlbFlushes = pHostCpu->cTlbFlushes;
3131 pVCpu->hm.s.uCurrentAsid = pHostCpu->uCurrentAsid;
3132 if (pHostCpu->fFlushAsidBeforeUse)
3133 {
3134 if (pVM->hm.s.vmx.enmTlbFlushVpid == VMXTLBFLUSHVPID_SINGLE_CONTEXT)
3135 hmR0VmxFlushVpid(pVCpu, VMXTLBFLUSHVPID_SINGLE_CONTEXT, 0 /* GCPtr */);
3136 else if (pVM->hm.s.vmx.enmTlbFlushVpid == VMXTLBFLUSHVPID_ALL_CONTEXTS)
3137 {
3138 hmR0VmxFlushVpid(pVCpu, VMXTLBFLUSHVPID_ALL_CONTEXTS, 0 /* GCPtr */);
3139 pHostCpu->fFlushAsidBeforeUse = false;
3140 }
3141 else
3142 {
3143 /* hmR0VmxSetupTaggedTlb() ensures we never get here. Paranoia. */
3144 AssertMsgFailed(("Unsupported VPID-flush context type.\n"));
3145 }
3146 }
3147 }
3148
3149 AssertMsg(pVCpu->hm.s.cTlbFlushes == pHostCpu->cTlbFlushes,
3150 ("Flush count mismatch for cpu %d (%u vs %u)\n", pHostCpu->idCpu, pVCpu->hm.s.cTlbFlushes, pHostCpu->cTlbFlushes));
3151 AssertMsg(pHostCpu->uCurrentAsid >= 1 && pHostCpu->uCurrentAsid < pVM->hm.s.uMaxAsid,
3152 ("Cpu[%u] uCurrentAsid=%u cTlbFlushes=%u pVCpu->idLastCpu=%u pVCpu->cTlbFlushes=%u\n", pHostCpu->idCpu,
3153 pHostCpu->uCurrentAsid, pHostCpu->cTlbFlushes, pVCpu->hm.s.idLastCpu, pVCpu->hm.s.cTlbFlushes));
3154 AssertMsg(pVCpu->hm.s.uCurrentAsid >= 1 && pVCpu->hm.s.uCurrentAsid < pVM->hm.s.uMaxAsid,
3155 ("Cpu[%u] pVCpu->uCurrentAsid=%u\n", pHostCpu->idCpu, pVCpu->hm.s.uCurrentAsid));
3156
3157 int rc = VMXWriteVmcs16(VMX_VMCS16_VPID, pVCpu->hm.s.uCurrentAsid);
3158 AssertRC(rc);
3159}
3160
3161
3162/**
3163 * Flushes the guest TLB entry based on CPU capabilities.
3164 *
3165 * @param pHostCpu The HM physical-CPU structure.
3166 * @param pVCpu The cross context virtual CPU structure.
3167 * @param pVmcsInfo The VMCS info. object.
3168 *
3169 * @remarks Called with interrupts disabled.
3170 */
3171static void hmR0VmxFlushTaggedTlb(PHMPHYSCPU pHostCpu, PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo)
3172{
3173#ifdef HMVMX_ALWAYS_FLUSH_TLB
3174 VMCPU_FF_SET(pVCpu, VMCPU_FF_TLB_FLUSH);
3175#endif
3176 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
3177 switch (pVM->hm.s.vmx.enmTlbFlushType)
3178 {
3179 case VMXTLBFLUSHTYPE_EPT_VPID: hmR0VmxFlushTaggedTlbBoth(pHostCpu, pVCpu, pVmcsInfo); break;
3180 case VMXTLBFLUSHTYPE_EPT: hmR0VmxFlushTaggedTlbEpt(pHostCpu, pVCpu, pVmcsInfo); break;
3181 case VMXTLBFLUSHTYPE_VPID: hmR0VmxFlushTaggedTlbVpid(pHostCpu, pVCpu); break;
3182 case VMXTLBFLUSHTYPE_NONE: hmR0VmxFlushTaggedTlbNone(pHostCpu, pVCpu); break;
3183 default:
3184 AssertMsgFailed(("Invalid flush-tag function identifier\n"));
3185 break;
3186 }
3187 /* Don't assert that VMCPU_FF_TLB_FLUSH should no longer be pending. It can be set by other EMTs. */
3188}
3189
3190
3191/**
3192 * Sets up the appropriate tagged TLB-flush level and handler for flushing guest
3193 * TLB entries from the host TLB before VM-entry.
3194 *
3195 * @returns VBox status code.
3196 * @param pVM The cross context VM structure.
3197 */
3198static int hmR0VmxSetupTaggedTlb(PVMCC pVM)
3199{
3200 /*
3201 * Determine optimal flush type for nested paging.
3202 * We cannot ignore EPT if no suitable flush-types is supported by the CPU as we've already setup
3203 * unrestricted guest execution (see hmR3InitFinalizeR0()).
3204 */
3205 if (pVM->hm.s.fNestedPaging)
3206 {
3207 if (pVM->hm.s.vmx.Msrs.u64EptVpidCaps & MSR_IA32_VMX_EPT_VPID_CAP_INVEPT)
3208 {
3209 if (pVM->hm.s.vmx.Msrs.u64EptVpidCaps & MSR_IA32_VMX_EPT_VPID_CAP_INVEPT_SINGLE_CONTEXT)
3210 pVM->hm.s.vmx.enmTlbFlushEpt = VMXTLBFLUSHEPT_SINGLE_CONTEXT;
3211 else if (pVM->hm.s.vmx.Msrs.u64EptVpidCaps & MSR_IA32_VMX_EPT_VPID_CAP_INVEPT_ALL_CONTEXTS)
3212 pVM->hm.s.vmx.enmTlbFlushEpt = VMXTLBFLUSHEPT_ALL_CONTEXTS;
3213 else
3214 {
3215 /* Shouldn't happen. EPT is supported but no suitable flush-types supported. */
3216 pVM->hm.s.vmx.enmTlbFlushEpt = VMXTLBFLUSHEPT_NOT_SUPPORTED;
3217 VMCC_GET_CPU_0(pVM)->hm.s.u32HMError = VMX_UFC_EPT_FLUSH_TYPE_UNSUPPORTED;
3218 return VERR_HM_UNSUPPORTED_CPU_FEATURE_COMBO;
3219 }
3220
3221 /* Make sure the write-back cacheable memory type for EPT is supported. */
3222 if (RT_UNLIKELY(!(pVM->hm.s.vmx.Msrs.u64EptVpidCaps & MSR_IA32_VMX_EPT_VPID_CAP_EMT_WB)))
3223 {
3224 pVM->hm.s.vmx.enmTlbFlushEpt = VMXTLBFLUSHEPT_NOT_SUPPORTED;
3225 VMCC_GET_CPU_0(pVM)->hm.s.u32HMError = VMX_UFC_EPT_MEM_TYPE_NOT_WB;
3226 return VERR_HM_UNSUPPORTED_CPU_FEATURE_COMBO;
3227 }
3228
3229 /* EPT requires a page-walk length of 4. */
3230 if (RT_UNLIKELY(!(pVM->hm.s.vmx.Msrs.u64EptVpidCaps & MSR_IA32_VMX_EPT_VPID_CAP_PAGE_WALK_LENGTH_4)))
3231 {
3232 pVM->hm.s.vmx.enmTlbFlushEpt = VMXTLBFLUSHEPT_NOT_SUPPORTED;
3233 VMCC_GET_CPU_0(pVM)->hm.s.u32HMError = VMX_UFC_EPT_PAGE_WALK_LENGTH_UNSUPPORTED;
3234 return VERR_HM_UNSUPPORTED_CPU_FEATURE_COMBO;
3235 }
3236 }
3237 else
3238 {
3239 /* Shouldn't happen. EPT is supported but INVEPT instruction is not supported. */
3240 pVM->hm.s.vmx.enmTlbFlushEpt = VMXTLBFLUSHEPT_NOT_SUPPORTED;
3241 VMCC_GET_CPU_0(pVM)->hm.s.u32HMError = VMX_UFC_EPT_INVEPT_UNAVAILABLE;
3242 return VERR_HM_UNSUPPORTED_CPU_FEATURE_COMBO;
3243 }
3244 }
3245
3246 /*
3247 * Determine optimal flush type for VPID.
3248 */
3249 if (pVM->hm.s.vmx.fVpid)
3250 {
3251 if (pVM->hm.s.vmx.Msrs.u64EptVpidCaps & MSR_IA32_VMX_EPT_VPID_CAP_INVVPID)
3252 {
3253 if (pVM->hm.s.vmx.Msrs.u64EptVpidCaps & MSR_IA32_VMX_EPT_VPID_CAP_INVVPID_SINGLE_CONTEXT)
3254 pVM->hm.s.vmx.enmTlbFlushVpid = VMXTLBFLUSHVPID_SINGLE_CONTEXT;
3255 else if (pVM->hm.s.vmx.Msrs.u64EptVpidCaps & MSR_IA32_VMX_EPT_VPID_CAP_INVVPID_ALL_CONTEXTS)
3256 pVM->hm.s.vmx.enmTlbFlushVpid = VMXTLBFLUSHVPID_ALL_CONTEXTS;
3257 else
3258 {
3259 /* Neither SINGLE nor ALL-context flush types for VPID is supported by the CPU. Ignore VPID capability. */
3260 if (pVM->hm.s.vmx.Msrs.u64EptVpidCaps & MSR_IA32_VMX_EPT_VPID_CAP_INVVPID_INDIV_ADDR)
3261 LogRelFunc(("Only INDIV_ADDR supported. Ignoring VPID.\n"));
3262 if (pVM->hm.s.vmx.Msrs.u64EptVpidCaps & MSR_IA32_VMX_EPT_VPID_CAP_INVVPID_SINGLE_CONTEXT_RETAIN_GLOBALS)
3263 LogRelFunc(("Only SINGLE_CONTEXT_RETAIN_GLOBALS supported. Ignoring VPID.\n"));
3264 pVM->hm.s.vmx.enmTlbFlushVpid = VMXTLBFLUSHVPID_NOT_SUPPORTED;
3265 pVM->hm.s.vmx.fVpid = false;
3266 }
3267 }
3268 else
3269 {
3270 /* Shouldn't happen. VPID is supported but INVVPID is not supported by the CPU. Ignore VPID capability. */
3271 Log4Func(("VPID supported without INVEPT support. Ignoring VPID.\n"));
3272 pVM->hm.s.vmx.enmTlbFlushVpid = VMXTLBFLUSHVPID_NOT_SUPPORTED;
3273 pVM->hm.s.vmx.fVpid = false;
3274 }
3275 }
3276
3277 /*
3278 * Setup the handler for flushing tagged-TLBs.
3279 */
3280 if (pVM->hm.s.fNestedPaging && pVM->hm.s.vmx.fVpid)
3281 pVM->hm.s.vmx.enmTlbFlushType = VMXTLBFLUSHTYPE_EPT_VPID;
3282 else if (pVM->hm.s.fNestedPaging)
3283 pVM->hm.s.vmx.enmTlbFlushType = VMXTLBFLUSHTYPE_EPT;
3284 else if (pVM->hm.s.vmx.fVpid)
3285 pVM->hm.s.vmx.enmTlbFlushType = VMXTLBFLUSHTYPE_VPID;
3286 else
3287 pVM->hm.s.vmx.enmTlbFlushType = VMXTLBFLUSHTYPE_NONE;
3288 return VINF_SUCCESS;
3289}
3290
3291
3292#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
3293/**
3294 * Sets up the shadow VMCS fields arrays.
3295 *
3296 * This function builds arrays of VMCS fields to sync the shadow VMCS later while
3297 * executing the guest.
3298 *
3299 * @returns VBox status code.
3300 * @param pVM The cross context VM structure.
3301 */
3302static int hmR0VmxSetupShadowVmcsFieldsArrays(PVMCC pVM)
3303{
3304 /*
3305 * Paranoia. Ensure we haven't exposed the VMWRITE-All VMX feature to the guest
3306 * when the host does not support it.
3307 */
3308 bool const fGstVmwriteAll = pVM->cpum.ro.GuestFeatures.fVmxVmwriteAll;
3309 if ( !fGstVmwriteAll
3310 || (pVM->hm.s.vmx.Msrs.u64Misc & VMX_MISC_VMWRITE_ALL))
3311 { /* likely. */ }
3312 else
3313 {
3314 LogRelFunc(("VMX VMWRITE-All feature exposed to the guest but host CPU does not support it!\n"));
3315 VMCC_GET_CPU_0(pVM)->hm.s.u32HMError = VMX_UFC_GST_HOST_VMWRITE_ALL;
3316 return VERR_HM_UNSUPPORTED_CPU_FEATURE_COMBO;
3317 }
3318
3319 uint32_t const cVmcsFields = RT_ELEMENTS(g_aVmcsFields);
3320 uint32_t cRwFields = 0;
3321 uint32_t cRoFields = 0;
3322 for (uint32_t i = 0; i < cVmcsFields; i++)
3323 {
3324 VMXVMCSFIELD VmcsField;
3325 VmcsField.u = g_aVmcsFields[i];
3326
3327 /*
3328 * We will be writing "FULL" (64-bit) fields while syncing the shadow VMCS.
3329 * Therefore, "HIGH" (32-bit portion of 64-bit) fields must not be included
3330 * in the shadow VMCS fields array as they would be redundant.
3331 *
3332 * If the VMCS field depends on a CPU feature that is not exposed to the guest,
3333 * we must not include it in the shadow VMCS fields array. Guests attempting to
3334 * VMREAD/VMWRITE such VMCS fields would cause a VM-exit and we shall emulate
3335 * the required behavior.
3336 */
3337 if ( VmcsField.n.fAccessType == VMX_VMCSFIELD_ACCESS_FULL
3338 && CPUMIsGuestVmxVmcsFieldValid(pVM, VmcsField.u))
3339 {
3340 /*
3341 * Read-only fields are placed in a separate array so that while syncing shadow
3342 * VMCS fields later (which is more performance critical) we can avoid branches.
3343 *
3344 * However, if the guest can write to all fields (including read-only fields),
3345 * we treat it a as read/write field. Otherwise, writing to these fields would
3346 * cause a VMWRITE instruction error while syncing the shadow VMCS.
3347 */
3348 if ( fGstVmwriteAll
3349 || !VMXIsVmcsFieldReadOnly(VmcsField.u))
3350 pVM->hm.s.vmx.paShadowVmcsFields[cRwFields++] = VmcsField.u;
3351 else
3352 pVM->hm.s.vmx.paShadowVmcsRoFields[cRoFields++] = VmcsField.u;
3353 }
3354 }
3355
3356 /* Update the counts. */
3357 pVM->hm.s.vmx.cShadowVmcsFields = cRwFields;
3358 pVM->hm.s.vmx.cShadowVmcsRoFields = cRoFields;
3359 return VINF_SUCCESS;
3360}
3361
3362
3363/**
3364 * Sets up the VMREAD and VMWRITE bitmaps.
3365 *
3366 * @param pVM The cross context VM structure.
3367 */
3368static void hmR0VmxSetupVmreadVmwriteBitmaps(PVMCC pVM)
3369{
3370 /*
3371 * By default, ensure guest attempts to access any VMCS fields cause VM-exits.
3372 */
3373 uint32_t const cbBitmap = X86_PAGE_4K_SIZE;
3374 uint8_t *pbVmreadBitmap = (uint8_t *)pVM->hm.s.vmx.pvVmreadBitmap;
3375 uint8_t *pbVmwriteBitmap = (uint8_t *)pVM->hm.s.vmx.pvVmwriteBitmap;
3376 ASMMemFill32(pbVmreadBitmap, cbBitmap, UINT32_C(0xffffffff));
3377 ASMMemFill32(pbVmwriteBitmap, cbBitmap, UINT32_C(0xffffffff));
3378
3379 /*
3380 * Skip intercepting VMREAD/VMWRITE to guest read/write fields in the
3381 * VMREAD and VMWRITE bitmaps.
3382 */
3383 {
3384 uint32_t const *paShadowVmcsFields = pVM->hm.s.vmx.paShadowVmcsFields;
3385 uint32_t const cShadowVmcsFields = pVM->hm.s.vmx.cShadowVmcsFields;
3386 for (uint32_t i = 0; i < cShadowVmcsFields; i++)
3387 {
3388 uint32_t const uVmcsField = paShadowVmcsFields[i];
3389 Assert(!(uVmcsField & VMX_VMCSFIELD_RSVD_MASK));
3390 Assert(uVmcsField >> 3 < cbBitmap);
3391 ASMBitClear(pbVmreadBitmap + (uVmcsField >> 3), uVmcsField & 7);
3392 ASMBitClear(pbVmwriteBitmap + (uVmcsField >> 3), uVmcsField & 7);
3393 }
3394 }
3395
3396 /*
3397 * Skip intercepting VMREAD for guest read-only fields in the VMREAD bitmap
3398 * if the host supports VMWRITE to all supported VMCS fields.
3399 */
3400 if (pVM->hm.s.vmx.Msrs.u64Misc & VMX_MISC_VMWRITE_ALL)
3401 {
3402 uint32_t const *paShadowVmcsRoFields = pVM->hm.s.vmx.paShadowVmcsRoFields;
3403 uint32_t const cShadowVmcsRoFields = pVM->hm.s.vmx.cShadowVmcsRoFields;
3404 for (uint32_t i = 0; i < cShadowVmcsRoFields; i++)
3405 {
3406 uint32_t const uVmcsField = paShadowVmcsRoFields[i];
3407 Assert(!(uVmcsField & VMX_VMCSFIELD_RSVD_MASK));
3408 Assert(uVmcsField >> 3 < cbBitmap);
3409 ASMBitClear(pbVmreadBitmap + (uVmcsField >> 3), uVmcsField & 7);
3410 }
3411 }
3412}
3413#endif /* VBOX_WITH_NESTED_HWVIRT_VMX */
3414
3415
3416/**
3417 * Sets up the virtual-APIC page address for the VMCS.
3418 *
3419 * @param pVmcsInfo The VMCS info. object.
3420 */
3421DECLINLINE(void) hmR0VmxSetupVmcsVirtApicAddr(PCVMXVMCSINFO pVmcsInfo)
3422{
3423 RTHCPHYS const HCPhysVirtApic = pVmcsInfo->HCPhysVirtApic;
3424 Assert(HCPhysVirtApic != NIL_RTHCPHYS);
3425 Assert(!(HCPhysVirtApic & 0xfff)); /* Bits 11:0 MBZ. */
3426 int rc = VMXWriteVmcs64(VMX_VMCS64_CTRL_VIRT_APIC_PAGEADDR_FULL, HCPhysVirtApic);
3427 AssertRC(rc);
3428}
3429
3430
3431/**
3432 * Sets up the MSR-bitmap address for the VMCS.
3433 *
3434 * @param pVmcsInfo The VMCS info. object.
3435 */
3436DECLINLINE(void) hmR0VmxSetupVmcsMsrBitmapAddr(PCVMXVMCSINFO pVmcsInfo)
3437{
3438 RTHCPHYS const HCPhysMsrBitmap = pVmcsInfo->HCPhysMsrBitmap;
3439 Assert(HCPhysMsrBitmap != NIL_RTHCPHYS);
3440 Assert(!(HCPhysMsrBitmap & 0xfff)); /* Bits 11:0 MBZ. */
3441 int rc = VMXWriteVmcs64(VMX_VMCS64_CTRL_MSR_BITMAP_FULL, HCPhysMsrBitmap);
3442 AssertRC(rc);
3443}
3444
3445
3446/**
3447 * Sets up the APIC-access page address for the VMCS.
3448 *
3449 * @param pVCpu The cross context virtual CPU structure.
3450 */
3451DECLINLINE(void) hmR0VmxSetupVmcsApicAccessAddr(PVMCPUCC pVCpu)
3452{
3453 RTHCPHYS const HCPhysApicAccess = pVCpu->CTX_SUFF(pVM)->hm.s.vmx.HCPhysApicAccess;
3454 Assert(HCPhysApicAccess != NIL_RTHCPHYS);
3455 Assert(!(HCPhysApicAccess & 0xfff)); /* Bits 11:0 MBZ. */
3456 int rc = VMXWriteVmcs64(VMX_VMCS64_CTRL_APIC_ACCESSADDR_FULL, HCPhysApicAccess);
3457 AssertRC(rc);
3458}
3459
3460
3461#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
3462/**
3463 * Sets up the VMREAD bitmap address for the VMCS.
3464 *
3465 * @param pVCpu The cross context virtual CPU structure.
3466 */
3467DECLINLINE(void) hmR0VmxSetupVmcsVmreadBitmapAddr(PVMCPUCC pVCpu)
3468{
3469 RTHCPHYS const HCPhysVmreadBitmap = pVCpu->CTX_SUFF(pVM)->hm.s.vmx.HCPhysVmreadBitmap;
3470 Assert(HCPhysVmreadBitmap != NIL_RTHCPHYS);
3471 Assert(!(HCPhysVmreadBitmap & 0xfff)); /* Bits 11:0 MBZ. */
3472 int rc = VMXWriteVmcs64(VMX_VMCS64_CTRL_VMREAD_BITMAP_FULL, HCPhysVmreadBitmap);
3473 AssertRC(rc);
3474}
3475
3476
3477/**
3478 * Sets up the VMWRITE bitmap address for the VMCS.
3479 *
3480 * @param pVCpu The cross context virtual CPU structure.
3481 */
3482DECLINLINE(void) hmR0VmxSetupVmcsVmwriteBitmapAddr(PVMCPUCC pVCpu)
3483{
3484 RTHCPHYS const HCPhysVmwriteBitmap = pVCpu->CTX_SUFF(pVM)->hm.s.vmx.HCPhysVmwriteBitmap;
3485 Assert(HCPhysVmwriteBitmap != NIL_RTHCPHYS);
3486 Assert(!(HCPhysVmwriteBitmap & 0xfff)); /* Bits 11:0 MBZ. */
3487 int rc = VMXWriteVmcs64(VMX_VMCS64_CTRL_VMWRITE_BITMAP_FULL, HCPhysVmwriteBitmap);
3488 AssertRC(rc);
3489}
3490#endif
3491
3492
3493/**
3494 * Sets up the VM-entry MSR load, VM-exit MSR-store and VM-exit MSR-load addresses
3495 * in the VMCS.
3496 *
3497 * @returns VBox status code.
3498 * @param pVmcsInfo The VMCS info. object.
3499 */
3500DECLINLINE(int) hmR0VmxSetupVmcsAutoLoadStoreMsrAddrs(PVMXVMCSINFO pVmcsInfo)
3501{
3502 RTHCPHYS const HCPhysGuestMsrLoad = pVmcsInfo->HCPhysGuestMsrLoad;
3503 Assert(HCPhysGuestMsrLoad != NIL_RTHCPHYS);
3504 Assert(!(HCPhysGuestMsrLoad & 0xf)); /* Bits 3:0 MBZ. */
3505
3506 RTHCPHYS const HCPhysGuestMsrStore = pVmcsInfo->HCPhysGuestMsrStore;
3507 Assert(HCPhysGuestMsrStore != NIL_RTHCPHYS);
3508 Assert(!(HCPhysGuestMsrStore & 0xf)); /* Bits 3:0 MBZ. */
3509
3510 RTHCPHYS const HCPhysHostMsrLoad = pVmcsInfo->HCPhysHostMsrLoad;
3511 Assert(HCPhysHostMsrLoad != NIL_RTHCPHYS);
3512 Assert(!(HCPhysHostMsrLoad & 0xf)); /* Bits 3:0 MBZ. */
3513
3514 int rc = VMXWriteVmcs64(VMX_VMCS64_CTRL_ENTRY_MSR_LOAD_FULL, HCPhysGuestMsrLoad); AssertRC(rc);
3515 rc = VMXWriteVmcs64(VMX_VMCS64_CTRL_EXIT_MSR_STORE_FULL, HCPhysGuestMsrStore); AssertRC(rc);
3516 rc = VMXWriteVmcs64(VMX_VMCS64_CTRL_EXIT_MSR_LOAD_FULL, HCPhysHostMsrLoad); AssertRC(rc);
3517 return VINF_SUCCESS;
3518}
3519
3520
3521/**
3522 * Sets up MSR permissions in the MSR bitmap of a VMCS info. object.
3523 *
3524 * @param pVCpu The cross context virtual CPU structure.
3525 * @param pVmcsInfo The VMCS info. object.
3526 */
3527static void hmR0VmxSetupVmcsMsrPermissions(PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo)
3528{
3529 Assert(pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_USE_MSR_BITMAPS);
3530
3531 /*
3532 * By default, ensure guest attempts to access any MSR cause VM-exits.
3533 * This shall later be relaxed for specific MSRs as necessary.
3534 *
3535 * Note: For nested-guests, the entire bitmap will be merged prior to
3536 * executing the nested-guest using hardware-assisted VMX and hence there
3537 * is no need to perform this operation. See hmR0VmxMergeMsrBitmapNested.
3538 */
3539 Assert(pVmcsInfo->pvMsrBitmap);
3540 ASMMemFill32(pVmcsInfo->pvMsrBitmap, X86_PAGE_4K_SIZE, UINT32_C(0xffffffff));
3541
3542 /*
3543 * The guest can access the following MSRs (read, write) without causing
3544 * VM-exits; they are loaded/stored automatically using fields in the VMCS.
3545 */
3546 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
3547 hmR0VmxSetMsrPermission(pVCpu, pVmcsInfo, false, MSR_IA32_SYSENTER_CS, VMXMSRPM_ALLOW_RD_WR);
3548 hmR0VmxSetMsrPermission(pVCpu, pVmcsInfo, false, MSR_IA32_SYSENTER_ESP, VMXMSRPM_ALLOW_RD_WR);
3549 hmR0VmxSetMsrPermission(pVCpu, pVmcsInfo, false, MSR_IA32_SYSENTER_EIP, VMXMSRPM_ALLOW_RD_WR);
3550 hmR0VmxSetMsrPermission(pVCpu, pVmcsInfo, false, MSR_K8_GS_BASE, VMXMSRPM_ALLOW_RD_WR);
3551 hmR0VmxSetMsrPermission(pVCpu, pVmcsInfo, false, MSR_K8_FS_BASE, VMXMSRPM_ALLOW_RD_WR);
3552
3553 /*
3554 * The IA32_PRED_CMD and IA32_FLUSH_CMD MSRs are write-only and has no state
3555 * associated with then. We never need to intercept access (writes need to be
3556 * executed without causing a VM-exit, reads will #GP fault anyway).
3557 *
3558 * The IA32_SPEC_CTRL MSR is read/write and has state. We allow the guest to
3559 * read/write them. We swap the the guest/host MSR value using the
3560 * auto-load/store MSR area.
3561 */
3562 if (pVM->cpum.ro.GuestFeatures.fIbpb)
3563 hmR0VmxSetMsrPermission(pVCpu, pVmcsInfo, false, MSR_IA32_PRED_CMD, VMXMSRPM_ALLOW_RD_WR);
3564 if (pVM->cpum.ro.GuestFeatures.fFlushCmd)
3565 hmR0VmxSetMsrPermission(pVCpu, pVmcsInfo, false, MSR_IA32_FLUSH_CMD, VMXMSRPM_ALLOW_RD_WR);
3566 if (pVM->cpum.ro.GuestFeatures.fIbrs)
3567 hmR0VmxSetMsrPermission(pVCpu, pVmcsInfo, false, MSR_IA32_SPEC_CTRL, VMXMSRPM_ALLOW_RD_WR);
3568
3569 /*
3570 * Allow full read/write access for the following MSRs (mandatory for VT-x)
3571 * required for 64-bit guests.
3572 */
3573 if (pVM->hm.s.fAllow64BitGuests)
3574 {
3575 hmR0VmxSetMsrPermission(pVCpu, pVmcsInfo, false, MSR_K8_LSTAR, VMXMSRPM_ALLOW_RD_WR);
3576 hmR0VmxSetMsrPermission(pVCpu, pVmcsInfo, false, MSR_K6_STAR, VMXMSRPM_ALLOW_RD_WR);
3577 hmR0VmxSetMsrPermission(pVCpu, pVmcsInfo, false, MSR_K8_SF_MASK, VMXMSRPM_ALLOW_RD_WR);
3578 hmR0VmxSetMsrPermission(pVCpu, pVmcsInfo, false, MSR_K8_KERNEL_GS_BASE, VMXMSRPM_ALLOW_RD_WR);
3579 }
3580
3581 /*
3582 * IA32_EFER MSR is always intercepted, see @bugref{9180#c37}.
3583 */
3584#ifdef VBOX_STRICT
3585 Assert(pVmcsInfo->pvMsrBitmap);
3586 uint32_t const fMsrpmEfer = CPUMGetVmxMsrPermission(pVmcsInfo->pvMsrBitmap, MSR_K6_EFER);
3587 Assert(fMsrpmEfer == VMXMSRPM_EXIT_RD_WR);
3588#endif
3589}
3590
3591
3592/**
3593 * Sets up pin-based VM-execution controls in the VMCS.
3594 *
3595 * @returns VBox status code.
3596 * @param pVCpu The cross context virtual CPU structure.
3597 * @param pVmcsInfo The VMCS info. object.
3598 */
3599static int hmR0VmxSetupVmcsPinCtls(PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo)
3600{
3601 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
3602 uint32_t fVal = pVM->hm.s.vmx.Msrs.PinCtls.n.allowed0; /* Bits set here must always be set. */
3603 uint32_t const fZap = pVM->hm.s.vmx.Msrs.PinCtls.n.allowed1; /* Bits cleared here must always be cleared. */
3604
3605 fVal |= VMX_PIN_CTLS_EXT_INT_EXIT /* External interrupts cause a VM-exit. */
3606 | VMX_PIN_CTLS_NMI_EXIT; /* Non-maskable interrupts (NMIs) cause a VM-exit. */
3607
3608 if (pVM->hm.s.vmx.Msrs.PinCtls.n.allowed1 & VMX_PIN_CTLS_VIRT_NMI)
3609 fVal |= VMX_PIN_CTLS_VIRT_NMI; /* Use virtual NMIs and virtual-NMI blocking features. */
3610
3611 /* Enable the VMX-preemption timer. */
3612 if (pVM->hm.s.vmx.fUsePreemptTimer)
3613 {
3614 Assert(pVM->hm.s.vmx.Msrs.PinCtls.n.allowed1 & VMX_PIN_CTLS_PREEMPT_TIMER);
3615 fVal |= VMX_PIN_CTLS_PREEMPT_TIMER;
3616 }
3617
3618#if 0
3619 /* Enable posted-interrupt processing. */
3620 if (pVM->hm.s.fPostedIntrs)
3621 {
3622 Assert(pVM->hm.s.vmx.Msrs.PinCtls.n.allowed1 & VMX_PIN_CTLS_POSTED_INT);
3623 Assert(pVM->hm.s.vmx.Msrs.ExitCtls.n.allowed1 & VMX_EXIT_CTLS_ACK_EXT_INT);
3624 fVal |= VMX_PIN_CTLS_POSTED_INT;
3625 }
3626#endif
3627
3628 if ((fVal & fZap) != fVal)
3629 {
3630 LogRelFunc(("Invalid pin-based VM-execution controls combo! Cpu=%#RX32 fVal=%#RX32 fZap=%#RX32\n",
3631 pVM->hm.s.vmx.Msrs.PinCtls.n.allowed0, fVal, fZap));
3632 pVCpu->hm.s.u32HMError = VMX_UFC_CTRL_PIN_EXEC;
3633 return VERR_HM_UNSUPPORTED_CPU_FEATURE_COMBO;
3634 }
3635
3636 /* Commit it to the VMCS and update our cache. */
3637 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PIN_EXEC, fVal);
3638 AssertRC(rc);
3639 pVmcsInfo->u32PinCtls = fVal;
3640
3641 return VINF_SUCCESS;
3642}
3643
3644
3645/**
3646 * Sets up secondary processor-based VM-execution controls in the VMCS.
3647 *
3648 * @returns VBox status code.
3649 * @param pVCpu The cross context virtual CPU structure.
3650 * @param pVmcsInfo The VMCS info. object.
3651 */
3652static int hmR0VmxSetupVmcsProcCtls2(PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo)
3653{
3654 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
3655 uint32_t fVal = pVM->hm.s.vmx.Msrs.ProcCtls2.n.allowed0; /* Bits set here must be set in the VMCS. */
3656 uint32_t const fZap = pVM->hm.s.vmx.Msrs.ProcCtls2.n.allowed1; /* Bits cleared here must be cleared in the VMCS. */
3657
3658 /* WBINVD causes a VM-exit. */
3659 if (pVM->hm.s.vmx.Msrs.ProcCtls2.n.allowed1 & VMX_PROC_CTLS2_WBINVD_EXIT)
3660 fVal |= VMX_PROC_CTLS2_WBINVD_EXIT;
3661
3662 /* Enable EPT (aka nested-paging). */
3663 if (pVM->hm.s.fNestedPaging)
3664 fVal |= VMX_PROC_CTLS2_EPT;
3665
3666 /* Enable the INVPCID instruction if we expose it to the guest and is supported
3667 by the hardware. Without this, guest executing INVPCID would cause a #UD. */
3668 if ( pVM->cpum.ro.GuestFeatures.fInvpcid
3669 && (pVM->hm.s.vmx.Msrs.ProcCtls2.n.allowed1 & VMX_PROC_CTLS2_INVPCID))
3670 fVal |= VMX_PROC_CTLS2_INVPCID;
3671
3672 /* Enable VPID. */
3673 if (pVM->hm.s.vmx.fVpid)
3674 fVal |= VMX_PROC_CTLS2_VPID;
3675
3676 /* Enable unrestricted guest execution. */
3677 if (pVM->hm.s.vmx.fUnrestrictedGuest)
3678 fVal |= VMX_PROC_CTLS2_UNRESTRICTED_GUEST;
3679
3680#if 0
3681 if (pVM->hm.s.fVirtApicRegs)
3682 {
3683 /* Enable APIC-register virtualization. */
3684 Assert(pVM->hm.s.vmx.Msrs.ProcCtls2.n.allowed1 & VMX_PROC_CTLS2_APIC_REG_VIRT);
3685 fVal |= VMX_PROC_CTLS2_APIC_REG_VIRT;
3686
3687 /* Enable virtual-interrupt delivery. */
3688 Assert(pVM->hm.s.vmx.Msrs.ProcCtls2.n.allowed1 & VMX_PROC_CTLS2_VIRT_INTR_DELIVERY);
3689 fVal |= VMX_PROC_CTLS2_VIRT_INTR_DELIVERY;
3690 }
3691#endif
3692
3693 /* Virtualize-APIC accesses if supported by the CPU. The virtual-APIC page is
3694 where the TPR shadow resides. */
3695 /** @todo VIRT_X2APIC support, it's mutually exclusive with this. So must be
3696 * done dynamically. */
3697 if (pVM->hm.s.vmx.Msrs.ProcCtls2.n.allowed1 & VMX_PROC_CTLS2_VIRT_APIC_ACCESS)
3698 {
3699 fVal |= VMX_PROC_CTLS2_VIRT_APIC_ACCESS;
3700 hmR0VmxSetupVmcsApicAccessAddr(pVCpu);
3701 }
3702
3703 /* Enable the RDTSCP instruction if we expose it to the guest and is supported
3704 by the hardware. Without this, guest executing RDTSCP would cause a #UD. */
3705 if ( pVM->cpum.ro.GuestFeatures.fRdTscP
3706 && (pVM->hm.s.vmx.Msrs.ProcCtls2.n.allowed1 & VMX_PROC_CTLS2_RDTSCP))
3707 fVal |= VMX_PROC_CTLS2_RDTSCP;
3708
3709 /* Enable Pause-Loop exiting. */
3710 if ( (pVM->hm.s.vmx.Msrs.ProcCtls2.n.allowed1 & VMX_PROC_CTLS2_PAUSE_LOOP_EXIT)
3711 && pVM->hm.s.vmx.cPleGapTicks
3712 && pVM->hm.s.vmx.cPleWindowTicks)
3713 {
3714 fVal |= VMX_PROC_CTLS2_PAUSE_LOOP_EXIT;
3715
3716 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PLE_GAP, pVM->hm.s.vmx.cPleGapTicks); AssertRC(rc);
3717 rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PLE_WINDOW, pVM->hm.s.vmx.cPleWindowTicks); AssertRC(rc);
3718 }
3719
3720 if ((fVal & fZap) != fVal)
3721 {
3722 LogRelFunc(("Invalid secondary processor-based VM-execution controls combo! cpu=%#RX32 fVal=%#RX32 fZap=%#RX32\n",
3723 pVM->hm.s.vmx.Msrs.ProcCtls2.n.allowed0, fVal, fZap));
3724 pVCpu->hm.s.u32HMError = VMX_UFC_CTRL_PROC_EXEC2;
3725 return VERR_HM_UNSUPPORTED_CPU_FEATURE_COMBO;
3726 }
3727
3728 /* Commit it to the VMCS and update our cache. */
3729 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC2, fVal);
3730 AssertRC(rc);
3731 pVmcsInfo->u32ProcCtls2 = fVal;
3732
3733 return VINF_SUCCESS;
3734}
3735
3736
3737/**
3738 * Sets up processor-based VM-execution controls in the VMCS.
3739 *
3740 * @returns VBox status code.
3741 * @param pVCpu The cross context virtual CPU structure.
3742 * @param pVmcsInfo The VMCS info. object.
3743 */
3744static int hmR0VmxSetupVmcsProcCtls(PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo)
3745{
3746 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
3747 uint32_t fVal = pVM->hm.s.vmx.Msrs.ProcCtls.n.allowed0; /* Bits set here must be set in the VMCS. */
3748 uint32_t const fZap = pVM->hm.s.vmx.Msrs.ProcCtls.n.allowed1; /* Bits cleared here must be cleared in the VMCS. */
3749
3750 fVal |= VMX_PROC_CTLS_HLT_EXIT /* HLT causes a VM-exit. */
3751 | VMX_PROC_CTLS_USE_TSC_OFFSETTING /* Use TSC-offsetting. */
3752 | VMX_PROC_CTLS_MOV_DR_EXIT /* MOV DRx causes a VM-exit. */
3753 | VMX_PROC_CTLS_UNCOND_IO_EXIT /* All IO instructions cause a VM-exit. */
3754 | VMX_PROC_CTLS_RDPMC_EXIT /* RDPMC causes a VM-exit. */
3755 | VMX_PROC_CTLS_MONITOR_EXIT /* MONITOR causes a VM-exit. */
3756 | VMX_PROC_CTLS_MWAIT_EXIT; /* MWAIT causes a VM-exit. */
3757
3758 /* We toggle VMX_PROC_CTLS_MOV_DR_EXIT later, check if it's not -always- needed to be set or clear. */
3759 if ( !(pVM->hm.s.vmx.Msrs.ProcCtls.n.allowed1 & VMX_PROC_CTLS_MOV_DR_EXIT)
3760 || (pVM->hm.s.vmx.Msrs.ProcCtls.n.allowed0 & VMX_PROC_CTLS_MOV_DR_EXIT))
3761 {
3762 pVCpu->hm.s.u32HMError = VMX_UFC_CTRL_PROC_MOV_DRX_EXIT;
3763 return VERR_HM_UNSUPPORTED_CPU_FEATURE_COMBO;
3764 }
3765
3766 /* Without nested paging, INVLPG (also affects INVPCID) and MOV CR3 instructions should cause VM-exits. */
3767 if (!pVM->hm.s.fNestedPaging)
3768 {
3769 Assert(!pVM->hm.s.vmx.fUnrestrictedGuest);
3770 fVal |= VMX_PROC_CTLS_INVLPG_EXIT
3771 | VMX_PROC_CTLS_CR3_LOAD_EXIT
3772 | VMX_PROC_CTLS_CR3_STORE_EXIT;
3773 }
3774
3775 /* Use TPR shadowing if supported by the CPU. */
3776 if ( PDMHasApic(pVM)
3777 && pVM->hm.s.vmx.Msrs.ProcCtls.n.allowed1 & VMX_PROC_CTLS_USE_TPR_SHADOW)
3778 {
3779 fVal |= VMX_PROC_CTLS_USE_TPR_SHADOW; /* CR8 reads from the Virtual-APIC page. */
3780 /* CR8 writes cause a VM-exit based on TPR threshold. */
3781 Assert(!(fVal & VMX_PROC_CTLS_CR8_STORE_EXIT));
3782 Assert(!(fVal & VMX_PROC_CTLS_CR8_LOAD_EXIT));
3783 hmR0VmxSetupVmcsVirtApicAddr(pVmcsInfo);
3784 }
3785 else
3786 {
3787 /* Some 32-bit CPUs do not support CR8 load/store exiting as MOV CR8 is
3788 invalid on 32-bit Intel CPUs. Set this control only for 64-bit guests. */
3789 if (pVM->hm.s.fAllow64BitGuests)
3790 {
3791 fVal |= VMX_PROC_CTLS_CR8_STORE_EXIT /* CR8 reads cause a VM-exit. */
3792 | VMX_PROC_CTLS_CR8_LOAD_EXIT; /* CR8 writes cause a VM-exit. */
3793 }
3794 }
3795
3796 /* Use MSR-bitmaps if supported by the CPU. */
3797 if (pVM->hm.s.vmx.Msrs.ProcCtls.n.allowed1 & VMX_PROC_CTLS_USE_MSR_BITMAPS)
3798 {
3799 fVal |= VMX_PROC_CTLS_USE_MSR_BITMAPS;
3800 hmR0VmxSetupVmcsMsrBitmapAddr(pVmcsInfo);
3801 }
3802
3803 /* Use the secondary processor-based VM-execution controls if supported by the CPU. */
3804 if (pVM->hm.s.vmx.Msrs.ProcCtls.n.allowed1 & VMX_PROC_CTLS_USE_SECONDARY_CTLS)
3805 fVal |= VMX_PROC_CTLS_USE_SECONDARY_CTLS;
3806
3807 if ((fVal & fZap) != fVal)
3808 {
3809 LogRelFunc(("Invalid processor-based VM-execution controls combo! cpu=%#RX32 fVal=%#RX32 fZap=%#RX32\n",
3810 pVM->hm.s.vmx.Msrs.ProcCtls.n.allowed0, fVal, fZap));
3811 pVCpu->hm.s.u32HMError = VMX_UFC_CTRL_PROC_EXEC;
3812 return VERR_HM_UNSUPPORTED_CPU_FEATURE_COMBO;
3813 }
3814
3815 /* Commit it to the VMCS and update our cache. */
3816 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, fVal);
3817 AssertRC(rc);
3818 pVmcsInfo->u32ProcCtls = fVal;
3819
3820 /* Set up MSR permissions that don't change through the lifetime of the VM. */
3821 if (pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_USE_MSR_BITMAPS)
3822 hmR0VmxSetupVmcsMsrPermissions(pVCpu, pVmcsInfo);
3823
3824 /* Set up secondary processor-based VM-execution controls if the CPU supports it. */
3825 if (pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_USE_SECONDARY_CTLS)
3826 return hmR0VmxSetupVmcsProcCtls2(pVCpu, pVmcsInfo);
3827
3828 /* Sanity check, should not really happen. */
3829 if (RT_LIKELY(!pVM->hm.s.vmx.fUnrestrictedGuest))
3830 { /* likely */ }
3831 else
3832 {
3833 pVCpu->hm.s.u32HMError = VMX_UFC_INVALID_UX_COMBO;
3834 return VERR_HM_UNSUPPORTED_CPU_FEATURE_COMBO;
3835 }
3836
3837 /* Old CPUs without secondary processor-based VM-execution controls would end up here. */
3838 return VINF_SUCCESS;
3839}
3840
3841
3842/**
3843 * Sets up miscellaneous (everything other than Pin, Processor and secondary
3844 * Processor-based VM-execution) control fields in the VMCS.
3845 *
3846 * @returns VBox status code.
3847 * @param pVCpu The cross context virtual CPU structure.
3848 * @param pVmcsInfo The VMCS info. object.
3849 */
3850static int hmR0VmxSetupVmcsMiscCtls(PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo)
3851{
3852#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
3853 if (pVCpu->CTX_SUFF(pVM)->hm.s.vmx.fUseVmcsShadowing)
3854 {
3855 hmR0VmxSetupVmcsVmreadBitmapAddr(pVCpu);
3856 hmR0VmxSetupVmcsVmwriteBitmapAddr(pVCpu);
3857 }
3858#endif
3859
3860 Assert(pVmcsInfo->u64VmcsLinkPtr == NIL_RTHCPHYS);
3861 int rc = VMXWriteVmcs64(VMX_VMCS64_GUEST_VMCS_LINK_PTR_FULL, NIL_RTHCPHYS);
3862 AssertRC(rc);
3863
3864 rc = hmR0VmxSetupVmcsAutoLoadStoreMsrAddrs(pVmcsInfo);
3865 if (RT_SUCCESS(rc))
3866 {
3867 uint64_t const u64Cr0Mask = hmR0VmxGetFixedCr0Mask(pVCpu);
3868 uint64_t const u64Cr4Mask = hmR0VmxGetFixedCr4Mask(pVCpu);
3869
3870 rc = VMXWriteVmcsNw(VMX_VMCS_CTRL_CR0_MASK, u64Cr0Mask); AssertRC(rc);
3871 rc = VMXWriteVmcsNw(VMX_VMCS_CTRL_CR4_MASK, u64Cr4Mask); AssertRC(rc);
3872
3873 pVmcsInfo->u64Cr0Mask = u64Cr0Mask;
3874 pVmcsInfo->u64Cr4Mask = u64Cr4Mask;
3875 return VINF_SUCCESS;
3876 }
3877 else
3878 LogRelFunc(("Failed to initialize VMCS auto-load/store MSR addresses. rc=%Rrc\n", rc));
3879 return rc;
3880}
3881
3882
3883/**
3884 * Sets up the initial exception bitmap in the VMCS based on static conditions.
3885 *
3886 * We shall setup those exception intercepts that don't change during the
3887 * lifetime of the VM here. The rest are done dynamically while loading the
3888 * guest state.
3889 *
3890 * @param pVCpu The cross context virtual CPU structure.
3891 * @param pVmcsInfo The VMCS info. object.
3892 */
3893static void hmR0VmxSetupVmcsXcptBitmap(PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo)
3894{
3895 /*
3896 * The following exceptions are always intercepted:
3897 *
3898 * #AC - To prevent the guest from hanging the CPU.
3899 * #DB - To maintain the DR6 state even when intercepting DRx reads/writes and
3900 * recursive #DBs can cause a CPU hang.
3901 * #PF - To sync our shadow page tables when nested-paging is not used.
3902 */
3903 bool const fNestedPaging = pVCpu->CTX_SUFF(pVM)->hm.s.fNestedPaging;
3904 uint32_t const uXcptBitmap = RT_BIT(X86_XCPT_AC)
3905 | RT_BIT(X86_XCPT_DB)
3906 | (fNestedPaging ? 0 : RT_BIT(X86_XCPT_PF));
3907
3908 /* Commit it to the VMCS. */
3909 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_EXCEPTION_BITMAP, uXcptBitmap);
3910 AssertRC(rc);
3911
3912 /* Update our cache of the exception bitmap. */
3913 pVmcsInfo->u32XcptBitmap = uXcptBitmap;
3914}
3915
3916
3917#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
3918/**
3919 * Sets up the VMCS for executing a nested-guest using hardware-assisted VMX.
3920 *
3921 * @returns VBox status code.
3922 * @param pVCpu The cross context virtual CPU structure.
3923 * @param pVmcsInfo The VMCS info. object.
3924 */
3925static int hmR0VmxSetupVmcsCtlsNested(PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo)
3926{
3927 Assert(pVmcsInfo->u64VmcsLinkPtr == NIL_RTHCPHYS);
3928 int rc = VMXWriteVmcs64(VMX_VMCS64_GUEST_VMCS_LINK_PTR_FULL, NIL_RTHCPHYS);
3929 AssertRC(rc);
3930
3931 rc = hmR0VmxSetupVmcsAutoLoadStoreMsrAddrs(pVmcsInfo);
3932 if (RT_SUCCESS(rc))
3933 {
3934 if (pVCpu->CTX_SUFF(pVM)->hm.s.vmx.Msrs.ProcCtls.n.allowed1 & VMX_PROC_CTLS_USE_MSR_BITMAPS)
3935 hmR0VmxSetupVmcsMsrBitmapAddr(pVmcsInfo);
3936
3937 /* Paranoia - We've not yet initialized these, they shall be done while merging the VMCS. */
3938 Assert(!pVmcsInfo->u64Cr0Mask);
3939 Assert(!pVmcsInfo->u64Cr4Mask);
3940 return VINF_SUCCESS;
3941 }
3942 else
3943 LogRelFunc(("Failed to set up the VMCS link pointer in the nested-guest VMCS. rc=%Rrc\n", rc));
3944 return rc;
3945}
3946#endif
3947
3948
3949/**
3950 * Sets up the VMCS for executing a guest (or nested-guest) using hardware-assisted
3951 * VMX.
3952 *
3953 * @returns VBox status code.
3954 * @param pVCpu The cross context virtual CPU structure.
3955 * @param pVmcsInfo The VMCS info. object.
3956 * @param fIsNstGstVmcs Whether this is a nested-guest VMCS.
3957 */
3958static int hmR0VmxSetupVmcs(PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo, bool fIsNstGstVmcs)
3959{
3960 Assert(pVmcsInfo->pvVmcs);
3961 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
3962
3963 /* Set the CPU specified revision identifier at the beginning of the VMCS structure. */
3964 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
3965 *(uint32_t *)pVmcsInfo->pvVmcs = RT_BF_GET(pVM->hm.s.vmx.Msrs.u64Basic, VMX_BF_BASIC_VMCS_ID);
3966 const char * const pszVmcs = fIsNstGstVmcs ? "nested-guest VMCS" : "guest VMCS";
3967
3968 LogFlowFunc(("\n"));
3969
3970 /*
3971 * Initialize the VMCS using VMCLEAR before loading the VMCS.
3972 * See Intel spec. 31.6 "Preparation And Launching A Virtual Machine".
3973 */
3974 int rc = hmR0VmxClearVmcs(pVmcsInfo);
3975 if (RT_SUCCESS(rc))
3976 {
3977 rc = hmR0VmxLoadVmcs(pVmcsInfo);
3978 if (RT_SUCCESS(rc))
3979 {
3980 if (!fIsNstGstVmcs)
3981 {
3982 rc = hmR0VmxSetupVmcsPinCtls(pVCpu, pVmcsInfo);
3983 if (RT_SUCCESS(rc))
3984 {
3985 rc = hmR0VmxSetupVmcsProcCtls(pVCpu, pVmcsInfo);
3986 if (RT_SUCCESS(rc))
3987 {
3988 rc = hmR0VmxSetupVmcsMiscCtls(pVCpu, pVmcsInfo);
3989 if (RT_SUCCESS(rc))
3990 {
3991 hmR0VmxSetupVmcsXcptBitmap(pVCpu, pVmcsInfo);
3992#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
3993 /*
3994 * If a shadow VMCS is allocated for the VMCS info. object, initialize the
3995 * VMCS revision ID and shadow VMCS indicator bit. Also, clear the VMCS
3996 * making it fit for use when VMCS shadowing is later enabled.
3997 */
3998 if (pVmcsInfo->pvShadowVmcs)
3999 {
4000 VMXVMCSREVID VmcsRevId;
4001 VmcsRevId.u = RT_BF_GET(pVM->hm.s.vmx.Msrs.u64Basic, VMX_BF_BASIC_VMCS_ID);
4002 VmcsRevId.n.fIsShadowVmcs = 1;
4003 *(uint32_t *)pVmcsInfo->pvShadowVmcs = VmcsRevId.u;
4004 rc = hmR0VmxClearShadowVmcs(pVmcsInfo);
4005 if (RT_SUCCESS(rc))
4006 { /* likely */ }
4007 else
4008 LogRelFunc(("Failed to initialize shadow VMCS. rc=%Rrc\n", rc));
4009 }
4010#endif
4011 }
4012 else
4013 LogRelFunc(("Failed to setup miscellaneous controls. rc=%Rrc\n", rc));
4014 }
4015 else
4016 LogRelFunc(("Failed to setup processor-based VM-execution controls. rc=%Rrc\n", rc));
4017 }
4018 else
4019 LogRelFunc(("Failed to setup pin-based controls. rc=%Rrc\n", rc));
4020 }
4021 else
4022 {
4023#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
4024 rc = hmR0VmxSetupVmcsCtlsNested(pVCpu, pVmcsInfo);
4025 if (RT_SUCCESS(rc))
4026 { /* likely */ }
4027 else
4028 LogRelFunc(("Failed to initialize nested-guest VMCS. rc=%Rrc\n", rc));
4029#else
4030 AssertFailed();
4031#endif
4032 }
4033 }
4034 else
4035 LogRelFunc(("Failed to load the %s. rc=%Rrc\n", rc, pszVmcs));
4036 }
4037 else
4038 LogRelFunc(("Failed to clear the %s. rc=%Rrc\n", rc, pszVmcs));
4039
4040 /* Sync any CPU internal VMCS data back into our VMCS in memory. */
4041 if (RT_SUCCESS(rc))
4042 {
4043 rc = hmR0VmxClearVmcs(pVmcsInfo);
4044 if (RT_SUCCESS(rc))
4045 { /* likely */ }
4046 else
4047 LogRelFunc(("Failed to clear the %s post setup. rc=%Rrc\n", rc, pszVmcs));
4048 }
4049
4050 /*
4051 * Update the last-error record both for failures and success, so we
4052 * can propagate the status code back to ring-3 for diagnostics.
4053 */
4054 hmR0VmxUpdateErrorRecord(pVCpu, rc);
4055 NOREF(pszVmcs);
4056 return rc;
4057}
4058
4059
4060/**
4061 * Does global VT-x initialization (called during module initialization).
4062 *
4063 * @returns VBox status code.
4064 */
4065VMMR0DECL(int) VMXR0GlobalInit(void)
4066{
4067#ifdef HMVMX_USE_FUNCTION_TABLE
4068 AssertCompile(VMX_EXIT_MAX + 1 == RT_ELEMENTS(g_apfnVMExitHandlers));
4069# ifdef VBOX_STRICT
4070 for (unsigned i = 0; i < RT_ELEMENTS(g_apfnVMExitHandlers); i++)
4071 Assert(g_apfnVMExitHandlers[i]);
4072# endif
4073#endif
4074 return VINF_SUCCESS;
4075}
4076
4077
4078/**
4079 * Does global VT-x termination (called during module termination).
4080 */
4081VMMR0DECL(void) VMXR0GlobalTerm()
4082{
4083 /* Nothing to do currently. */
4084}
4085
4086
4087/**
4088 * Sets up and activates VT-x on the current CPU.
4089 *
4090 * @returns VBox status code.
4091 * @param pHostCpu The HM physical-CPU structure.
4092 * @param pVM The cross context VM structure. Can be
4093 * NULL after a host resume operation.
4094 * @param pvCpuPage Pointer to the VMXON region (can be NULL if @a
4095 * fEnabledByHost is @c true).
4096 * @param HCPhysCpuPage Physical address of the VMXON region (can be 0 if
4097 * @a fEnabledByHost is @c true).
4098 * @param fEnabledByHost Set if SUPR0EnableVTx() or similar was used to
4099 * enable VT-x on the host.
4100 * @param pHwvirtMsrs Pointer to the hardware-virtualization MSRs.
4101 */
4102VMMR0DECL(int) VMXR0EnableCpu(PHMPHYSCPU pHostCpu, PVMCC pVM, void *pvCpuPage, RTHCPHYS HCPhysCpuPage, bool fEnabledByHost,
4103 PCSUPHWVIRTMSRS pHwvirtMsrs)
4104{
4105 AssertPtr(pHostCpu);
4106 AssertPtr(pHwvirtMsrs);
4107 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
4108
4109 /* Enable VT-x if it's not already enabled by the host. */
4110 if (!fEnabledByHost)
4111 {
4112 int rc = hmR0VmxEnterRootMode(pHostCpu, pVM, HCPhysCpuPage, pvCpuPage);
4113 if (RT_FAILURE(rc))
4114 return rc;
4115 }
4116
4117 /*
4118 * Flush all EPT tagged-TLB entries (in case VirtualBox or any other hypervisor have been
4119 * using EPTPs) so we don't retain any stale guest-physical mappings which won't get
4120 * invalidated when flushing by VPID.
4121 */
4122 if (pHwvirtMsrs->u.vmx.u64EptVpidCaps & MSR_IA32_VMX_EPT_VPID_CAP_INVEPT_ALL_CONTEXTS)
4123 {
4124 hmR0VmxFlushEpt(NULL /* pVCpu */, NULL /* pVmcsInfo */, VMXTLBFLUSHEPT_ALL_CONTEXTS);
4125 pHostCpu->fFlushAsidBeforeUse = false;
4126 }
4127 else
4128 pHostCpu->fFlushAsidBeforeUse = true;
4129
4130 /* Ensure each VCPU scheduled on this CPU gets a new VPID on resume. See @bugref{6255}. */
4131 ++pHostCpu->cTlbFlushes;
4132
4133 return VINF_SUCCESS;
4134}
4135
4136
4137/**
4138 * Deactivates VT-x on the current CPU.
4139 *
4140 * @returns VBox status code.
4141 * @param pHostCpu The HM physical-CPU structure.
4142 * @param pvCpuPage Pointer to the VMXON region.
4143 * @param HCPhysCpuPage Physical address of the VMXON region.
4144 *
4145 * @remarks This function should never be called when SUPR0EnableVTx() or
4146 * similar was used to enable VT-x on the host.
4147 */
4148VMMR0DECL(int) VMXR0DisableCpu(PHMPHYSCPU pHostCpu, void *pvCpuPage, RTHCPHYS HCPhysCpuPage)
4149{
4150 RT_NOREF2(pvCpuPage, HCPhysCpuPage);
4151
4152 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
4153 return hmR0VmxLeaveRootMode(pHostCpu);
4154}
4155
4156
4157/**
4158 * Does per-VM VT-x initialization.
4159 *
4160 * @returns VBox status code.
4161 * @param pVM The cross context VM structure.
4162 */
4163VMMR0DECL(int) VMXR0InitVM(PVMCC pVM)
4164{
4165 AssertPtr(pVM);
4166 LogFlowFunc(("pVM=%p\n", pVM));
4167
4168 hmR0VmxStructsInit(pVM);
4169 int rc = hmR0VmxStructsAlloc(pVM);
4170 if (RT_FAILURE(rc))
4171 {
4172 LogRelFunc(("Failed to allocated VMX structures. rc=%Rrc\n", rc));
4173 return rc;
4174 }
4175
4176 /* Setup the crash dump page. */
4177#ifdef VBOX_WITH_CRASHDUMP_MAGIC
4178 strcpy((char *)pVM->hm.s.vmx.pbScratch, "SCRATCH Magic");
4179 *(uint64_t *)(pVM->hm.s.vmx.pbScratch + 16) = UINT64_C(0xdeadbeefdeadbeef);
4180#endif
4181 return VINF_SUCCESS;
4182}
4183
4184
4185/**
4186 * Does per-VM VT-x termination.
4187 *
4188 * @returns VBox status code.
4189 * @param pVM The cross context VM structure.
4190 */
4191VMMR0DECL(int) VMXR0TermVM(PVMCC pVM)
4192{
4193 AssertPtr(pVM);
4194 LogFlowFunc(("pVM=%p\n", pVM));
4195
4196#ifdef VBOX_WITH_CRASHDUMP_MAGIC
4197 if (pVM->hm.s.vmx.hMemObjScratch != NIL_RTR0MEMOBJ)
4198 {
4199 Assert(pVM->hm.s.vmx.pvScratch);
4200 ASMMemZero32(pVM->hm.s.vmx.pvScratch, X86_PAGE_4K_SIZE);
4201 }
4202#endif
4203 hmR0VmxStructsFree(pVM);
4204 return VINF_SUCCESS;
4205}
4206
4207
4208/**
4209 * Sets up the VM for execution using hardware-assisted VMX.
4210 * This function is only called once per-VM during initialization.
4211 *
4212 * @returns VBox status code.
4213 * @param pVM The cross context VM structure.
4214 */
4215VMMR0DECL(int) VMXR0SetupVM(PVMCC pVM)
4216{
4217 AssertPtr(pVM);
4218 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
4219
4220 LogFlowFunc(("pVM=%p\n", pVM));
4221
4222 /*
4223 * At least verify if VMX is enabled, since we can't check if we're in VMX root mode or not
4224 * without causing a #GP.
4225 */
4226 RTCCUINTREG const uHostCr4 = ASMGetCR4();
4227 if (RT_LIKELY(uHostCr4 & X86_CR4_VMXE))
4228 { /* likely */ }
4229 else
4230 return VERR_VMX_NOT_IN_VMX_ROOT_MODE;
4231
4232 /*
4233 * Without unrestricted guest execution, pRealModeTSS and pNonPagingModeEPTPageTable *must*
4234 * always be allocated. We no longer support the highly unlikely case of unrestricted guest
4235 * without pRealModeTSS, see hmR3InitFinalizeR0Intel().
4236 */
4237 if ( !pVM->hm.s.vmx.fUnrestrictedGuest
4238 && ( !pVM->hm.s.vmx.pNonPagingModeEPTPageTable
4239 || !pVM->hm.s.vmx.pRealModeTSS))
4240 {
4241 LogRelFunc(("Invalid real-on-v86 state.\n"));
4242 return VERR_INTERNAL_ERROR;
4243 }
4244
4245 /* Initialize these always, see hmR3InitFinalizeR0().*/
4246 pVM->hm.s.vmx.enmTlbFlushEpt = VMXTLBFLUSHEPT_NONE;
4247 pVM->hm.s.vmx.enmTlbFlushVpid = VMXTLBFLUSHVPID_NONE;
4248
4249 /* Setup the tagged-TLB flush handlers. */
4250 int rc = hmR0VmxSetupTaggedTlb(pVM);
4251 if (RT_FAILURE(rc))
4252 {
4253 LogRelFunc(("Failed to setup tagged TLB. rc=%Rrc\n", rc));
4254 return rc;
4255 }
4256
4257#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
4258 /* Setup the shadow VMCS fields array and VMREAD/VMWRITE bitmaps. */
4259 if (pVM->hm.s.vmx.fUseVmcsShadowing)
4260 {
4261 rc = hmR0VmxSetupShadowVmcsFieldsArrays(pVM);
4262 if (RT_SUCCESS(rc))
4263 hmR0VmxSetupVmreadVmwriteBitmaps(pVM);
4264 else
4265 {
4266 LogRelFunc(("Failed to setup shadow VMCS fields arrays. rc=%Rrc\n", rc));
4267 return rc;
4268 }
4269 }
4270#endif
4271
4272 for (VMCPUID idCpu = 0; idCpu < pVM->cCpus; idCpu++)
4273 {
4274 PVMCPUCC pVCpu = VMCC_GET_CPU(pVM, idCpu);
4275 Log4Func(("pVCpu=%p idCpu=%RU32\n", pVCpu, pVCpu->idCpu));
4276
4277 rc = hmR0VmxSetupVmcs(pVCpu, &pVCpu->hm.s.vmx.VmcsInfo, false /* fIsNstGstVmcs */);
4278 if (RT_SUCCESS(rc))
4279 {
4280#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
4281 if (pVM->cpum.ro.GuestFeatures.fVmx)
4282 {
4283 rc = hmR0VmxSetupVmcs(pVCpu, &pVCpu->hm.s.vmx.VmcsInfoNstGst, true /* fIsNstGstVmcs */);
4284 if (RT_SUCCESS(rc))
4285 { /* likely */ }
4286 else
4287 {
4288 LogRelFunc(("Nested-guest VMCS setup failed. rc=%Rrc\n", rc));
4289 return rc;
4290 }
4291 }
4292#endif
4293 }
4294 else
4295 {
4296 LogRelFunc(("VMCS setup failed. rc=%Rrc\n", rc));
4297 return rc;
4298 }
4299 }
4300
4301 return VINF_SUCCESS;
4302}
4303
4304
4305/**
4306 * Saves the host control registers (CR0, CR3, CR4) into the host-state area in
4307 * the VMCS.
4308 */
4309static void hmR0VmxExportHostControlRegs(void)
4310{
4311 int rc = VMXWriteVmcsNw(VMX_VMCS_HOST_CR0, ASMGetCR0()); AssertRC(rc);
4312 rc = VMXWriteVmcsNw(VMX_VMCS_HOST_CR3, ASMGetCR3()); AssertRC(rc);
4313 rc = VMXWriteVmcsNw(VMX_VMCS_HOST_CR4, ASMGetCR4()); AssertRC(rc);
4314}
4315
4316
4317/**
4318 * Saves the host segment registers and GDTR, IDTR, (TR, GS and FS bases) into
4319 * the host-state area in the VMCS.
4320 *
4321 * @returns VBox status code.
4322 * @param pVCpu The cross context virtual CPU structure.
4323 */
4324static int hmR0VmxExportHostSegmentRegs(PVMCPUCC pVCpu)
4325{
4326/**
4327 * Macro for adjusting host segment selectors to satisfy VT-x's VM-entry
4328 * requirements. See hmR0VmxExportHostSegmentRegs().
4329 */
4330#define VMXLOCAL_ADJUST_HOST_SEG(a_Seg, a_selValue) \
4331 if ((a_selValue) & (X86_SEL_RPL | X86_SEL_LDT)) \
4332 { \
4333 bool fValidSelector = true; \
4334 if ((a_selValue) & X86_SEL_LDT) \
4335 { \
4336 uint32_t const uAttr = ASMGetSegAttr(a_selValue); \
4337 fValidSelector = RT_BOOL(uAttr != UINT32_MAX && (uAttr & X86_DESC_P)); \
4338 } \
4339 if (fValidSelector) \
4340 { \
4341 pVCpu->hm.s.vmx.fRestoreHostFlags |= VMX_RESTORE_HOST_SEL_##a_Seg; \
4342 pVCpu->hm.s.vmx.RestoreHost.uHostSel##a_Seg = (a_selValue); \
4343 } \
4344 (a_selValue) = 0; \
4345 }
4346
4347 /*
4348 * If we've executed guest code using hardware-assisted VMX, the host-state bits
4349 * will be messed up. We should -not- save the messed up state without restoring
4350 * the original host-state, see @bugref{7240}.
4351 *
4352 * This apparently can happen (most likely the FPU changes), deal with it rather than
4353 * asserting. Was observed booting Solaris 10u10 32-bit guest.
4354 */
4355 if ( (pVCpu->hm.s.vmx.fRestoreHostFlags & VMX_RESTORE_HOST_REQUIRED)
4356 && (pVCpu->hm.s.vmx.fRestoreHostFlags & ~VMX_RESTORE_HOST_REQUIRED))
4357 {
4358 Log4Func(("Restoring Host State: fRestoreHostFlags=%#RX32 HostCpuId=%u\n", pVCpu->hm.s.vmx.fRestoreHostFlags,
4359 pVCpu->idCpu));
4360 VMXRestoreHostState(pVCpu->hm.s.vmx.fRestoreHostFlags, &pVCpu->hm.s.vmx.RestoreHost);
4361 }
4362 pVCpu->hm.s.vmx.fRestoreHostFlags = 0;
4363
4364 /*
4365 * Host segment registers.
4366 */
4367 RTSEL uSelES = ASMGetES();
4368 RTSEL uSelCS = ASMGetCS();
4369 RTSEL uSelSS = ASMGetSS();
4370 RTSEL uSelDS = ASMGetDS();
4371 RTSEL uSelFS = ASMGetFS();
4372 RTSEL uSelGS = ASMGetGS();
4373 RTSEL uSelTR = ASMGetTR();
4374
4375 /*
4376 * Determine if the host segment registers are suitable for VT-x. Otherwise use zero to
4377 * gain VM-entry and restore them before we get preempted.
4378 *
4379 * See Intel spec. 26.2.3 "Checks on Host Segment and Descriptor-Table Registers".
4380 */
4381 VMXLOCAL_ADJUST_HOST_SEG(DS, uSelDS);
4382 VMXLOCAL_ADJUST_HOST_SEG(ES, uSelES);
4383 VMXLOCAL_ADJUST_HOST_SEG(FS, uSelFS);
4384 VMXLOCAL_ADJUST_HOST_SEG(GS, uSelGS);
4385
4386 /* Verification based on Intel spec. 26.2.3 "Checks on Host Segment and Descriptor-Table Registers" */
4387 Assert(!(uSelCS & X86_SEL_RPL)); Assert(!(uSelCS & X86_SEL_LDT));
4388 Assert(!(uSelSS & X86_SEL_RPL)); Assert(!(uSelSS & X86_SEL_LDT));
4389 Assert(!(uSelDS & X86_SEL_RPL)); Assert(!(uSelDS & X86_SEL_LDT));
4390 Assert(!(uSelES & X86_SEL_RPL)); Assert(!(uSelES & X86_SEL_LDT));
4391 Assert(!(uSelFS & X86_SEL_RPL)); Assert(!(uSelFS & X86_SEL_LDT));
4392 Assert(!(uSelGS & X86_SEL_RPL)); Assert(!(uSelGS & X86_SEL_LDT));
4393 Assert(!(uSelTR & X86_SEL_RPL)); Assert(!(uSelTR & X86_SEL_LDT));
4394 Assert(uSelCS);
4395 Assert(uSelTR);
4396
4397 /* Write these host selector fields into the host-state area in the VMCS. */
4398 int rc = VMXWriteVmcs16(VMX_VMCS16_HOST_CS_SEL, uSelCS); AssertRC(rc);
4399 rc = VMXWriteVmcs16(VMX_VMCS16_HOST_SS_SEL, uSelSS); AssertRC(rc);
4400 rc = VMXWriteVmcs16(VMX_VMCS16_HOST_DS_SEL, uSelDS); AssertRC(rc);
4401 rc = VMXWriteVmcs16(VMX_VMCS16_HOST_ES_SEL, uSelES); AssertRC(rc);
4402 rc = VMXWriteVmcs16(VMX_VMCS16_HOST_FS_SEL, uSelFS); AssertRC(rc);
4403 rc = VMXWriteVmcs16(VMX_VMCS16_HOST_GS_SEL, uSelGS); AssertRC(rc);
4404 rc = VMXWriteVmcs16(VMX_VMCS16_HOST_TR_SEL, uSelTR); AssertRC(rc);
4405
4406 /*
4407 * Host GDTR and IDTR.
4408 */
4409 RTGDTR Gdtr;
4410 RTIDTR Idtr;
4411 RT_ZERO(Gdtr);
4412 RT_ZERO(Idtr);
4413 ASMGetGDTR(&Gdtr);
4414 ASMGetIDTR(&Idtr);
4415 rc = VMXWriteVmcsNw(VMX_VMCS_HOST_GDTR_BASE, Gdtr.pGdt); AssertRC(rc);
4416 rc = VMXWriteVmcsNw(VMX_VMCS_HOST_IDTR_BASE, Idtr.pIdt); AssertRC(rc);
4417
4418 /*
4419 * Determine if we need to manually need to restore the GDTR and IDTR limits as VT-x zaps
4420 * them to the maximum limit (0xffff) on every VM-exit.
4421 */
4422 if (Gdtr.cbGdt != 0xffff)
4423 pVCpu->hm.s.vmx.fRestoreHostFlags |= VMX_RESTORE_HOST_GDTR;
4424
4425 /*
4426 * IDT limit is effectively capped at 0xfff. (See Intel spec. 6.14.1 "64-Bit Mode IDT" and
4427 * Intel spec. 6.2 "Exception and Interrupt Vectors".) Therefore if the host has the limit
4428 * as 0xfff, VT-x bloating the limit to 0xffff shouldn't cause any different CPU behavior.
4429 * However, several hosts either insists on 0xfff being the limit (Windows Patch Guard) or
4430 * uses the limit for other purposes (darwin puts the CPU ID in there but botches sidt
4431 * alignment in at least one consumer). So, we're only allowing the IDTR.LIMIT to be left
4432 * at 0xffff on hosts where we are sure it won't cause trouble.
4433 */
4434#if defined(RT_OS_LINUX) || defined(RT_OS_SOLARIS)
4435 if (Idtr.cbIdt < 0x0fff)
4436#else
4437 if (Idtr.cbIdt != 0xffff)
4438#endif
4439 {
4440 pVCpu->hm.s.vmx.fRestoreHostFlags |= VMX_RESTORE_HOST_IDTR;
4441 AssertCompile(sizeof(Idtr) == sizeof(X86XDTR64));
4442 memcpy(&pVCpu->hm.s.vmx.RestoreHost.HostIdtr, &Idtr, sizeof(X86XDTR64));
4443 }
4444
4445 /*
4446 * Host TR base. Verify that TR selector doesn't point past the GDT. Masking off the TI
4447 * and RPL bits is effectively what the CPU does for "scaling by 8". TI is always 0 and
4448 * RPL should be too in most cases.
4449 */
4450 AssertMsgReturn((uSelTR | X86_SEL_RPL_LDT) <= Gdtr.cbGdt,
4451 ("TR selector exceeds limit. TR=%RTsel cbGdt=%#x\n", uSelTR, Gdtr.cbGdt), VERR_VMX_INVALID_HOST_STATE);
4452
4453 PCX86DESCHC pDesc = (PCX86DESCHC)(Gdtr.pGdt + (uSelTR & X86_SEL_MASK));
4454 uintptr_t const uTRBase = X86DESC64_BASE(pDesc);
4455
4456 /*
4457 * VT-x unconditionally restores the TR limit to 0x67 and type to 11 (32-bit busy TSS) on
4458 * all VM-exits. The type is the same for 64-bit busy TSS[1]. The limit needs manual
4459 * restoration if the host has something else. Task switching is not supported in 64-bit
4460 * mode[2], but the limit still matters as IOPM is supported in 64-bit mode. Restoring the
4461 * limit lazily while returning to ring-3 is safe because IOPM is not applicable in ring-0.
4462 *
4463 * [1] See Intel spec. 3.5 "System Descriptor Types".
4464 * [2] See Intel spec. 7.2.3 "TSS Descriptor in 64-bit mode".
4465 */
4466 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
4467 Assert(pDesc->System.u4Type == 11);
4468 if ( pDesc->System.u16LimitLow != 0x67
4469 || pDesc->System.u4LimitHigh)
4470 {
4471 pVCpu->hm.s.vmx.fRestoreHostFlags |= VMX_RESTORE_HOST_SEL_TR;
4472 /* If the host has made GDT read-only, we would need to temporarily toggle CR0.WP before writing the GDT. */
4473 if (pVM->hm.s.fHostKernelFeatures & SUPKERNELFEATURES_GDT_READ_ONLY)
4474 pVCpu->hm.s.vmx.fRestoreHostFlags |= VMX_RESTORE_HOST_GDT_READ_ONLY;
4475 pVCpu->hm.s.vmx.RestoreHost.uHostSelTR = uSelTR;
4476 }
4477
4478 /*
4479 * Store the GDTR as we need it when restoring the GDT and while restoring the TR.
4480 */
4481 if (pVCpu->hm.s.vmx.fRestoreHostFlags & (VMX_RESTORE_HOST_GDTR | VMX_RESTORE_HOST_SEL_TR))
4482 {
4483 AssertCompile(sizeof(Gdtr) == sizeof(X86XDTR64));
4484 memcpy(&pVCpu->hm.s.vmx.RestoreHost.HostGdtr, &Gdtr, sizeof(X86XDTR64));
4485 if (pVM->hm.s.fHostKernelFeatures & SUPKERNELFEATURES_GDT_NEED_WRITABLE)
4486 {
4487 /* The GDT is read-only but the writable GDT is available. */
4488 pVCpu->hm.s.vmx.fRestoreHostFlags |= VMX_RESTORE_HOST_GDT_NEED_WRITABLE;
4489 pVCpu->hm.s.vmx.RestoreHost.HostGdtrRw.cb = Gdtr.cbGdt;
4490 rc = SUPR0GetCurrentGdtRw(&pVCpu->hm.s.vmx.RestoreHost.HostGdtrRw.uAddr);
4491 AssertRCReturn(rc, rc);
4492 }
4493 }
4494
4495 rc = VMXWriteVmcsNw(VMX_VMCS_HOST_TR_BASE, uTRBase);
4496 AssertRC(rc);
4497
4498 /*
4499 * Host FS base and GS base.
4500 */
4501 uint64_t const u64FSBase = ASMRdMsr(MSR_K8_FS_BASE);
4502 uint64_t const u64GSBase = ASMRdMsr(MSR_K8_GS_BASE);
4503 rc = VMXWriteVmcsNw(VMX_VMCS_HOST_FS_BASE, u64FSBase); AssertRC(rc);
4504 rc = VMXWriteVmcsNw(VMX_VMCS_HOST_GS_BASE, u64GSBase); AssertRC(rc);
4505
4506 /* Store the base if we have to restore FS or GS manually as we need to restore the base as well. */
4507 if (pVCpu->hm.s.vmx.fRestoreHostFlags & VMX_RESTORE_HOST_SEL_FS)
4508 pVCpu->hm.s.vmx.RestoreHost.uHostFSBase = u64FSBase;
4509 if (pVCpu->hm.s.vmx.fRestoreHostFlags & VMX_RESTORE_HOST_SEL_GS)
4510 pVCpu->hm.s.vmx.RestoreHost.uHostGSBase = u64GSBase;
4511
4512 return VINF_SUCCESS;
4513#undef VMXLOCAL_ADJUST_HOST_SEG
4514}
4515
4516
4517/**
4518 * Exports certain host MSRs in the VM-exit MSR-load area and some in the
4519 * host-state area of the VMCS.
4520 *
4521 * These MSRs will be automatically restored on the host after every successful
4522 * VM-exit.
4523 *
4524 * @param pVCpu The cross context virtual CPU structure.
4525 *
4526 * @remarks No-long-jump zone!!!
4527 */
4528static void hmR0VmxExportHostMsrs(PVMCPUCC pVCpu)
4529{
4530 AssertPtr(pVCpu);
4531
4532 /*
4533 * Save MSRs that we restore lazily (due to preemption or transition to ring-3)
4534 * rather than swapping them on every VM-entry.
4535 */
4536 hmR0VmxLazySaveHostMsrs(pVCpu);
4537
4538 /*
4539 * Host Sysenter MSRs.
4540 */
4541 int rc = VMXWriteVmcs32(VMX_VMCS32_HOST_SYSENTER_CS, ASMRdMsr_Low(MSR_IA32_SYSENTER_CS)); AssertRC(rc);
4542 rc = VMXWriteVmcsNw(VMX_VMCS_HOST_SYSENTER_ESP, ASMRdMsr(MSR_IA32_SYSENTER_ESP)); AssertRC(rc);
4543 rc = VMXWriteVmcsNw(VMX_VMCS_HOST_SYSENTER_EIP, ASMRdMsr(MSR_IA32_SYSENTER_EIP)); AssertRC(rc);
4544
4545 /*
4546 * Host EFER MSR.
4547 *
4548 * If the CPU supports the newer VMCS controls for managing EFER, use it. Otherwise it's
4549 * done as part of auto-load/store MSR area in the VMCS, see hmR0VmxExportGuestMsrs().
4550 */
4551 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
4552 if (pVM->hm.s.vmx.fSupportsVmcsEfer)
4553 {
4554 rc = VMXWriteVmcs64(VMX_VMCS64_HOST_EFER_FULL, pVM->hm.s.vmx.u64HostMsrEfer);
4555 AssertRC(rc);
4556 }
4557
4558 /** @todo IA32_PERF_GLOBALCTRL, IA32_PAT also see
4559 * hmR0VmxExportGuestEntryExitCtls(). */
4560}
4561
4562
4563/**
4564 * Figures out if we need to swap the EFER MSR which is particularly expensive.
4565 *
4566 * We check all relevant bits. For now, that's everything besides LMA/LME, as
4567 * these two bits are handled by VM-entry, see hmR0VMxExportGuestEntryExitCtls().
4568 *
4569 * @returns true if we need to load guest EFER, false otherwise.
4570 * @param pVCpu The cross context virtual CPU structure.
4571 * @param pVmxTransient The VMX-transient structure.
4572 *
4573 * @remarks Requires EFER, CR4.
4574 * @remarks No-long-jump zone!!!
4575 */
4576static bool hmR0VmxShouldSwapEferMsr(PCVMCPUCC pVCpu, PCVMXTRANSIENT pVmxTransient)
4577{
4578#ifdef HMVMX_ALWAYS_SWAP_EFER
4579 RT_NOREF2(pVCpu, pVmxTransient);
4580 return true;
4581#else
4582 PCCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
4583 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
4584 uint64_t const u64HostEfer = pVM->hm.s.vmx.u64HostMsrEfer;
4585 uint64_t const u64GuestEfer = pCtx->msrEFER;
4586
4587# ifdef VBOX_WITH_NESTED_HWVIRT_VMX
4588 /*
4589 * For nested-guests, we shall honor swapping the EFER MSR when requested by
4590 * the nested-guest.
4591 */
4592 if ( pVmxTransient->fIsNestedGuest
4593 && ( CPUMIsGuestVmxEntryCtlsSet(pCtx, VMX_ENTRY_CTLS_LOAD_EFER_MSR)
4594 || CPUMIsGuestVmxExitCtlsSet(pCtx, VMX_EXIT_CTLS_SAVE_EFER_MSR)
4595 || CPUMIsGuestVmxExitCtlsSet(pCtx, VMX_EXIT_CTLS_LOAD_EFER_MSR)))
4596 return true;
4597# else
4598 RT_NOREF(pVmxTransient);
4599#endif
4600
4601 /*
4602 * For 64-bit guests, if EFER.SCE bit differs, we need to swap the EFER MSR
4603 * to ensure that the guest's SYSCALL behaviour isn't broken, see @bugref{7386}.
4604 */
4605 if ( CPUMIsGuestInLongModeEx(pCtx)
4606 && (u64GuestEfer & MSR_K6_EFER_SCE) != (u64HostEfer & MSR_K6_EFER_SCE))
4607 return true;
4608
4609 /*
4610 * If the guest uses PAE and EFER.NXE bit differs, we need to swap the EFER MSR
4611 * as it affects guest paging. 64-bit paging implies CR4.PAE as well.
4612 *
4613 * See Intel spec. 4.5 "IA-32e Paging".
4614 * See Intel spec. 4.1.1 "Three Paging Modes".
4615 *
4616 * Verify that we always intercept CR4.PAE and CR0.PG bits, so we don't need to
4617 * import CR4 and CR0 from the VMCS here as those bits are always up to date.
4618 */
4619 Assert(hmR0VmxGetFixedCr4Mask(pVCpu) & X86_CR4_PAE);
4620 Assert(hmR0VmxGetFixedCr0Mask(pVCpu) & X86_CR0_PG);
4621 if ( (pCtx->cr4 & X86_CR4_PAE)
4622 && (pCtx->cr0 & X86_CR0_PG))
4623 {
4624 /*
4625 * If nested paging is not used, verify that the guest paging mode matches the
4626 * shadow paging mode which is/will be placed in the VMCS (which is what will
4627 * actually be used while executing the guest and not the CR4 shadow value).
4628 */
4629 AssertMsg(pVM->hm.s.fNestedPaging || ( pVCpu->hm.s.enmShadowMode == PGMMODE_PAE
4630 || pVCpu->hm.s.enmShadowMode == PGMMODE_PAE_NX
4631 || pVCpu->hm.s.enmShadowMode == PGMMODE_AMD64
4632 || pVCpu->hm.s.enmShadowMode == PGMMODE_AMD64_NX),
4633 ("enmShadowMode=%u\n", pVCpu->hm.s.enmShadowMode));
4634 if ((u64GuestEfer & MSR_K6_EFER_NXE) != (u64HostEfer & MSR_K6_EFER_NXE))
4635 {
4636 /* Verify that the host is NX capable. */
4637 Assert(pVCpu->CTX_SUFF(pVM)->cpum.ro.HostFeatures.fNoExecute);
4638 return true;
4639 }
4640 }
4641
4642 return false;
4643#endif
4644}
4645
4646
4647/**
4648 * Exports the guest state with appropriate VM-entry and VM-exit controls in the
4649 * VMCS.
4650 *
4651 * This is typically required when the guest changes paging mode.
4652 *
4653 * @returns VBox status code.
4654 * @param pVCpu The cross context virtual CPU structure.
4655 * @param pVmxTransient The VMX-transient structure.
4656 *
4657 * @remarks Requires EFER.
4658 * @remarks No-long-jump zone!!!
4659 */
4660static int hmR0VmxExportGuestEntryExitCtls(PVMCPUCC pVCpu, PCVMXTRANSIENT pVmxTransient)
4661{
4662 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_VMX_ENTRY_EXIT_CTLS)
4663 {
4664 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
4665 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
4666 bool const fGstInLongMode = CPUMIsGuestInLongModeEx(&pVCpu->cpum.GstCtx);
4667
4668 /*
4669 * VMRUN function.
4670 * If the guest is in long mode, use the 64-bit guest handler, else the 32-bit guest handler.
4671 * The host is always 64-bit since we no longer support 32-bit hosts.
4672 */
4673 if (fGstInLongMode)
4674 {
4675#ifndef VBOX_WITH_64_BITS_GUESTS
4676 return VERR_PGM_UNSUPPORTED_SHADOW_PAGING_MODE;
4677#else
4678 Assert(pVM->hm.s.fAllow64BitGuests); /* Guaranteed by hmR3InitFinalizeR0(). */
4679 pVmcsInfo->pfnStartVM = VMXR0StartVM64;
4680#endif
4681 }
4682 else
4683 pVmcsInfo->pfnStartVM = VMXR0StartVM32;
4684
4685 /*
4686 * VM-entry controls.
4687 */
4688 {
4689 uint32_t fVal = pVM->hm.s.vmx.Msrs.EntryCtls.n.allowed0; /* Bits set here must be set in the VMCS. */
4690 uint32_t const fZap = pVM->hm.s.vmx.Msrs.EntryCtls.n.allowed1; /* Bits cleared here must be cleared in the VMCS. */
4691
4692 /*
4693 * Load the guest debug controls (DR7 and IA32_DEBUGCTL MSR) on VM-entry.
4694 * The first VT-x capable CPUs only supported the 1-setting of this bit.
4695 *
4696 * For nested-guests, this is a mandatory VM-entry control. It's also
4697 * required because we do not want to leak host bits to the nested-guest.
4698 */
4699 fVal |= VMX_ENTRY_CTLS_LOAD_DEBUG;
4700
4701 /*
4702 * Set if the guest is in long mode. This will set/clear the EFER.LMA bit on VM-entry.
4703 *
4704 * For nested-guests, the "IA-32e mode guest" control we initialize with what is
4705 * required to get the nested-guest working with hardware-assisted VMX execution.
4706 * It depends on the nested-guest's IA32_EFER.LMA bit. Remember, a nested hypervisor
4707 * can skip intercepting changes to the EFER MSR. This is why it it needs to be done
4708 * here rather than while merging the guest VMCS controls.
4709 */
4710 if (fGstInLongMode)
4711 {
4712 Assert(pVCpu->cpum.GstCtx.msrEFER & MSR_K6_EFER_LME);
4713 fVal |= VMX_ENTRY_CTLS_IA32E_MODE_GUEST;
4714 }
4715 else
4716 Assert(!(fVal & VMX_ENTRY_CTLS_IA32E_MODE_GUEST));
4717
4718 /*
4719 * If the CPU supports the newer VMCS controls for managing guest/host EFER, use it.
4720 *
4721 * For nested-guests, we use the "load IA32_EFER" if the hardware supports it,
4722 * regardless of whether the nested-guest VMCS specifies it because we are free to
4723 * load whatever MSRs we require and we do not need to modify the guest visible copy
4724 * of the VM-entry MSR load area.
4725 */
4726 if ( pVM->hm.s.vmx.fSupportsVmcsEfer
4727 && hmR0VmxShouldSwapEferMsr(pVCpu, pVmxTransient))
4728 fVal |= VMX_ENTRY_CTLS_LOAD_EFER_MSR;
4729 else
4730 Assert(!(fVal & VMX_ENTRY_CTLS_LOAD_EFER_MSR));
4731
4732 /*
4733 * The following should -not- be set (since we're not in SMM mode):
4734 * - VMX_ENTRY_CTLS_ENTRY_TO_SMM
4735 * - VMX_ENTRY_CTLS_DEACTIVATE_DUAL_MON
4736 */
4737
4738 /** @todo VMX_ENTRY_CTLS_LOAD_PERF_MSR,
4739 * VMX_ENTRY_CTLS_LOAD_PAT_MSR. */
4740
4741 if ((fVal & fZap) == fVal)
4742 { /* likely */ }
4743 else
4744 {
4745 Log4Func(("Invalid VM-entry controls combo! Cpu=%#RX32 fVal=%#RX32 fZap=%#RX32\n",
4746 pVM->hm.s.vmx.Msrs.EntryCtls.n.allowed0, fVal, fZap));
4747 pVCpu->hm.s.u32HMError = VMX_UFC_CTRL_ENTRY;
4748 return VERR_HM_UNSUPPORTED_CPU_FEATURE_COMBO;
4749 }
4750
4751 /* Commit it to the VMCS. */
4752 if (pVmcsInfo->u32EntryCtls != fVal)
4753 {
4754 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_ENTRY, fVal);
4755 AssertRC(rc);
4756 pVmcsInfo->u32EntryCtls = fVal;
4757 }
4758 }
4759
4760 /*
4761 * VM-exit controls.
4762 */
4763 {
4764 uint32_t fVal = pVM->hm.s.vmx.Msrs.ExitCtls.n.allowed0; /* Bits set here must be set in the VMCS. */
4765 uint32_t const fZap = pVM->hm.s.vmx.Msrs.ExitCtls.n.allowed1; /* Bits cleared here must be cleared in the VMCS. */
4766
4767 /*
4768 * Save debug controls (DR7 & IA32_DEBUGCTL_MSR). The first VT-x CPUs only
4769 * supported the 1-setting of this bit.
4770 *
4771 * For nested-guests, we set the "save debug controls" as the converse
4772 * "load debug controls" is mandatory for nested-guests anyway.
4773 */
4774 fVal |= VMX_EXIT_CTLS_SAVE_DEBUG;
4775
4776 /*
4777 * Set the host long mode active (EFER.LMA) bit (which Intel calls
4778 * "Host address-space size") if necessary. On VM-exit, VT-x sets both the
4779 * host EFER.LMA and EFER.LME bit to this value. See assertion in
4780 * hmR0VmxExportHostMsrs().
4781 *
4782 * For nested-guests, we always set this bit as we do not support 32-bit
4783 * hosts.
4784 */
4785 fVal |= VMX_EXIT_CTLS_HOST_ADDR_SPACE_SIZE;
4786
4787 /*
4788 * If the VMCS EFER MSR fields are supported by the hardware, we use it.
4789 *
4790 * For nested-guests, we should use the "save IA32_EFER" control if we also
4791 * used the "load IA32_EFER" control while exporting VM-entry controls.
4792 */
4793 if ( pVM->hm.s.vmx.fSupportsVmcsEfer
4794 && hmR0VmxShouldSwapEferMsr(pVCpu, pVmxTransient))
4795 {
4796 fVal |= VMX_EXIT_CTLS_SAVE_EFER_MSR
4797 | VMX_EXIT_CTLS_LOAD_EFER_MSR;
4798 }
4799
4800 /*
4801 * Enable saving of the VMX-preemption timer value on VM-exit.
4802 * For nested-guests, currently not exposed/used.
4803 */
4804 if ( pVM->hm.s.vmx.fUsePreemptTimer
4805 && (pVM->hm.s.vmx.Msrs.ExitCtls.n.allowed1 & VMX_EXIT_CTLS_SAVE_PREEMPT_TIMER))
4806 fVal |= VMX_EXIT_CTLS_SAVE_PREEMPT_TIMER;
4807
4808 /* Don't acknowledge external interrupts on VM-exit. We want to let the host do that. */
4809 Assert(!(fVal & VMX_EXIT_CTLS_ACK_EXT_INT));
4810
4811 /** @todo VMX_EXIT_CTLS_LOAD_PERF_MSR,
4812 * VMX_EXIT_CTLS_SAVE_PAT_MSR,
4813 * VMX_EXIT_CTLS_LOAD_PAT_MSR. */
4814
4815 if ((fVal & fZap) == fVal)
4816 { /* likely */ }
4817 else
4818 {
4819 Log4Func(("Invalid VM-exit controls combo! cpu=%#RX32 fVal=%#RX32 fZap=%R#X32\n",
4820 pVM->hm.s.vmx.Msrs.ExitCtls.n.allowed0, fVal, fZap));
4821 pVCpu->hm.s.u32HMError = VMX_UFC_CTRL_EXIT;
4822 return VERR_HM_UNSUPPORTED_CPU_FEATURE_COMBO;
4823 }
4824
4825 /* Commit it to the VMCS. */
4826 if (pVmcsInfo->u32ExitCtls != fVal)
4827 {
4828 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_EXIT, fVal);
4829 AssertRC(rc);
4830 pVmcsInfo->u32ExitCtls = fVal;
4831 }
4832 }
4833
4834 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_VMX_ENTRY_EXIT_CTLS);
4835 }
4836 return VINF_SUCCESS;
4837}
4838
4839
4840/**
4841 * Sets the TPR threshold in the VMCS.
4842 *
4843 * @param pVmcsInfo The VMCS info. object.
4844 * @param u32TprThreshold The TPR threshold (task-priority class only).
4845 */
4846DECLINLINE(void) hmR0VmxApicSetTprThreshold(PVMXVMCSINFO pVmcsInfo, uint32_t u32TprThreshold)
4847{
4848 Assert(!(u32TprThreshold & ~VMX_TPR_THRESHOLD_MASK)); /* Bits 31:4 MBZ. */
4849 Assert(pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_USE_TPR_SHADOW);
4850 RT_NOREF(pVmcsInfo);
4851 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_TPR_THRESHOLD, u32TprThreshold);
4852 AssertRC(rc);
4853}
4854
4855
4856/**
4857 * Exports the guest APIC TPR state into the VMCS.
4858 *
4859 * @param pVCpu The cross context virtual CPU structure.
4860 * @param pVmxTransient The VMX-transient structure.
4861 *
4862 * @remarks No-long-jump zone!!!
4863 */
4864static void hmR0VmxExportGuestApicTpr(PVMCPUCC pVCpu, PCVMXTRANSIENT pVmxTransient)
4865{
4866 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_APIC_TPR)
4867 {
4868 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_APIC_TPR);
4869
4870 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
4871 if (!pVmxTransient->fIsNestedGuest)
4872 {
4873 if ( PDMHasApic(pVCpu->CTX_SUFF(pVM))
4874 && APICIsEnabled(pVCpu))
4875 {
4876 /*
4877 * Setup TPR shadowing.
4878 */
4879 if (pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_USE_TPR_SHADOW)
4880 {
4881 bool fPendingIntr = false;
4882 uint8_t u8Tpr = 0;
4883 uint8_t u8PendingIntr = 0;
4884 int rc = APICGetTpr(pVCpu, &u8Tpr, &fPendingIntr, &u8PendingIntr);
4885 AssertRC(rc);
4886
4887 /*
4888 * If there are interrupts pending but masked by the TPR, instruct VT-x to
4889 * cause a TPR-below-threshold VM-exit when the guest lowers its TPR below the
4890 * priority of the pending interrupt so we can deliver the interrupt. If there
4891 * are no interrupts pending, set threshold to 0 to not cause any
4892 * TPR-below-threshold VM-exits.
4893 */
4894 uint32_t u32TprThreshold = 0;
4895 if (fPendingIntr)
4896 {
4897 /* Bits 3:0 of the TPR threshold field correspond to bits 7:4 of the TPR
4898 (which is the Task-Priority Class). */
4899 const uint8_t u8PendingPriority = u8PendingIntr >> 4;
4900 const uint8_t u8TprPriority = u8Tpr >> 4;
4901 if (u8PendingPriority <= u8TprPriority)
4902 u32TprThreshold = u8PendingPriority;
4903 }
4904
4905 hmR0VmxApicSetTprThreshold(pVmcsInfo, u32TprThreshold);
4906 }
4907 }
4908 }
4909 /* else: the TPR threshold has already been updated while merging the nested-guest VMCS. */
4910 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_APIC_TPR);
4911 }
4912}
4913
4914
4915/**
4916 * Gets the guest interruptibility-state.
4917 *
4918 * @returns Guest's interruptibility-state.
4919 * @param pVCpu The cross context virtual CPU structure.
4920 *
4921 * @remarks No-long-jump zone!!!
4922 */
4923static uint32_t hmR0VmxGetGuestIntrState(PVMCPUCC pVCpu)
4924{
4925 /*
4926 * Check if we should inhibit interrupt delivery due to instructions like STI and MOV SS.
4927 */
4928 uint32_t fIntrState = 0;
4929 if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS))
4930 {
4931 /* If inhibition is active, RIP and RFLAGS should've been imported from the VMCS already. */
4932 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_RIP | CPUMCTX_EXTRN_RFLAGS);
4933
4934 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
4935 if (pCtx->rip == EMGetInhibitInterruptsPC(pVCpu))
4936 {
4937 if (pCtx->eflags.Bits.u1IF)
4938 fIntrState = VMX_VMCS_GUEST_INT_STATE_BLOCK_STI;
4939 else
4940 fIntrState = VMX_VMCS_GUEST_INT_STATE_BLOCK_MOVSS;
4941 }
4942 else if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS))
4943 {
4944 /*
4945 * We can clear the inhibit force flag as even if we go back to the recompiler
4946 * without executing guest code in VT-x, the flag's condition to be cleared is
4947 * met and thus the cleared state is correct.
4948 */
4949 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS);
4950 }
4951 }
4952
4953 /*
4954 * Check if we should inhibit NMI delivery.
4955 */
4956 if (CPUMIsGuestNmiBlocking(pVCpu))
4957 fIntrState |= VMX_VMCS_GUEST_INT_STATE_BLOCK_NMI;
4958
4959 return fIntrState;
4960}
4961
4962
4963/**
4964 * Exports the exception intercepts required for guest execution in the VMCS.
4965 *
4966 * @param pVCpu The cross context virtual CPU structure.
4967 * @param pVmxTransient The VMX-transient structure.
4968 *
4969 * @remarks No-long-jump zone!!!
4970 */
4971static void hmR0VmxExportGuestXcptIntercepts(PVMCPUCC pVCpu, PCVMXTRANSIENT pVmxTransient)
4972{
4973 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_VMX_XCPT_INTERCEPTS)
4974 {
4975 /* When executing a nested-guest, we do not need to trap GIM hypercalls by intercepting #UD. */
4976 if ( !pVmxTransient->fIsNestedGuest
4977 && pVCpu->hm.s.fGIMTrapXcptUD)
4978 hmR0VmxAddXcptIntercept(pVmxTransient, X86_XCPT_UD);
4979 else
4980 hmR0VmxRemoveXcptIntercept(pVCpu, pVmxTransient, X86_XCPT_UD);
4981
4982 /* Other exception intercepts are handled elsewhere, e.g. while exporting guest CR0. */
4983 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_VMX_XCPT_INTERCEPTS);
4984 }
4985}
4986
4987
4988/**
4989 * Exports the guest's RIP into the guest-state area in the VMCS.
4990 *
4991 * @param pVCpu The cross context virtual CPU structure.
4992 *
4993 * @remarks No-long-jump zone!!!
4994 */
4995static void hmR0VmxExportGuestRip(PVMCPUCC pVCpu)
4996{
4997 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_RIP)
4998 {
4999 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_RIP);
5000
5001 int rc = VMXWriteVmcsNw(VMX_VMCS_GUEST_RIP, pVCpu->cpum.GstCtx.rip);
5002 AssertRC(rc);
5003
5004 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_RIP);
5005 Log4Func(("rip=%#RX64\n", pVCpu->cpum.GstCtx.rip));
5006 }
5007}
5008
5009
5010/**
5011 * Exports the guest's RSP into the guest-state area in the VMCS.
5012 *
5013 * @param pVCpu The cross context virtual CPU structure.
5014 *
5015 * @remarks No-long-jump zone!!!
5016 */
5017static void hmR0VmxExportGuestRsp(PVMCPUCC pVCpu)
5018{
5019 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_RSP)
5020 {
5021 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_RSP);
5022
5023 int rc = VMXWriteVmcsNw(VMX_VMCS_GUEST_RSP, pVCpu->cpum.GstCtx.rsp);
5024 AssertRC(rc);
5025
5026 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_RSP);
5027 Log4Func(("rsp=%#RX64\n", pVCpu->cpum.GstCtx.rsp));
5028 }
5029}
5030
5031
5032/**
5033 * Exports the guest's RFLAGS into the guest-state area in the VMCS.
5034 *
5035 * @param pVCpu The cross context virtual CPU structure.
5036 * @param pVmxTransient The VMX-transient structure.
5037 *
5038 * @remarks No-long-jump zone!!!
5039 */
5040static void hmR0VmxExportGuestRflags(PVMCPUCC pVCpu, PCVMXTRANSIENT pVmxTransient)
5041{
5042 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_RFLAGS)
5043 {
5044 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_RFLAGS);
5045
5046 /* Intel spec. 2.3.1 "System Flags and Fields in IA-32e Mode" claims the upper 32-bits of RFLAGS are reserved (MBZ).
5047 Let us assert it as such and use 32-bit VMWRITE. */
5048 Assert(!RT_HI_U32(pVCpu->cpum.GstCtx.rflags.u64));
5049 X86EFLAGS fEFlags = pVCpu->cpum.GstCtx.eflags;
5050 Assert(fEFlags.u32 & X86_EFL_RA1_MASK);
5051 Assert(!(fEFlags.u32 & ~(X86_EFL_1 | X86_EFL_LIVE_MASK)));
5052
5053 /*
5054 * If we're emulating real-mode using Virtual 8086 mode, save the real-mode eflags so
5055 * we can restore them on VM-exit. Modify the real-mode guest's eflags so that VT-x
5056 * can run the real-mode guest code under Virtual 8086 mode.
5057 */
5058 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
5059 if (pVmcsInfo->RealMode.fRealOnV86Active)
5060 {
5061 Assert(pVCpu->CTX_SUFF(pVM)->hm.s.vmx.pRealModeTSS);
5062 Assert(PDMVmmDevHeapIsEnabled(pVCpu->CTX_SUFF(pVM)));
5063 Assert(!pVmxTransient->fIsNestedGuest);
5064 pVmcsInfo->RealMode.Eflags.u32 = fEFlags.u32; /* Save the original eflags of the real-mode guest. */
5065 fEFlags.Bits.u1VM = 1; /* Set the Virtual 8086 mode bit. */
5066 fEFlags.Bits.u2IOPL = 0; /* Change IOPL to 0, otherwise certain instructions won't fault. */
5067 }
5068
5069 int rc = VMXWriteVmcsNw(VMX_VMCS_GUEST_RFLAGS, fEFlags.u32);
5070 AssertRC(rc);
5071
5072 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_RFLAGS);
5073 Log4Func(("eflags=%#RX32\n", fEFlags.u32));
5074 }
5075}
5076
5077
5078#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
5079/**
5080 * Copies the nested-guest VMCS to the shadow VMCS.
5081 *
5082 * @returns VBox status code.
5083 * @param pVCpu The cross context virtual CPU structure.
5084 * @param pVmcsInfo The VMCS info. object.
5085 *
5086 * @remarks No-long-jump zone!!!
5087 */
5088static int hmR0VmxCopyNstGstToShadowVmcs(PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo)
5089{
5090 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
5091 PCVMXVVMCS pVmcsNstGst = pVCpu->cpum.GstCtx.hwvirt.vmx.CTX_SUFF(pVmcs);
5092
5093 /*
5094 * Disable interrupts so we don't get preempted while the shadow VMCS is the
5095 * current VMCS, as we may try saving guest lazy MSRs.
5096 *
5097 * Strictly speaking the lazy MSRs are not in the VMCS, but I'd rather not risk
5098 * calling the import VMCS code which is currently performing the guest MSR reads
5099 * (on 64-bit hosts) and accessing the auto-load/store MSR area on 32-bit hosts
5100 * and the rest of the VMX leave session machinery.
5101 */
5102 RTCCUINTREG const fEFlags = ASMIntDisableFlags();
5103
5104 int rc = hmR0VmxLoadShadowVmcs(pVmcsInfo);
5105 if (RT_SUCCESS(rc))
5106 {
5107 /*
5108 * Copy all guest read/write VMCS fields.
5109 *
5110 * We don't check for VMWRITE failures here for performance reasons and
5111 * because they are not expected to fail, barring irrecoverable conditions
5112 * like hardware errors.
5113 */
5114 uint32_t const cShadowVmcsFields = pVM->hm.s.vmx.cShadowVmcsFields;
5115 for (uint32_t i = 0; i < cShadowVmcsFields; i++)
5116 {
5117 uint64_t u64Val;
5118 uint32_t const uVmcsField = pVM->hm.s.vmx.paShadowVmcsFields[i];
5119 IEMReadVmxVmcsField(pVmcsNstGst, uVmcsField, &u64Val);
5120 VMXWriteVmcs64(uVmcsField, u64Val);
5121 }
5122
5123 /*
5124 * If the host CPU supports writing all VMCS fields, copy the guest read-only
5125 * VMCS fields, so the guest can VMREAD them without causing a VM-exit.
5126 */
5127 if (pVM->hm.s.vmx.Msrs.u64Misc & VMX_MISC_VMWRITE_ALL)
5128 {
5129 uint32_t const cShadowVmcsRoFields = pVM->hm.s.vmx.cShadowVmcsRoFields;
5130 for (uint32_t i = 0; i < cShadowVmcsRoFields; i++)
5131 {
5132 uint64_t u64Val;
5133 uint32_t const uVmcsField = pVM->hm.s.vmx.paShadowVmcsRoFields[i];
5134 IEMReadVmxVmcsField(pVmcsNstGst, uVmcsField, &u64Val);
5135 VMXWriteVmcs64(uVmcsField, u64Val);
5136 }
5137 }
5138
5139 rc = hmR0VmxClearShadowVmcs(pVmcsInfo);
5140 rc |= hmR0VmxLoadVmcs(pVmcsInfo);
5141 }
5142
5143 ASMSetFlags(fEFlags);
5144 return rc;
5145}
5146
5147
5148/**
5149 * Copies the shadow VMCS to the nested-guest VMCS.
5150 *
5151 * @returns VBox status code.
5152 * @param pVCpu The cross context virtual CPU structure.
5153 * @param pVmcsInfo The VMCS info. object.
5154 *
5155 * @remarks Called with interrupts disabled.
5156 */
5157static int hmR0VmxCopyShadowToNstGstVmcs(PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo)
5158{
5159 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
5160 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
5161 PVMXVVMCS pVmcsNstGst = pVCpu->cpum.GstCtx.hwvirt.vmx.CTX_SUFF(pVmcs);
5162
5163 int rc = hmR0VmxLoadShadowVmcs(pVmcsInfo);
5164 if (RT_SUCCESS(rc))
5165 {
5166 /*
5167 * Copy guest read/write fields from the shadow VMCS.
5168 * Guest read-only fields cannot be modified, so no need to copy them.
5169 *
5170 * We don't check for VMREAD failures here for performance reasons and
5171 * because they are not expected to fail, barring irrecoverable conditions
5172 * like hardware errors.
5173 */
5174 uint32_t const cShadowVmcsFields = pVM->hm.s.vmx.cShadowVmcsFields;
5175 for (uint32_t i = 0; i < cShadowVmcsFields; i++)
5176 {
5177 uint64_t u64Val;
5178 uint32_t const uVmcsField = pVM->hm.s.vmx.paShadowVmcsFields[i];
5179 VMXReadVmcs64(uVmcsField, &u64Val);
5180 IEMWriteVmxVmcsField(pVmcsNstGst, uVmcsField, u64Val);
5181 }
5182
5183 rc = hmR0VmxClearShadowVmcs(pVmcsInfo);
5184 rc |= hmR0VmxLoadVmcs(pVmcsInfo);
5185 }
5186 return rc;
5187}
5188
5189
5190/**
5191 * Enables VMCS shadowing for the given VMCS info. object.
5192 *
5193 * @param pVmcsInfo The VMCS info. object.
5194 *
5195 * @remarks No-long-jump zone!!!
5196 */
5197static void hmR0VmxEnableVmcsShadowing(PVMXVMCSINFO pVmcsInfo)
5198{
5199 uint32_t uProcCtls2 = pVmcsInfo->u32ProcCtls2;
5200 if (!(uProcCtls2 & VMX_PROC_CTLS2_VMCS_SHADOWING))
5201 {
5202 Assert(pVmcsInfo->HCPhysShadowVmcs != 0 && pVmcsInfo->HCPhysShadowVmcs != NIL_RTHCPHYS);
5203 uProcCtls2 |= VMX_PROC_CTLS2_VMCS_SHADOWING;
5204 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC2, uProcCtls2); AssertRC(rc);
5205 rc = VMXWriteVmcs64(VMX_VMCS64_GUEST_VMCS_LINK_PTR_FULL, pVmcsInfo->HCPhysShadowVmcs); AssertRC(rc);
5206 pVmcsInfo->u32ProcCtls2 = uProcCtls2;
5207 pVmcsInfo->u64VmcsLinkPtr = pVmcsInfo->HCPhysShadowVmcs;
5208 Log4Func(("Enabled\n"));
5209 }
5210}
5211
5212
5213/**
5214 * Disables VMCS shadowing for the given VMCS info. object.
5215 *
5216 * @param pVmcsInfo The VMCS info. object.
5217 *
5218 * @remarks No-long-jump zone!!!
5219 */
5220static void hmR0VmxDisableVmcsShadowing(PVMXVMCSINFO pVmcsInfo)
5221{
5222 /*
5223 * We want all VMREAD and VMWRITE instructions to cause VM-exits, so we clear the
5224 * VMCS shadowing control. However, VM-entry requires the shadow VMCS indicator bit
5225 * to match the VMCS shadowing control if the VMCS link pointer is not NIL_RTHCPHYS.
5226 * Hence, we must also reset the VMCS link pointer to ensure VM-entry does not fail.
5227 *
5228 * See Intel spec. 26.2.1.1 "VM-Execution Control Fields".
5229 * See Intel spec. 26.3.1.5 "Checks on Guest Non-Register State".
5230 */
5231 uint32_t uProcCtls2 = pVmcsInfo->u32ProcCtls2;
5232 if (uProcCtls2 & VMX_PROC_CTLS2_VMCS_SHADOWING)
5233 {
5234 uProcCtls2 &= ~VMX_PROC_CTLS2_VMCS_SHADOWING;
5235 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC2, uProcCtls2); AssertRC(rc);
5236 rc = VMXWriteVmcs64(VMX_VMCS64_GUEST_VMCS_LINK_PTR_FULL, NIL_RTHCPHYS); AssertRC(rc);
5237 pVmcsInfo->u32ProcCtls2 = uProcCtls2;
5238 pVmcsInfo->u64VmcsLinkPtr = NIL_RTHCPHYS;
5239 Log4Func(("Disabled\n"));
5240 }
5241}
5242#endif
5243
5244
5245/**
5246 * Exports the guest hardware-virtualization state.
5247 *
5248 * @returns VBox status code.
5249 * @param pVCpu The cross context virtual CPU structure.
5250 * @param pVmxTransient The VMX-transient structure.
5251 *
5252 * @remarks No-long-jump zone!!!
5253 */
5254static int hmR0VmxExportGuestHwvirtState(PVMCPUCC pVCpu, PCVMXTRANSIENT pVmxTransient)
5255{
5256 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_HWVIRT)
5257 {
5258#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
5259 /*
5260 * Check if the VMX feature is exposed to the guest and if the host CPU supports
5261 * VMCS shadowing.
5262 */
5263 if (pVCpu->CTX_SUFF(pVM)->hm.s.vmx.fUseVmcsShadowing)
5264 {
5265 /*
5266 * If the nested hypervisor has loaded a current VMCS and is in VMX root mode,
5267 * copy the nested hypervisor's current VMCS into the shadow VMCS and enable
5268 * VMCS shadowing to skip intercepting some or all VMREAD/VMWRITE VM-exits.
5269 *
5270 * We check for VMX root mode here in case the guest executes VMXOFF without
5271 * clearing the current VMCS pointer and our VMXOFF instruction emulation does
5272 * not clear the current VMCS pointer.
5273 */
5274 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
5275 if ( CPUMIsGuestInVmxRootMode(&pVCpu->cpum.GstCtx)
5276 && !CPUMIsGuestInVmxNonRootMode(&pVCpu->cpum.GstCtx)
5277 && CPUMIsGuestVmxCurrentVmcsValid(&pVCpu->cpum.GstCtx))
5278 {
5279 /* Paranoia. */
5280 Assert(!pVmxTransient->fIsNestedGuest);
5281
5282 /*
5283 * For performance reasons, also check if the nested hypervisor's current VMCS
5284 * was newly loaded or modified before copying it to the shadow VMCS.
5285 */
5286 if (!pVCpu->hm.s.vmx.fCopiedNstGstToShadowVmcs)
5287 {
5288 int rc = hmR0VmxCopyNstGstToShadowVmcs(pVCpu, pVmcsInfo);
5289 AssertRCReturn(rc, rc);
5290 pVCpu->hm.s.vmx.fCopiedNstGstToShadowVmcs = true;
5291 }
5292 hmR0VmxEnableVmcsShadowing(pVmcsInfo);
5293 }
5294 else
5295 hmR0VmxDisableVmcsShadowing(pVmcsInfo);
5296 }
5297#else
5298 NOREF(pVmxTransient);
5299#endif
5300 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_HWVIRT);
5301 }
5302 return VINF_SUCCESS;
5303}
5304
5305
5306/**
5307 * Exports the guest CR0 control register into the guest-state area in the VMCS.
5308 *
5309 * The guest FPU state is always pre-loaded hence we don't need to bother about
5310 * sharing FPU related CR0 bits between the guest and host.
5311 *
5312 * @returns VBox status code.
5313 * @param pVCpu The cross context virtual CPU structure.
5314 * @param pVmxTransient The VMX-transient structure.
5315 *
5316 * @remarks No-long-jump zone!!!
5317 */
5318static int hmR0VmxExportGuestCR0(PVMCPUCC pVCpu, PCVMXTRANSIENT pVmxTransient)
5319{
5320 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_CR0)
5321 {
5322 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
5323 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
5324
5325 uint64_t fSetCr0 = pVM->hm.s.vmx.Msrs.u64Cr0Fixed0;
5326 uint64_t const fZapCr0 = pVM->hm.s.vmx.Msrs.u64Cr0Fixed1;
5327 if (pVM->hm.s.vmx.fUnrestrictedGuest)
5328 fSetCr0 &= ~(uint64_t)(X86_CR0_PE | X86_CR0_PG);
5329 else
5330 Assert((fSetCr0 & (X86_CR0_PE | X86_CR0_PG)) == (X86_CR0_PE | X86_CR0_PG));
5331
5332 if (!pVmxTransient->fIsNestedGuest)
5333 {
5334 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_CR0);
5335 uint64_t u64GuestCr0 = pVCpu->cpum.GstCtx.cr0;
5336 uint64_t const u64ShadowCr0 = u64GuestCr0;
5337 Assert(!RT_HI_U32(u64GuestCr0));
5338
5339 /*
5340 * Setup VT-x's view of the guest CR0.
5341 */
5342 uint32_t uProcCtls = pVmcsInfo->u32ProcCtls;
5343 if (pVM->hm.s.fNestedPaging)
5344 {
5345 if (CPUMIsGuestPagingEnabled(pVCpu))
5346 {
5347 /* The guest has paging enabled, let it access CR3 without causing a VM-exit if supported. */
5348 uProcCtls &= ~( VMX_PROC_CTLS_CR3_LOAD_EXIT
5349 | VMX_PROC_CTLS_CR3_STORE_EXIT);
5350 }
5351 else
5352 {
5353 /* The guest doesn't have paging enabled, make CR3 access cause a VM-exit to update our shadow. */
5354 uProcCtls |= VMX_PROC_CTLS_CR3_LOAD_EXIT
5355 | VMX_PROC_CTLS_CR3_STORE_EXIT;
5356 }
5357
5358 /* If we have unrestricted guest execution, we never have to intercept CR3 reads. */
5359 if (pVM->hm.s.vmx.fUnrestrictedGuest)
5360 uProcCtls &= ~VMX_PROC_CTLS_CR3_STORE_EXIT;
5361 }
5362 else
5363 {
5364 /* Guest CPL 0 writes to its read-only pages should cause a #PF VM-exit. */
5365 u64GuestCr0 |= X86_CR0_WP;
5366 }
5367
5368 /*
5369 * Guest FPU bits.
5370 *
5371 * Since we pre-load the guest FPU always before VM-entry there is no need to track lazy state
5372 * using CR0.TS.
5373 *
5374 * Intel spec. 23.8 "Restrictions on VMX operation" mentions that CR0.NE bit must always be
5375 * set on the first CPUs to support VT-x and no mention of with regards to UX in VM-entry checks.
5376 */
5377 u64GuestCr0 |= X86_CR0_NE;
5378
5379 /* If CR0.NE isn't set, we need to intercept #MF exceptions and report them to the guest differently. */
5380 bool const fInterceptMF = !(u64ShadowCr0 & X86_CR0_NE);
5381
5382 /*
5383 * Update exception intercepts.
5384 */
5385 uint32_t uXcptBitmap = pVmcsInfo->u32XcptBitmap;
5386 if (pVmcsInfo->RealMode.fRealOnV86Active)
5387 {
5388 Assert(PDMVmmDevHeapIsEnabled(pVM));
5389 Assert(pVM->hm.s.vmx.pRealModeTSS);
5390 uXcptBitmap |= HMVMX_REAL_MODE_XCPT_MASK;
5391 }
5392 else
5393 {
5394 /* For now, cleared here as mode-switches can happen outside HM/VT-x. See @bugref{7626#c11}. */
5395 uXcptBitmap &= ~HMVMX_REAL_MODE_XCPT_MASK;
5396 if (fInterceptMF)
5397 uXcptBitmap |= RT_BIT(X86_XCPT_MF);
5398 }
5399
5400 /* Additional intercepts for debugging, define these yourself explicitly. */
5401#ifdef HMVMX_ALWAYS_TRAP_ALL_XCPTS
5402 uXcptBitmap |= 0
5403 | RT_BIT(X86_XCPT_BP)
5404 | RT_BIT(X86_XCPT_DE)
5405 | RT_BIT(X86_XCPT_NM)
5406 | RT_BIT(X86_XCPT_TS)
5407 | RT_BIT(X86_XCPT_UD)
5408 | RT_BIT(X86_XCPT_NP)
5409 | RT_BIT(X86_XCPT_SS)
5410 | RT_BIT(X86_XCPT_GP)
5411 | RT_BIT(X86_XCPT_PF)
5412 | RT_BIT(X86_XCPT_MF)
5413 ;
5414#elif defined(HMVMX_ALWAYS_TRAP_PF)
5415 uXcptBitmap |= RT_BIT(X86_XCPT_PF);
5416#endif
5417 if (pVCpu->hm.s.fTrapXcptGpForLovelyMesaDrv)
5418 uXcptBitmap |= RT_BIT(X86_XCPT_GP);
5419 Assert(pVM->hm.s.fNestedPaging || (uXcptBitmap & RT_BIT(X86_XCPT_PF)));
5420
5421 /* Apply the hardware specified CR0 fixed bits and enable caching. */
5422 u64GuestCr0 |= fSetCr0;
5423 u64GuestCr0 &= fZapCr0;
5424 u64GuestCr0 &= ~(uint64_t)(X86_CR0_CD | X86_CR0_NW);
5425
5426 /* Commit the CR0 and related fields to the guest VMCS. */
5427 int rc = VMXWriteVmcsNw(VMX_VMCS_GUEST_CR0, u64GuestCr0); AssertRC(rc);
5428 rc = VMXWriteVmcsNw(VMX_VMCS_CTRL_CR0_READ_SHADOW, u64ShadowCr0); AssertRC(rc);
5429 if (uProcCtls != pVmcsInfo->u32ProcCtls)
5430 {
5431 rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, uProcCtls);
5432 AssertRC(rc);
5433 }
5434 if (uXcptBitmap != pVmcsInfo->u32XcptBitmap)
5435 {
5436 rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_EXCEPTION_BITMAP, uXcptBitmap);
5437 AssertRC(rc);
5438 }
5439
5440 /* Update our caches. */
5441 pVmcsInfo->u32ProcCtls = uProcCtls;
5442 pVmcsInfo->u32XcptBitmap = uXcptBitmap;
5443
5444 Log4Func(("cr0=%#RX64 shadow=%#RX64 set=%#RX64 zap=%#RX64\n", u64GuestCr0, u64ShadowCr0, fSetCr0, fZapCr0));
5445 }
5446 else
5447 {
5448 /*
5449 * With nested-guests, we may have extended the guest/host mask here since we
5450 * merged in the outer guest's mask. Thus, the merged mask can include more bits
5451 * (to read from the nested-guest CR0 read-shadow) than the nested hypervisor
5452 * originally supplied. We must copy those bits from the nested-guest CR0 into
5453 * the nested-guest CR0 read-shadow.
5454 */
5455 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_CR0);
5456 uint64_t u64GuestCr0 = pVCpu->cpum.GstCtx.cr0;
5457 uint64_t const u64ShadowCr0 = CPUMGetGuestVmxMaskedCr0(&pVCpu->cpum.GstCtx, pVmcsInfo->u64Cr0Mask);
5458 Assert(!RT_HI_U32(u64GuestCr0));
5459 Assert(u64GuestCr0 & X86_CR0_NE);
5460
5461 /* Apply the hardware specified CR0 fixed bits and enable caching. */
5462 u64GuestCr0 |= fSetCr0;
5463 u64GuestCr0 &= fZapCr0;
5464 u64GuestCr0 &= ~(uint64_t)(X86_CR0_CD | X86_CR0_NW);
5465
5466 /* Commit the CR0 and CR0 read-shadow to the nested-guest VMCS. */
5467 int rc = VMXWriteVmcsNw(VMX_VMCS_GUEST_CR0, u64GuestCr0); AssertRC(rc);
5468 rc = VMXWriteVmcsNw(VMX_VMCS_CTRL_CR0_READ_SHADOW, u64ShadowCr0); AssertRC(rc);
5469
5470 Log4Func(("cr0=%#RX64 shadow=%#RX64 (set=%#RX64 zap=%#RX64)\n", u64GuestCr0, u64ShadowCr0, fSetCr0, fZapCr0));
5471 }
5472
5473 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_CR0);
5474 }
5475
5476 return VINF_SUCCESS;
5477}
5478
5479
5480/**
5481 * Exports the guest control registers (CR3, CR4) into the guest-state area
5482 * in the VMCS.
5483 *
5484 * @returns VBox strict status code.
5485 * @retval VINF_EM_RESCHEDULE_REM if we try to emulate non-paged guest code
5486 * without unrestricted guest access and the VMMDev is not presently
5487 * mapped (e.g. EFI32).
5488 *
5489 * @param pVCpu The cross context virtual CPU structure.
5490 * @param pVmxTransient The VMX-transient structure.
5491 *
5492 * @remarks No-long-jump zone!!!
5493 */
5494static VBOXSTRICTRC hmR0VmxExportGuestCR3AndCR4(PVMCPUCC pVCpu, PCVMXTRANSIENT pVmxTransient)
5495{
5496 int rc = VINF_SUCCESS;
5497 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
5498
5499 /*
5500 * Guest CR2.
5501 * It's always loaded in the assembler code. Nothing to do here.
5502 */
5503
5504 /*
5505 * Guest CR3.
5506 */
5507 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_CR3)
5508 {
5509 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_CR3);
5510
5511 if (pVM->hm.s.fNestedPaging)
5512 {
5513 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
5514 pVmcsInfo->HCPhysEPTP = PGMGetHyperCR3(pVCpu);
5515
5516 /* Validate. See Intel spec. 28.2.2 "EPT Translation Mechanism" and 24.6.11 "Extended-Page-Table Pointer (EPTP)" */
5517 Assert(pVmcsInfo->HCPhysEPTP != NIL_RTHCPHYS);
5518 Assert(!(pVmcsInfo->HCPhysEPTP & UINT64_C(0xfff0000000000000)));
5519 Assert(!(pVmcsInfo->HCPhysEPTP & 0xfff));
5520
5521 /* VMX_EPT_MEMTYPE_WB support is already checked in hmR0VmxSetupTaggedTlb(). */
5522 pVmcsInfo->HCPhysEPTP |= VMX_EPT_MEMTYPE_WB
5523 | (VMX_EPT_PAGE_WALK_LENGTH_DEFAULT << VMX_EPT_PAGE_WALK_LENGTH_SHIFT);
5524
5525 /* Validate. See Intel spec. 26.2.1 "Checks on VMX Controls" */
5526 AssertMsg( ((pVmcsInfo->HCPhysEPTP >> 3) & 0x07) == 3 /* Bits 3:5 (EPT page walk length - 1) must be 3. */
5527 && ((pVmcsInfo->HCPhysEPTP >> 7) & 0x1f) == 0, /* Bits 7:11 MBZ. */
5528 ("EPTP %#RX64\n", pVmcsInfo->HCPhysEPTP));
5529 AssertMsg( !((pVmcsInfo->HCPhysEPTP >> 6) & 0x01) /* Bit 6 (EPT accessed & dirty bit). */
5530 || (pVM->hm.s.vmx.Msrs.u64EptVpidCaps & MSR_IA32_VMX_EPT_VPID_CAP_EPT_ACCESS_DIRTY),
5531 ("EPTP accessed/dirty bit not supported by CPU but set %#RX64\n", pVmcsInfo->HCPhysEPTP));
5532
5533 rc = VMXWriteVmcs64(VMX_VMCS64_CTRL_EPTP_FULL, pVmcsInfo->HCPhysEPTP);
5534 AssertRC(rc);
5535
5536 uint64_t u64GuestCr3;
5537 PCCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
5538 if ( pVM->hm.s.vmx.fUnrestrictedGuest
5539 || CPUMIsGuestPagingEnabledEx(pCtx))
5540 {
5541 /* If the guest is in PAE mode, pass the PDPEs to VT-x using the VMCS fields. */
5542 if (CPUMIsGuestInPAEModeEx(pCtx))
5543 {
5544 rc = PGMGstGetPaePdpes(pVCpu, &pVCpu->hm.s.aPdpes[0]);
5545 AssertRC(rc);
5546 rc = VMXWriteVmcs64(VMX_VMCS64_GUEST_PDPTE0_FULL, pVCpu->hm.s.aPdpes[0].u); AssertRC(rc);
5547 rc = VMXWriteVmcs64(VMX_VMCS64_GUEST_PDPTE1_FULL, pVCpu->hm.s.aPdpes[1].u); AssertRC(rc);
5548 rc = VMXWriteVmcs64(VMX_VMCS64_GUEST_PDPTE2_FULL, pVCpu->hm.s.aPdpes[2].u); AssertRC(rc);
5549 rc = VMXWriteVmcs64(VMX_VMCS64_GUEST_PDPTE3_FULL, pVCpu->hm.s.aPdpes[3].u); AssertRC(rc);
5550 }
5551
5552 /*
5553 * The guest's view of its CR3 is unblemished with nested paging when the
5554 * guest is using paging or we have unrestricted guest execution to handle
5555 * the guest when it's not using paging.
5556 */
5557 u64GuestCr3 = pCtx->cr3;
5558 }
5559 else
5560 {
5561 /*
5562 * The guest is not using paging, but the CPU (VT-x) has to. While the guest
5563 * thinks it accesses physical memory directly, we use our identity-mapped
5564 * page table to map guest-linear to guest-physical addresses. EPT takes care
5565 * of translating it to host-physical addresses.
5566 */
5567 RTGCPHYS GCPhys;
5568 Assert(pVM->hm.s.vmx.pNonPagingModeEPTPageTable);
5569
5570 /* We obtain it here every time as the guest could have relocated this PCI region. */
5571 rc = PDMVmmDevHeapR3ToGCPhys(pVM, pVM->hm.s.vmx.pNonPagingModeEPTPageTable, &GCPhys);
5572 if (RT_SUCCESS(rc))
5573 { /* likely */ }
5574 else if (rc == VERR_PDM_DEV_HEAP_R3_TO_GCPHYS)
5575 {
5576 Log4Func(("VERR_PDM_DEV_HEAP_R3_TO_GCPHYS -> VINF_EM_RESCHEDULE_REM\n"));
5577 return VINF_EM_RESCHEDULE_REM; /* We cannot execute now, switch to REM/IEM till the guest maps in VMMDev. */
5578 }
5579 else
5580 AssertMsgFailedReturn(("%Rrc\n", rc), rc);
5581
5582 u64GuestCr3 = GCPhys;
5583 }
5584
5585 Log4Func(("guest_cr3=%#RX64 (GstN)\n", u64GuestCr3));
5586 rc = VMXWriteVmcsNw(VMX_VMCS_GUEST_CR3, u64GuestCr3);
5587 AssertRC(rc);
5588 }
5589 else
5590 {
5591 Assert(!pVmxTransient->fIsNestedGuest);
5592 /* Non-nested paging case, just use the hypervisor's CR3. */
5593 RTHCPHYS const HCPhysGuestCr3 = PGMGetHyperCR3(pVCpu);
5594
5595 Log4Func(("guest_cr3=%#RX64 (HstN)\n", HCPhysGuestCr3));
5596 rc = VMXWriteVmcsNw(VMX_VMCS_GUEST_CR3, HCPhysGuestCr3);
5597 AssertRC(rc);
5598 }
5599
5600 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_CR3);
5601 }
5602
5603 /*
5604 * Guest CR4.
5605 * ASSUMES this is done everytime we get in from ring-3! (XCR0)
5606 */
5607 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_CR4)
5608 {
5609 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
5610 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
5611
5612 uint64_t const fSetCr4 = pVM->hm.s.vmx.Msrs.u64Cr4Fixed0;
5613 uint64_t const fZapCr4 = pVM->hm.s.vmx.Msrs.u64Cr4Fixed1;
5614
5615 /*
5616 * With nested-guests, we may have extended the guest/host mask here (since we
5617 * merged in the outer guest's mask, see hmR0VmxMergeVmcsNested). This means, the
5618 * mask can include more bits (to read from the nested-guest CR4 read-shadow) than
5619 * the nested hypervisor originally supplied. Thus, we should, in essence, copy
5620 * those bits from the nested-guest CR4 into the nested-guest CR4 read-shadow.
5621 */
5622 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_CR4);
5623 uint64_t u64GuestCr4 = pCtx->cr4;
5624 uint64_t const u64ShadowCr4 = !pVmxTransient->fIsNestedGuest
5625 ? pCtx->cr4
5626 : CPUMGetGuestVmxMaskedCr4(pCtx, pVmcsInfo->u64Cr4Mask);
5627 Assert(!RT_HI_U32(u64GuestCr4));
5628
5629 /*
5630 * Setup VT-x's view of the guest CR4.
5631 *
5632 * If we're emulating real-mode using virtual-8086 mode, we want to redirect software
5633 * interrupts to the 8086 program interrupt handler. Clear the VME bit (the interrupt
5634 * redirection bitmap is already all 0, see hmR3InitFinalizeR0())
5635 *
5636 * See Intel spec. 20.2 "Software Interrupt Handling Methods While in Virtual-8086 Mode".
5637 */
5638 if (pVmcsInfo->RealMode.fRealOnV86Active)
5639 {
5640 Assert(pVM->hm.s.vmx.pRealModeTSS);
5641 Assert(PDMVmmDevHeapIsEnabled(pVM));
5642 u64GuestCr4 &= ~(uint64_t)X86_CR4_VME;
5643 }
5644
5645 if (pVM->hm.s.fNestedPaging)
5646 {
5647 if ( !CPUMIsGuestPagingEnabledEx(pCtx)
5648 && !pVM->hm.s.vmx.fUnrestrictedGuest)
5649 {
5650 /* We use 4 MB pages in our identity mapping page table when the guest doesn't have paging. */
5651 u64GuestCr4 |= X86_CR4_PSE;
5652 /* Our identity mapping is a 32-bit page directory. */
5653 u64GuestCr4 &= ~(uint64_t)X86_CR4_PAE;
5654 }
5655 /* else use guest CR4.*/
5656 }
5657 else
5658 {
5659 Assert(!pVmxTransient->fIsNestedGuest);
5660
5661 /*
5662 * The shadow paging modes and guest paging modes are different, the shadow is in accordance with the host
5663 * paging mode and thus we need to adjust VT-x's view of CR4 depending on our shadow page tables.
5664 */
5665 switch (pVCpu->hm.s.enmShadowMode)
5666 {
5667 case PGMMODE_REAL: /* Real-mode. */
5668 case PGMMODE_PROTECTED: /* Protected mode without paging. */
5669 case PGMMODE_32_BIT: /* 32-bit paging. */
5670 {
5671 u64GuestCr4 &= ~(uint64_t)X86_CR4_PAE;
5672 break;
5673 }
5674
5675 case PGMMODE_PAE: /* PAE paging. */
5676 case PGMMODE_PAE_NX: /* PAE paging with NX. */
5677 {
5678 u64GuestCr4 |= X86_CR4_PAE;
5679 break;
5680 }
5681
5682 case PGMMODE_AMD64: /* 64-bit AMD paging (long mode). */
5683 case PGMMODE_AMD64_NX: /* 64-bit AMD paging (long mode) with NX enabled. */
5684 {
5685#ifdef VBOX_WITH_64_BITS_GUESTS
5686 /* For our assumption in hmR0VmxShouldSwapEferMsr. */
5687 Assert(u64GuestCr4 & X86_CR4_PAE);
5688 break;
5689#endif
5690 }
5691 default:
5692 AssertFailed();
5693 return VERR_PGM_UNSUPPORTED_SHADOW_PAGING_MODE;
5694 }
5695 }
5696
5697 /* Apply the hardware specified CR4 fixed bits (mainly CR4.VMXE). */
5698 u64GuestCr4 |= fSetCr4;
5699 u64GuestCr4 &= fZapCr4;
5700
5701 /* Commit the CR4 and CR4 read-shadow to the guest VMCS. */
5702 rc = VMXWriteVmcsNw(VMX_VMCS_GUEST_CR4, u64GuestCr4); AssertRC(rc);
5703 rc = VMXWriteVmcsNw(VMX_VMCS_CTRL_CR4_READ_SHADOW, u64ShadowCr4); AssertRC(rc);
5704
5705 /* Whether to save/load/restore XCR0 during world switch depends on CR4.OSXSAVE and host+guest XCR0. */
5706 pVCpu->hm.s.fLoadSaveGuestXcr0 = (pCtx->cr4 & X86_CR4_OSXSAVE) && pCtx->aXcr[0] != ASMGetXcr0();
5707
5708 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_CR4);
5709
5710 Log4Func(("cr4=%#RX64 shadow=%#RX64 (set=%#RX64 zap=%#RX64)\n", u64GuestCr4, u64ShadowCr4, fSetCr4, fZapCr4));
5711 }
5712 return rc;
5713}
5714
5715
5716/**
5717 * Exports the guest debug registers into the guest-state area in the VMCS.
5718 * The guest debug bits are partially shared with the host (e.g. DR6, DR0-3).
5719 *
5720 * This also sets up whether \#DB and MOV DRx accesses cause VM-exits.
5721 *
5722 * @returns VBox status code.
5723 * @param pVCpu The cross context virtual CPU structure.
5724 * @param pVmxTransient The VMX-transient structure.
5725 *
5726 * @remarks No-long-jump zone!!!
5727 */
5728static int hmR0VmxExportSharedDebugState(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
5729{
5730 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
5731
5732 /** @todo NSTVMX: Figure out what we want to do with nested-guest instruction
5733 * stepping. */
5734 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
5735 if (pVmxTransient->fIsNestedGuest)
5736 {
5737 int rc = VMXWriteVmcsNw(VMX_VMCS_GUEST_DR7, CPUMGetGuestDR7(pVCpu));
5738 AssertRC(rc);
5739
5740 /* Always intercept Mov DRx accesses for the nested-guest for now. */
5741 pVmcsInfo->u32ProcCtls |= VMX_PROC_CTLS_MOV_DR_EXIT;
5742 rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, pVmcsInfo->u32ProcCtls);
5743 AssertRC(rc);
5744 return VINF_SUCCESS;
5745 }
5746
5747#ifdef VBOX_STRICT
5748 /* Validate. Intel spec. 26.3.1.1 "Checks on Guest Controls Registers, Debug Registers, MSRs" */
5749 if (pVmcsInfo->u32EntryCtls & VMX_ENTRY_CTLS_LOAD_DEBUG)
5750 {
5751 /* Validate. Intel spec. 17.2 "Debug Registers", recompiler paranoia checks. */
5752 Assert((pVCpu->cpum.GstCtx.dr[7] & (X86_DR7_MBZ_MASK | X86_DR7_RAZ_MASK)) == 0);
5753 Assert((pVCpu->cpum.GstCtx.dr[7] & X86_DR7_RA1_MASK) == X86_DR7_RA1_MASK);
5754 }
5755#endif
5756
5757 bool fSteppingDB = false;
5758 bool fInterceptMovDRx = false;
5759 uint32_t uProcCtls = pVmcsInfo->u32ProcCtls;
5760 if (pVCpu->hm.s.fSingleInstruction)
5761 {
5762 /* If the CPU supports the monitor trap flag, use it for single stepping in DBGF and avoid intercepting #DB. */
5763 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
5764 if (pVM->hm.s.vmx.Msrs.ProcCtls.n.allowed1 & VMX_PROC_CTLS_MONITOR_TRAP_FLAG)
5765 {
5766 uProcCtls |= VMX_PROC_CTLS_MONITOR_TRAP_FLAG;
5767 Assert(fSteppingDB == false);
5768 }
5769 else
5770 {
5771 pVCpu->cpum.GstCtx.eflags.u32 |= X86_EFL_TF;
5772 pVCpu->hm.s.fCtxChanged |= HM_CHANGED_GUEST_RFLAGS;
5773 pVCpu->hm.s.fClearTrapFlag = true;
5774 fSteppingDB = true;
5775 }
5776 }
5777
5778 uint64_t u64GuestDr7;
5779 if ( fSteppingDB
5780 || (CPUMGetHyperDR7(pVCpu) & X86_DR7_ENABLED_MASK))
5781 {
5782 /*
5783 * Use the combined guest and host DRx values found in the hypervisor register set
5784 * because the hypervisor debugger has breakpoints active or someone is single stepping
5785 * on the host side without a monitor trap flag.
5786 *
5787 * Note! DBGF expects a clean DR6 state before executing guest code.
5788 */
5789 if (!CPUMIsHyperDebugStateActive(pVCpu))
5790 {
5791 CPUMR0LoadHyperDebugState(pVCpu, true /* include DR6 */);
5792 Assert(CPUMIsHyperDebugStateActive(pVCpu));
5793 Assert(!CPUMIsGuestDebugStateActive(pVCpu));
5794 }
5795
5796 /* Update DR7 with the hypervisor value (other DRx registers are handled by CPUM one way or another). */
5797 u64GuestDr7 = CPUMGetHyperDR7(pVCpu);
5798 pVCpu->hm.s.fUsingHyperDR7 = true;
5799 fInterceptMovDRx = true;
5800 }
5801 else
5802 {
5803 /*
5804 * If the guest has enabled debug registers, we need to load them prior to
5805 * executing guest code so they'll trigger at the right time.
5806 */
5807 if (pVCpu->cpum.GstCtx.dr[7] & (X86_DR7_ENABLED_MASK | X86_DR7_GD))
5808 {
5809 if (!CPUMIsGuestDebugStateActive(pVCpu))
5810 {
5811 CPUMR0LoadGuestDebugState(pVCpu, true /* include DR6 */);
5812 Assert(CPUMIsGuestDebugStateActive(pVCpu));
5813 Assert(!CPUMIsHyperDebugStateActive(pVCpu));
5814 STAM_COUNTER_INC(&pVCpu->hm.s.StatDRxArmed);
5815 }
5816 Assert(!fInterceptMovDRx);
5817 }
5818 else if (!CPUMIsGuestDebugStateActive(pVCpu))
5819 {
5820 /*
5821 * If no debugging enabled, we'll lazy load DR0-3. Unlike on AMD-V, we
5822 * must intercept #DB in order to maintain a correct DR6 guest value, and
5823 * because we need to intercept it to prevent nested #DBs from hanging the
5824 * CPU, we end up always having to intercept it. See hmR0VmxSetupVmcsXcptBitmap().
5825 */
5826 fInterceptMovDRx = true;
5827 }
5828
5829 /* Update DR7 with the actual guest value. */
5830 u64GuestDr7 = pVCpu->cpum.GstCtx.dr[7];
5831 pVCpu->hm.s.fUsingHyperDR7 = false;
5832 }
5833
5834 if (fInterceptMovDRx)
5835 uProcCtls |= VMX_PROC_CTLS_MOV_DR_EXIT;
5836 else
5837 uProcCtls &= ~VMX_PROC_CTLS_MOV_DR_EXIT;
5838
5839 /*
5840 * Update the processor-based VM-execution controls with the MOV-DRx intercepts and the
5841 * monitor-trap flag and update our cache.
5842 */
5843 if (uProcCtls != pVmcsInfo->u32ProcCtls)
5844 {
5845 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, uProcCtls);
5846 AssertRC(rc);
5847 pVmcsInfo->u32ProcCtls = uProcCtls;
5848 }
5849
5850 /*
5851 * Update guest DR7.
5852 */
5853 int rc = VMXWriteVmcsNw(VMX_VMCS_GUEST_DR7, u64GuestDr7);
5854 AssertRC(rc);
5855
5856 /*
5857 * If we have forced EFLAGS.TF to be set because we're single-stepping in the hypervisor debugger,
5858 * we need to clear interrupt inhibition if any as otherwise it causes a VM-entry failure.
5859 *
5860 * See Intel spec. 26.3.1.5 "Checks on Guest Non-Register State".
5861 */
5862 if (fSteppingDB)
5863 {
5864 Assert(pVCpu->hm.s.fSingleInstruction);
5865 Assert(pVCpu->cpum.GstCtx.eflags.Bits.u1TF);
5866
5867 uint32_t fIntrState = 0;
5868 rc = VMXReadVmcs32(VMX_VMCS32_GUEST_INT_STATE, &fIntrState);
5869 AssertRC(rc);
5870
5871 if (fIntrState & (VMX_VMCS_GUEST_INT_STATE_BLOCK_STI | VMX_VMCS_GUEST_INT_STATE_BLOCK_MOVSS))
5872 {
5873 fIntrState &= ~(VMX_VMCS_GUEST_INT_STATE_BLOCK_STI | VMX_VMCS_GUEST_INT_STATE_BLOCK_MOVSS);
5874 rc = VMXWriteVmcs32(VMX_VMCS32_GUEST_INT_STATE, fIntrState);
5875 AssertRC(rc);
5876 }
5877 }
5878
5879 return VINF_SUCCESS;
5880}
5881
5882
5883#ifdef VBOX_STRICT
5884/**
5885 * Strict function to validate segment registers.
5886 *
5887 * @param pVCpu The cross context virtual CPU structure.
5888 * @param pVmcsInfo The VMCS info. object.
5889 *
5890 * @remarks Will import guest CR0 on strict builds during validation of
5891 * segments.
5892 */
5893static void hmR0VmxValidateSegmentRegs(PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo)
5894{
5895 /*
5896 * Validate segment registers. See Intel spec. 26.3.1.2 "Checks on Guest Segment Registers".
5897 *
5898 * The reason we check for attribute value 0 in this function and not just the unusable bit is
5899 * because hmR0VmxExportGuestSegReg() only updates the VMCS' copy of the value with the
5900 * unusable bit and doesn't change the guest-context value.
5901 */
5902 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
5903 PCCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
5904 hmR0VmxImportGuestState(pVCpu, pVmcsInfo, CPUMCTX_EXTRN_CR0);
5905 if ( !pVM->hm.s.vmx.fUnrestrictedGuest
5906 && ( !CPUMIsGuestInRealModeEx(pCtx)
5907 && !CPUMIsGuestInV86ModeEx(pCtx)))
5908 {
5909 /* Protected mode checks */
5910 /* CS */
5911 Assert(pCtx->cs.Attr.n.u1Present);
5912 Assert(!(pCtx->cs.Attr.u & 0xf00));
5913 Assert(!(pCtx->cs.Attr.u & 0xfffe0000));
5914 Assert( (pCtx->cs.u32Limit & 0xfff) == 0xfff
5915 || !(pCtx->cs.Attr.n.u1Granularity));
5916 Assert( !(pCtx->cs.u32Limit & 0xfff00000)
5917 || (pCtx->cs.Attr.n.u1Granularity));
5918 /* CS cannot be loaded with NULL in protected mode. */
5919 Assert(pCtx->cs.Attr.u && !(pCtx->cs.Attr.u & X86DESCATTR_UNUSABLE)); /** @todo is this really true even for 64-bit CS? */
5920 if (pCtx->cs.Attr.n.u4Type == 9 || pCtx->cs.Attr.n.u4Type == 11)
5921 Assert(pCtx->cs.Attr.n.u2Dpl == pCtx->ss.Attr.n.u2Dpl);
5922 else if (pCtx->cs.Attr.n.u4Type == 13 || pCtx->cs.Attr.n.u4Type == 15)
5923 Assert(pCtx->cs.Attr.n.u2Dpl <= pCtx->ss.Attr.n.u2Dpl);
5924 else
5925 AssertMsgFailed(("Invalid CS Type %#x\n", pCtx->cs.Attr.n.u2Dpl));
5926 /* SS */
5927 Assert((pCtx->ss.Sel & X86_SEL_RPL) == (pCtx->cs.Sel & X86_SEL_RPL));
5928 Assert(pCtx->ss.Attr.n.u2Dpl == (pCtx->ss.Sel & X86_SEL_RPL));
5929 if ( !(pCtx->cr0 & X86_CR0_PE)
5930 || pCtx->cs.Attr.n.u4Type == 3)
5931 {
5932 Assert(!pCtx->ss.Attr.n.u2Dpl);
5933 }
5934 if (pCtx->ss.Attr.u && !(pCtx->ss.Attr.u & X86DESCATTR_UNUSABLE))
5935 {
5936 Assert((pCtx->ss.Sel & X86_SEL_RPL) == (pCtx->cs.Sel & X86_SEL_RPL));
5937 Assert(pCtx->ss.Attr.n.u4Type == 3 || pCtx->ss.Attr.n.u4Type == 7);
5938 Assert(pCtx->ss.Attr.n.u1Present);
5939 Assert(!(pCtx->ss.Attr.u & 0xf00));
5940 Assert(!(pCtx->ss.Attr.u & 0xfffe0000));
5941 Assert( (pCtx->ss.u32Limit & 0xfff) == 0xfff
5942 || !(pCtx->ss.Attr.n.u1Granularity));
5943 Assert( !(pCtx->ss.u32Limit & 0xfff00000)
5944 || (pCtx->ss.Attr.n.u1Granularity));
5945 }
5946 /* DS, ES, FS, GS - only check for usable selectors, see hmR0VmxExportGuestSegReg(). */
5947 if (pCtx->ds.Attr.u && !(pCtx->ds.Attr.u & X86DESCATTR_UNUSABLE))
5948 {
5949 Assert(pCtx->ds.Attr.n.u4Type & X86_SEL_TYPE_ACCESSED);
5950 Assert(pCtx->ds.Attr.n.u1Present);
5951 Assert(pCtx->ds.Attr.n.u4Type > 11 || pCtx->ds.Attr.n.u2Dpl >= (pCtx->ds.Sel & X86_SEL_RPL));
5952 Assert(!(pCtx->ds.Attr.u & 0xf00));
5953 Assert(!(pCtx->ds.Attr.u & 0xfffe0000));
5954 Assert( (pCtx->ds.u32Limit & 0xfff) == 0xfff
5955 || !(pCtx->ds.Attr.n.u1Granularity));
5956 Assert( !(pCtx->ds.u32Limit & 0xfff00000)
5957 || (pCtx->ds.Attr.n.u1Granularity));
5958 Assert( !(pCtx->ds.Attr.n.u4Type & X86_SEL_TYPE_CODE)
5959 || (pCtx->ds.Attr.n.u4Type & X86_SEL_TYPE_READ));
5960 }
5961 if (pCtx->es.Attr.u && !(pCtx->es.Attr.u & X86DESCATTR_UNUSABLE))
5962 {
5963 Assert(pCtx->es.Attr.n.u4Type & X86_SEL_TYPE_ACCESSED);
5964 Assert(pCtx->es.Attr.n.u1Present);
5965 Assert(pCtx->es.Attr.n.u4Type > 11 || pCtx->es.Attr.n.u2Dpl >= (pCtx->es.Sel & X86_SEL_RPL));
5966 Assert(!(pCtx->es.Attr.u & 0xf00));
5967 Assert(!(pCtx->es.Attr.u & 0xfffe0000));
5968 Assert( (pCtx->es.u32Limit & 0xfff) == 0xfff
5969 || !(pCtx->es.Attr.n.u1Granularity));
5970 Assert( !(pCtx->es.u32Limit & 0xfff00000)
5971 || (pCtx->es.Attr.n.u1Granularity));
5972 Assert( !(pCtx->es.Attr.n.u4Type & X86_SEL_TYPE_CODE)
5973 || (pCtx->es.Attr.n.u4Type & X86_SEL_TYPE_READ));
5974 }
5975 if (pCtx->fs.Attr.u && !(pCtx->fs.Attr.u & X86DESCATTR_UNUSABLE))
5976 {
5977 Assert(pCtx->fs.Attr.n.u4Type & X86_SEL_TYPE_ACCESSED);
5978 Assert(pCtx->fs.Attr.n.u1Present);
5979 Assert(pCtx->fs.Attr.n.u4Type > 11 || pCtx->fs.Attr.n.u2Dpl >= (pCtx->fs.Sel & X86_SEL_RPL));
5980 Assert(!(pCtx->fs.Attr.u & 0xf00));
5981 Assert(!(pCtx->fs.Attr.u & 0xfffe0000));
5982 Assert( (pCtx->fs.u32Limit & 0xfff) == 0xfff
5983 || !(pCtx->fs.Attr.n.u1Granularity));
5984 Assert( !(pCtx->fs.u32Limit & 0xfff00000)
5985 || (pCtx->fs.Attr.n.u1Granularity));
5986 Assert( !(pCtx->fs.Attr.n.u4Type & X86_SEL_TYPE_CODE)
5987 || (pCtx->fs.Attr.n.u4Type & X86_SEL_TYPE_READ));
5988 }
5989 if (pCtx->gs.Attr.u && !(pCtx->gs.Attr.u & X86DESCATTR_UNUSABLE))
5990 {
5991 Assert(pCtx->gs.Attr.n.u4Type & X86_SEL_TYPE_ACCESSED);
5992 Assert(pCtx->gs.Attr.n.u1Present);
5993 Assert(pCtx->gs.Attr.n.u4Type > 11 || pCtx->gs.Attr.n.u2Dpl >= (pCtx->gs.Sel & X86_SEL_RPL));
5994 Assert(!(pCtx->gs.Attr.u & 0xf00));
5995 Assert(!(pCtx->gs.Attr.u & 0xfffe0000));
5996 Assert( (pCtx->gs.u32Limit & 0xfff) == 0xfff
5997 || !(pCtx->gs.Attr.n.u1Granularity));
5998 Assert( !(pCtx->gs.u32Limit & 0xfff00000)
5999 || (pCtx->gs.Attr.n.u1Granularity));
6000 Assert( !(pCtx->gs.Attr.n.u4Type & X86_SEL_TYPE_CODE)
6001 || (pCtx->gs.Attr.n.u4Type & X86_SEL_TYPE_READ));
6002 }
6003 /* 64-bit capable CPUs. */
6004 Assert(!RT_HI_U32(pCtx->cs.u64Base));
6005 Assert(!pCtx->ss.Attr.u || !RT_HI_U32(pCtx->ss.u64Base));
6006 Assert(!pCtx->ds.Attr.u || !RT_HI_U32(pCtx->ds.u64Base));
6007 Assert(!pCtx->es.Attr.u || !RT_HI_U32(pCtx->es.u64Base));
6008 }
6009 else if ( CPUMIsGuestInV86ModeEx(pCtx)
6010 || ( CPUMIsGuestInRealModeEx(pCtx)
6011 && !pVM->hm.s.vmx.fUnrestrictedGuest))
6012 {
6013 /* Real and v86 mode checks. */
6014 /* hmR0VmxExportGuestSegReg() writes the modified in VMCS. We want what we're feeding to VT-x. */
6015 uint32_t u32CSAttr, u32SSAttr, u32DSAttr, u32ESAttr, u32FSAttr, u32GSAttr;
6016 if (pVmcsInfo->RealMode.fRealOnV86Active)
6017 {
6018 u32CSAttr = 0xf3; u32SSAttr = 0xf3; u32DSAttr = 0xf3;
6019 u32ESAttr = 0xf3; u32FSAttr = 0xf3; u32GSAttr = 0xf3;
6020 }
6021 else
6022 {
6023 u32CSAttr = pCtx->cs.Attr.u; u32SSAttr = pCtx->ss.Attr.u; u32DSAttr = pCtx->ds.Attr.u;
6024 u32ESAttr = pCtx->es.Attr.u; u32FSAttr = pCtx->fs.Attr.u; u32GSAttr = pCtx->gs.Attr.u;
6025 }
6026
6027 /* CS */
6028 AssertMsg((pCtx->cs.u64Base == (uint64_t)pCtx->cs.Sel << 4), ("CS base %#x %#x\n", pCtx->cs.u64Base, pCtx->cs.Sel));
6029 Assert(pCtx->cs.u32Limit == 0xffff);
6030 Assert(u32CSAttr == 0xf3);
6031 /* SS */
6032 Assert(pCtx->ss.u64Base == (uint64_t)pCtx->ss.Sel << 4);
6033 Assert(pCtx->ss.u32Limit == 0xffff);
6034 Assert(u32SSAttr == 0xf3);
6035 /* DS */
6036 Assert(pCtx->ds.u64Base == (uint64_t)pCtx->ds.Sel << 4);
6037 Assert(pCtx->ds.u32Limit == 0xffff);
6038 Assert(u32DSAttr == 0xf3);
6039 /* ES */
6040 Assert(pCtx->es.u64Base == (uint64_t)pCtx->es.Sel << 4);
6041 Assert(pCtx->es.u32Limit == 0xffff);
6042 Assert(u32ESAttr == 0xf3);
6043 /* FS */
6044 Assert(pCtx->fs.u64Base == (uint64_t)pCtx->fs.Sel << 4);
6045 Assert(pCtx->fs.u32Limit == 0xffff);
6046 Assert(u32FSAttr == 0xf3);
6047 /* GS */
6048 Assert(pCtx->gs.u64Base == (uint64_t)pCtx->gs.Sel << 4);
6049 Assert(pCtx->gs.u32Limit == 0xffff);
6050 Assert(u32GSAttr == 0xf3);
6051 /* 64-bit capable CPUs. */
6052 Assert(!RT_HI_U32(pCtx->cs.u64Base));
6053 Assert(!u32SSAttr || !RT_HI_U32(pCtx->ss.u64Base));
6054 Assert(!u32DSAttr || !RT_HI_U32(pCtx->ds.u64Base));
6055 Assert(!u32ESAttr || !RT_HI_U32(pCtx->es.u64Base));
6056 }
6057}
6058#endif /* VBOX_STRICT */
6059
6060
6061/**
6062 * Exports a guest segment register into the guest-state area in the VMCS.
6063 *
6064 * @returns VBox status code.
6065 * @param pVCpu The cross context virtual CPU structure.
6066 * @param pVmcsInfo The VMCS info. object.
6067 * @param iSegReg The segment register number (X86_SREG_XXX).
6068 * @param pSelReg Pointer to the segment selector.
6069 *
6070 * @remarks No-long-jump zone!!!
6071 */
6072static int hmR0VmxExportGuestSegReg(PVMCPUCC pVCpu, PCVMXVMCSINFO pVmcsInfo, uint8_t iSegReg, PCCPUMSELREG pSelReg)
6073{
6074 Assert(iSegReg < X86_SREG_COUNT);
6075 uint32_t const idxSel = g_aVmcsSegSel[iSegReg];
6076 uint32_t const idxLimit = g_aVmcsSegLimit[iSegReg];
6077 uint32_t const idxBase = g_aVmcsSegBase[iSegReg];
6078 uint32_t const idxAttr = g_aVmcsSegAttr[iSegReg];
6079
6080 uint32_t u32Access = pSelReg->Attr.u;
6081 if (pVmcsInfo->RealMode.fRealOnV86Active)
6082 {
6083 /* VT-x requires our real-using-v86 mode hack to override the segment access-right bits. */
6084 u32Access = 0xf3;
6085 Assert(pVCpu->CTX_SUFF(pVM)->hm.s.vmx.pRealModeTSS);
6086 Assert(PDMVmmDevHeapIsEnabled(pVCpu->CTX_SUFF(pVM)));
6087 RT_NOREF_PV(pVCpu);
6088 }
6089 else
6090 {
6091 /*
6092 * The way to differentiate between whether this is really a null selector or was just
6093 * a selector loaded with 0 in real-mode is using the segment attributes. A selector
6094 * loaded in real-mode with the value 0 is valid and usable in protected-mode and we
6095 * should -not- mark it as an unusable segment. Both the recompiler & VT-x ensures
6096 * NULL selectors loaded in protected-mode have their attribute as 0.
6097 */
6098 if (!u32Access)
6099 u32Access = X86DESCATTR_UNUSABLE;
6100 }
6101
6102 /* Validate segment access rights. Refer to Intel spec. "26.3.1.2 Checks on Guest Segment Registers". */
6103 AssertMsg((u32Access & X86DESCATTR_UNUSABLE) || (u32Access & X86_SEL_TYPE_ACCESSED),
6104 ("Access bit not set for usable segment. idx=%#x sel=%#x attr %#x\n", idxBase, pSelReg, pSelReg->Attr.u));
6105
6106 /*
6107 * Commit it to the VMCS.
6108 */
6109 int rc = VMXWriteVmcs32(idxSel, pSelReg->Sel); AssertRC(rc);
6110 rc = VMXWriteVmcs32(idxLimit, pSelReg->u32Limit); AssertRC(rc);
6111 rc = VMXWriteVmcsNw(idxBase, pSelReg->u64Base); AssertRC(rc);
6112 rc = VMXWriteVmcs32(idxAttr, u32Access); AssertRC(rc);
6113 return VINF_SUCCESS;
6114}
6115
6116
6117/**
6118 * Exports the guest segment registers, GDTR, IDTR, LDTR, TR into the guest-state
6119 * area in the VMCS.
6120 *
6121 * @returns VBox status code.
6122 * @param pVCpu The cross context virtual CPU structure.
6123 * @param pVmxTransient The VMX-transient structure.
6124 *
6125 * @remarks Will import guest CR0 on strict builds during validation of
6126 * segments.
6127 * @remarks No-long-jump zone!!!
6128 */
6129static int hmR0VmxExportGuestSegRegsXdtr(PVMCPUCC pVCpu, PCVMXTRANSIENT pVmxTransient)
6130{
6131 int rc = VERR_INTERNAL_ERROR_5;
6132 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
6133 PCCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
6134 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
6135
6136 /*
6137 * Guest Segment registers: CS, SS, DS, ES, FS, GS.
6138 */
6139 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_SREG_MASK)
6140 {
6141 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_CS)
6142 {
6143 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_CS);
6144 if (pVmcsInfo->RealMode.fRealOnV86Active)
6145 pVmcsInfo->RealMode.AttrCS.u = pCtx->cs.Attr.u;
6146 rc = hmR0VmxExportGuestSegReg(pVCpu, pVmcsInfo, X86_SREG_CS, &pCtx->cs);
6147 AssertRC(rc);
6148 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_CS);
6149 }
6150
6151 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_SS)
6152 {
6153 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_SS);
6154 if (pVmcsInfo->RealMode.fRealOnV86Active)
6155 pVmcsInfo->RealMode.AttrSS.u = pCtx->ss.Attr.u;
6156 rc = hmR0VmxExportGuestSegReg(pVCpu, pVmcsInfo, X86_SREG_SS, &pCtx->ss);
6157 AssertRC(rc);
6158 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_SS);
6159 }
6160
6161 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_DS)
6162 {
6163 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_DS);
6164 if (pVmcsInfo->RealMode.fRealOnV86Active)
6165 pVmcsInfo->RealMode.AttrDS.u = pCtx->ds.Attr.u;
6166 rc = hmR0VmxExportGuestSegReg(pVCpu, pVmcsInfo, X86_SREG_DS, &pCtx->ds);
6167 AssertRC(rc);
6168 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_DS);
6169 }
6170
6171 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_ES)
6172 {
6173 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_ES);
6174 if (pVmcsInfo->RealMode.fRealOnV86Active)
6175 pVmcsInfo->RealMode.AttrES.u = pCtx->es.Attr.u;
6176 rc = hmR0VmxExportGuestSegReg(pVCpu, pVmcsInfo, X86_SREG_ES, &pCtx->es);
6177 AssertRC(rc);
6178 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_ES);
6179 }
6180
6181 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_FS)
6182 {
6183 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_FS);
6184 if (pVmcsInfo->RealMode.fRealOnV86Active)
6185 pVmcsInfo->RealMode.AttrFS.u = pCtx->fs.Attr.u;
6186 rc = hmR0VmxExportGuestSegReg(pVCpu, pVmcsInfo, X86_SREG_FS, &pCtx->fs);
6187 AssertRC(rc);
6188 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_FS);
6189 }
6190
6191 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_GS)
6192 {
6193 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_GS);
6194 if (pVmcsInfo->RealMode.fRealOnV86Active)
6195 pVmcsInfo->RealMode.AttrGS.u = pCtx->gs.Attr.u;
6196 rc = hmR0VmxExportGuestSegReg(pVCpu, pVmcsInfo, X86_SREG_GS, &pCtx->gs);
6197 AssertRC(rc);
6198 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_GS);
6199 }
6200
6201#ifdef VBOX_STRICT
6202 hmR0VmxValidateSegmentRegs(pVCpu, pVmcsInfo);
6203#endif
6204 Log4Func(("cs={%#04x base=%#RX64 limit=%#RX32 attr=%#RX32}\n", pCtx->cs.Sel, pCtx->cs.u64Base, pCtx->cs.u32Limit,
6205 pCtx->cs.Attr.u));
6206 }
6207
6208 /*
6209 * Guest TR.
6210 */
6211 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_TR)
6212 {
6213 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_TR);
6214
6215 /*
6216 * Real-mode emulation using virtual-8086 mode with CR4.VME. Interrupt redirection is
6217 * achieved using the interrupt redirection bitmap (all bits cleared to let the guest
6218 * handle INT-n's) in the TSS. See hmR3InitFinalizeR0() to see how pRealModeTSS is setup.
6219 */
6220 uint16_t u16Sel;
6221 uint32_t u32Limit;
6222 uint64_t u64Base;
6223 uint32_t u32AccessRights;
6224 if (!pVmcsInfo->RealMode.fRealOnV86Active)
6225 {
6226 u16Sel = pCtx->tr.Sel;
6227 u32Limit = pCtx->tr.u32Limit;
6228 u64Base = pCtx->tr.u64Base;
6229 u32AccessRights = pCtx->tr.Attr.u;
6230 }
6231 else
6232 {
6233 Assert(!pVmxTransient->fIsNestedGuest);
6234 Assert(pVM->hm.s.vmx.pRealModeTSS);
6235 Assert(PDMVmmDevHeapIsEnabled(pVM)); /* Guaranteed by HMCanExecuteGuest() -XXX- what about inner loop changes? */
6236
6237 /* We obtain it here every time as PCI regions could be reconfigured in the guest, changing the VMMDev base. */
6238 RTGCPHYS GCPhys;
6239 rc = PDMVmmDevHeapR3ToGCPhys(pVM, pVM->hm.s.vmx.pRealModeTSS, &GCPhys);
6240 AssertRCReturn(rc, rc);
6241
6242 X86DESCATTR DescAttr;
6243 DescAttr.u = 0;
6244 DescAttr.n.u1Present = 1;
6245 DescAttr.n.u4Type = X86_SEL_TYPE_SYS_386_TSS_BUSY;
6246
6247 u16Sel = 0;
6248 u32Limit = HM_VTX_TSS_SIZE;
6249 u64Base = GCPhys;
6250 u32AccessRights = DescAttr.u;
6251 }
6252
6253 /* Validate. */
6254 Assert(!(u16Sel & RT_BIT(2)));
6255 AssertMsg( (u32AccessRights & 0xf) == X86_SEL_TYPE_SYS_386_TSS_BUSY
6256 || (u32AccessRights & 0xf) == X86_SEL_TYPE_SYS_286_TSS_BUSY, ("TSS is not busy!? %#x\n", u32AccessRights));
6257 AssertMsg(!(u32AccessRights & X86DESCATTR_UNUSABLE), ("TR unusable bit is not clear!? %#x\n", u32AccessRights));
6258 Assert(!(u32AccessRights & RT_BIT(4))); /* System MBZ.*/
6259 Assert(u32AccessRights & RT_BIT(7)); /* Present MB1.*/
6260 Assert(!(u32AccessRights & 0xf00)); /* 11:8 MBZ. */
6261 Assert(!(u32AccessRights & 0xfffe0000)); /* 31:17 MBZ. */
6262 Assert( (u32Limit & 0xfff) == 0xfff
6263 || !(u32AccessRights & RT_BIT(15))); /* Granularity MBZ. */
6264 Assert( !(pCtx->tr.u32Limit & 0xfff00000)
6265 || (u32AccessRights & RT_BIT(15))); /* Granularity MB1. */
6266
6267 rc = VMXWriteVmcs16(VMX_VMCS16_GUEST_TR_SEL, u16Sel); AssertRC(rc);
6268 rc = VMXWriteVmcs32(VMX_VMCS32_GUEST_TR_LIMIT, u32Limit); AssertRC(rc);
6269 rc = VMXWriteVmcs32(VMX_VMCS32_GUEST_TR_ACCESS_RIGHTS, u32AccessRights); AssertRC(rc);
6270 rc = VMXWriteVmcsNw(VMX_VMCS_GUEST_TR_BASE, u64Base); AssertRC(rc);
6271
6272 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_TR);
6273 Log4Func(("tr base=%#RX64 limit=%#RX32\n", pCtx->tr.u64Base, pCtx->tr.u32Limit));
6274 }
6275
6276 /*
6277 * Guest GDTR.
6278 */
6279 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_GDTR)
6280 {
6281 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_GDTR);
6282
6283 rc = VMXWriteVmcs32(VMX_VMCS32_GUEST_GDTR_LIMIT, pCtx->gdtr.cbGdt); AssertRC(rc);
6284 rc = VMXWriteVmcsNw(VMX_VMCS_GUEST_GDTR_BASE, pCtx->gdtr.pGdt); AssertRC(rc);
6285
6286 /* Validate. */
6287 Assert(!(pCtx->gdtr.cbGdt & 0xffff0000)); /* Bits 31:16 MBZ. */
6288
6289 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_GDTR);
6290 Log4Func(("gdtr base=%#RX64 limit=%#RX32\n", pCtx->gdtr.pGdt, pCtx->gdtr.cbGdt));
6291 }
6292
6293 /*
6294 * Guest LDTR.
6295 */
6296 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_LDTR)
6297 {
6298 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_LDTR);
6299
6300 /* The unusable bit is specific to VT-x, if it's a null selector mark it as an unusable segment. */
6301 uint32_t u32Access;
6302 if ( !pVmxTransient->fIsNestedGuest
6303 && !pCtx->ldtr.Attr.u)
6304 u32Access = X86DESCATTR_UNUSABLE;
6305 else
6306 u32Access = pCtx->ldtr.Attr.u;
6307
6308 rc = VMXWriteVmcs16(VMX_VMCS16_GUEST_LDTR_SEL, pCtx->ldtr.Sel); AssertRC(rc);
6309 rc = VMXWriteVmcs32(VMX_VMCS32_GUEST_LDTR_LIMIT, pCtx->ldtr.u32Limit); AssertRC(rc);
6310 rc = VMXWriteVmcs32(VMX_VMCS32_GUEST_LDTR_ACCESS_RIGHTS, u32Access); AssertRC(rc);
6311 rc = VMXWriteVmcsNw(VMX_VMCS_GUEST_LDTR_BASE, pCtx->ldtr.u64Base); AssertRC(rc);
6312
6313 /* Validate. */
6314 if (!(u32Access & X86DESCATTR_UNUSABLE))
6315 {
6316 Assert(!(pCtx->ldtr.Sel & RT_BIT(2))); /* TI MBZ. */
6317 Assert(pCtx->ldtr.Attr.n.u4Type == 2); /* Type MB2 (LDT). */
6318 Assert(!pCtx->ldtr.Attr.n.u1DescType); /* System MBZ. */
6319 Assert(pCtx->ldtr.Attr.n.u1Present == 1); /* Present MB1. */
6320 Assert(!pCtx->ldtr.Attr.n.u4LimitHigh); /* 11:8 MBZ. */
6321 Assert(!(pCtx->ldtr.Attr.u & 0xfffe0000)); /* 31:17 MBZ. */
6322 Assert( (pCtx->ldtr.u32Limit & 0xfff) == 0xfff
6323 || !pCtx->ldtr.Attr.n.u1Granularity); /* Granularity MBZ. */
6324 Assert( !(pCtx->ldtr.u32Limit & 0xfff00000)
6325 || pCtx->ldtr.Attr.n.u1Granularity); /* Granularity MB1. */
6326 }
6327
6328 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_LDTR);
6329 Log4Func(("ldtr base=%#RX64 limit=%#RX32\n", pCtx->ldtr.u64Base, pCtx->ldtr.u32Limit));
6330 }
6331
6332 /*
6333 * Guest IDTR.
6334 */
6335 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_IDTR)
6336 {
6337 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_IDTR);
6338
6339 rc = VMXWriteVmcs32(VMX_VMCS32_GUEST_IDTR_LIMIT, pCtx->idtr.cbIdt); AssertRC(rc);
6340 rc = VMXWriteVmcsNw(VMX_VMCS_GUEST_IDTR_BASE, pCtx->idtr.pIdt); AssertRC(rc);
6341
6342 /* Validate. */
6343 Assert(!(pCtx->idtr.cbIdt & 0xffff0000)); /* Bits 31:16 MBZ. */
6344
6345 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_IDTR);
6346 Log4Func(("idtr base=%#RX64 limit=%#RX32\n", pCtx->idtr.pIdt, pCtx->idtr.cbIdt));
6347 }
6348
6349 return VINF_SUCCESS;
6350}
6351
6352
6353/**
6354 * Exports certain guest MSRs into the VM-entry MSR-load and VM-exit MSR-store
6355 * areas.
6356 *
6357 * These MSRs will automatically be loaded to the host CPU on every successful
6358 * VM-entry and stored from the host CPU on every successful VM-exit.
6359 *
6360 * We creates/updates MSR slots for the host MSRs in the VM-exit MSR-load area. The
6361 * actual host MSR values are not- updated here for performance reasons. See
6362 * hmR0VmxExportHostMsrs().
6363 *
6364 * We also exports the guest sysenter MSRs into the guest-state area in the VMCS.
6365 *
6366 * @returns VBox status code.
6367 * @param pVCpu The cross context virtual CPU structure.
6368 * @param pVmxTransient The VMX-transient structure.
6369 *
6370 * @remarks No-long-jump zone!!!
6371 */
6372static int hmR0VmxExportGuestMsrs(PVMCPUCC pVCpu, PCVMXTRANSIENT pVmxTransient)
6373{
6374 AssertPtr(pVCpu);
6375 AssertPtr(pVmxTransient);
6376
6377 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
6378 PCCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
6379
6380 /*
6381 * MSRs that we use the auto-load/store MSR area in the VMCS.
6382 * For 64-bit hosts, we load/restore them lazily, see hmR0VmxLazyLoadGuestMsrs(),
6383 * nothing to do here. The host MSR values are updated when it's safe in
6384 * hmR0VmxLazySaveHostMsrs().
6385 *
6386 * For nested-guests, the guests MSRs from the VM-entry MSR-load area are already
6387 * loaded (into the guest-CPU context) by the VMLAUNCH/VMRESUME instruction
6388 * emulation. The merged MSR permission bitmap will ensure that we get VM-exits
6389 * for any MSR that are not part of the lazy MSRs so we do not need to place
6390 * those MSRs into the auto-load/store MSR area. Nothing to do here.
6391 */
6392 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_VMX_GUEST_AUTO_MSRS)
6393 {
6394 /* No auto-load/store MSRs currently. */
6395 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_VMX_GUEST_AUTO_MSRS);
6396 }
6397
6398 /*
6399 * Guest Sysenter MSRs.
6400 */
6401 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_SYSENTER_MSR_MASK)
6402 {
6403 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_SYSENTER_MSRS);
6404
6405 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_SYSENTER_CS_MSR)
6406 {
6407 int rc = VMXWriteVmcs32(VMX_VMCS32_GUEST_SYSENTER_CS, pCtx->SysEnter.cs);
6408 AssertRC(rc);
6409 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_SYSENTER_CS_MSR);
6410 }
6411
6412 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_SYSENTER_EIP_MSR)
6413 {
6414 int rc = VMXWriteVmcsNw(VMX_VMCS_GUEST_SYSENTER_EIP, pCtx->SysEnter.eip);
6415 AssertRC(rc);
6416 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_SYSENTER_EIP_MSR);
6417 }
6418
6419 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_SYSENTER_ESP_MSR)
6420 {
6421 int rc = VMXWriteVmcsNw(VMX_VMCS_GUEST_SYSENTER_ESP, pCtx->SysEnter.esp);
6422 AssertRC(rc);
6423 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_SYSENTER_ESP_MSR);
6424 }
6425 }
6426
6427 /*
6428 * Guest/host EFER MSR.
6429 */
6430 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_EFER_MSR)
6431 {
6432 /* Whether we are using the VMCS to swap the EFER MSR must have been
6433 determined earlier while exporting VM-entry/VM-exit controls. */
6434 Assert(!(ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_VMX_ENTRY_EXIT_CTLS));
6435 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_EFER);
6436
6437 if (hmR0VmxShouldSwapEferMsr(pVCpu, pVmxTransient))
6438 {
6439 /*
6440 * EFER.LME is written by software, while EFER.LMA is set by the CPU to (CR0.PG & EFER.LME).
6441 * This means a guest can set EFER.LME=1 while CR0.PG=0 and EFER.LMA can remain 0.
6442 * VT-x requires that "IA-32e mode guest" VM-entry control must be identical to EFER.LMA
6443 * and to CR0.PG. Without unrestricted execution, CR0.PG (used for VT-x, not the shadow)
6444 * must always be 1. This forces us to effectively clear both EFER.LMA and EFER.LME until
6445 * the guest has also set CR0.PG=1. Otherwise, we would run into an invalid-guest state
6446 * during VM-entry.
6447 */
6448 uint64_t uGuestEferMsr = pCtx->msrEFER;
6449 if (!pVM->hm.s.vmx.fUnrestrictedGuest)
6450 {
6451 if (!(pCtx->msrEFER & MSR_K6_EFER_LMA))
6452 uGuestEferMsr &= ~MSR_K6_EFER_LME;
6453 else
6454 Assert((pCtx->msrEFER & (MSR_K6_EFER_LMA | MSR_K6_EFER_LME)) == (MSR_K6_EFER_LMA | MSR_K6_EFER_LME));
6455 }
6456
6457 /*
6458 * If the CPU supports VMCS controls for swapping EFER, use it. Otherwise, we have no option
6459 * but to use the auto-load store MSR area in the VMCS for swapping EFER. See @bugref{7368}.
6460 */
6461 if (pVM->hm.s.vmx.fSupportsVmcsEfer)
6462 {
6463 int rc = VMXWriteVmcs64(VMX_VMCS64_GUEST_EFER_FULL, uGuestEferMsr);
6464 AssertRC(rc);
6465 }
6466 else
6467 {
6468 /*
6469 * We shall use the auto-load/store MSR area only for loading the EFER MSR but we must
6470 * continue to intercept guest read and write accesses to it, see @bugref{7386#c16}.
6471 */
6472 int rc = hmR0VmxAddAutoLoadStoreMsr(pVCpu, pVmxTransient, MSR_K6_EFER, uGuestEferMsr,
6473 false /* fSetReadWrite */, false /* fUpdateHostMsr */);
6474 AssertRCReturn(rc, rc);
6475 }
6476
6477 Log4Func(("efer=%#RX64 shadow=%#RX64\n", uGuestEferMsr, pCtx->msrEFER));
6478 }
6479 else if (!pVM->hm.s.vmx.fSupportsVmcsEfer)
6480 hmR0VmxRemoveAutoLoadStoreMsr(pVCpu, pVmxTransient, MSR_K6_EFER);
6481
6482 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_EFER_MSR);
6483 }
6484
6485 /*
6486 * Other MSRs.
6487 * Speculation Control (R/W).
6488 */
6489 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_OTHER_MSRS)
6490 {
6491 HMVMX_CPUMCTX_ASSERT(pVCpu, HM_CHANGED_GUEST_OTHER_MSRS);
6492 if (pVM->cpum.ro.GuestFeatures.fIbrs)
6493 {
6494 int rc = hmR0VmxAddAutoLoadStoreMsr(pVCpu, pVmxTransient, MSR_IA32_SPEC_CTRL, CPUMGetGuestSpecCtrl(pVCpu),
6495 false /* fSetReadWrite */, false /* fUpdateHostMsr */);
6496 AssertRCReturn(rc, rc);
6497 }
6498 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_OTHER_MSRS);
6499 }
6500
6501 return VINF_SUCCESS;
6502}
6503
6504
6505/**
6506 * Wrapper for running the guest code in VT-x.
6507 *
6508 * @returns VBox status code, no informational status codes.
6509 * @param pVCpu The cross context virtual CPU structure.
6510 * @param pVmxTransient The VMX-transient structure.
6511 *
6512 * @remarks No-long-jump zone!!!
6513 */
6514DECLINLINE(int) hmR0VmxRunGuest(PVMCPUCC pVCpu, PCVMXTRANSIENT pVmxTransient)
6515{
6516 /* Mark that HM is the keeper of all guest-CPU registers now that we're going to execute guest code. */
6517 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
6518 pCtx->fExtrn |= HMVMX_CPUMCTX_EXTRN_ALL | CPUMCTX_EXTRN_KEEPER_HM;
6519
6520 /** @todo Add stats for VMRESUME vs VMLAUNCH. */
6521
6522 /*
6523 * 64-bit Windows uses XMM registers in the kernel as the Microsoft compiler expresses
6524 * floating-point operations using SSE instructions. Some XMM registers (XMM6-XMM15) are
6525 * callee-saved and thus the need for this XMM wrapper.
6526 *
6527 * See MSDN "Configuring Programs for 64-bit/x64 Software Conventions / Register Usage".
6528 */
6529 PCVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
6530 bool const fResumeVM = RT_BOOL(pVmcsInfo->fVmcsState & VMX_V_VMCS_LAUNCH_STATE_LAUNCHED);
6531 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
6532#ifdef VBOX_WITH_KERNEL_USING_XMM
6533 int rc = hmR0VMXStartVMWrapXMM(fResumeVM, pCtx, NULL /*pvUnused*/, pVM, pVCpu, pVmcsInfo->pfnStartVM);
6534#else
6535 int rc = pVmcsInfo->pfnStartVM(fResumeVM, pCtx, NULL /*pvUnused*/, pVM, pVCpu);
6536#endif
6537 AssertMsg(rc <= VINF_SUCCESS, ("%Rrc\n", rc));
6538 return rc;
6539}
6540
6541
6542/**
6543 * Reports world-switch error and dumps some useful debug info.
6544 *
6545 * @param pVCpu The cross context virtual CPU structure.
6546 * @param rcVMRun The return code from VMLAUNCH/VMRESUME.
6547 * @param pVmxTransient The VMX-transient structure (only
6548 * exitReason updated).
6549 */
6550static void hmR0VmxReportWorldSwitchError(PVMCPUCC pVCpu, int rcVMRun, PVMXTRANSIENT pVmxTransient)
6551{
6552 Assert(pVCpu);
6553 Assert(pVmxTransient);
6554 HMVMX_ASSERT_PREEMPT_SAFE(pVCpu);
6555
6556 Log4Func(("VM-entry failure: %Rrc\n", rcVMRun));
6557 switch (rcVMRun)
6558 {
6559 case VERR_VMX_INVALID_VMXON_PTR:
6560 AssertFailed();
6561 break;
6562 case VINF_SUCCESS: /* VMLAUNCH/VMRESUME succeeded but VM-entry failed... yeah, true story. */
6563 case VERR_VMX_UNABLE_TO_START_VM: /* VMLAUNCH/VMRESUME itself failed. */
6564 {
6565 int rc = VMXReadVmcs32(VMX_VMCS32_RO_EXIT_REASON, &pVCpu->hm.s.vmx.LastError.u32ExitReason);
6566 rc |= VMXReadVmcs32(VMX_VMCS32_RO_VM_INSTR_ERROR, &pVCpu->hm.s.vmx.LastError.u32InstrError);
6567 AssertRC(rc);
6568 hmR0VmxReadExitQualVmcs(pVmxTransient);
6569
6570 pVCpu->hm.s.vmx.LastError.idEnteredCpu = pVCpu->hm.s.idEnteredCpu;
6571 /* LastError.idCurrentCpu was already updated in hmR0VmxPreRunGuestCommitted().
6572 Cannot do it here as we may have been long preempted. */
6573
6574#ifdef VBOX_STRICT
6575 PVMXVMCSINFO pVmcsInfo = hmGetVmxActiveVmcsInfo(pVCpu);
6576 Log4(("uExitReason %#RX32 (VmxTransient %#RX16)\n", pVCpu->hm.s.vmx.LastError.u32ExitReason,
6577 pVmxTransient->uExitReason));
6578 Log4(("Exit Qualification %#RX64\n", pVmxTransient->uExitQual));
6579 Log4(("InstrError %#RX32\n", pVCpu->hm.s.vmx.LastError.u32InstrError));
6580 if (pVCpu->hm.s.vmx.LastError.u32InstrError <= HMVMX_INSTR_ERROR_MAX)
6581 Log4(("InstrError Desc. \"%s\"\n", g_apszVmxInstrErrors[pVCpu->hm.s.vmx.LastError.u32InstrError]));
6582 else
6583 Log4(("InstrError Desc. Range exceeded %u\n", HMVMX_INSTR_ERROR_MAX));
6584 Log4(("Entered host CPU %u\n", pVCpu->hm.s.vmx.LastError.idEnteredCpu));
6585 Log4(("Current host CPU %u\n", pVCpu->hm.s.vmx.LastError.idCurrentCpu));
6586
6587 static struct
6588 {
6589 /** Name of the field to log. */
6590 const char *pszName;
6591 /** The VMCS field. */
6592 uint32_t uVmcsField;
6593 /** Whether host support of this field needs to be checked. */
6594 bool fCheckSupport;
6595 } const s_aVmcsFields[] =
6596 {
6597 { "VMX_VMCS32_CTRL_PIN_EXEC", VMX_VMCS32_CTRL_PIN_EXEC, false },
6598 { "VMX_VMCS32_CTRL_PROC_EXEC", VMX_VMCS32_CTRL_PROC_EXEC, false },
6599 { "VMX_VMCS32_CTRL_PROC_EXEC2", VMX_VMCS32_CTRL_PROC_EXEC2, true },
6600 { "VMX_VMCS32_CTRL_ENTRY", VMX_VMCS32_CTRL_ENTRY, false },
6601 { "VMX_VMCS32_CTRL_EXIT", VMX_VMCS32_CTRL_EXIT, false },
6602 { "VMX_VMCS32_CTRL_CR3_TARGET_COUNT", VMX_VMCS32_CTRL_CR3_TARGET_COUNT, false },
6603 { "VMX_VMCS32_CTRL_ENTRY_INTERRUPTION_INFO", VMX_VMCS32_CTRL_ENTRY_INTERRUPTION_INFO, false },
6604 { "VMX_VMCS32_CTRL_ENTRY_EXCEPTION_ERRCODE", VMX_VMCS32_CTRL_ENTRY_EXCEPTION_ERRCODE, false },
6605 { "VMX_VMCS32_CTRL_ENTRY_INSTR_LENGTH", VMX_VMCS32_CTRL_ENTRY_INSTR_LENGTH, false },
6606 { "VMX_VMCS32_CTRL_TPR_THRESHOLD", VMX_VMCS32_CTRL_TPR_THRESHOLD, false },
6607 { "VMX_VMCS32_CTRL_EXIT_MSR_STORE_COUNT", VMX_VMCS32_CTRL_EXIT_MSR_STORE_COUNT, false },
6608 { "VMX_VMCS32_CTRL_EXIT_MSR_LOAD_COUNT", VMX_VMCS32_CTRL_EXIT_MSR_LOAD_COUNT, false },
6609 { "VMX_VMCS32_CTRL_ENTRY_MSR_LOAD_COUNT", VMX_VMCS32_CTRL_ENTRY_MSR_LOAD_COUNT, false },
6610 { "VMX_VMCS32_CTRL_EXCEPTION_BITMAP", VMX_VMCS32_CTRL_EXCEPTION_BITMAP, false },
6611 { "VMX_VMCS32_CTRL_PAGEFAULT_ERROR_MASK", VMX_VMCS32_CTRL_PAGEFAULT_ERROR_MASK, false },
6612 { "VMX_VMCS32_CTRL_PAGEFAULT_ERROR_MATCH", VMX_VMCS32_CTRL_PAGEFAULT_ERROR_MATCH, false },
6613 { "VMX_VMCS_CTRL_CR0_MASK", VMX_VMCS_CTRL_CR0_MASK, false },
6614 { "VMX_VMCS_CTRL_CR0_READ_SHADOW", VMX_VMCS_CTRL_CR0_READ_SHADOW, false },
6615 { "VMX_VMCS_CTRL_CR4_MASK", VMX_VMCS_CTRL_CR4_MASK, false },
6616 { "VMX_VMCS_CTRL_CR4_READ_SHADOW", VMX_VMCS_CTRL_CR4_READ_SHADOW, false },
6617 { "VMX_VMCS64_CTRL_EPTP_FULL", VMX_VMCS64_CTRL_EPTP_FULL, true },
6618 { "VMX_VMCS_GUEST_RIP", VMX_VMCS_GUEST_RIP, false },
6619 { "VMX_VMCS_GUEST_RSP", VMX_VMCS_GUEST_RSP, false },
6620 { "VMX_VMCS_GUEST_RFLAGS", VMX_VMCS_GUEST_RFLAGS, false },
6621 { "VMX_VMCS16_VPID", VMX_VMCS16_VPID, true, },
6622 { "VMX_VMCS_HOST_CR0", VMX_VMCS_HOST_CR0, false },
6623 { "VMX_VMCS_HOST_CR3", VMX_VMCS_HOST_CR3, false },
6624 { "VMX_VMCS_HOST_CR4", VMX_VMCS_HOST_CR4, false },
6625 /* The order of selector fields below are fixed! */
6626 { "VMX_VMCS16_HOST_ES_SEL", VMX_VMCS16_HOST_ES_SEL, false },
6627 { "VMX_VMCS16_HOST_CS_SEL", VMX_VMCS16_HOST_CS_SEL, false },
6628 { "VMX_VMCS16_HOST_SS_SEL", VMX_VMCS16_HOST_SS_SEL, false },
6629 { "VMX_VMCS16_HOST_DS_SEL", VMX_VMCS16_HOST_DS_SEL, false },
6630 { "VMX_VMCS16_HOST_FS_SEL", VMX_VMCS16_HOST_FS_SEL, false },
6631 { "VMX_VMCS16_HOST_GS_SEL", VMX_VMCS16_HOST_GS_SEL, false },
6632 { "VMX_VMCS16_HOST_TR_SEL", VMX_VMCS16_HOST_TR_SEL, false },
6633 /* End of ordered selector fields. */
6634 { "VMX_VMCS_HOST_TR_BASE", VMX_VMCS_HOST_TR_BASE, false },
6635 { "VMX_VMCS_HOST_GDTR_BASE", VMX_VMCS_HOST_GDTR_BASE, false },
6636 { "VMX_VMCS_HOST_IDTR_BASE", VMX_VMCS_HOST_IDTR_BASE, false },
6637 { "VMX_VMCS32_HOST_SYSENTER_CS", VMX_VMCS32_HOST_SYSENTER_CS, false },
6638 { "VMX_VMCS_HOST_SYSENTER_EIP", VMX_VMCS_HOST_SYSENTER_EIP, false },
6639 { "VMX_VMCS_HOST_SYSENTER_ESP", VMX_VMCS_HOST_SYSENTER_ESP, false },
6640 { "VMX_VMCS_HOST_RSP", VMX_VMCS_HOST_RSP, false },
6641 { "VMX_VMCS_HOST_RIP", VMX_VMCS_HOST_RIP, false }
6642 };
6643
6644 RTGDTR HostGdtr;
6645 ASMGetGDTR(&HostGdtr);
6646
6647 uint32_t const cVmcsFields = RT_ELEMENTS(s_aVmcsFields);
6648 for (uint32_t i = 0; i < cVmcsFields; i++)
6649 {
6650 uint32_t const uVmcsField = s_aVmcsFields[i].uVmcsField;
6651
6652 bool fSupported;
6653 if (!s_aVmcsFields[i].fCheckSupport)
6654 fSupported = true;
6655 else
6656 {
6657 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
6658 switch (uVmcsField)
6659 {
6660 case VMX_VMCS64_CTRL_EPTP_FULL: fSupported = pVM->hm.s.fNestedPaging; break;
6661 case VMX_VMCS16_VPID: fSupported = pVM->hm.s.vmx.fVpid; break;
6662 case VMX_VMCS32_CTRL_PROC_EXEC2:
6663 fSupported = RT_BOOL(pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_USE_SECONDARY_CTLS);
6664 break;
6665 default:
6666 AssertMsgFailedReturnVoid(("Failed to provide VMCS field support for %#RX32\n", uVmcsField));
6667 }
6668 }
6669
6670 if (fSupported)
6671 {
6672 uint8_t const uWidth = RT_BF_GET(uVmcsField, VMX_BF_VMCSFIELD_WIDTH);
6673 switch (uWidth)
6674 {
6675 case VMX_VMCSFIELD_WIDTH_16BIT:
6676 {
6677 uint16_t u16Val;
6678 rc = VMXReadVmcs16(uVmcsField, &u16Val);
6679 AssertRC(rc);
6680 Log4(("%-40s = %#RX16\n", s_aVmcsFields[i].pszName, u16Val));
6681
6682 if ( uVmcsField >= VMX_VMCS16_HOST_ES_SEL
6683 && uVmcsField <= VMX_VMCS16_HOST_TR_SEL)
6684 {
6685 if (u16Val < HostGdtr.cbGdt)
6686 {
6687 /* Order of selectors in s_apszSel is fixed and matches the order in s_aVmcsFields. */
6688 static const char * const s_apszSel[] = { "Host ES", "Host CS", "Host SS", "Host DS",
6689 "Host FS", "Host GS", "Host TR" };
6690 uint8_t const idxSel = RT_BF_GET(uVmcsField, VMX_BF_VMCSFIELD_INDEX);
6691 Assert(idxSel < RT_ELEMENTS(s_apszSel));
6692 PCX86DESCHC pDesc = (PCX86DESCHC)(HostGdtr.pGdt + (u16Val & X86_SEL_MASK));
6693 hmR0DumpDescriptor(pDesc, u16Val, s_apszSel[idxSel]);
6694 }
6695 else
6696 Log4((" Selector value exceeds GDT limit!\n"));
6697 }
6698 break;
6699 }
6700
6701 case VMX_VMCSFIELD_WIDTH_32BIT:
6702 {
6703 uint32_t u32Val;
6704 rc = VMXReadVmcs32(uVmcsField, &u32Val);
6705 AssertRC(rc);
6706 Log4(("%-40s = %#RX32\n", s_aVmcsFields[i].pszName, u32Val));
6707 break;
6708 }
6709
6710 case VMX_VMCSFIELD_WIDTH_64BIT:
6711 case VMX_VMCSFIELD_WIDTH_NATURAL:
6712 {
6713 uint64_t u64Val;
6714 rc = VMXReadVmcs64(uVmcsField, &u64Val);
6715 AssertRC(rc);
6716 Log4(("%-40s = %#RX64\n", s_aVmcsFields[i].pszName, u64Val));
6717 break;
6718 }
6719 }
6720 }
6721 }
6722
6723 Log4(("MSR_K6_EFER = %#RX64\n", ASMRdMsr(MSR_K6_EFER)));
6724 Log4(("MSR_K8_CSTAR = %#RX64\n", ASMRdMsr(MSR_K8_CSTAR)));
6725 Log4(("MSR_K8_LSTAR = %#RX64\n", ASMRdMsr(MSR_K8_LSTAR)));
6726 Log4(("MSR_K6_STAR = %#RX64\n", ASMRdMsr(MSR_K6_STAR)));
6727 Log4(("MSR_K8_SF_MASK = %#RX64\n", ASMRdMsr(MSR_K8_SF_MASK)));
6728 Log4(("MSR_K8_KERNEL_GS_BASE = %#RX64\n", ASMRdMsr(MSR_K8_KERNEL_GS_BASE)));
6729#endif /* VBOX_STRICT */
6730 break;
6731 }
6732
6733 default:
6734 /* Impossible */
6735 AssertMsgFailed(("hmR0VmxReportWorldSwitchError %Rrc (%#x)\n", rcVMRun, rcVMRun));
6736 break;
6737 }
6738}
6739
6740
6741/**
6742 * Sets up the usage of TSC-offsetting and updates the VMCS.
6743 *
6744 * If offsetting is not possible, cause VM-exits on RDTSC(P)s. Also sets up the
6745 * VMX-preemption timer.
6746 *
6747 * @returns VBox status code.
6748 * @param pVCpu The cross context virtual CPU structure.
6749 * @param pVmxTransient The VMX-transient structure.
6750 *
6751 * @remarks No-long-jump zone!!!
6752 */
6753static void hmR0VmxUpdateTscOffsettingAndPreemptTimer(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
6754{
6755 bool fOffsettedTsc;
6756 bool fParavirtTsc;
6757 uint64_t uTscOffset;
6758 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
6759 PVMXVMCSINFO pVmcsInfo = hmGetVmxActiveVmcsInfo(pVCpu);
6760
6761 if (pVM->hm.s.vmx.fUsePreemptTimer)
6762 {
6763 uint64_t cTicksToDeadline = TMCpuTickGetDeadlineAndTscOffset(pVM, pVCpu, &uTscOffset, &fOffsettedTsc, &fParavirtTsc);
6764
6765 /* Make sure the returned values have sane upper and lower boundaries. */
6766 uint64_t u64CpuHz = SUPGetCpuHzFromGipBySetIndex(g_pSUPGlobalInfoPage, pVCpu->iHostCpuSet);
6767 cTicksToDeadline = RT_MIN(cTicksToDeadline, u64CpuHz / 64); /* 1/64th of a second */
6768 cTicksToDeadline = RT_MAX(cTicksToDeadline, u64CpuHz / 2048); /* 1/2048th of a second */
6769 cTicksToDeadline >>= pVM->hm.s.vmx.cPreemptTimerShift;
6770
6771 /** @todo r=ramshankar: We need to find a way to integrate nested-guest
6772 * preemption timers here. We probably need to clamp the preemption timer,
6773 * after converting the timer value to the host. */
6774 uint32_t const cPreemptionTickCount = (uint32_t)RT_MIN(cTicksToDeadline, UINT32_MAX - 16);
6775 int rc = VMXWriteVmcs32(VMX_VMCS32_PREEMPT_TIMER_VALUE, cPreemptionTickCount);
6776 AssertRC(rc);
6777 }
6778 else
6779 fOffsettedTsc = TMCpuTickCanUseRealTSC(pVM, pVCpu, &uTscOffset, &fParavirtTsc);
6780
6781 if (fParavirtTsc)
6782 {
6783 /* Currently neither Hyper-V nor KVM need to update their paravirt. TSC
6784 information before every VM-entry, hence disable it for performance sake. */
6785#if 0
6786 int rc = GIMR0UpdateParavirtTsc(pVM, 0 /* u64Offset */);
6787 AssertRC(rc);
6788#endif
6789 STAM_COUNTER_INC(&pVCpu->hm.s.StatTscParavirt);
6790 }
6791
6792 if ( fOffsettedTsc
6793 && RT_LIKELY(!pVCpu->hm.s.fDebugWantRdTscExit))
6794 {
6795 if (pVmxTransient->fIsNestedGuest)
6796 uTscOffset = CPUMApplyNestedGuestTscOffset(pVCpu, uTscOffset);
6797 hmR0VmxSetTscOffsetVmcs(pVmcsInfo, uTscOffset);
6798 hmR0VmxRemoveProcCtlsVmcs(pVCpu, pVmxTransient, VMX_PROC_CTLS_RDTSC_EXIT);
6799 }
6800 else
6801 {
6802 /* We can't use TSC-offsetting (non-fixed TSC, warp drive active etc.), VM-exit on RDTSC(P). */
6803 hmR0VmxSetProcCtlsVmcs(pVmxTransient, VMX_PROC_CTLS_RDTSC_EXIT);
6804 }
6805}
6806
6807
6808/**
6809 * Gets the IEM exception flags for the specified vector and IDT vectoring /
6810 * VM-exit interruption info type.
6811 *
6812 * @returns The IEM exception flags.
6813 * @param uVector The event vector.
6814 * @param uVmxEventType The VMX event type.
6815 *
6816 * @remarks This function currently only constructs flags required for
6817 * IEMEvaluateRecursiveXcpt and not the complete flags (e.g, error-code
6818 * and CR2 aspects of an exception are not included).
6819 */
6820static uint32_t hmR0VmxGetIemXcptFlags(uint8_t uVector, uint32_t uVmxEventType)
6821{
6822 uint32_t fIemXcptFlags;
6823 switch (uVmxEventType)
6824 {
6825 case VMX_IDT_VECTORING_INFO_TYPE_HW_XCPT:
6826 case VMX_IDT_VECTORING_INFO_TYPE_NMI:
6827 fIemXcptFlags = IEM_XCPT_FLAGS_T_CPU_XCPT;
6828 break;
6829
6830 case VMX_IDT_VECTORING_INFO_TYPE_EXT_INT:
6831 fIemXcptFlags = IEM_XCPT_FLAGS_T_EXT_INT;
6832 break;
6833
6834 case VMX_IDT_VECTORING_INFO_TYPE_PRIV_SW_XCPT:
6835 fIemXcptFlags = IEM_XCPT_FLAGS_T_SOFT_INT | IEM_XCPT_FLAGS_ICEBP_INSTR;
6836 break;
6837
6838 case VMX_IDT_VECTORING_INFO_TYPE_SW_XCPT:
6839 {
6840 fIemXcptFlags = IEM_XCPT_FLAGS_T_SOFT_INT;
6841 if (uVector == X86_XCPT_BP)
6842 fIemXcptFlags |= IEM_XCPT_FLAGS_BP_INSTR;
6843 else if (uVector == X86_XCPT_OF)
6844 fIemXcptFlags |= IEM_XCPT_FLAGS_OF_INSTR;
6845 else
6846 {
6847 fIemXcptFlags = 0;
6848 AssertMsgFailed(("Unexpected vector for software exception. uVector=%#x", uVector));
6849 }
6850 break;
6851 }
6852
6853 case VMX_IDT_VECTORING_INFO_TYPE_SW_INT:
6854 fIemXcptFlags = IEM_XCPT_FLAGS_T_SOFT_INT;
6855 break;
6856
6857 default:
6858 fIemXcptFlags = 0;
6859 AssertMsgFailed(("Unexpected vector type! uVmxEventType=%#x uVector=%#x", uVmxEventType, uVector));
6860 break;
6861 }
6862 return fIemXcptFlags;
6863}
6864
6865
6866/**
6867 * Sets an event as a pending event to be injected into the guest.
6868 *
6869 * @param pVCpu The cross context virtual CPU structure.
6870 * @param u32IntInfo The VM-entry interruption-information field.
6871 * @param cbInstr The VM-entry instruction length in bytes (for
6872 * software interrupts, exceptions and privileged
6873 * software exceptions).
6874 * @param u32ErrCode The VM-entry exception error code.
6875 * @param GCPtrFaultAddress The fault-address (CR2) in case it's a
6876 * page-fault.
6877 */
6878DECLINLINE(void) hmR0VmxSetPendingEvent(PVMCPUCC pVCpu, uint32_t u32IntInfo, uint32_t cbInstr, uint32_t u32ErrCode,
6879 RTGCUINTPTR GCPtrFaultAddress)
6880{
6881 Assert(!pVCpu->hm.s.Event.fPending);
6882 pVCpu->hm.s.Event.fPending = true;
6883 pVCpu->hm.s.Event.u64IntInfo = u32IntInfo;
6884 pVCpu->hm.s.Event.u32ErrCode = u32ErrCode;
6885 pVCpu->hm.s.Event.cbInstr = cbInstr;
6886 pVCpu->hm.s.Event.GCPtrFaultAddress = GCPtrFaultAddress;
6887}
6888
6889
6890/**
6891 * Sets an external interrupt as pending-for-injection into the VM.
6892 *
6893 * @param pVCpu The cross context virtual CPU structure.
6894 * @param u8Interrupt The external interrupt vector.
6895 */
6896DECLINLINE(void) hmR0VmxSetPendingExtInt(PVMCPUCC pVCpu, uint8_t u8Interrupt)
6897{
6898 uint32_t const u32IntInfo = RT_BF_MAKE(VMX_BF_EXIT_INT_INFO_VECTOR, u8Interrupt)
6899 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_TYPE, VMX_ENTRY_INT_INFO_TYPE_EXT_INT)
6900 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_ERR_CODE_VALID, 0)
6901 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_VALID, 1);
6902 hmR0VmxSetPendingEvent(pVCpu, u32IntInfo, 0 /* cbInstr */, 0 /* u32ErrCode */, 0 /* GCPtrFaultAddress */);
6903}
6904
6905
6906/**
6907 * Sets an NMI (\#NMI) exception as pending-for-injection into the VM.
6908 *
6909 * @param pVCpu The cross context virtual CPU structure.
6910 */
6911DECLINLINE(void) hmR0VmxSetPendingXcptNmi(PVMCPUCC pVCpu)
6912{
6913 uint32_t const u32IntInfo = RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_VECTOR, X86_XCPT_NMI)
6914 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_TYPE, VMX_ENTRY_INT_INFO_TYPE_NMI)
6915 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_ERR_CODE_VALID, 0)
6916 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_VALID, 1);
6917 hmR0VmxSetPendingEvent(pVCpu, u32IntInfo, 0 /* cbInstr */, 0 /* u32ErrCode */, 0 /* GCPtrFaultAddress */);
6918}
6919
6920
6921/**
6922 * Sets a double-fault (\#DF) exception as pending-for-injection into the VM.
6923 *
6924 * @param pVCpu The cross context virtual CPU structure.
6925 */
6926DECLINLINE(void) hmR0VmxSetPendingXcptDF(PVMCPUCC pVCpu)
6927{
6928 uint32_t const u32IntInfo = RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_VECTOR, X86_XCPT_DF)
6929 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_TYPE, VMX_EXIT_INT_INFO_TYPE_HW_XCPT)
6930 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_ERR_CODE_VALID, 1)
6931 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_VALID, 1);
6932 hmR0VmxSetPendingEvent(pVCpu, u32IntInfo, 0 /* cbInstr */, 0 /* u32ErrCode */, 0 /* GCPtrFaultAddress */);
6933}
6934
6935
6936/**
6937 * Sets an invalid-opcode (\#UD) exception as pending-for-injection into the VM.
6938 *
6939 * @param pVCpu The cross context virtual CPU structure.
6940 */
6941DECLINLINE(void) hmR0VmxSetPendingXcptUD(PVMCPUCC pVCpu)
6942{
6943 uint32_t const u32IntInfo = RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_VECTOR, X86_XCPT_UD)
6944 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_TYPE, VMX_EXIT_INT_INFO_TYPE_HW_XCPT)
6945 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_ERR_CODE_VALID, 0)
6946 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_VALID, 1);
6947 hmR0VmxSetPendingEvent(pVCpu, u32IntInfo, 0 /* cbInstr */, 0 /* u32ErrCode */, 0 /* GCPtrFaultAddress */);
6948}
6949
6950
6951/**
6952 * Sets a debug (\#DB) exception as pending-for-injection into the VM.
6953 *
6954 * @param pVCpu The cross context virtual CPU structure.
6955 */
6956DECLINLINE(void) hmR0VmxSetPendingXcptDB(PVMCPUCC pVCpu)
6957{
6958 uint32_t const u32IntInfo = RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_VECTOR, X86_XCPT_DB)
6959 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_TYPE, VMX_EXIT_INT_INFO_TYPE_HW_XCPT)
6960 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_ERR_CODE_VALID, 0)
6961 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_VALID, 1);
6962 hmR0VmxSetPendingEvent(pVCpu, u32IntInfo, 0 /* cbInstr */, 0 /* u32ErrCode */, 0 /* GCPtrFaultAddress */);
6963}
6964
6965
6966#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
6967/**
6968 * Sets a general-protection (\#GP) exception as pending-for-injection into the VM.
6969 *
6970 * @param pVCpu The cross context virtual CPU structure.
6971 * @param u32ErrCode The error code for the general-protection exception.
6972 */
6973DECLINLINE(void) hmR0VmxSetPendingXcptGP(PVMCPUCC pVCpu, uint32_t u32ErrCode)
6974{
6975 uint32_t const u32IntInfo = RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_VECTOR, X86_XCPT_GP)
6976 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_TYPE, VMX_EXIT_INT_INFO_TYPE_HW_XCPT)
6977 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_ERR_CODE_VALID, 1)
6978 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_VALID, 1);
6979 hmR0VmxSetPendingEvent(pVCpu, u32IntInfo, 0 /* cbInstr */, u32ErrCode, 0 /* GCPtrFaultAddress */);
6980}
6981
6982
6983/**
6984 * Sets a stack (\#SS) exception as pending-for-injection into the VM.
6985 *
6986 * @param pVCpu The cross context virtual CPU structure.
6987 * @param u32ErrCode The error code for the stack exception.
6988 */
6989DECLINLINE(void) hmR0VmxSetPendingXcptSS(PVMCPUCC pVCpu, uint32_t u32ErrCode)
6990{
6991 uint32_t const u32IntInfo = RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_VECTOR, X86_XCPT_SS)
6992 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_TYPE, VMX_EXIT_INT_INFO_TYPE_HW_XCPT)
6993 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_ERR_CODE_VALID, 1)
6994 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_VALID, 1);
6995 hmR0VmxSetPendingEvent(pVCpu, u32IntInfo, 0 /* cbInstr */, u32ErrCode, 0 /* GCPtrFaultAddress */);
6996}
6997#endif /* VBOX_WITH_NESTED_HWVIRT_VMX */
6998
6999
7000/**
7001 * Fixes up attributes for the specified segment register.
7002 *
7003 * @param pVCpu The cross context virtual CPU structure.
7004 * @param pSelReg The segment register that needs fixing.
7005 * @param idxSel The VMCS field for the corresponding segment register.
7006 */
7007static void hmR0VmxFixUnusableSegRegAttr(PVMCPUCC pVCpu, PCPUMSELREG pSelReg, uint32_t idxSel)
7008{
7009 Assert(pSelReg->Attr.u & X86DESCATTR_UNUSABLE);
7010
7011 /*
7012 * If VT-x marks the segment as unusable, most other bits remain undefined:
7013 * - For CS the L, D and G bits have meaning.
7014 * - For SS the DPL has meaning (it -is- the CPL for Intel and VBox).
7015 * - For the remaining data segments no bits are defined.
7016 *
7017 * The present bit and the unusable bit has been observed to be set at the
7018 * same time (the selector was supposed to be invalid as we started executing
7019 * a V8086 interrupt in ring-0).
7020 *
7021 * What should be important for the rest of the VBox code, is that the P bit is
7022 * cleared. Some of the other VBox code recognizes the unusable bit, but
7023 * AMD-V certainly don't, and REM doesn't really either. So, to be on the
7024 * safe side here, we'll strip off P and other bits we don't care about. If
7025 * any code breaks because Attr.u != 0 when Sel < 4, it should be fixed.
7026 *
7027 * See Intel spec. 27.3.2 "Saving Segment Registers and Descriptor-Table Registers".
7028 */
7029#ifdef VBOX_STRICT
7030 uint32_t const uAttr = pSelReg->Attr.u;
7031#endif
7032
7033 /* Masking off: X86DESCATTR_P, X86DESCATTR_LIMIT_HIGH, and X86DESCATTR_AVL. The latter two are really irrelevant. */
7034 pSelReg->Attr.u &= X86DESCATTR_UNUSABLE | X86DESCATTR_L | X86DESCATTR_D | X86DESCATTR_G
7035 | X86DESCATTR_DPL | X86DESCATTR_TYPE | X86DESCATTR_DT;
7036
7037#ifdef VBOX_STRICT
7038 VMMRZCallRing3Disable(pVCpu);
7039 Log4Func(("Unusable %#x: sel=%#x attr=%#x -> %#x\n", idxSel, pSelReg->Sel, uAttr, pSelReg->Attr.u));
7040# ifdef DEBUG_bird
7041 AssertMsg((uAttr & ~X86DESCATTR_P) == pSelReg->Attr.u,
7042 ("%#x: %#x != %#x (sel=%#x base=%#llx limit=%#x)\n",
7043 idxSel, uAttr, pSelReg->Attr.u, pSelReg->Sel, pSelReg->u64Base, pSelReg->u32Limit));
7044# endif
7045 VMMRZCallRing3Enable(pVCpu);
7046 NOREF(uAttr);
7047#endif
7048 RT_NOREF2(pVCpu, idxSel);
7049}
7050
7051
7052/**
7053 * Imports a guest segment register from the current VMCS into the guest-CPU
7054 * context.
7055 *
7056 * @param pVCpu The cross context virtual CPU structure.
7057 * @param iSegReg The segment register number (X86_SREG_XXX).
7058 *
7059 * @remarks Called with interrupts and/or preemption disabled.
7060 */
7061static void hmR0VmxImportGuestSegReg(PVMCPUCC pVCpu, uint8_t iSegReg)
7062{
7063 Assert(iSegReg < X86_SREG_COUNT);
7064
7065 uint32_t const idxSel = g_aVmcsSegSel[iSegReg];
7066 uint32_t const idxLimit = g_aVmcsSegLimit[iSegReg];
7067 uint32_t const idxAttr = g_aVmcsSegAttr[iSegReg];
7068 uint32_t const idxBase = g_aVmcsSegBase[iSegReg];
7069
7070 uint16_t u16Sel;
7071 uint64_t u64Base;
7072 uint32_t u32Limit, u32Attr;
7073 int rc = VMXReadVmcs16(idxSel, &u16Sel); AssertRC(rc);
7074 rc = VMXReadVmcs32(idxLimit, &u32Limit); AssertRC(rc);
7075 rc = VMXReadVmcs32(idxAttr, &u32Attr); AssertRC(rc);
7076 rc = VMXReadVmcsNw(idxBase, &u64Base); AssertRC(rc);
7077
7078 PCPUMSELREG pSelReg = &pVCpu->cpum.GstCtx.aSRegs[iSegReg];
7079 pSelReg->Sel = u16Sel;
7080 pSelReg->ValidSel = u16Sel;
7081 pSelReg->fFlags = CPUMSELREG_FLAGS_VALID;
7082 pSelReg->u32Limit = u32Limit;
7083 pSelReg->u64Base = u64Base;
7084 pSelReg->Attr.u = u32Attr;
7085 if (u32Attr & X86DESCATTR_UNUSABLE)
7086 hmR0VmxFixUnusableSegRegAttr(pVCpu, pSelReg, idxSel);
7087}
7088
7089
7090/**
7091 * Imports the guest LDTR from the current VMCS into the guest-CPU context.
7092 *
7093 * @param pVCpu The cross context virtual CPU structure.
7094 *
7095 * @remarks Called with interrupts and/or preemption disabled.
7096 */
7097static void hmR0VmxImportGuestLdtr(PVMCPUCC pVCpu)
7098{
7099 uint16_t u16Sel;
7100 uint64_t u64Base;
7101 uint32_t u32Limit, u32Attr;
7102 int rc = VMXReadVmcs16(VMX_VMCS16_GUEST_LDTR_SEL, &u16Sel); AssertRC(rc);
7103 rc = VMXReadVmcs32(VMX_VMCS32_GUEST_LDTR_LIMIT, &u32Limit); AssertRC(rc);
7104 rc = VMXReadVmcs32(VMX_VMCS32_GUEST_LDTR_ACCESS_RIGHTS, &u32Attr); AssertRC(rc);
7105 rc = VMXReadVmcsNw(VMX_VMCS_GUEST_LDTR_BASE, &u64Base); AssertRC(rc);
7106
7107 pVCpu->cpum.GstCtx.ldtr.Sel = u16Sel;
7108 pVCpu->cpum.GstCtx.ldtr.ValidSel = u16Sel;
7109 pVCpu->cpum.GstCtx.ldtr.fFlags = CPUMSELREG_FLAGS_VALID;
7110 pVCpu->cpum.GstCtx.ldtr.u32Limit = u32Limit;
7111 pVCpu->cpum.GstCtx.ldtr.u64Base = u64Base;
7112 pVCpu->cpum.GstCtx.ldtr.Attr.u = u32Attr;
7113 if (u32Attr & X86DESCATTR_UNUSABLE)
7114 hmR0VmxFixUnusableSegRegAttr(pVCpu, &pVCpu->cpum.GstCtx.ldtr, VMX_VMCS16_GUEST_LDTR_SEL);
7115}
7116
7117
7118/**
7119 * Imports the guest TR from the current VMCS into the guest-CPU context.
7120 *
7121 * @param pVCpu The cross context virtual CPU structure.
7122 *
7123 * @remarks Called with interrupts and/or preemption disabled.
7124 */
7125static void hmR0VmxImportGuestTr(PVMCPUCC pVCpu)
7126{
7127 uint16_t u16Sel;
7128 uint64_t u64Base;
7129 uint32_t u32Limit, u32Attr;
7130 int rc = VMXReadVmcs16(VMX_VMCS16_GUEST_TR_SEL, &u16Sel); AssertRC(rc);
7131 rc = VMXReadVmcs32(VMX_VMCS32_GUEST_TR_LIMIT, &u32Limit); AssertRC(rc);
7132 rc = VMXReadVmcs32(VMX_VMCS32_GUEST_TR_ACCESS_RIGHTS, &u32Attr); AssertRC(rc);
7133 rc = VMXReadVmcsNw(VMX_VMCS_GUEST_TR_BASE, &u64Base); AssertRC(rc);
7134
7135 pVCpu->cpum.GstCtx.tr.Sel = u16Sel;
7136 pVCpu->cpum.GstCtx.tr.ValidSel = u16Sel;
7137 pVCpu->cpum.GstCtx.tr.fFlags = CPUMSELREG_FLAGS_VALID;
7138 pVCpu->cpum.GstCtx.tr.u32Limit = u32Limit;
7139 pVCpu->cpum.GstCtx.tr.u64Base = u64Base;
7140 pVCpu->cpum.GstCtx.tr.Attr.u = u32Attr;
7141 /* TR is the only selector that can never be unusable. */
7142 Assert(!(u32Attr & X86DESCATTR_UNUSABLE));
7143}
7144
7145
7146/**
7147 * Imports the guest RIP from the VMCS back into the guest-CPU context.
7148 *
7149 * @param pVCpu The cross context virtual CPU structure.
7150 *
7151 * @remarks Called with interrupts and/or preemption disabled, should not assert!
7152 * @remarks Do -not- call this function directly, use hmR0VmxImportGuestState()
7153 * instead!!!
7154 */
7155static void hmR0VmxImportGuestRip(PVMCPUCC pVCpu)
7156{
7157 uint64_t u64Val;
7158 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
7159 if (pCtx->fExtrn & CPUMCTX_EXTRN_RIP)
7160 {
7161 int rc = VMXReadVmcsNw(VMX_VMCS_GUEST_RIP, &u64Val);
7162 AssertRC(rc);
7163
7164 pCtx->rip = u64Val;
7165 EMR0HistoryUpdatePC(pVCpu, pCtx->rip, false);
7166 pCtx->fExtrn &= ~CPUMCTX_EXTRN_RIP;
7167 }
7168}
7169
7170
7171/**
7172 * Imports the guest RFLAGS from the VMCS back into the guest-CPU context.
7173 *
7174 * @param pVCpu The cross context virtual CPU structure.
7175 * @param pVmcsInfo The VMCS info. object.
7176 *
7177 * @remarks Called with interrupts and/or preemption disabled, should not assert!
7178 * @remarks Do -not- call this function directly, use hmR0VmxImportGuestState()
7179 * instead!!!
7180 */
7181static void hmR0VmxImportGuestRFlags(PVMCPUCC pVCpu, PCVMXVMCSINFO pVmcsInfo)
7182{
7183 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
7184 if (pCtx->fExtrn & CPUMCTX_EXTRN_RFLAGS)
7185 {
7186 uint64_t u64Val;
7187 int rc = VMXReadVmcsNw(VMX_VMCS_GUEST_RFLAGS, &u64Val);
7188 AssertRC(rc);
7189
7190 pCtx->rflags.u64 = u64Val;
7191 if (pVmcsInfo->RealMode.fRealOnV86Active)
7192 {
7193 pCtx->eflags.Bits.u1VM = 0;
7194 pCtx->eflags.Bits.u2IOPL = pVmcsInfo->RealMode.Eflags.Bits.u2IOPL;
7195 }
7196 pCtx->fExtrn &= ~CPUMCTX_EXTRN_RFLAGS;
7197 }
7198}
7199
7200
7201/**
7202 * Imports the guest interruptibility-state from the VMCS back into the guest-CPU
7203 * context.
7204 *
7205 * @param pVCpu The cross context virtual CPU structure.
7206 * @param pVmcsInfo The VMCS info. object.
7207 *
7208 * @remarks Called with interrupts and/or preemption disabled, try not to assert and
7209 * do not log!
7210 * @remarks Do -not- call this function directly, use hmR0VmxImportGuestState()
7211 * instead!!!
7212 */
7213static void hmR0VmxImportGuestIntrState(PVMCPUCC pVCpu, PCVMXVMCSINFO pVmcsInfo)
7214{
7215 uint32_t u32Val;
7216 int rc = VMXReadVmcs32(VMX_VMCS32_GUEST_INT_STATE, &u32Val); AssertRC(rc);
7217 if (!u32Val)
7218 {
7219 if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS))
7220 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS);
7221 CPUMSetGuestNmiBlocking(pVCpu, false);
7222 }
7223 else
7224 {
7225 /*
7226 * We must import RIP here to set our EM interrupt-inhibited state.
7227 * We also import RFLAGS as our code that evaluates pending interrupts
7228 * before VM-entry requires it.
7229 */
7230 hmR0VmxImportGuestRip(pVCpu);
7231 hmR0VmxImportGuestRFlags(pVCpu, pVmcsInfo);
7232
7233 if (u32Val & (VMX_VMCS_GUEST_INT_STATE_BLOCK_MOVSS | VMX_VMCS_GUEST_INT_STATE_BLOCK_STI))
7234 EMSetInhibitInterruptsPC(pVCpu, pVCpu->cpum.GstCtx.rip);
7235 else if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS))
7236 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS);
7237
7238 bool const fNmiBlocking = RT_BOOL(u32Val & VMX_VMCS_GUEST_INT_STATE_BLOCK_NMI);
7239 CPUMSetGuestNmiBlocking(pVCpu, fNmiBlocking);
7240 }
7241}
7242
7243
7244/**
7245 * Worker for VMXR0ImportStateOnDemand.
7246 *
7247 * @returns VBox status code.
7248 * @param pVCpu The cross context virtual CPU structure.
7249 * @param pVmcsInfo The VMCS info. object.
7250 * @param fWhat What to import, CPUMCTX_EXTRN_XXX.
7251 */
7252static int hmR0VmxImportGuestState(PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo, uint64_t fWhat)
7253{
7254 int rc = VINF_SUCCESS;
7255 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
7256 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
7257 uint32_t u32Val;
7258
7259 /*
7260 * Note! This is hack to workaround a mysterious BSOD observed with release builds
7261 * on Windows 10 64-bit hosts. Profile and debug builds are not affected and
7262 * neither are other host platforms.
7263 *
7264 * Committing this temporarily as it prevents BSOD.
7265 *
7266 * Update: This is very likely a compiler optimization bug, see @bugref{9180}.
7267 */
7268#ifdef RT_OS_WINDOWS
7269 if (pVM == 0 || pVM == (void *)(uintptr_t)-1)
7270 return VERR_HM_IPE_1;
7271#endif
7272
7273 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatImportGuestState, x);
7274
7275 /*
7276 * We disable interrupts to make the updating of the state and in particular
7277 * the fExtrn modification atomic wrt to preemption hooks.
7278 */
7279 RTCCUINTREG const fEFlags = ASMIntDisableFlags();
7280
7281 fWhat &= pCtx->fExtrn;
7282 if (fWhat)
7283 {
7284 do
7285 {
7286 if (fWhat & CPUMCTX_EXTRN_RIP)
7287 hmR0VmxImportGuestRip(pVCpu);
7288
7289 if (fWhat & CPUMCTX_EXTRN_RFLAGS)
7290 hmR0VmxImportGuestRFlags(pVCpu, pVmcsInfo);
7291
7292 if (fWhat & CPUMCTX_EXTRN_HM_VMX_INT_STATE)
7293 hmR0VmxImportGuestIntrState(pVCpu, pVmcsInfo);
7294
7295 if (fWhat & CPUMCTX_EXTRN_RSP)
7296 {
7297 rc = VMXReadVmcsNw(VMX_VMCS_GUEST_RSP, &pCtx->rsp);
7298 AssertRC(rc);
7299 }
7300
7301 if (fWhat & CPUMCTX_EXTRN_SREG_MASK)
7302 {
7303 bool const fRealOnV86Active = pVmcsInfo->RealMode.fRealOnV86Active;
7304 if (fWhat & CPUMCTX_EXTRN_CS)
7305 {
7306 hmR0VmxImportGuestSegReg(pVCpu, X86_SREG_CS);
7307 hmR0VmxImportGuestRip(pVCpu);
7308 if (fRealOnV86Active)
7309 pCtx->cs.Attr.u = pVmcsInfo->RealMode.AttrCS.u;
7310 EMR0HistoryUpdatePC(pVCpu, pCtx->cs.u64Base + pCtx->rip, true /* fFlattened */);
7311 }
7312 if (fWhat & CPUMCTX_EXTRN_SS)
7313 {
7314 hmR0VmxImportGuestSegReg(pVCpu, X86_SREG_SS);
7315 if (fRealOnV86Active)
7316 pCtx->ss.Attr.u = pVmcsInfo->RealMode.AttrSS.u;
7317 }
7318 if (fWhat & CPUMCTX_EXTRN_DS)
7319 {
7320 hmR0VmxImportGuestSegReg(pVCpu, X86_SREG_DS);
7321 if (fRealOnV86Active)
7322 pCtx->ds.Attr.u = pVmcsInfo->RealMode.AttrDS.u;
7323 }
7324 if (fWhat & CPUMCTX_EXTRN_ES)
7325 {
7326 hmR0VmxImportGuestSegReg(pVCpu, X86_SREG_ES);
7327 if (fRealOnV86Active)
7328 pCtx->es.Attr.u = pVmcsInfo->RealMode.AttrES.u;
7329 }
7330 if (fWhat & CPUMCTX_EXTRN_FS)
7331 {
7332 hmR0VmxImportGuestSegReg(pVCpu, X86_SREG_FS);
7333 if (fRealOnV86Active)
7334 pCtx->fs.Attr.u = pVmcsInfo->RealMode.AttrFS.u;
7335 }
7336 if (fWhat & CPUMCTX_EXTRN_GS)
7337 {
7338 hmR0VmxImportGuestSegReg(pVCpu, X86_SREG_GS);
7339 if (fRealOnV86Active)
7340 pCtx->gs.Attr.u = pVmcsInfo->RealMode.AttrGS.u;
7341 }
7342 }
7343
7344 if (fWhat & CPUMCTX_EXTRN_TABLE_MASK)
7345 {
7346 if (fWhat & CPUMCTX_EXTRN_LDTR)
7347 hmR0VmxImportGuestLdtr(pVCpu);
7348
7349 if (fWhat & CPUMCTX_EXTRN_GDTR)
7350 {
7351 rc = VMXReadVmcsNw(VMX_VMCS_GUEST_GDTR_BASE, &pCtx->gdtr.pGdt); AssertRC(rc);
7352 rc = VMXReadVmcs32(VMX_VMCS32_GUEST_GDTR_LIMIT, &u32Val); AssertRC(rc);
7353 pCtx->gdtr.cbGdt = u32Val;
7354 }
7355
7356 /* Guest IDTR. */
7357 if (fWhat & CPUMCTX_EXTRN_IDTR)
7358 {
7359 rc = VMXReadVmcsNw(VMX_VMCS_GUEST_IDTR_BASE, &pCtx->idtr.pIdt); AssertRC(rc);
7360 rc = VMXReadVmcs32(VMX_VMCS32_GUEST_IDTR_LIMIT, &u32Val); AssertRC(rc);
7361 pCtx->idtr.cbIdt = u32Val;
7362 }
7363
7364 /* Guest TR. */
7365 if (fWhat & CPUMCTX_EXTRN_TR)
7366 {
7367 /* Real-mode emulation using virtual-8086 mode has the fake TSS (pRealModeTSS) in TR,
7368 don't need to import that one. */
7369 if (!pVmcsInfo->RealMode.fRealOnV86Active)
7370 hmR0VmxImportGuestTr(pVCpu);
7371 }
7372 }
7373
7374 if (fWhat & CPUMCTX_EXTRN_DR7)
7375 {
7376 if (!pVCpu->hm.s.fUsingHyperDR7)
7377 rc = VMXReadVmcsNw(VMX_VMCS_GUEST_DR7, &pCtx->dr[7]); AssertRC(rc);
7378 }
7379
7380 if (fWhat & CPUMCTX_EXTRN_SYSENTER_MSRS)
7381 {
7382 rc = VMXReadVmcsNw(VMX_VMCS_GUEST_SYSENTER_EIP, &pCtx->SysEnter.eip); AssertRC(rc);
7383 rc = VMXReadVmcsNw(VMX_VMCS_GUEST_SYSENTER_ESP, &pCtx->SysEnter.esp); AssertRC(rc);
7384 rc = VMXReadVmcs32(VMX_VMCS32_GUEST_SYSENTER_CS, &u32Val); AssertRC(rc);
7385 pCtx->SysEnter.cs = u32Val;
7386 }
7387
7388 if (fWhat & CPUMCTX_EXTRN_KERNEL_GS_BASE)
7389 {
7390 if ( pVM->hm.s.fAllow64BitGuests
7391 && (pVCpu->hm.s.vmx.fLazyMsrs & VMX_LAZY_MSRS_LOADED_GUEST))
7392 pCtx->msrKERNELGSBASE = ASMRdMsr(MSR_K8_KERNEL_GS_BASE);
7393 }
7394
7395 if (fWhat & CPUMCTX_EXTRN_SYSCALL_MSRS)
7396 {
7397 if ( pVM->hm.s.fAllow64BitGuests
7398 && (pVCpu->hm.s.vmx.fLazyMsrs & VMX_LAZY_MSRS_LOADED_GUEST))
7399 {
7400 pCtx->msrLSTAR = ASMRdMsr(MSR_K8_LSTAR);
7401 pCtx->msrSTAR = ASMRdMsr(MSR_K6_STAR);
7402 pCtx->msrSFMASK = ASMRdMsr(MSR_K8_SF_MASK);
7403 }
7404 }
7405
7406 if (fWhat & (CPUMCTX_EXTRN_TSC_AUX | CPUMCTX_EXTRN_OTHER_MSRS))
7407 {
7408 PCVMXAUTOMSR pMsrs = (PCVMXAUTOMSR)pVmcsInfo->pvGuestMsrStore;
7409 uint32_t const cMsrs = pVmcsInfo->cExitMsrStore;
7410 Assert(pMsrs);
7411 Assert(cMsrs <= VMX_MISC_MAX_MSRS(pVM->hm.s.vmx.Msrs.u64Misc));
7412 Assert(sizeof(*pMsrs) * cMsrs <= X86_PAGE_4K_SIZE);
7413 for (uint32_t i = 0; i < cMsrs; i++)
7414 {
7415 uint32_t const idMsr = pMsrs[i].u32Msr;
7416 switch (idMsr)
7417 {
7418 case MSR_K8_TSC_AUX: CPUMSetGuestTscAux(pVCpu, pMsrs[i].u64Value); break;
7419 case MSR_IA32_SPEC_CTRL: CPUMSetGuestSpecCtrl(pVCpu, pMsrs[i].u64Value); break;
7420 case MSR_K6_EFER: /* Can't be changed without causing a VM-exit */ break;
7421 default:
7422 {
7423 pCtx->fExtrn = 0;
7424 pVCpu->hm.s.u32HMError = pMsrs->u32Msr;
7425 ASMSetFlags(fEFlags);
7426 AssertMsgFailed(("Unexpected MSR in auto-load/store area. idMsr=%#RX32 cMsrs=%u\n", idMsr, cMsrs));
7427 return VERR_HM_UNEXPECTED_LD_ST_MSR;
7428 }
7429 }
7430 }
7431 }
7432
7433 if (fWhat & CPUMCTX_EXTRN_CR_MASK)
7434 {
7435 if (fWhat & CPUMCTX_EXTRN_CR0)
7436 {
7437 uint64_t u64Cr0;
7438 uint64_t u64Shadow;
7439 rc = VMXReadVmcsNw(VMX_VMCS_GUEST_CR0, &u64Cr0); AssertRC(rc);
7440 rc = VMXReadVmcsNw(VMX_VMCS_CTRL_CR0_READ_SHADOW, &u64Shadow); AssertRC(rc);
7441#ifndef VBOX_WITH_NESTED_HWVIRT_VMX
7442 u64Cr0 = (u64Cr0 & ~pVmcsInfo->u64Cr0Mask)
7443 | (u64Shadow & pVmcsInfo->u64Cr0Mask);
7444#else
7445 if (!CPUMIsGuestInVmxNonRootMode(pCtx))
7446 {
7447 u64Cr0 = (u64Cr0 & ~pVmcsInfo->u64Cr0Mask)
7448 | (u64Shadow & pVmcsInfo->u64Cr0Mask);
7449 }
7450 else
7451 {
7452 /*
7453 * We've merged the guest and nested-guest's CR0 guest/host mask while executing
7454 * the nested-guest using hardware-assisted VMX. Accordingly we need to
7455 * re-construct CR0. See @bugref{9180#c95} for details.
7456 */
7457 PCVMXVMCSINFO pVmcsInfoGst = &pVCpu->hm.s.vmx.VmcsInfo;
7458 PCVMXVVMCS pVmcsNstGst = pVCpu->cpum.GstCtx.hwvirt.vmx.CTX_SUFF(pVmcs);
7459 u64Cr0 = (u64Cr0 & ~pVmcsInfo->u64Cr0Mask)
7460 | (pVmcsNstGst->u64GuestCr0.u & pVmcsNstGst->u64Cr0Mask.u)
7461 | (u64Shadow & (pVmcsInfoGst->u64Cr0Mask & ~pVmcsNstGst->u64Cr0Mask.u));
7462 }
7463#endif
7464 VMMRZCallRing3Disable(pVCpu); /* May call into PGM which has Log statements. */
7465 CPUMSetGuestCR0(pVCpu, u64Cr0);
7466 VMMRZCallRing3Enable(pVCpu);
7467 }
7468
7469 if (fWhat & CPUMCTX_EXTRN_CR4)
7470 {
7471 uint64_t u64Cr4;
7472 uint64_t u64Shadow;
7473 rc = VMXReadVmcsNw(VMX_VMCS_GUEST_CR4, &u64Cr4); AssertRC(rc);
7474 rc |= VMXReadVmcsNw(VMX_VMCS_CTRL_CR4_READ_SHADOW, &u64Shadow); AssertRC(rc);
7475#ifndef VBOX_WITH_NESTED_HWVIRT_VMX
7476 u64Cr4 = (u64Cr4 & ~pVmcsInfo->u64Cr4Mask)
7477 | (u64Shadow & pVmcsInfo->u64Cr4Mask);
7478#else
7479 if (!CPUMIsGuestInVmxNonRootMode(pCtx))
7480 {
7481 u64Cr4 = (u64Cr4 & ~pVmcsInfo->u64Cr4Mask)
7482 | (u64Shadow & pVmcsInfo->u64Cr4Mask);
7483 }
7484 else
7485 {
7486 /*
7487 * We've merged the guest and nested-guest's CR4 guest/host mask while executing
7488 * the nested-guest using hardware-assisted VMX. Accordingly we need to
7489 * re-construct CR4. See @bugref{9180#c95} for details.
7490 */
7491 PCVMXVMCSINFO pVmcsInfoGst = &pVCpu->hm.s.vmx.VmcsInfo;
7492 PCVMXVVMCS pVmcsNstGst = pVCpu->cpum.GstCtx.hwvirt.vmx.CTX_SUFF(pVmcs);
7493 u64Cr4 = (u64Cr4 & ~pVmcsInfo->u64Cr4Mask)
7494 | (pVmcsNstGst->u64GuestCr4.u & pVmcsNstGst->u64Cr4Mask.u)
7495 | (u64Shadow & (pVmcsInfoGst->u64Cr4Mask & ~pVmcsNstGst->u64Cr4Mask.u));
7496 }
7497#endif
7498 pCtx->cr4 = u64Cr4;
7499 }
7500
7501 if (fWhat & CPUMCTX_EXTRN_CR3)
7502 {
7503 /* CR0.PG bit changes are always intercepted, so it's up to date. */
7504 if ( pVM->hm.s.vmx.fUnrestrictedGuest
7505 || ( pVM->hm.s.fNestedPaging
7506 && CPUMIsGuestPagingEnabledEx(pCtx)))
7507 {
7508 uint64_t u64Cr3;
7509 rc = VMXReadVmcsNw(VMX_VMCS_GUEST_CR3, &u64Cr3); AssertRC(rc);
7510 if (pCtx->cr3 != u64Cr3)
7511 {
7512 pCtx->cr3 = u64Cr3;
7513 VMCPU_FF_SET(pVCpu, VMCPU_FF_HM_UPDATE_CR3);
7514 }
7515
7516 /* If the guest is in PAE mode, sync back the PDPE's into the guest state.
7517 Note: CR4.PAE, CR0.PG, EFER MSR changes are always intercepted, so they're up to date. */
7518 if (CPUMIsGuestInPAEModeEx(pCtx))
7519 {
7520 rc = VMXReadVmcs64(VMX_VMCS64_GUEST_PDPTE0_FULL, &pVCpu->hm.s.aPdpes[0].u); AssertRC(rc);
7521 rc = VMXReadVmcs64(VMX_VMCS64_GUEST_PDPTE1_FULL, &pVCpu->hm.s.aPdpes[1].u); AssertRC(rc);
7522 rc = VMXReadVmcs64(VMX_VMCS64_GUEST_PDPTE2_FULL, &pVCpu->hm.s.aPdpes[2].u); AssertRC(rc);
7523 rc = VMXReadVmcs64(VMX_VMCS64_GUEST_PDPTE3_FULL, &pVCpu->hm.s.aPdpes[3].u); AssertRC(rc);
7524 VMCPU_FF_SET(pVCpu, VMCPU_FF_HM_UPDATE_PAE_PDPES);
7525 }
7526 }
7527 }
7528 }
7529
7530#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
7531 if (fWhat & CPUMCTX_EXTRN_HWVIRT)
7532 {
7533 if ( (pVmcsInfo->u32ProcCtls2 & VMX_PROC_CTLS2_VMCS_SHADOWING)
7534 && !CPUMIsGuestInVmxNonRootMode(pCtx))
7535 {
7536 Assert(CPUMIsGuestInVmxRootMode(pCtx));
7537 rc = hmR0VmxCopyShadowToNstGstVmcs(pVCpu, pVmcsInfo);
7538 if (RT_SUCCESS(rc))
7539 { /* likely */ }
7540 else
7541 break;
7542 }
7543 }
7544#endif
7545 } while (0);
7546
7547 if (RT_SUCCESS(rc))
7548 {
7549 /* Update fExtrn. */
7550 pCtx->fExtrn &= ~fWhat;
7551
7552 /* If everything has been imported, clear the HM keeper bit. */
7553 if (!(pCtx->fExtrn & HMVMX_CPUMCTX_EXTRN_ALL))
7554 {
7555 pCtx->fExtrn &= ~CPUMCTX_EXTRN_KEEPER_HM;
7556 Assert(!pCtx->fExtrn);
7557 }
7558 }
7559 }
7560 else
7561 AssertMsg(!pCtx->fExtrn || (pCtx->fExtrn & HMVMX_CPUMCTX_EXTRN_ALL), ("%#RX64\n", pCtx->fExtrn));
7562
7563 /*
7564 * Restore interrupts.
7565 */
7566 ASMSetFlags(fEFlags);
7567
7568 STAM_PROFILE_ADV_STOP(& pVCpu->hm.s.StatImportGuestState, x);
7569
7570 if (RT_SUCCESS(rc))
7571 { /* likely */ }
7572 else
7573 return rc;
7574
7575 /*
7576 * Honor any pending CR3 updates.
7577 *
7578 * Consider this scenario: VM-exit -> VMMRZCallRing3Enable() -> do stuff that causes a longjmp -> VMXR0CallRing3Callback()
7579 * -> VMMRZCallRing3Disable() -> hmR0VmxImportGuestState() -> Sets VMCPU_FF_HM_UPDATE_CR3 pending -> return from the longjmp
7580 * -> continue with VM-exit handling -> hmR0VmxImportGuestState() and here we are.
7581 *
7582 * The reason for such complicated handling is because VM-exits that call into PGM expect CR3 to be up-to-date and thus
7583 * if any CR3-saves -before- the VM-exit (longjmp) postponed the CR3 update via the force-flag, any VM-exit handler that
7584 * calls into PGM when it re-saves CR3 will end up here and we call PGMUpdateCR3(). This is why the code below should
7585 * -NOT- check if CPUMCTX_EXTRN_CR3 is set!
7586 *
7587 * The longjmp exit path can't check these CR3 force-flags and call code that takes a lock again. We cover for it here.
7588 */
7589 if (VMMRZCallRing3IsEnabled(pVCpu))
7590 {
7591 if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_HM_UPDATE_CR3))
7592 {
7593 Assert(!(ASMAtomicUoReadU64(&pCtx->fExtrn) & CPUMCTX_EXTRN_CR3));
7594 PGMUpdateCR3(pVCpu, CPUMGetGuestCR3(pVCpu));
7595 }
7596
7597 if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_HM_UPDATE_PAE_PDPES))
7598 PGMGstUpdatePaePdpes(pVCpu, &pVCpu->hm.s.aPdpes[0]);
7599
7600 Assert(!VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_HM_UPDATE_CR3));
7601 Assert(!VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_HM_UPDATE_PAE_PDPES));
7602 }
7603
7604 return VINF_SUCCESS;
7605}
7606
7607
7608/**
7609 * Saves the guest state from the VMCS into the guest-CPU context.
7610 *
7611 * @returns VBox status code.
7612 * @param pVCpu The cross context virtual CPU structure.
7613 * @param fWhat What to import, CPUMCTX_EXTRN_XXX.
7614 */
7615VMMR0DECL(int) VMXR0ImportStateOnDemand(PVMCPUCC pVCpu, uint64_t fWhat)
7616{
7617 AssertPtr(pVCpu);
7618 PVMXVMCSINFO pVmcsInfo = hmGetVmxActiveVmcsInfo(pVCpu);
7619 return hmR0VmxImportGuestState(pVCpu, pVmcsInfo, fWhat);
7620}
7621
7622
7623/**
7624 * Check per-VM and per-VCPU force flag actions that require us to go back to
7625 * ring-3 for one reason or another.
7626 *
7627 * @returns Strict VBox status code (i.e. informational status codes too)
7628 * @retval VINF_SUCCESS if we don't have any actions that require going back to
7629 * ring-3.
7630 * @retval VINF_PGM_SYNC_CR3 if we have pending PGM CR3 sync.
7631 * @retval VINF_EM_PENDING_REQUEST if we have pending requests (like hardware
7632 * interrupts)
7633 * @retval VINF_PGM_POOL_FLUSH_PENDING if PGM is doing a pool flush and requires
7634 * all EMTs to be in ring-3.
7635 * @retval VINF_EM_RAW_TO_R3 if there is pending DMA requests.
7636 * @retval VINF_EM_NO_MEMORY PGM is out of memory, we need to return
7637 * to the EM loop.
7638 *
7639 * @param pVCpu The cross context virtual CPU structure.
7640 * @param pVmxTransient The VMX-transient structure.
7641 * @param fStepping Whether we are single-stepping the guest using the
7642 * hypervisor debugger.
7643 *
7644 * @remarks This might cause nested-guest VM-exits, caller must check if the guest
7645 * is no longer in VMX non-root mode.
7646 */
7647static VBOXSTRICTRC hmR0VmxCheckForceFlags(PVMCPUCC pVCpu, PCVMXTRANSIENT pVmxTransient, bool fStepping)
7648{
7649 Assert(VMMRZCallRing3IsEnabled(pVCpu));
7650
7651 /*
7652 * Update pending interrupts into the APIC's IRR.
7653 */
7654 if (VMCPU_FF_TEST_AND_CLEAR(pVCpu, VMCPU_FF_UPDATE_APIC))
7655 APICUpdatePendingInterrupts(pVCpu);
7656
7657 /*
7658 * Anything pending? Should be more likely than not if we're doing a good job.
7659 */
7660 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
7661 if ( !fStepping
7662 ? !VM_FF_IS_ANY_SET(pVM, VM_FF_HP_R0_PRE_HM_MASK)
7663 && !VMCPU_FF_IS_ANY_SET(pVCpu, VMCPU_FF_HP_R0_PRE_HM_MASK)
7664 : !VM_FF_IS_ANY_SET(pVM, VM_FF_HP_R0_PRE_HM_STEP_MASK)
7665 && !VMCPU_FF_IS_ANY_SET(pVCpu, VMCPU_FF_HP_R0_PRE_HM_STEP_MASK) )
7666 return VINF_SUCCESS;
7667
7668 /* Pending PGM C3 sync. */
7669 if (VMCPU_FF_IS_ANY_SET(pVCpu,VMCPU_FF_PGM_SYNC_CR3 | VMCPU_FF_PGM_SYNC_CR3_NON_GLOBAL))
7670 {
7671 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
7672 Assert(!(ASMAtomicUoReadU64(&pCtx->fExtrn) & (CPUMCTX_EXTRN_CR0 | CPUMCTX_EXTRN_CR3 | CPUMCTX_EXTRN_CR4)));
7673 VBOXSTRICTRC rcStrict = PGMSyncCR3(pVCpu, pCtx->cr0, pCtx->cr3, pCtx->cr4,
7674 VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_PGM_SYNC_CR3));
7675 if (rcStrict != VINF_SUCCESS)
7676 {
7677 AssertRC(VBOXSTRICTRC_VAL(rcStrict));
7678 Log4Func(("PGMSyncCR3 forcing us back to ring-3. rc2=%d\n", VBOXSTRICTRC_VAL(rcStrict)));
7679 return rcStrict;
7680 }
7681 }
7682
7683 /* Pending HM-to-R3 operations (critsects, timers, EMT rendezvous etc.) */
7684 if ( VM_FF_IS_ANY_SET(pVM, VM_FF_HM_TO_R3_MASK)
7685 || VMCPU_FF_IS_ANY_SET(pVCpu, VMCPU_FF_HM_TO_R3_MASK))
7686 {
7687 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchHmToR3FF);
7688 int rc = RT_LIKELY(!VM_FF_IS_SET(pVM, VM_FF_PGM_NO_MEMORY)) ? VINF_EM_RAW_TO_R3 : VINF_EM_NO_MEMORY;
7689 Log4Func(("HM_TO_R3 forcing us back to ring-3. rc=%d\n", rc));
7690 return rc;
7691 }
7692
7693 /* Pending VM request packets, such as hardware interrupts. */
7694 if ( VM_FF_IS_SET(pVM, VM_FF_REQUEST)
7695 || VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_REQUEST))
7696 {
7697 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchVmReq);
7698 Log4Func(("Pending VM request forcing us back to ring-3\n"));
7699 return VINF_EM_PENDING_REQUEST;
7700 }
7701
7702 /* Pending PGM pool flushes. */
7703 if (VM_FF_IS_SET(pVM, VM_FF_PGM_POOL_FLUSH_PENDING))
7704 {
7705 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchPgmPoolFlush);
7706 Log4Func(("PGM pool flush pending forcing us back to ring-3\n"));
7707 return VINF_PGM_POOL_FLUSH_PENDING;
7708 }
7709
7710 /* Pending DMA requests. */
7711 if (VM_FF_IS_SET(pVM, VM_FF_PDM_DMA))
7712 {
7713 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchDma);
7714 Log4Func(("Pending DMA request forcing us back to ring-3\n"));
7715 return VINF_EM_RAW_TO_R3;
7716 }
7717
7718#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
7719 /*
7720 * Pending nested-guest events.
7721 *
7722 * Please note the priority of these events are specified and important.
7723 * See Intel spec. 29.4.3.2 "APIC-Write Emulation".
7724 * See Intel spec. 6.9 "Priority Among Simultaneous Exceptions And Interrupts".
7725 */
7726 if (pVmxTransient->fIsNestedGuest)
7727 {
7728 /* Pending nested-guest APIC-write. */
7729 if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_VMX_APIC_WRITE))
7730 {
7731 Log4Func(("Pending nested-guest APIC-write\n"));
7732 VBOXSTRICTRC rcStrict = IEMExecVmxVmexitApicWrite(pVCpu);
7733 Assert(rcStrict != VINF_VMX_INTERCEPT_NOT_ACTIVE);
7734 return rcStrict;
7735 }
7736
7737 /* Pending nested-guest monitor-trap flag (MTF). */
7738 if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_VMX_MTF))
7739 {
7740 Log4Func(("Pending nested-guest MTF\n"));
7741 VBOXSTRICTRC rcStrict = IEMExecVmxVmexit(pVCpu, VMX_EXIT_MTF, 0 /* uExitQual */);
7742 Assert(rcStrict != VINF_VMX_INTERCEPT_NOT_ACTIVE);
7743 return rcStrict;
7744 }
7745
7746 /* Pending nested-guest VMX-preemption timer expired. */
7747 if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_VMX_PREEMPT_TIMER))
7748 {
7749 Log4Func(("Pending nested-guest MTF\n"));
7750 VBOXSTRICTRC rcStrict = IEMExecVmxVmexitPreemptTimer(pVCpu);
7751 Assert(rcStrict != VINF_VMX_INTERCEPT_NOT_ACTIVE);
7752 return rcStrict;
7753 }
7754 }
7755#else
7756 NOREF(pVmxTransient);
7757#endif
7758
7759 return VINF_SUCCESS;
7760}
7761
7762
7763/**
7764 * Converts any TRPM trap into a pending HM event. This is typically used when
7765 * entering from ring-3 (not longjmp returns).
7766 *
7767 * @param pVCpu The cross context virtual CPU structure.
7768 */
7769static void hmR0VmxTrpmTrapToPendingEvent(PVMCPUCC pVCpu)
7770{
7771 Assert(TRPMHasTrap(pVCpu));
7772 Assert(!pVCpu->hm.s.Event.fPending);
7773
7774 uint8_t uVector;
7775 TRPMEVENT enmTrpmEvent;
7776 uint32_t uErrCode;
7777 RTGCUINTPTR GCPtrFaultAddress;
7778 uint8_t cbInstr;
7779 bool fIcebp;
7780
7781 int rc = TRPMQueryTrapAll(pVCpu, &uVector, &enmTrpmEvent, &uErrCode, &GCPtrFaultAddress, &cbInstr, &fIcebp);
7782 AssertRC(rc);
7783
7784 uint32_t u32IntInfo;
7785 u32IntInfo = uVector | VMX_IDT_VECTORING_INFO_VALID;
7786 u32IntInfo |= HMTrpmEventTypeToVmxEventType(uVector, enmTrpmEvent, fIcebp);
7787
7788 rc = TRPMResetTrap(pVCpu);
7789 AssertRC(rc);
7790 Log4(("TRPM->HM event: u32IntInfo=%#RX32 enmTrpmEvent=%d cbInstr=%u uErrCode=%#RX32 GCPtrFaultAddress=%#RGv\n",
7791 u32IntInfo, enmTrpmEvent, cbInstr, uErrCode, GCPtrFaultAddress));
7792
7793 hmR0VmxSetPendingEvent(pVCpu, u32IntInfo, cbInstr, uErrCode, GCPtrFaultAddress);
7794}
7795
7796
7797/**
7798 * Converts the pending HM event into a TRPM trap.
7799 *
7800 * @param pVCpu The cross context virtual CPU structure.
7801 */
7802static void hmR0VmxPendingEventToTrpmTrap(PVMCPUCC pVCpu)
7803{
7804 Assert(pVCpu->hm.s.Event.fPending);
7805
7806 /* If a trap was already pending, we did something wrong! */
7807 Assert(TRPMQueryTrap(pVCpu, NULL /* pu8TrapNo */, NULL /* pEnmType */) == VERR_TRPM_NO_ACTIVE_TRAP);
7808
7809 uint32_t const u32IntInfo = pVCpu->hm.s.Event.u64IntInfo;
7810 uint32_t const uVector = VMX_IDT_VECTORING_INFO_VECTOR(u32IntInfo);
7811 TRPMEVENT const enmTrapType = HMVmxEventTypeToTrpmEventType(u32IntInfo);
7812
7813 Log4(("HM event->TRPM: uVector=%#x enmTrapType=%d\n", uVector, enmTrapType));
7814
7815 int rc = TRPMAssertTrap(pVCpu, uVector, enmTrapType);
7816 AssertRC(rc);
7817
7818 if (VMX_IDT_VECTORING_INFO_IS_ERROR_CODE_VALID(u32IntInfo))
7819 TRPMSetErrorCode(pVCpu, pVCpu->hm.s.Event.u32ErrCode);
7820
7821 if (VMX_IDT_VECTORING_INFO_IS_XCPT_PF(u32IntInfo))
7822 TRPMSetFaultAddress(pVCpu, pVCpu->hm.s.Event.GCPtrFaultAddress);
7823 else if (VMX_IDT_VECTORING_INFO_TYPE(u32IntInfo) == VMX_IDT_VECTORING_INFO_TYPE_SW_INT)
7824 TRPMSetInstrLength(pVCpu, pVCpu->hm.s.Event.cbInstr);
7825
7826 if (VMX_IDT_VECTORING_INFO_TYPE(u32IntInfo) == VMX_IDT_VECTORING_INFO_TYPE_PRIV_SW_XCPT)
7827 TRPMSetTrapDueToIcebp(pVCpu);
7828
7829 /* We're now done converting the pending event. */
7830 pVCpu->hm.s.Event.fPending = false;
7831}
7832
7833
7834/**
7835 * Sets the interrupt-window exiting control in the VMCS which instructs VT-x to
7836 * cause a VM-exit as soon as the guest is in a state to receive interrupts.
7837 *
7838 * @param pVCpu The cross context virtual CPU structure.
7839 * @param pVmcsInfo The VMCS info. object.
7840 */
7841static void hmR0VmxSetIntWindowExitVmcs(PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo)
7842{
7843 if (pVCpu->CTX_SUFF(pVM)->hm.s.vmx.Msrs.ProcCtls.n.allowed1 & VMX_PROC_CTLS_INT_WINDOW_EXIT)
7844 {
7845 if (!(pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_INT_WINDOW_EXIT))
7846 {
7847 pVmcsInfo->u32ProcCtls |= VMX_PROC_CTLS_INT_WINDOW_EXIT;
7848 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, pVmcsInfo->u32ProcCtls);
7849 AssertRC(rc);
7850 }
7851 } /* else we will deliver interrupts whenever the guest Vm-exits next and is in a state to receive the interrupt. */
7852}
7853
7854
7855/**
7856 * Clears the interrupt-window exiting control in the VMCS.
7857 *
7858 * @param pVmcsInfo The VMCS info. object.
7859 */
7860DECLINLINE(void) hmR0VmxClearIntWindowExitVmcs(PVMXVMCSINFO pVmcsInfo)
7861{
7862 if (pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_INT_WINDOW_EXIT)
7863 {
7864 pVmcsInfo->u32ProcCtls &= ~VMX_PROC_CTLS_INT_WINDOW_EXIT;
7865 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, pVmcsInfo->u32ProcCtls);
7866 AssertRC(rc);
7867 }
7868}
7869
7870
7871/**
7872 * Sets the NMI-window exiting control in the VMCS which instructs VT-x to
7873 * cause a VM-exit as soon as the guest is in a state to receive NMIs.
7874 *
7875 * @param pVCpu The cross context virtual CPU structure.
7876 * @param pVmcsInfo The VMCS info. object.
7877 */
7878static void hmR0VmxSetNmiWindowExitVmcs(PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo)
7879{
7880 if (pVCpu->CTX_SUFF(pVM)->hm.s.vmx.Msrs.ProcCtls.n.allowed1 & VMX_PROC_CTLS_NMI_WINDOW_EXIT)
7881 {
7882 if (!(pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_NMI_WINDOW_EXIT))
7883 {
7884 pVmcsInfo->u32ProcCtls |= VMX_PROC_CTLS_NMI_WINDOW_EXIT;
7885 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, pVmcsInfo->u32ProcCtls);
7886 AssertRC(rc);
7887 Log4Func(("Setup NMI-window exiting\n"));
7888 }
7889 } /* else we will deliver NMIs whenever we VM-exit next, even possibly nesting NMIs. Can't be helped on ancient CPUs. */
7890}
7891
7892
7893/**
7894 * Clears the NMI-window exiting control in the VMCS.
7895 *
7896 * @param pVmcsInfo The VMCS info. object.
7897 */
7898DECLINLINE(void) hmR0VmxClearNmiWindowExitVmcs(PVMXVMCSINFO pVmcsInfo)
7899{
7900 if (pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_NMI_WINDOW_EXIT)
7901 {
7902 pVmcsInfo->u32ProcCtls &= ~VMX_PROC_CTLS_NMI_WINDOW_EXIT;
7903 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, pVmcsInfo->u32ProcCtls);
7904 AssertRC(rc);
7905 }
7906}
7907
7908
7909/**
7910 * Does the necessary state syncing before returning to ring-3 for any reason
7911 * (longjmp, preemption, voluntary exits to ring-3) from VT-x.
7912 *
7913 * @returns VBox status code.
7914 * @param pVCpu The cross context virtual CPU structure.
7915 * @param fImportState Whether to import the guest state from the VMCS back
7916 * to the guest-CPU context.
7917 *
7918 * @remarks No-long-jmp zone!!!
7919 */
7920static int hmR0VmxLeave(PVMCPUCC pVCpu, bool fImportState)
7921{
7922 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
7923 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
7924
7925 RTCPUID const idCpu = RTMpCpuId();
7926 Log4Func(("HostCpuId=%u\n", idCpu));
7927
7928 /*
7929 * !!! IMPORTANT !!!
7930 * If you modify code here, check whether VMXR0CallRing3Callback() needs to be updated too.
7931 */
7932
7933 /* Save the guest state if necessary. */
7934 PVMXVMCSINFO pVmcsInfo = hmGetVmxActiveVmcsInfo(pVCpu);
7935 if (fImportState)
7936 {
7937 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, HMVMX_CPUMCTX_EXTRN_ALL);
7938 AssertRCReturn(rc, rc);
7939 }
7940
7941 /* Restore host FPU state if necessary. We will resync on next R0 reentry. */
7942 CPUMR0FpuStateMaybeSaveGuestAndRestoreHost(pVCpu);
7943 Assert(!CPUMIsGuestFPUStateActive(pVCpu));
7944
7945 /* Restore host debug registers if necessary. We will resync on next R0 reentry. */
7946#ifdef VBOX_STRICT
7947 if (CPUMIsHyperDebugStateActive(pVCpu))
7948 Assert(pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_MOV_DR_EXIT);
7949#endif
7950 CPUMR0DebugStateMaybeSaveGuestAndRestoreHost(pVCpu, true /* save DR6 */);
7951 Assert(!CPUMIsGuestDebugStateActive(pVCpu) && !CPUMIsGuestDebugStateActivePending(pVCpu));
7952 Assert(!CPUMIsHyperDebugStateActive(pVCpu) && !CPUMIsHyperDebugStateActivePending(pVCpu));
7953
7954 /* Restore host-state bits that VT-x only restores partially. */
7955 if ( (pVCpu->hm.s.vmx.fRestoreHostFlags & VMX_RESTORE_HOST_REQUIRED)
7956 && (pVCpu->hm.s.vmx.fRestoreHostFlags & ~VMX_RESTORE_HOST_REQUIRED))
7957 {
7958 Log4Func(("Restoring Host State: fRestoreHostFlags=%#RX32 HostCpuId=%u\n", pVCpu->hm.s.vmx.fRestoreHostFlags, idCpu));
7959 VMXRestoreHostState(pVCpu->hm.s.vmx.fRestoreHostFlags, &pVCpu->hm.s.vmx.RestoreHost);
7960 }
7961 pVCpu->hm.s.vmx.fRestoreHostFlags = 0;
7962
7963 /* Restore the lazy host MSRs as we're leaving VT-x context. */
7964 if (pVCpu->hm.s.vmx.fLazyMsrs & VMX_LAZY_MSRS_LOADED_GUEST)
7965 {
7966 /* We shouldn't restore the host MSRs without saving the guest MSRs first. */
7967 if (!fImportState)
7968 {
7969 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, CPUMCTX_EXTRN_KERNEL_GS_BASE | CPUMCTX_EXTRN_SYSCALL_MSRS);
7970 AssertRCReturn(rc, rc);
7971 }
7972 hmR0VmxLazyRestoreHostMsrs(pVCpu);
7973 Assert(!pVCpu->hm.s.vmx.fLazyMsrs);
7974 }
7975 else
7976 pVCpu->hm.s.vmx.fLazyMsrs = 0;
7977
7978 /* Update auto-load/store host MSRs values when we re-enter VT-x (as we could be on a different CPU). */
7979 pVCpu->hm.s.vmx.fUpdatedHostAutoMsrs = false;
7980
7981 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatEntry);
7982 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatImportGuestState);
7983 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatExportGuestState);
7984 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatPreExit);
7985 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatExitHandling);
7986 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatExitIO);
7987 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatExitMovCRx);
7988 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatExitXcptNmi);
7989 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatExitVmentry);
7990 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchLongJmpToR3);
7991
7992 VMCPU_CMPXCHG_STATE(pVCpu, VMCPUSTATE_STARTED_HM, VMCPUSTATE_STARTED_EXEC);
7993
7994 /** @todo This partially defeats the purpose of having preemption hooks.
7995 * The problem is, deregistering the hooks should be moved to a place that
7996 * lasts until the EMT is about to be destroyed not everytime while leaving HM
7997 * context.
7998 */
7999 int rc = hmR0VmxClearVmcs(pVmcsInfo);
8000 AssertRCReturn(rc, rc);
8001
8002#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
8003 /*
8004 * A valid shadow VMCS is made active as part of VM-entry. It is necessary to
8005 * clear a shadow VMCS before allowing that VMCS to become active on another
8006 * logical processor. We may or may not be importing guest state which clears
8007 * it, so cover for it here.
8008 *
8009 * See Intel spec. 24.11.1 "Software Use of Virtual-Machine Control Structures".
8010 */
8011 if ( pVmcsInfo->pvShadowVmcs
8012 && pVmcsInfo->fShadowVmcsState != VMX_V_VMCS_LAUNCH_STATE_CLEAR)
8013 {
8014 rc = hmR0VmxClearShadowVmcs(pVmcsInfo);
8015 AssertRCReturn(rc, rc);
8016 }
8017
8018 /*
8019 * Flag that we need to re-export the host state if we switch to this VMCS before
8020 * executing guest or nested-guest code.
8021 */
8022 pVmcsInfo->idHostCpuState = NIL_RTCPUID;
8023#endif
8024
8025 Log4Func(("Cleared Vmcs. HostCpuId=%u\n", idCpu));
8026 NOREF(idCpu);
8027 return VINF_SUCCESS;
8028}
8029
8030
8031/**
8032 * Leaves the VT-x session.
8033 *
8034 * @returns VBox status code.
8035 * @param pVCpu The cross context virtual CPU structure.
8036 *
8037 * @remarks No-long-jmp zone!!!
8038 */
8039static int hmR0VmxLeaveSession(PVMCPUCC pVCpu)
8040{
8041 HM_DISABLE_PREEMPT(pVCpu);
8042 HMVMX_ASSERT_CPU_SAFE(pVCpu);
8043 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
8044 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
8045
8046 /* When thread-context hooks are used, we can avoid doing the leave again if we had been preempted before
8047 and done this from the VMXR0ThreadCtxCallback(). */
8048 if (!pVCpu->hm.s.fLeaveDone)
8049 {
8050 int rc2 = hmR0VmxLeave(pVCpu, true /* fImportState */);
8051 AssertRCReturnStmt(rc2, HM_RESTORE_PREEMPT(), rc2);
8052 pVCpu->hm.s.fLeaveDone = true;
8053 }
8054 Assert(!pVCpu->cpum.GstCtx.fExtrn);
8055
8056 /*
8057 * !!! IMPORTANT !!!
8058 * If you modify code here, make sure to check whether VMXR0CallRing3Callback() needs to be updated too.
8059 */
8060
8061 /* Deregister hook now that we've left HM context before re-enabling preemption. */
8062 /** @todo Deregistering here means we need to VMCLEAR always
8063 * (longjmp/exit-to-r3) in VT-x which is not efficient, eliminate need
8064 * for calling VMMR0ThreadCtxHookDisable here! */
8065 VMMR0ThreadCtxHookDisable(pVCpu);
8066
8067 /* Leave HM context. This takes care of local init (term) and deregistering the longjmp-to-ring-3 callback. */
8068 int rc = HMR0LeaveCpu(pVCpu);
8069 HM_RESTORE_PREEMPT();
8070 return rc;
8071}
8072
8073
8074/**
8075 * Does the necessary state syncing before doing a longjmp to ring-3.
8076 *
8077 * @returns VBox status code.
8078 * @param pVCpu The cross context virtual CPU structure.
8079 *
8080 * @remarks No-long-jmp zone!!!
8081 */
8082DECLINLINE(int) hmR0VmxLongJmpToRing3(PVMCPUCC pVCpu)
8083{
8084 return hmR0VmxLeaveSession(pVCpu);
8085}
8086
8087
8088/**
8089 * Take necessary actions before going back to ring-3.
8090 *
8091 * An action requires us to go back to ring-3. This function does the necessary
8092 * steps before we can safely return to ring-3. This is not the same as longjmps
8093 * to ring-3, this is voluntary and prepares the guest so it may continue
8094 * executing outside HM (recompiler/IEM).
8095 *
8096 * @returns VBox status code.
8097 * @param pVCpu The cross context virtual CPU structure.
8098 * @param rcExit The reason for exiting to ring-3. Can be
8099 * VINF_VMM_UNKNOWN_RING3_CALL.
8100 */
8101static int hmR0VmxExitToRing3(PVMCPUCC pVCpu, VBOXSTRICTRC rcExit)
8102{
8103 HMVMX_ASSERT_PREEMPT_SAFE(pVCpu);
8104
8105 PVMXVMCSINFO pVmcsInfo = hmGetVmxActiveVmcsInfo(pVCpu);
8106 if (RT_UNLIKELY(rcExit == VERR_VMX_INVALID_VMCS_PTR))
8107 {
8108 VMXGetCurrentVmcs(&pVCpu->hm.s.vmx.LastError.HCPhysCurrentVmcs);
8109 pVCpu->hm.s.vmx.LastError.u32VmcsRev = *(uint32_t *)pVmcsInfo->pvVmcs;
8110 pVCpu->hm.s.vmx.LastError.idEnteredCpu = pVCpu->hm.s.idEnteredCpu;
8111 /* LastError.idCurrentCpu was updated in hmR0VmxPreRunGuestCommitted(). */
8112 }
8113
8114 /* Please, no longjumps here (any logging shouldn't flush jump back to ring-3). NO LOGGING BEFORE THIS POINT! */
8115 VMMRZCallRing3Disable(pVCpu);
8116 Log4Func(("rcExit=%d\n", VBOXSTRICTRC_VAL(rcExit)));
8117
8118 /*
8119 * Convert any pending HM events back to TRPM due to premature exits to ring-3.
8120 * We need to do this only on returns to ring-3 and not for longjmps to ring3.
8121 *
8122 * This is because execution may continue from ring-3 and we would need to inject
8123 * the event from there (hence place it back in TRPM).
8124 */
8125 if (pVCpu->hm.s.Event.fPending)
8126 {
8127 hmR0VmxPendingEventToTrpmTrap(pVCpu);
8128 Assert(!pVCpu->hm.s.Event.fPending);
8129
8130 /* Clear the events from the VMCS. */
8131 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_ENTRY_INTERRUPTION_INFO, 0); AssertRC(rc);
8132 rc = VMXWriteVmcs32(VMX_VMCS_GUEST_PENDING_DEBUG_XCPTS, 0); AssertRC(rc);
8133 }
8134#ifdef VBOX_STRICT
8135 else
8136 {
8137 /*
8138 * Ensure we don't accidentally clear a pending HM event without clearing the VMCS.
8139 * This can be pretty hard to debug otherwise, interrupts might get injected twice
8140 * occasionally, see @bugref{9180#c42}.
8141 *
8142 * However, if the VM-entry failed, any VM entry-interruption info. field would
8143 * be left unmodified as the event would not have been injected to the guest. In
8144 * such cases, don't assert, we're not going to continue guest execution anyway.
8145 */
8146 uint32_t uExitReason;
8147 uint32_t uEntryIntInfo;
8148 int rc = VMXReadVmcs32(VMX_VMCS32_RO_EXIT_REASON, &uExitReason);
8149 rc |= VMXReadVmcs32(VMX_VMCS32_CTRL_ENTRY_INTERRUPTION_INFO, &uEntryIntInfo);
8150 AssertRC(rc);
8151 Assert(VMX_EXIT_REASON_HAS_ENTRY_FAILED(uExitReason) || !VMX_ENTRY_INT_INFO_IS_VALID(uEntryIntInfo));
8152 }
8153#endif
8154
8155 /*
8156 * Clear the interrupt-window and NMI-window VMCS controls as we could have got
8157 * a VM-exit with higher priority than interrupt-window or NMI-window VM-exits
8158 * (e.g. TPR below threshold).
8159 */
8160 if (!CPUMIsGuestInVmxNonRootMode(&pVCpu->cpum.GstCtx))
8161 {
8162 hmR0VmxClearIntWindowExitVmcs(pVmcsInfo);
8163 hmR0VmxClearNmiWindowExitVmcs(pVmcsInfo);
8164 }
8165
8166 /* If we're emulating an instruction, we shouldn't have any TRPM traps pending
8167 and if we're injecting an event we should have a TRPM trap pending. */
8168 AssertMsg(rcExit != VINF_EM_RAW_INJECT_TRPM_EVENT || TRPMHasTrap(pVCpu), ("%Rrc\n", VBOXSTRICTRC_VAL(rcExit)));
8169#ifndef DEBUG_bird /* Triggered after firing an NMI against NT4SP1, possibly a triple fault in progress. */
8170 AssertMsg(rcExit != VINF_EM_RAW_EMULATE_INSTR || !TRPMHasTrap(pVCpu), ("%Rrc\n", VBOXSTRICTRC_VAL(rcExit)));
8171#endif
8172
8173 /* Save guest state and restore host state bits. */
8174 int rc = hmR0VmxLeaveSession(pVCpu);
8175 AssertRCReturn(rc, rc);
8176 STAM_COUNTER_DEC(&pVCpu->hm.s.StatSwitchLongJmpToR3);
8177
8178 /* Thread-context hooks are unregistered at this point!!! */
8179 /* Ring-3 callback notifications are unregistered at this point!!! */
8180
8181 /* Sync recompiler state. */
8182 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_TO_R3);
8183 CPUMSetChangedFlags(pVCpu, CPUM_CHANGED_SYSENTER_MSR
8184 | CPUM_CHANGED_LDTR
8185 | CPUM_CHANGED_GDTR
8186 | CPUM_CHANGED_IDTR
8187 | CPUM_CHANGED_TR
8188 | CPUM_CHANGED_HIDDEN_SEL_REGS);
8189 if ( pVCpu->CTX_SUFF(pVM)->hm.s.fNestedPaging
8190 && CPUMIsGuestPagingEnabledEx(&pVCpu->cpum.GstCtx))
8191 CPUMSetChangedFlags(pVCpu, CPUM_CHANGED_GLOBAL_TLB_FLUSH);
8192
8193 Assert(!pVCpu->hm.s.fClearTrapFlag);
8194
8195 /* Update the exit-to-ring 3 reason. */
8196 pVCpu->hm.s.rcLastExitToR3 = VBOXSTRICTRC_VAL(rcExit);
8197
8198 /* On our way back from ring-3 reload the guest state if there is a possibility of it being changed. */
8199 if ( rcExit != VINF_EM_RAW_INTERRUPT
8200 || CPUMIsGuestInVmxNonRootMode(&pVCpu->cpum.GstCtx))
8201 {
8202 Assert(!(pVCpu->cpum.GstCtx.fExtrn & HMVMX_CPUMCTX_EXTRN_ALL));
8203 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_ALL_GUEST);
8204 }
8205
8206 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchExitToR3);
8207 VMMRZCallRing3Enable(pVCpu);
8208 return rc;
8209}
8210
8211
8212/**
8213 * VMMRZCallRing3() callback wrapper which saves the guest state before we
8214 * longjump to ring-3 and possibly get preempted.
8215 *
8216 * @returns VBox status code.
8217 * @param pVCpu The cross context virtual CPU structure.
8218 * @param enmOperation The operation causing the ring-3 longjump.
8219 */
8220VMMR0DECL(int) VMXR0CallRing3Callback(PVMCPUCC pVCpu, VMMCALLRING3 enmOperation)
8221{
8222 if (enmOperation == VMMCALLRING3_VM_R0_ASSERTION)
8223 {
8224 /*
8225 * !!! IMPORTANT !!!
8226 * If you modify code here, check whether hmR0VmxLeave() and hmR0VmxLeaveSession() needs to be updated too.
8227 * This is a stripped down version which gets out ASAP, trying to not trigger any further assertions.
8228 */
8229 VMMRZCallRing3RemoveNotification(pVCpu);
8230 VMMRZCallRing3Disable(pVCpu);
8231 HM_DISABLE_PREEMPT(pVCpu);
8232
8233 PVMXVMCSINFO pVmcsInfo = hmGetVmxActiveVmcsInfo(pVCpu);
8234 hmR0VmxImportGuestState(pVCpu, pVmcsInfo, HMVMX_CPUMCTX_EXTRN_ALL);
8235 CPUMR0FpuStateMaybeSaveGuestAndRestoreHost(pVCpu);
8236 CPUMR0DebugStateMaybeSaveGuestAndRestoreHost(pVCpu, true /* save DR6 */);
8237
8238 /* Restore host-state bits that VT-x only restores partially. */
8239 if ( (pVCpu->hm.s.vmx.fRestoreHostFlags & VMX_RESTORE_HOST_REQUIRED)
8240 && (pVCpu->hm.s.vmx.fRestoreHostFlags & ~VMX_RESTORE_HOST_REQUIRED))
8241 VMXRestoreHostState(pVCpu->hm.s.vmx.fRestoreHostFlags, &pVCpu->hm.s.vmx.RestoreHost);
8242 pVCpu->hm.s.vmx.fRestoreHostFlags = 0;
8243
8244 /* Restore the lazy host MSRs as we're leaving VT-x context. */
8245 if (pVCpu->hm.s.vmx.fLazyMsrs & VMX_LAZY_MSRS_LOADED_GUEST)
8246 hmR0VmxLazyRestoreHostMsrs(pVCpu);
8247
8248 /* Update auto-load/store host MSRs values when we re-enter VT-x (as we could be on a different CPU). */
8249 pVCpu->hm.s.vmx.fUpdatedHostAutoMsrs = false;
8250 VMCPU_CMPXCHG_STATE(pVCpu, VMCPUSTATE_STARTED_HM, VMCPUSTATE_STARTED_EXEC);
8251
8252 /* Clear the current VMCS data back to memory (shadow VMCS if any would have been
8253 cleared as part of importing the guest state above. */
8254 hmR0VmxClearVmcs(pVmcsInfo);
8255
8256 /** @todo eliminate the need for calling VMMR0ThreadCtxHookDisable here! */
8257 VMMR0ThreadCtxHookDisable(pVCpu);
8258
8259 /* Leave HM context. This takes care of local init (term). */
8260 HMR0LeaveCpu(pVCpu);
8261 HM_RESTORE_PREEMPT();
8262 return VINF_SUCCESS;
8263 }
8264
8265 Assert(pVCpu);
8266 Assert(VMMRZCallRing3IsEnabled(pVCpu));
8267 HMVMX_ASSERT_PREEMPT_SAFE(pVCpu);
8268
8269 VMMRZCallRing3Disable(pVCpu);
8270 Assert(VMMR0IsLogFlushDisabled(pVCpu));
8271
8272 Log4Func(("-> hmR0VmxLongJmpToRing3 enmOperation=%d\n", enmOperation));
8273
8274 int rc = hmR0VmxLongJmpToRing3(pVCpu);
8275 AssertRCReturn(rc, rc);
8276
8277 VMMRZCallRing3Enable(pVCpu);
8278 return VINF_SUCCESS;
8279}
8280
8281
8282/**
8283 * Pushes a 2-byte value onto the real-mode (in virtual-8086 mode) guest's
8284 * stack.
8285 *
8286 * @returns Strict VBox status code (i.e. informational status codes too).
8287 * @retval VINF_EM_RESET if pushing a value to the stack caused a triple-fault.
8288 * @param pVCpu The cross context virtual CPU structure.
8289 * @param uValue The value to push to the guest stack.
8290 */
8291static VBOXSTRICTRC hmR0VmxRealModeGuestStackPush(PVMCPUCC pVCpu, uint16_t uValue)
8292{
8293 /*
8294 * The stack limit is 0xffff in real-on-virtual 8086 mode. Real-mode with weird stack limits cannot be run in
8295 * virtual 8086 mode in VT-x. See Intel spec. 26.3.1.2 "Checks on Guest Segment Registers".
8296 * See Intel Instruction reference for PUSH and Intel spec. 22.33.1 "Segment Wraparound".
8297 */
8298 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
8299 if (pCtx->sp == 1)
8300 return VINF_EM_RESET;
8301 pCtx->sp -= sizeof(uint16_t); /* May wrap around which is expected behaviour. */
8302 int rc = PGMPhysSimpleWriteGCPhys(pVCpu->CTX_SUFF(pVM), pCtx->ss.u64Base + pCtx->sp, &uValue, sizeof(uint16_t));
8303 AssertRC(rc);
8304 return rc;
8305}
8306
8307
8308/**
8309 * Injects an event into the guest upon VM-entry by updating the relevant fields
8310 * in the VM-entry area in the VMCS.
8311 *
8312 * @returns Strict VBox status code (i.e. informational status codes too).
8313 * @retval VINF_SUCCESS if the event is successfully injected into the VMCS.
8314 * @retval VINF_EM_RESET if event injection resulted in a triple-fault.
8315 *
8316 * @param pVCpu The cross context virtual CPU structure.
8317 * @param pVmxTransient The VMX-transient structure.
8318 * @param pEvent The event being injected.
8319 * @param pfIntrState Pointer to the VT-x guest-interruptibility-state. This
8320 * will be updated if necessary. This cannot not be NULL.
8321 * @param fStepping Whether we're single-stepping guest execution and should
8322 * return VINF_EM_DBG_STEPPED if the event is injected
8323 * directly (registers modified by us, not by hardware on
8324 * VM-entry).
8325 */
8326static VBOXSTRICTRC hmR0VmxInjectEventVmcs(PVMCPUCC pVCpu, PCVMXTRANSIENT pVmxTransient, PCHMEVENT pEvent, bool fStepping,
8327 uint32_t *pfIntrState)
8328{
8329 /* Intel spec. 24.8.3 "VM-Entry Controls for Event Injection" specifies the interruption-information field to be 32-bits. */
8330 AssertMsg(!RT_HI_U32(pEvent->u64IntInfo), ("%#RX64\n", pEvent->u64IntInfo));
8331 Assert(pfIntrState);
8332
8333 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
8334 uint32_t u32IntInfo = pEvent->u64IntInfo;
8335 uint32_t const u32ErrCode = pEvent->u32ErrCode;
8336 uint32_t const cbInstr = pEvent->cbInstr;
8337 RTGCUINTPTR const GCPtrFault = pEvent->GCPtrFaultAddress;
8338 uint8_t const uVector = VMX_ENTRY_INT_INFO_VECTOR(u32IntInfo);
8339 uint32_t const uIntType = VMX_ENTRY_INT_INFO_TYPE(u32IntInfo);
8340
8341#ifdef VBOX_STRICT
8342 /*
8343 * Validate the error-code-valid bit for hardware exceptions.
8344 * No error codes for exceptions in real-mode.
8345 *
8346 * See Intel spec. 20.1.4 "Interrupt and Exception Handling"
8347 */
8348 if ( uIntType == VMX_EXIT_INT_INFO_TYPE_HW_XCPT
8349 && !CPUMIsGuestInRealModeEx(pCtx))
8350 {
8351 switch (uVector)
8352 {
8353 case X86_XCPT_PF:
8354 case X86_XCPT_DF:
8355 case X86_XCPT_TS:
8356 case X86_XCPT_NP:
8357 case X86_XCPT_SS:
8358 case X86_XCPT_GP:
8359 case X86_XCPT_AC:
8360 AssertMsg(VMX_ENTRY_INT_INFO_IS_ERROR_CODE_VALID(u32IntInfo),
8361 ("Error-code-valid bit not set for exception that has an error code uVector=%#x\n", uVector));
8362 RT_FALL_THRU();
8363 default:
8364 break;
8365 }
8366 }
8367
8368 /* Cannot inject an NMI when block-by-MOV SS is in effect. */
8369 Assert( uIntType != VMX_EXIT_INT_INFO_TYPE_NMI
8370 || !(*pfIntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_MOVSS));
8371#endif
8372
8373 STAM_COUNTER_INC(&pVCpu->hm.s.paStatInjectedIrqsR0[uVector & MASK_INJECT_IRQ_STAT]);
8374
8375 /*
8376 * Hardware interrupts & exceptions cannot be delivered through the software interrupt
8377 * redirection bitmap to the real mode task in virtual-8086 mode. We must jump to the
8378 * interrupt handler in the (real-mode) guest.
8379 *
8380 * See Intel spec. 20.3 "Interrupt and Exception handling in Virtual-8086 Mode".
8381 * See Intel spec. 20.1.4 "Interrupt and Exception Handling" for real-mode interrupt handling.
8382 */
8383 if (CPUMIsGuestInRealModeEx(pCtx)) /* CR0.PE bit changes are always intercepted, so it's up to date. */
8384 {
8385 if (pVCpu->CTX_SUFF(pVM)->hm.s.vmx.fUnrestrictedGuest)
8386 {
8387 /*
8388 * For CPUs with unrestricted guest execution enabled and with the guest
8389 * in real-mode, we must not set the deliver-error-code bit.
8390 *
8391 * See Intel spec. 26.2.1.3 "VM-Entry Control Fields".
8392 */
8393 u32IntInfo &= ~VMX_ENTRY_INT_INFO_ERROR_CODE_VALID;
8394 }
8395 else
8396 {
8397 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
8398 Assert(PDMVmmDevHeapIsEnabled(pVM));
8399 Assert(pVM->hm.s.vmx.pRealModeTSS);
8400 Assert(!CPUMIsGuestInVmxNonRootMode(&pVCpu->cpum.GstCtx));
8401
8402 /* We require RIP, RSP, RFLAGS, CS, IDTR, import them. */
8403 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
8404 int rc2 = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, CPUMCTX_EXTRN_SREG_MASK | CPUMCTX_EXTRN_TABLE_MASK
8405 | CPUMCTX_EXTRN_RIP | CPUMCTX_EXTRN_RSP | CPUMCTX_EXTRN_RFLAGS);
8406 AssertRCReturn(rc2, rc2);
8407
8408 /* Check if the interrupt handler is present in the IVT (real-mode IDT). IDT limit is (4N - 1). */
8409 size_t const cbIdtEntry = sizeof(X86IDTR16);
8410 if (uVector * cbIdtEntry + (cbIdtEntry - 1) > pCtx->idtr.cbIdt)
8411 {
8412 /* If we are trying to inject a #DF with no valid IDT entry, return a triple-fault. */
8413 if (uVector == X86_XCPT_DF)
8414 return VINF_EM_RESET;
8415
8416 /* If we're injecting a #GP with no valid IDT entry, inject a double-fault.
8417 No error codes for exceptions in real-mode. */
8418 if (uVector == X86_XCPT_GP)
8419 {
8420 uint32_t const uXcptDfInfo = RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_VECTOR, X86_XCPT_DF)
8421 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_TYPE, VMX_ENTRY_INT_INFO_TYPE_HW_XCPT)
8422 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_ERR_CODE_VALID, 0)
8423 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_VALID, 1);
8424 HMEVENT EventXcptDf;
8425 RT_ZERO(EventXcptDf);
8426 EventXcptDf.u64IntInfo = uXcptDfInfo;
8427 return hmR0VmxInjectEventVmcs(pVCpu, pVmxTransient, &EventXcptDf, fStepping, pfIntrState);
8428 }
8429
8430 /*
8431 * If we're injecting an event with no valid IDT entry, inject a #GP.
8432 * No error codes for exceptions in real-mode.
8433 *
8434 * See Intel spec. 20.1.4 "Interrupt and Exception Handling"
8435 */
8436 uint32_t const uXcptGpInfo = RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_VECTOR, X86_XCPT_GP)
8437 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_TYPE, VMX_ENTRY_INT_INFO_TYPE_HW_XCPT)
8438 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_ERR_CODE_VALID, 0)
8439 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_VALID, 1);
8440 HMEVENT EventXcptGp;
8441 RT_ZERO(EventXcptGp);
8442 EventXcptGp.u64IntInfo = uXcptGpInfo;
8443 return hmR0VmxInjectEventVmcs(pVCpu, pVmxTransient, &EventXcptGp, fStepping, pfIntrState);
8444 }
8445
8446 /* Software exceptions (#BP and #OF exceptions thrown as a result of INT3 or INTO) */
8447 uint16_t uGuestIp = pCtx->ip;
8448 if (uIntType == VMX_ENTRY_INT_INFO_TYPE_SW_XCPT)
8449 {
8450 Assert(uVector == X86_XCPT_BP || uVector == X86_XCPT_OF);
8451 /* #BP and #OF are both benign traps, we need to resume the next instruction. */
8452 uGuestIp = pCtx->ip + (uint16_t)cbInstr;
8453 }
8454 else if (uIntType == VMX_ENTRY_INT_INFO_TYPE_SW_INT)
8455 uGuestIp = pCtx->ip + (uint16_t)cbInstr;
8456
8457 /* Get the code segment selector and offset from the IDT entry for the interrupt handler. */
8458 X86IDTR16 IdtEntry;
8459 RTGCPHYS const GCPhysIdtEntry = (RTGCPHYS)pCtx->idtr.pIdt + uVector * cbIdtEntry;
8460 rc2 = PGMPhysSimpleReadGCPhys(pVM, &IdtEntry, GCPhysIdtEntry, cbIdtEntry);
8461 AssertRCReturn(rc2, rc2);
8462
8463 /* Construct the stack frame for the interrupt/exception handler. */
8464 VBOXSTRICTRC rcStrict;
8465 rcStrict = hmR0VmxRealModeGuestStackPush(pVCpu, pCtx->eflags.u32);
8466 if (rcStrict == VINF_SUCCESS)
8467 {
8468 rcStrict = hmR0VmxRealModeGuestStackPush(pVCpu, pCtx->cs.Sel);
8469 if (rcStrict == VINF_SUCCESS)
8470 rcStrict = hmR0VmxRealModeGuestStackPush(pVCpu, uGuestIp);
8471 }
8472
8473 /* Clear the required eflag bits and jump to the interrupt/exception handler. */
8474 if (rcStrict == VINF_SUCCESS)
8475 {
8476 pCtx->eflags.u32 &= ~(X86_EFL_IF | X86_EFL_TF | X86_EFL_RF | X86_EFL_AC);
8477 pCtx->rip = IdtEntry.offSel;
8478 pCtx->cs.Sel = IdtEntry.uSel;
8479 pCtx->cs.ValidSel = IdtEntry.uSel;
8480 pCtx->cs.u64Base = IdtEntry.uSel << cbIdtEntry;
8481 if ( uIntType == VMX_ENTRY_INT_INFO_TYPE_HW_XCPT
8482 && uVector == X86_XCPT_PF)
8483 pCtx->cr2 = GCPtrFault;
8484
8485 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_CS | HM_CHANGED_GUEST_CR2
8486 | HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS
8487 | HM_CHANGED_GUEST_RSP);
8488
8489 /*
8490 * If we delivered a hardware exception (other than an NMI) and if there was
8491 * block-by-STI in effect, we should clear it.
8492 */
8493 if (*pfIntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_STI)
8494 {
8495 Assert( uIntType != VMX_ENTRY_INT_INFO_TYPE_NMI
8496 && uIntType != VMX_ENTRY_INT_INFO_TYPE_EXT_INT);
8497 Log4Func(("Clearing inhibition due to STI\n"));
8498 *pfIntrState &= ~VMX_VMCS_GUEST_INT_STATE_BLOCK_STI;
8499 }
8500
8501 Log4(("Injected real-mode: u32IntInfo=%#x u32ErrCode=%#x cbInstr=%#x Eflags=%#x CS:EIP=%04x:%04x\n",
8502 u32IntInfo, u32ErrCode, cbInstr, pCtx->eflags.u, pCtx->cs.Sel, pCtx->eip));
8503
8504 /*
8505 * The event has been truly dispatched to the guest. Mark it as no longer pending so
8506 * we don't attempt to undo it if we are returning to ring-3 before executing guest code.
8507 */
8508 pVCpu->hm.s.Event.fPending = false;
8509
8510 /*
8511 * If we eventually support nested-guest execution without unrestricted guest execution,
8512 * we should set fInterceptEvents here.
8513 */
8514 Assert(!pVmxTransient->fIsNestedGuest);
8515
8516 /* If we're stepping and we've changed cs:rip above, bail out of the VMX R0 execution loop. */
8517 if (fStepping)
8518 rcStrict = VINF_EM_DBG_STEPPED;
8519 }
8520 AssertMsg(rcStrict == VINF_SUCCESS || rcStrict == VINF_EM_RESET || (rcStrict == VINF_EM_DBG_STEPPED && fStepping),
8521 ("%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
8522 return rcStrict;
8523 }
8524 }
8525
8526 /*
8527 * Validate.
8528 */
8529 Assert(VMX_ENTRY_INT_INFO_IS_VALID(u32IntInfo)); /* Bit 31 (Valid bit) must be set by caller. */
8530 Assert(!(u32IntInfo & VMX_BF_ENTRY_INT_INFO_RSVD_12_30_MASK)); /* Bits 30:12 MBZ. */
8531
8532 /*
8533 * Inject the event into the VMCS.
8534 */
8535 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_ENTRY_INTERRUPTION_INFO, u32IntInfo);
8536 if (VMX_ENTRY_INT_INFO_IS_ERROR_CODE_VALID(u32IntInfo))
8537 rc |= VMXWriteVmcs32(VMX_VMCS32_CTRL_ENTRY_EXCEPTION_ERRCODE, u32ErrCode);
8538 rc |= VMXWriteVmcs32(VMX_VMCS32_CTRL_ENTRY_INSTR_LENGTH, cbInstr);
8539 AssertRC(rc);
8540
8541 /*
8542 * Update guest CR2 if this is a page-fault.
8543 */
8544 if (VMX_ENTRY_INT_INFO_IS_XCPT_PF(u32IntInfo))
8545 pCtx->cr2 = GCPtrFault;
8546
8547 Log4(("Injecting u32IntInfo=%#x u32ErrCode=%#x cbInstr=%#x CR2=%#RX64\n", u32IntInfo, u32ErrCode, cbInstr, pCtx->cr2));
8548 return VINF_SUCCESS;
8549}
8550
8551
8552/**
8553 * Evaluates the event to be delivered to the guest and sets it as the pending
8554 * event.
8555 *
8556 * Toggling of interrupt force-flags here is safe since we update TRPM on premature
8557 * exits to ring-3 before executing guest code, see hmR0VmxExitToRing3(). We must
8558 * NOT restore these force-flags.
8559 *
8560 * @returns Strict VBox status code (i.e. informational status codes too).
8561 * @param pVCpu The cross context virtual CPU structure.
8562 * @param pVmxTransient The VMX-transient structure.
8563 * @param pfIntrState Where to store the VT-x guest-interruptibility state.
8564 */
8565static VBOXSTRICTRC hmR0VmxEvaluatePendingEvent(PVMCPUCC pVCpu, PCVMXTRANSIENT pVmxTransient, uint32_t *pfIntrState)
8566{
8567 Assert(pfIntrState);
8568 Assert(!TRPMHasTrap(pVCpu));
8569
8570 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
8571 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
8572 bool const fIsNestedGuest = pVmxTransient->fIsNestedGuest;
8573
8574 /*
8575 * Compute/update guest-interruptibility state related FFs.
8576 */
8577 /** @todo r=ramshankar: Move this outside this function to the caller. */
8578 {
8579 /* Get the current interruptibility-state of the guest or nested-guest (this updates FFs). */
8580 uint32_t const fIntrState = hmR0VmxGetGuestIntrState(pVCpu);
8581
8582#ifdef VBOX_STRICT
8583 /* Validate. */
8584 Assert(!(fIntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_SMI)); /* We don't support block-by-SMI yet.*/
8585 if (fIntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_STI)
8586 {
8587 /* Block-by-STI must not be set when interrupts are disabled. */
8588 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_RFLAGS);
8589 Assert(pCtx->eflags.Bits.u1IF);
8590 }
8591#endif
8592
8593 /* Update interruptibility state to the caller. */
8594 *pfIntrState = fIntrState;
8595 }
8596
8597 /*
8598 * Evaluate if a new event needs to be injected.
8599 * An event that's already pending has already performed all necessary checks.
8600 */
8601 if ( !pVCpu->hm.s.Event.fPending
8602 && !VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS))
8603 {
8604 /** @todo SMI. SMIs take priority over NMIs. */
8605
8606 /*
8607 * NMIs.
8608 * NMIs take priority over external interrupts.
8609 */
8610 if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_INTERRUPT_NMI))
8611 {
8612 /*
8613 * For a guest, the FF always indicates the guest's ability to receive an NMI.
8614 *
8615 * For a nested-guest, the FF always indicates the outer guest's ability to
8616 * receive an NMI while the guest-interruptibility state bit depends on whether
8617 * the nested-hypervisor is using virtual-NMIs.
8618 */
8619 if (!VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_BLOCK_NMIS))
8620 {
8621#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
8622 if ( fIsNestedGuest
8623 && CPUMIsGuestVmxPinCtlsSet(pCtx, VMX_PIN_CTLS_NMI_EXIT))
8624 return IEMExecVmxVmexitXcptNmi(pVCpu);
8625#endif
8626 hmR0VmxSetPendingXcptNmi(pVCpu);
8627 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INTERRUPT_NMI);
8628 Log4Func(("NMI pending injection\n"));
8629
8630 /* We've injected the NMI, bail. */
8631 return VINF_SUCCESS;
8632 }
8633 else if (!fIsNestedGuest)
8634 hmR0VmxSetNmiWindowExitVmcs(pVCpu, pVmcsInfo);
8635 }
8636
8637 /*
8638 * External interrupts (PIC/APIC).
8639 * Once PDMGetInterrupt() returns a valid interrupt we -must- deliver it.
8640 * We cannot re-request the interrupt from the controller again.
8641 */
8642 if ( VMCPU_FF_IS_ANY_SET(pVCpu, VMCPU_FF_INTERRUPT_APIC | VMCPU_FF_INTERRUPT_PIC)
8643 && !pVCpu->hm.s.fSingleInstruction)
8644 {
8645 Assert(!DBGFIsStepping(pVCpu));
8646 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, CPUMCTX_EXTRN_RFLAGS);
8647 AssertRC(rc);
8648
8649 if (pCtx->eflags.u32 & X86_EFL_IF)
8650 {
8651#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
8652 if ( fIsNestedGuest
8653 && CPUMIsGuestVmxPinCtlsSet(pCtx, VMX_PIN_CTLS_EXT_INT_EXIT)
8654 && !CPUMIsGuestVmxExitCtlsSet(pCtx, VMX_EXIT_CTLS_ACK_EXT_INT))
8655 {
8656 VBOXSTRICTRC rcStrict = IEMExecVmxVmexitExtInt(pVCpu, 0 /* uVector */, true /* fIntPending */);
8657 Assert(rcStrict != VINF_VMX_INTERCEPT_NOT_ACTIVE);
8658 return rcStrict;
8659 }
8660#endif
8661 uint8_t u8Interrupt;
8662 rc = PDMGetInterrupt(pVCpu, &u8Interrupt);
8663 if (RT_SUCCESS(rc))
8664 {
8665#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
8666 if ( fIsNestedGuest
8667 && CPUMIsGuestVmxPinCtlsSet(pCtx, VMX_PIN_CTLS_EXT_INT_EXIT)
8668 && CPUMIsGuestVmxExitCtlsSet(pCtx, VMX_EXIT_CTLS_ACK_EXT_INT))
8669 {
8670 VBOXSTRICTRC rcStrict = IEMExecVmxVmexitExtInt(pVCpu, u8Interrupt, false /* fIntPending */);
8671 Assert(rcStrict != VINF_VMX_INTERCEPT_NOT_ACTIVE);
8672 return rcStrict;
8673 }
8674#endif
8675 hmR0VmxSetPendingExtInt(pVCpu, u8Interrupt);
8676 Log4Func(("External interrupt (%#x) pending injection\n", u8Interrupt));
8677 }
8678 else if (rc == VERR_APIC_INTR_MASKED_BY_TPR)
8679 {
8680 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchTprMaskedIrq);
8681
8682 if ( !fIsNestedGuest
8683 && (pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_USE_TPR_SHADOW))
8684 hmR0VmxApicSetTprThreshold(pVmcsInfo, u8Interrupt >> 4);
8685 /* else: for nested-guests, TPR threshold is picked up while merging VMCS controls. */
8686
8687 /*
8688 * If the CPU doesn't have TPR shadowing, we will always get a VM-exit on TPR changes and
8689 * APICSetTpr() will end up setting the VMCPU_FF_INTERRUPT_APIC if required, so there is no
8690 * need to re-set this force-flag here.
8691 */
8692 }
8693 else
8694 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchGuestIrq);
8695
8696 /* We've injected the interrupt or taken necessary action, bail. */
8697 return VINF_SUCCESS;
8698 }
8699 else if (!fIsNestedGuest)
8700 hmR0VmxSetIntWindowExitVmcs(pVCpu, pVmcsInfo);
8701 }
8702 }
8703 else if (!fIsNestedGuest)
8704 {
8705 /*
8706 * An event is being injected or we are in an interrupt shadow. Check if another event is
8707 * pending. If so, instruct VT-x to cause a VM-exit as soon as the guest is ready to accept
8708 * the pending event.
8709 */
8710 if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_INTERRUPT_NMI))
8711 hmR0VmxSetNmiWindowExitVmcs(pVCpu, pVmcsInfo);
8712 else if ( VMCPU_FF_IS_ANY_SET(pVCpu, VMCPU_FF_INTERRUPT_APIC | VMCPU_FF_INTERRUPT_PIC)
8713 && !pVCpu->hm.s.fSingleInstruction)
8714 hmR0VmxSetIntWindowExitVmcs(pVCpu, pVmcsInfo);
8715 }
8716 /* else: for nested-guests, NMI/interrupt-window exiting will be picked up when merging VMCS controls. */
8717
8718 return VINF_SUCCESS;
8719}
8720
8721
8722/**
8723 * Injects any pending events into the guest if the guest is in a state to
8724 * receive them.
8725 *
8726 * @returns Strict VBox status code (i.e. informational status codes too).
8727 * @param pVCpu The cross context virtual CPU structure.
8728 * @param pVmxTransient The VMX-transient structure.
8729 * @param fIntrState The VT-x guest-interruptibility state.
8730 * @param fStepping Whether we are single-stepping the guest using the
8731 * hypervisor debugger and should return
8732 * VINF_EM_DBG_STEPPED if the event was dispatched
8733 * directly.
8734 */
8735static VBOXSTRICTRC hmR0VmxInjectPendingEvent(PVMCPUCC pVCpu, PCVMXTRANSIENT pVmxTransient, uint32_t fIntrState, bool fStepping)
8736{
8737 HMVMX_ASSERT_PREEMPT_SAFE(pVCpu);
8738 Assert(VMMRZCallRing3IsEnabled(pVCpu));
8739
8740#ifdef VBOX_STRICT
8741 /*
8742 * Verify guest-interruptibility state.
8743 *
8744 * We put this in a scoped block so we do not accidentally use fBlockSti or fBlockMovSS,
8745 * since injecting an event may modify the interruptibility state and we must thus always
8746 * use fIntrState.
8747 */
8748 {
8749 bool const fBlockMovSS = RT_BOOL(fIntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_MOVSS);
8750 bool const fBlockSti = RT_BOOL(fIntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_STI);
8751 Assert(!fBlockSti || !(ASMAtomicUoReadU64(&pVCpu->cpum.GstCtx.fExtrn) & CPUMCTX_EXTRN_RFLAGS));
8752 Assert(!fBlockSti || pVCpu->cpum.GstCtx.eflags.Bits.u1IF); /* Cannot set block-by-STI when interrupts are disabled. */
8753 Assert(!(fIntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_SMI)); /* We don't support block-by-SMI yet.*/
8754 Assert(!TRPMHasTrap(pVCpu));
8755 NOREF(fBlockMovSS); NOREF(fBlockSti);
8756 }
8757#endif
8758
8759 VBOXSTRICTRC rcStrict = VINF_SUCCESS;
8760 if (pVCpu->hm.s.Event.fPending)
8761 {
8762 /*
8763 * Do -not- clear any interrupt-window exiting control here. We might have an interrupt
8764 * pending even while injecting an event and in this case, we want a VM-exit as soon as
8765 * the guest is ready for the next interrupt, see @bugref{6208#c45}.
8766 *
8767 * See Intel spec. 26.6.5 "Interrupt-Window Exiting and Virtual-Interrupt Delivery".
8768 */
8769 uint32_t const uIntType = VMX_ENTRY_INT_INFO_TYPE(pVCpu->hm.s.Event.u64IntInfo);
8770#ifdef VBOX_STRICT
8771 if (uIntType == VMX_ENTRY_INT_INFO_TYPE_EXT_INT)
8772 {
8773 Assert(pVCpu->cpum.GstCtx.eflags.u32 & X86_EFL_IF);
8774 Assert(!(fIntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_STI));
8775 Assert(!(fIntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_MOVSS));
8776 }
8777 else if (uIntType == VMX_ENTRY_INT_INFO_TYPE_NMI)
8778 {
8779 Assert(!(fIntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_NMI));
8780 Assert(!(fIntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_STI));
8781 Assert(!(fIntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_MOVSS));
8782 }
8783#endif
8784 Log4(("Injecting pending event vcpu[%RU32] u64IntInfo=%#RX64 Type=%#RX32\n", pVCpu->idCpu, pVCpu->hm.s.Event.u64IntInfo,
8785 uIntType));
8786
8787 /*
8788 * Inject the event and get any changes to the guest-interruptibility state.
8789 *
8790 * The guest-interruptibility state may need to be updated if we inject the event
8791 * into the guest IDT ourselves (for real-on-v86 guest injecting software interrupts).
8792 */
8793 rcStrict = hmR0VmxInjectEventVmcs(pVCpu, pVmxTransient, &pVCpu->hm.s.Event, fStepping, &fIntrState);
8794 AssertRCReturn(VBOXSTRICTRC_VAL(rcStrict), rcStrict);
8795
8796 if (uIntType == VMX_ENTRY_INT_INFO_TYPE_EXT_INT)
8797 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectInterrupt);
8798 else
8799 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectXcpt);
8800 }
8801
8802 /*
8803 * Deliver any pending debug exceptions if the guest is single-stepping using EFLAGS.TF and
8804 * is an interrupt shadow (block-by-STI or block-by-MOV SS).
8805 */
8806 if ( (fIntrState & (VMX_VMCS_GUEST_INT_STATE_BLOCK_STI | VMX_VMCS_GUEST_INT_STATE_BLOCK_MOVSS))
8807 && !pVmxTransient->fIsNestedGuest)
8808 {
8809 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_RFLAGS);
8810
8811 if (!pVCpu->hm.s.fSingleInstruction)
8812 {
8813 /*
8814 * Set or clear the BS bit depending on whether the trap flag is active or not. We need
8815 * to do both since we clear the BS bit from the VMCS while exiting to ring-3.
8816 */
8817 Assert(!DBGFIsStepping(pVCpu));
8818 uint8_t const fTrapFlag = !!(pVCpu->cpum.GstCtx.eflags.u32 & X86_EFL_TF);
8819 int rc = VMXWriteVmcsNw(VMX_VMCS_GUEST_PENDING_DEBUG_XCPTS, fTrapFlag << VMX_BF_VMCS_PENDING_DBG_XCPT_BS_SHIFT);
8820 AssertRC(rc);
8821 }
8822 else if (pVCpu->cpum.GstCtx.eflags.u32 & X86_EFL_TF)
8823 {
8824 /*
8825 * We must not deliver a debug exception when single-stepping in the hypervisor debugger
8826 * using EFLAGS.T. Instead, clear interrupt inhibition.
8827 */
8828 Assert(!(pVCpu->CTX_SUFF(pVM)->hm.s.vmx.Msrs.ProcCtls.n.allowed1 & VMX_PROC_CTLS_MONITOR_TRAP_FLAG));
8829 fIntrState = 0;
8830 }
8831 }
8832 /* else: for nested-guest currently handling while merging controls. */
8833
8834 /*
8835 * Finally, update the guest-interruptibility state.
8836 *
8837 * This is required for the real-on-v86 software interrupt injection, for
8838 * pending debug exceptions as well as updates to the guest state from ring-3 (IEM).
8839 */
8840 int rc = VMXWriteVmcs32(VMX_VMCS32_GUEST_INT_STATE, fIntrState);
8841 AssertRC(rc);
8842
8843 /*
8844 * There's no need to clear the VM-entry interruption-information field here if we're not
8845 * injecting anything. VT-x clears the valid bit on every VM-exit.
8846 *
8847 * See Intel spec. 24.8.3 "VM-Entry Controls for Event Injection".
8848 */
8849
8850 Assert(rcStrict == VINF_SUCCESS || rcStrict == VINF_EM_RESET || (rcStrict == VINF_EM_DBG_STEPPED && fStepping));
8851 return rcStrict;
8852}
8853
8854
8855/**
8856 * Enters the VT-x session.
8857 *
8858 * @returns VBox status code.
8859 * @param pVCpu The cross context virtual CPU structure.
8860 */
8861VMMR0DECL(int) VMXR0Enter(PVMCPUCC pVCpu)
8862{
8863 AssertPtr(pVCpu);
8864 Assert(pVCpu->CTX_SUFF(pVM)->hm.s.vmx.fSupported);
8865 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
8866
8867 LogFlowFunc(("pVCpu=%p\n", pVCpu));
8868 Assert((pVCpu->hm.s.fCtxChanged & (HM_CHANGED_HOST_CONTEXT | HM_CHANGED_VMX_HOST_GUEST_SHARED_STATE))
8869 == (HM_CHANGED_HOST_CONTEXT | HM_CHANGED_VMX_HOST_GUEST_SHARED_STATE));
8870
8871#ifdef VBOX_STRICT
8872 /* At least verify VMX is enabled, since we can't check if we're in VMX root mode without #GP'ing. */
8873 RTCCUINTREG uHostCr4 = ASMGetCR4();
8874 if (!(uHostCr4 & X86_CR4_VMXE))
8875 {
8876 LogRelFunc(("X86_CR4_VMXE bit in CR4 is not set!\n"));
8877 return VERR_VMX_X86_CR4_VMXE_CLEARED;
8878 }
8879#endif
8880
8881 /*
8882 * Load the appropriate VMCS as the current and active one.
8883 */
8884 PVMXVMCSINFO pVmcsInfo;
8885 bool const fInNestedGuestMode = CPUMIsGuestInVmxNonRootMode(&pVCpu->cpum.GstCtx);
8886 if (!fInNestedGuestMode)
8887 pVmcsInfo = &pVCpu->hm.s.vmx.VmcsInfo;
8888 else
8889 pVmcsInfo = &pVCpu->hm.s.vmx.VmcsInfoNstGst;
8890 int rc = hmR0VmxLoadVmcs(pVmcsInfo);
8891 if (RT_SUCCESS(rc))
8892 {
8893 pVCpu->hm.s.vmx.fSwitchedToNstGstVmcs = fInNestedGuestMode;
8894 pVCpu->hm.s.fLeaveDone = false;
8895 Log4Func(("Loaded Vmcs. HostCpuId=%u\n", RTMpCpuId()));
8896
8897 /*
8898 * Do the EMT scheduled L1D flush here if needed.
8899 */
8900 if (pVCpu->CTX_SUFF(pVM)->hm.s.fL1dFlushOnSched)
8901 ASMWrMsr(MSR_IA32_FLUSH_CMD, MSR_IA32_FLUSH_CMD_F_L1D);
8902 else if (pVCpu->CTX_SUFF(pVM)->hm.s.fMdsClearOnSched)
8903 hmR0MdsClear();
8904 }
8905 return rc;
8906}
8907
8908
8909/**
8910 * The thread-context callback (only on platforms which support it).
8911 *
8912 * @param enmEvent The thread-context event.
8913 * @param pVCpu The cross context virtual CPU structure.
8914 * @param fGlobalInit Whether global VT-x/AMD-V init. was used.
8915 * @thread EMT(pVCpu)
8916 */
8917VMMR0DECL(void) VMXR0ThreadCtxCallback(RTTHREADCTXEVENT enmEvent, PVMCPUCC pVCpu, bool fGlobalInit)
8918{
8919 AssertPtr(pVCpu);
8920 RT_NOREF1(fGlobalInit);
8921
8922 switch (enmEvent)
8923 {
8924 case RTTHREADCTXEVENT_OUT:
8925 {
8926 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
8927 Assert(VMMR0ThreadCtxHookIsEnabled(pVCpu));
8928 VMCPU_ASSERT_EMT(pVCpu);
8929
8930 /* No longjmps (logger flushes, locks) in this fragile context. */
8931 VMMRZCallRing3Disable(pVCpu);
8932 Log4Func(("Preempting: HostCpuId=%u\n", RTMpCpuId()));
8933
8934 /* Restore host-state (FPU, debug etc.) */
8935 if (!pVCpu->hm.s.fLeaveDone)
8936 {
8937 /*
8938 * Do -not- import the guest-state here as we might already be in the middle of importing
8939 * it, esp. bad if we're holding the PGM lock, see comment in hmR0VmxImportGuestState().
8940 */
8941 hmR0VmxLeave(pVCpu, false /* fImportState */);
8942 pVCpu->hm.s.fLeaveDone = true;
8943 }
8944
8945 /* Leave HM context, takes care of local init (term). */
8946 int rc = HMR0LeaveCpu(pVCpu);
8947 AssertRC(rc);
8948
8949 /* Restore longjmp state. */
8950 VMMRZCallRing3Enable(pVCpu);
8951 STAM_REL_COUNTER_INC(&pVCpu->hm.s.StatSwitchPreempt);
8952 break;
8953 }
8954
8955 case RTTHREADCTXEVENT_IN:
8956 {
8957 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
8958 Assert(VMMR0ThreadCtxHookIsEnabled(pVCpu));
8959 VMCPU_ASSERT_EMT(pVCpu);
8960
8961 /* No longjmps here, as we don't want to trigger preemption (& its hook) while resuming. */
8962 VMMRZCallRing3Disable(pVCpu);
8963 Log4Func(("Resumed: HostCpuId=%u\n", RTMpCpuId()));
8964
8965 /* Initialize the bare minimum state required for HM. This takes care of
8966 initializing VT-x if necessary (onlined CPUs, local init etc.) */
8967 int rc = hmR0EnterCpu(pVCpu);
8968 AssertRC(rc);
8969 Assert( (pVCpu->hm.s.fCtxChanged & (HM_CHANGED_HOST_CONTEXT | HM_CHANGED_VMX_HOST_GUEST_SHARED_STATE))
8970 == (HM_CHANGED_HOST_CONTEXT | HM_CHANGED_VMX_HOST_GUEST_SHARED_STATE));
8971
8972 /* Load the active VMCS as the current one. */
8973 PVMXVMCSINFO pVmcsInfo = hmGetVmxActiveVmcsInfo(pVCpu);
8974 rc = hmR0VmxLoadVmcs(pVmcsInfo);
8975 AssertRC(rc);
8976 Log4Func(("Resumed: Loaded Vmcs. HostCpuId=%u\n", RTMpCpuId()));
8977 pVCpu->hm.s.fLeaveDone = false;
8978
8979 /* Do the EMT scheduled L1D flush if needed. */
8980 if (pVCpu->CTX_SUFF(pVM)->hm.s.fL1dFlushOnSched)
8981 ASMWrMsr(MSR_IA32_FLUSH_CMD, MSR_IA32_FLUSH_CMD_F_L1D);
8982
8983 /* Restore longjmp state. */
8984 VMMRZCallRing3Enable(pVCpu);
8985 break;
8986 }
8987
8988 default:
8989 break;
8990 }
8991}
8992
8993
8994/**
8995 * Exports the host state into the VMCS host-state area.
8996 * Sets up the VM-exit MSR-load area.
8997 *
8998 * The CPU state will be loaded from these fields on every successful VM-exit.
8999 *
9000 * @returns VBox status code.
9001 * @param pVCpu The cross context virtual CPU structure.
9002 *
9003 * @remarks No-long-jump zone!!!
9004 */
9005static int hmR0VmxExportHostState(PVMCPUCC pVCpu)
9006{
9007 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
9008
9009 int rc = VINF_SUCCESS;
9010 if (pVCpu->hm.s.fCtxChanged & HM_CHANGED_HOST_CONTEXT)
9011 {
9012 hmR0VmxExportHostControlRegs();
9013
9014 rc = hmR0VmxExportHostSegmentRegs(pVCpu);
9015 AssertLogRelMsgRCReturn(rc, ("rc=%Rrc\n", rc), rc);
9016
9017 hmR0VmxExportHostMsrs(pVCpu);
9018
9019 pVCpu->hm.s.fCtxChanged &= ~HM_CHANGED_HOST_CONTEXT;
9020 }
9021 return rc;
9022}
9023
9024
9025/**
9026 * Saves the host state in the VMCS host-state.
9027 *
9028 * @returns VBox status code.
9029 * @param pVCpu The cross context virtual CPU structure.
9030 *
9031 * @remarks No-long-jump zone!!!
9032 */
9033VMMR0DECL(int) VMXR0ExportHostState(PVMCPUCC pVCpu)
9034{
9035 AssertPtr(pVCpu);
9036 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
9037
9038 /*
9039 * Export the host state here while entering HM context.
9040 * When thread-context hooks are used, we might get preempted and have to re-save the host
9041 * state but most of the time we won't be, so do it here before we disable interrupts.
9042 */
9043 return hmR0VmxExportHostState(pVCpu);
9044}
9045
9046
9047/**
9048 * Exports the guest state into the VMCS guest-state area.
9049 *
9050 * The will typically be done before VM-entry when the guest-CPU state and the
9051 * VMCS state may potentially be out of sync.
9052 *
9053 * Sets up the VM-entry MSR-load and VM-exit MSR-store areas. Sets up the
9054 * VM-entry controls.
9055 * Sets up the appropriate VMX non-root function to execute guest code based on
9056 * the guest CPU mode.
9057 *
9058 * @returns VBox strict status code.
9059 * @retval VINF_EM_RESCHEDULE_REM if we try to emulate non-paged guest code
9060 * without unrestricted guest execution and the VMMDev is not presently
9061 * mapped (e.g. EFI32).
9062 *
9063 * @param pVCpu The cross context virtual CPU structure.
9064 * @param pVmxTransient The VMX-transient structure.
9065 *
9066 * @remarks No-long-jump zone!!!
9067 */
9068static VBOXSTRICTRC hmR0VmxExportGuestState(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
9069{
9070 AssertPtr(pVCpu);
9071 HMVMX_ASSERT_PREEMPT_SAFE(pVCpu);
9072 LogFlowFunc(("pVCpu=%p\n", pVCpu));
9073
9074 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatExportGuestState, x);
9075
9076 /*
9077 * Determine real-on-v86 mode.
9078 * Used when the guest is in real-mode and unrestricted guest execution is not used.
9079 */
9080 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
9081 if ( pVCpu->CTX_SUFF(pVM)->hm.s.vmx.fUnrestrictedGuest
9082 || !CPUMIsGuestInRealModeEx(&pVCpu->cpum.GstCtx))
9083 pVmcsInfo->RealMode.fRealOnV86Active = false;
9084 else
9085 {
9086 Assert(!pVmxTransient->fIsNestedGuest);
9087 pVmcsInfo->RealMode.fRealOnV86Active = true;
9088 }
9089
9090 /*
9091 * Any ordering dependency among the sub-functions below must be explicitly stated using comments.
9092 * Ideally, assert that the cross-dependent bits are up-to-date at the point of using it.
9093 */
9094 int rc = hmR0VmxExportGuestEntryExitCtls(pVCpu, pVmxTransient);
9095 AssertLogRelMsgRCReturn(rc, ("rc=%Rrc\n", rc), rc);
9096
9097 rc = hmR0VmxExportGuestCR0(pVCpu, pVmxTransient);
9098 AssertLogRelMsgRCReturn(rc, ("rc=%Rrc\n", rc), rc);
9099
9100 VBOXSTRICTRC rcStrict = hmR0VmxExportGuestCR3AndCR4(pVCpu, pVmxTransient);
9101 if (rcStrict == VINF_SUCCESS)
9102 { /* likely */ }
9103 else
9104 {
9105 Assert(rcStrict == VINF_EM_RESCHEDULE_REM || RT_FAILURE_NP(rcStrict));
9106 return rcStrict;
9107 }
9108
9109 rc = hmR0VmxExportGuestSegRegsXdtr(pVCpu, pVmxTransient);
9110 AssertLogRelMsgRCReturn(rc, ("rc=%Rrc\n", rc), rc);
9111
9112 rc = hmR0VmxExportGuestMsrs(pVCpu, pVmxTransient);
9113 AssertLogRelMsgRCReturn(rc, ("rc=%Rrc\n", rc), rc);
9114
9115 hmR0VmxExportGuestApicTpr(pVCpu, pVmxTransient);
9116 hmR0VmxExportGuestXcptIntercepts(pVCpu, pVmxTransient);
9117 hmR0VmxExportGuestRip(pVCpu);
9118 hmR0VmxExportGuestRsp(pVCpu);
9119 hmR0VmxExportGuestRflags(pVCpu, pVmxTransient);
9120
9121 rc = hmR0VmxExportGuestHwvirtState(pVCpu, pVmxTransient);
9122 AssertLogRelMsgRCReturn(rc, ("rc=%Rrc\n", rc), rc);
9123
9124 /* Clear any bits that may be set but exported unconditionally or unused/reserved bits. */
9125 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~( (HM_CHANGED_GUEST_GPRS_MASK & ~HM_CHANGED_GUEST_RSP)
9126 | HM_CHANGED_GUEST_CR2
9127 | (HM_CHANGED_GUEST_DR_MASK & ~HM_CHANGED_GUEST_DR7)
9128 | HM_CHANGED_GUEST_X87
9129 | HM_CHANGED_GUEST_SSE_AVX
9130 | HM_CHANGED_GUEST_OTHER_XSAVE
9131 | HM_CHANGED_GUEST_XCRx
9132 | HM_CHANGED_GUEST_KERNEL_GS_BASE /* Part of lazy or auto load-store MSRs. */
9133 | HM_CHANGED_GUEST_SYSCALL_MSRS /* Part of lazy or auto load-store MSRs. */
9134 | HM_CHANGED_GUEST_TSC_AUX
9135 | HM_CHANGED_GUEST_OTHER_MSRS
9136 | (HM_CHANGED_KEEPER_STATE_MASK & ~HM_CHANGED_VMX_MASK)));
9137
9138 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExportGuestState, x);
9139 return rc;
9140}
9141
9142
9143/**
9144 * Exports the state shared between the host and guest into the VMCS.
9145 *
9146 * @param pVCpu The cross context virtual CPU structure.
9147 * @param pVmxTransient The VMX-transient structure.
9148 *
9149 * @remarks No-long-jump zone!!!
9150 */
9151static void hmR0VmxExportSharedState(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
9152{
9153 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
9154 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
9155
9156 if (pVCpu->hm.s.fCtxChanged & HM_CHANGED_GUEST_DR_MASK)
9157 {
9158 int rc = hmR0VmxExportSharedDebugState(pVCpu, pVmxTransient);
9159 AssertRC(rc);
9160 pVCpu->hm.s.fCtxChanged &= ~HM_CHANGED_GUEST_DR_MASK;
9161
9162 /* Loading shared debug bits might have changed eflags.TF bit for debugging purposes. */
9163 if (pVCpu->hm.s.fCtxChanged & HM_CHANGED_GUEST_RFLAGS)
9164 hmR0VmxExportGuestRflags(pVCpu, pVmxTransient);
9165 }
9166
9167 if (pVCpu->hm.s.fCtxChanged & HM_CHANGED_VMX_GUEST_LAZY_MSRS)
9168 {
9169 hmR0VmxLazyLoadGuestMsrs(pVCpu);
9170 pVCpu->hm.s.fCtxChanged &= ~HM_CHANGED_VMX_GUEST_LAZY_MSRS;
9171 }
9172
9173 AssertMsg(!(pVCpu->hm.s.fCtxChanged & HM_CHANGED_VMX_HOST_GUEST_SHARED_STATE),
9174 ("fCtxChanged=%#RX64\n", pVCpu->hm.s.fCtxChanged));
9175}
9176
9177
9178/**
9179 * Worker for loading the guest-state bits in the inner VT-x execution loop.
9180 *
9181 * @returns Strict VBox status code (i.e. informational status codes too).
9182 * @retval VINF_EM_RESCHEDULE_REM if we try to emulate non-paged guest code
9183 * without unrestricted guest execution and the VMMDev is not presently
9184 * mapped (e.g. EFI32).
9185 *
9186 * @param pVCpu The cross context virtual CPU structure.
9187 * @param pVmxTransient The VMX-transient structure.
9188 *
9189 * @remarks No-long-jump zone!!!
9190 */
9191static VBOXSTRICTRC hmR0VmxExportGuestStateOptimal(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
9192{
9193 HMVMX_ASSERT_PREEMPT_SAFE(pVCpu);
9194 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
9195 Assert(VMMR0IsLogFlushDisabled(pVCpu));
9196
9197#ifdef HMVMX_ALWAYS_SYNC_FULL_GUEST_STATE
9198 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_ALL_GUEST);
9199#endif
9200
9201 /*
9202 * For many VM-exits only RIP/RSP/RFLAGS (and HWVIRT state when executing a nested-guest)
9203 * changes. First try to export only these without going through all other changed-flag checks.
9204 */
9205 VBOXSTRICTRC rcStrict;
9206 uint64_t const fCtxMask = HM_CHANGED_ALL_GUEST & ~HM_CHANGED_VMX_HOST_GUEST_SHARED_STATE;
9207 uint64_t const fMinimalMask = HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RSP | HM_CHANGED_GUEST_RFLAGS | HM_CHANGED_GUEST_HWVIRT;
9208 uint64_t const fCtxChanged = ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged);
9209
9210 /* If only RIP/RSP/RFLAGS/HWVIRT changed, export only those (quicker, happens more often).*/
9211 if ( (fCtxChanged & fMinimalMask)
9212 && !(fCtxChanged & (fCtxMask & ~fMinimalMask)))
9213 {
9214 hmR0VmxExportGuestRip(pVCpu);
9215 hmR0VmxExportGuestRsp(pVCpu);
9216 hmR0VmxExportGuestRflags(pVCpu, pVmxTransient);
9217 rcStrict = hmR0VmxExportGuestHwvirtState(pVCpu, pVmxTransient);
9218 STAM_COUNTER_INC(&pVCpu->hm.s.StatExportMinimal);
9219 }
9220 /* If anything else also changed, go through the full export routine and export as required. */
9221 else if (fCtxChanged & fCtxMask)
9222 {
9223 rcStrict = hmR0VmxExportGuestState(pVCpu, pVmxTransient);
9224 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
9225 { /* likely */}
9226 else
9227 {
9228 AssertMsg(rcStrict == VINF_EM_RESCHEDULE_REM, ("Failed to export guest state! rc=%Rrc\n",
9229 VBOXSTRICTRC_VAL(rcStrict)));
9230 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
9231 return rcStrict;
9232 }
9233 STAM_COUNTER_INC(&pVCpu->hm.s.StatExportFull);
9234 }
9235 /* Nothing changed, nothing to load here. */
9236 else
9237 rcStrict = VINF_SUCCESS;
9238
9239#ifdef VBOX_STRICT
9240 /* All the guest state bits should be loaded except maybe the host context and/or the shared host/guest bits. */
9241 uint64_t const fCtxChangedCur = ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged);
9242 AssertMsg(!(fCtxChangedCur & fCtxMask), ("fCtxChangedCur=%#RX64\n", fCtxChangedCur));
9243#endif
9244 return rcStrict;
9245}
9246
9247
9248/**
9249 * Tries to determine what part of the guest-state VT-x has deemed as invalid
9250 * and update error record fields accordingly.
9251 *
9252 * @returns VMX_IGS_* error codes.
9253 * @retval VMX_IGS_REASON_NOT_FOUND if this function could not find anything
9254 * wrong with the guest state.
9255 *
9256 * @param pVCpu The cross context virtual CPU structure.
9257 * @param pVmcsInfo The VMCS info. object.
9258 *
9259 * @remarks This function assumes our cache of the VMCS controls
9260 * are valid, i.e. hmR0VmxCheckVmcsCtls() succeeded.
9261 */
9262static uint32_t hmR0VmxCheckGuestState(PVMCPUCC pVCpu, PCVMXVMCSINFO pVmcsInfo)
9263{
9264#define HMVMX_ERROR_BREAK(err) { uError = (err); break; }
9265#define HMVMX_CHECK_BREAK(expr, err) do { \
9266 if (!(expr)) { uError = (err); break; } \
9267 } while (0)
9268
9269 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
9270 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
9271 uint32_t uError = VMX_IGS_ERROR;
9272 uint32_t u32IntrState = 0;
9273 bool const fUnrestrictedGuest = pVM->hm.s.vmx.fUnrestrictedGuest;
9274 do
9275 {
9276 int rc;
9277
9278 /*
9279 * Guest-interruptibility state.
9280 *
9281 * Read this first so that any check that fails prior to those that actually
9282 * require the guest-interruptibility state would still reflect the correct
9283 * VMCS value and avoids causing further confusion.
9284 */
9285 rc = VMXReadVmcs32(VMX_VMCS32_GUEST_INT_STATE, &u32IntrState);
9286 AssertRC(rc);
9287
9288 uint32_t u32Val;
9289 uint64_t u64Val;
9290
9291 /*
9292 * CR0.
9293 */
9294 /** @todo Why do we need to OR and AND the fixed-0 and fixed-1 bits below? */
9295 uint64_t fSetCr0 = (pVM->hm.s.vmx.Msrs.u64Cr0Fixed0 & pVM->hm.s.vmx.Msrs.u64Cr0Fixed1);
9296 uint64_t const fZapCr0 = (pVM->hm.s.vmx.Msrs.u64Cr0Fixed0 | pVM->hm.s.vmx.Msrs.u64Cr0Fixed1);
9297 /* Exceptions for unrestricted guest execution for CR0 fixed bits (PE, PG).
9298 See Intel spec. 26.3.1 "Checks on Guest Control Registers, Debug Registers and MSRs." */
9299 if (fUnrestrictedGuest)
9300 fSetCr0 &= ~(uint64_t)(X86_CR0_PE | X86_CR0_PG);
9301
9302 uint64_t u64GuestCr0;
9303 rc = VMXReadVmcsNw(VMX_VMCS_GUEST_CR0, &u64GuestCr0);
9304 AssertRC(rc);
9305 HMVMX_CHECK_BREAK((u64GuestCr0 & fSetCr0) == fSetCr0, VMX_IGS_CR0_FIXED1);
9306 HMVMX_CHECK_BREAK(!(u64GuestCr0 & ~fZapCr0), VMX_IGS_CR0_FIXED0);
9307 if ( !fUnrestrictedGuest
9308 && (u64GuestCr0 & X86_CR0_PG)
9309 && !(u64GuestCr0 & X86_CR0_PE))
9310 HMVMX_ERROR_BREAK(VMX_IGS_CR0_PG_PE_COMBO);
9311
9312 /*
9313 * CR4.
9314 */
9315 /** @todo Why do we need to OR and AND the fixed-0 and fixed-1 bits below? */
9316 uint64_t const fSetCr4 = (pVM->hm.s.vmx.Msrs.u64Cr4Fixed0 & pVM->hm.s.vmx.Msrs.u64Cr4Fixed1);
9317 uint64_t const fZapCr4 = (pVM->hm.s.vmx.Msrs.u64Cr4Fixed0 | pVM->hm.s.vmx.Msrs.u64Cr4Fixed1);
9318
9319 uint64_t u64GuestCr4;
9320 rc = VMXReadVmcsNw(VMX_VMCS_GUEST_CR4, &u64GuestCr4);
9321 AssertRC(rc);
9322 HMVMX_CHECK_BREAK((u64GuestCr4 & fSetCr4) == fSetCr4, VMX_IGS_CR4_FIXED1);
9323 HMVMX_CHECK_BREAK(!(u64GuestCr4 & ~fZapCr4), VMX_IGS_CR4_FIXED0);
9324
9325 /*
9326 * IA32_DEBUGCTL MSR.
9327 */
9328 rc = VMXReadVmcs64(VMX_VMCS64_GUEST_DEBUGCTL_FULL, &u64Val);
9329 AssertRC(rc);
9330 if ( (pVmcsInfo->u32EntryCtls & VMX_ENTRY_CTLS_LOAD_DEBUG)
9331 && (u64Val & 0xfffffe3c)) /* Bits 31:9, bits 5:2 MBZ. */
9332 {
9333 HMVMX_ERROR_BREAK(VMX_IGS_DEBUGCTL_MSR_RESERVED);
9334 }
9335 uint64_t u64DebugCtlMsr = u64Val;
9336
9337#ifdef VBOX_STRICT
9338 rc = VMXReadVmcs32(VMX_VMCS32_CTRL_ENTRY, &u32Val);
9339 AssertRC(rc);
9340 Assert(u32Val == pVmcsInfo->u32EntryCtls);
9341#endif
9342 bool const fLongModeGuest = RT_BOOL(pVmcsInfo->u32EntryCtls & VMX_ENTRY_CTLS_IA32E_MODE_GUEST);
9343
9344 /*
9345 * RIP and RFLAGS.
9346 */
9347 rc = VMXReadVmcsNw(VMX_VMCS_GUEST_RIP, &u64Val);
9348 AssertRC(rc);
9349 /* pCtx->rip can be different than the one in the VMCS (e.g. run guest code and VM-exits that don't update it). */
9350 if ( !fLongModeGuest
9351 || !pCtx->cs.Attr.n.u1Long)
9352 HMVMX_CHECK_BREAK(!(u64Val & UINT64_C(0xffffffff00000000)), VMX_IGS_LONGMODE_RIP_INVALID);
9353 /** @todo If the processor supports N < 64 linear-address bits, bits 63:N
9354 * must be identical if the "IA-32e mode guest" VM-entry
9355 * control is 1 and CS.L is 1. No check applies if the
9356 * CPU supports 64 linear-address bits. */
9357
9358 /* Flags in pCtx can be different (real-on-v86 for instance). We are only concerned about the VMCS contents here. */
9359 rc = VMXReadVmcsNw(VMX_VMCS_GUEST_RFLAGS, &u64Val);
9360 AssertRC(rc);
9361 HMVMX_CHECK_BREAK(!(u64Val & UINT64_C(0xffffffffffc08028)), /* Bit 63:22, Bit 15, 5, 3 MBZ. */
9362 VMX_IGS_RFLAGS_RESERVED);
9363 HMVMX_CHECK_BREAK((u64Val & X86_EFL_RA1_MASK), VMX_IGS_RFLAGS_RESERVED1); /* Bit 1 MB1. */
9364 uint32_t const u32Eflags = u64Val;
9365
9366 if ( fLongModeGuest
9367 || ( fUnrestrictedGuest
9368 && !(u64GuestCr0 & X86_CR0_PE)))
9369 {
9370 HMVMX_CHECK_BREAK(!(u32Eflags & X86_EFL_VM), VMX_IGS_RFLAGS_VM_INVALID);
9371 }
9372
9373 uint32_t u32EntryInfo;
9374 rc = VMXReadVmcs32(VMX_VMCS32_CTRL_ENTRY_INTERRUPTION_INFO, &u32EntryInfo);
9375 AssertRC(rc);
9376 if (VMX_ENTRY_INT_INFO_IS_EXT_INT(u32EntryInfo))
9377 HMVMX_CHECK_BREAK(u32Eflags & X86_EFL_IF, VMX_IGS_RFLAGS_IF_INVALID);
9378
9379 /*
9380 * 64-bit checks.
9381 */
9382 if (fLongModeGuest)
9383 {
9384 HMVMX_CHECK_BREAK(u64GuestCr0 & X86_CR0_PG, VMX_IGS_CR0_PG_LONGMODE);
9385 HMVMX_CHECK_BREAK(u64GuestCr4 & X86_CR4_PAE, VMX_IGS_CR4_PAE_LONGMODE);
9386 }
9387
9388 if ( !fLongModeGuest
9389 && (u64GuestCr4 & X86_CR4_PCIDE))
9390 HMVMX_ERROR_BREAK(VMX_IGS_CR4_PCIDE);
9391
9392 /** @todo CR3 field must be such that bits 63:52 and bits in the range
9393 * 51:32 beyond the processor's physical-address width are 0. */
9394
9395 if ( (pVmcsInfo->u32EntryCtls & VMX_ENTRY_CTLS_LOAD_DEBUG)
9396 && (pCtx->dr[7] & X86_DR7_MBZ_MASK))
9397 HMVMX_ERROR_BREAK(VMX_IGS_DR7_RESERVED);
9398
9399 rc = VMXReadVmcsNw(VMX_VMCS_HOST_SYSENTER_ESP, &u64Val);
9400 AssertRC(rc);
9401 HMVMX_CHECK_BREAK(X86_IS_CANONICAL(u64Val), VMX_IGS_SYSENTER_ESP_NOT_CANONICAL);
9402
9403 rc = VMXReadVmcsNw(VMX_VMCS_HOST_SYSENTER_EIP, &u64Val);
9404 AssertRC(rc);
9405 HMVMX_CHECK_BREAK(X86_IS_CANONICAL(u64Val), VMX_IGS_SYSENTER_EIP_NOT_CANONICAL);
9406
9407 /*
9408 * PERF_GLOBAL MSR.
9409 */
9410 if (pVmcsInfo->u32EntryCtls & VMX_ENTRY_CTLS_LOAD_PERF_MSR)
9411 {
9412 rc = VMXReadVmcs64(VMX_VMCS64_GUEST_PERF_GLOBAL_CTRL_FULL, &u64Val);
9413 AssertRC(rc);
9414 HMVMX_CHECK_BREAK(!(u64Val & UINT64_C(0xfffffff8fffffffc)),
9415 VMX_IGS_PERF_GLOBAL_MSR_RESERVED); /* Bits 63:35, bits 31:2 MBZ. */
9416 }
9417
9418 /*
9419 * PAT MSR.
9420 */
9421 if (pVmcsInfo->u32EntryCtls & VMX_ENTRY_CTLS_LOAD_PAT_MSR)
9422 {
9423 rc = VMXReadVmcs64(VMX_VMCS64_GUEST_PAT_FULL, &u64Val);
9424 AssertRC(rc);
9425 HMVMX_CHECK_BREAK(!(u64Val & UINT64_C(0x707070707070707)), VMX_IGS_PAT_MSR_RESERVED);
9426 for (unsigned i = 0; i < 8; i++)
9427 {
9428 uint8_t u8Val = (u64Val & 0xff);
9429 if ( u8Val != 0 /* UC */
9430 && u8Val != 1 /* WC */
9431 && u8Val != 4 /* WT */
9432 && u8Val != 5 /* WP */
9433 && u8Val != 6 /* WB */
9434 && u8Val != 7 /* UC- */)
9435 HMVMX_ERROR_BREAK(VMX_IGS_PAT_MSR_INVALID);
9436 u64Val >>= 8;
9437 }
9438 }
9439
9440 /*
9441 * EFER MSR.
9442 */
9443 if (pVmcsInfo->u32EntryCtls & VMX_ENTRY_CTLS_LOAD_EFER_MSR)
9444 {
9445 Assert(pVM->hm.s.vmx.fSupportsVmcsEfer);
9446 rc = VMXReadVmcs64(VMX_VMCS64_GUEST_EFER_FULL, &u64Val);
9447 AssertRC(rc);
9448 HMVMX_CHECK_BREAK(!(u64Val & UINT64_C(0xfffffffffffff2fe)),
9449 VMX_IGS_EFER_MSR_RESERVED); /* Bits 63:12, bit 9, bits 7:1 MBZ. */
9450 HMVMX_CHECK_BREAK(RT_BOOL(u64Val & MSR_K6_EFER_LMA) == RT_BOOL( pVmcsInfo->u32EntryCtls
9451 & VMX_ENTRY_CTLS_IA32E_MODE_GUEST),
9452 VMX_IGS_EFER_LMA_GUEST_MODE_MISMATCH);
9453 /** @todo r=ramshankar: Unrestricted check here is probably wrong, see
9454 * iemVmxVmentryCheckGuestState(). */
9455 HMVMX_CHECK_BREAK( fUnrestrictedGuest
9456 || !(u64GuestCr0 & X86_CR0_PG)
9457 || RT_BOOL(u64Val & MSR_K6_EFER_LMA) == RT_BOOL(u64Val & MSR_K6_EFER_LME),
9458 VMX_IGS_EFER_LMA_LME_MISMATCH);
9459 }
9460
9461 /*
9462 * Segment registers.
9463 */
9464 HMVMX_CHECK_BREAK( (pCtx->ldtr.Attr.u & X86DESCATTR_UNUSABLE)
9465 || !(pCtx->ldtr.Sel & X86_SEL_LDT), VMX_IGS_LDTR_TI_INVALID);
9466 if (!(u32Eflags & X86_EFL_VM))
9467 {
9468 /* CS */
9469 HMVMX_CHECK_BREAK(pCtx->cs.Attr.n.u1Present, VMX_IGS_CS_ATTR_P_INVALID);
9470 HMVMX_CHECK_BREAK(!(pCtx->cs.Attr.u & 0xf00), VMX_IGS_CS_ATTR_RESERVED);
9471 HMVMX_CHECK_BREAK(!(pCtx->cs.Attr.u & 0xfffe0000), VMX_IGS_CS_ATTR_RESERVED);
9472 HMVMX_CHECK_BREAK( (pCtx->cs.u32Limit & 0xfff) == 0xfff
9473 || !(pCtx->cs.Attr.n.u1Granularity), VMX_IGS_CS_ATTR_G_INVALID);
9474 HMVMX_CHECK_BREAK( !(pCtx->cs.u32Limit & 0xfff00000)
9475 || (pCtx->cs.Attr.n.u1Granularity), VMX_IGS_CS_ATTR_G_INVALID);
9476 /* CS cannot be loaded with NULL in protected mode. */
9477 HMVMX_CHECK_BREAK(pCtx->cs.Attr.u && !(pCtx->cs.Attr.u & X86DESCATTR_UNUSABLE), VMX_IGS_CS_ATTR_UNUSABLE);
9478 HMVMX_CHECK_BREAK(pCtx->cs.Attr.n.u1DescType, VMX_IGS_CS_ATTR_S_INVALID);
9479 if (pCtx->cs.Attr.n.u4Type == 9 || pCtx->cs.Attr.n.u4Type == 11)
9480 HMVMX_CHECK_BREAK(pCtx->cs.Attr.n.u2Dpl == pCtx->ss.Attr.n.u2Dpl, VMX_IGS_CS_SS_ATTR_DPL_UNEQUAL);
9481 else if (pCtx->cs.Attr.n.u4Type == 13 || pCtx->cs.Attr.n.u4Type == 15)
9482 HMVMX_CHECK_BREAK(pCtx->cs.Attr.n.u2Dpl <= pCtx->ss.Attr.n.u2Dpl, VMX_IGS_CS_SS_ATTR_DPL_MISMATCH);
9483 else if (pVM->hm.s.vmx.fUnrestrictedGuest && pCtx->cs.Attr.n.u4Type == 3)
9484 HMVMX_CHECK_BREAK(pCtx->cs.Attr.n.u2Dpl == 0, VMX_IGS_CS_ATTR_DPL_INVALID);
9485 else
9486 HMVMX_ERROR_BREAK(VMX_IGS_CS_ATTR_TYPE_INVALID);
9487
9488 /* SS */
9489 HMVMX_CHECK_BREAK( pVM->hm.s.vmx.fUnrestrictedGuest
9490 || (pCtx->ss.Sel & X86_SEL_RPL) == (pCtx->cs.Sel & X86_SEL_RPL), VMX_IGS_SS_CS_RPL_UNEQUAL);
9491 HMVMX_CHECK_BREAK(pCtx->ss.Attr.n.u2Dpl == (pCtx->ss.Sel & X86_SEL_RPL), VMX_IGS_SS_ATTR_DPL_RPL_UNEQUAL);
9492 if ( !(pCtx->cr0 & X86_CR0_PE)
9493 || pCtx->cs.Attr.n.u4Type == 3)
9494 HMVMX_CHECK_BREAK(!pCtx->ss.Attr.n.u2Dpl, VMX_IGS_SS_ATTR_DPL_INVALID);
9495
9496 if (!(pCtx->ss.Attr.u & X86DESCATTR_UNUSABLE))
9497 {
9498 HMVMX_CHECK_BREAK(pCtx->ss.Attr.n.u4Type == 3 || pCtx->ss.Attr.n.u4Type == 7, VMX_IGS_SS_ATTR_TYPE_INVALID);
9499 HMVMX_CHECK_BREAK(pCtx->ss.Attr.n.u1Present, VMX_IGS_SS_ATTR_P_INVALID);
9500 HMVMX_CHECK_BREAK(!(pCtx->ss.Attr.u & 0xf00), VMX_IGS_SS_ATTR_RESERVED);
9501 HMVMX_CHECK_BREAK(!(pCtx->ss.Attr.u & 0xfffe0000), VMX_IGS_SS_ATTR_RESERVED);
9502 HMVMX_CHECK_BREAK( (pCtx->ss.u32Limit & 0xfff) == 0xfff
9503 || !(pCtx->ss.Attr.n.u1Granularity), VMX_IGS_SS_ATTR_G_INVALID);
9504 HMVMX_CHECK_BREAK( !(pCtx->ss.u32Limit & 0xfff00000)
9505 || (pCtx->ss.Attr.n.u1Granularity), VMX_IGS_SS_ATTR_G_INVALID);
9506 }
9507
9508 /* DS, ES, FS, GS - only check for usable selectors, see hmR0VmxExportGuestSReg(). */
9509 if (!(pCtx->ds.Attr.u & X86DESCATTR_UNUSABLE))
9510 {
9511 HMVMX_CHECK_BREAK(pCtx->ds.Attr.n.u4Type & X86_SEL_TYPE_ACCESSED, VMX_IGS_DS_ATTR_A_INVALID);
9512 HMVMX_CHECK_BREAK(pCtx->ds.Attr.n.u1Present, VMX_IGS_DS_ATTR_P_INVALID);
9513 HMVMX_CHECK_BREAK( pVM->hm.s.vmx.fUnrestrictedGuest
9514 || pCtx->ds.Attr.n.u4Type > 11
9515 || pCtx->ds.Attr.n.u2Dpl >= (pCtx->ds.Sel & X86_SEL_RPL), VMX_IGS_DS_ATTR_DPL_RPL_UNEQUAL);
9516 HMVMX_CHECK_BREAK(!(pCtx->ds.Attr.u & 0xf00), VMX_IGS_DS_ATTR_RESERVED);
9517 HMVMX_CHECK_BREAK(!(pCtx->ds.Attr.u & 0xfffe0000), VMX_IGS_DS_ATTR_RESERVED);
9518 HMVMX_CHECK_BREAK( (pCtx->ds.u32Limit & 0xfff) == 0xfff
9519 || !(pCtx->ds.Attr.n.u1Granularity), VMX_IGS_DS_ATTR_G_INVALID);
9520 HMVMX_CHECK_BREAK( !(pCtx->ds.u32Limit & 0xfff00000)
9521 || (pCtx->ds.Attr.n.u1Granularity), VMX_IGS_DS_ATTR_G_INVALID);
9522 HMVMX_CHECK_BREAK( !(pCtx->ds.Attr.n.u4Type & X86_SEL_TYPE_CODE)
9523 || (pCtx->ds.Attr.n.u4Type & X86_SEL_TYPE_READ), VMX_IGS_DS_ATTR_TYPE_INVALID);
9524 }
9525 if (!(pCtx->es.Attr.u & X86DESCATTR_UNUSABLE))
9526 {
9527 HMVMX_CHECK_BREAK(pCtx->es.Attr.n.u4Type & X86_SEL_TYPE_ACCESSED, VMX_IGS_ES_ATTR_A_INVALID);
9528 HMVMX_CHECK_BREAK(pCtx->es.Attr.n.u1Present, VMX_IGS_ES_ATTR_P_INVALID);
9529 HMVMX_CHECK_BREAK( pVM->hm.s.vmx.fUnrestrictedGuest
9530 || pCtx->es.Attr.n.u4Type > 11
9531 || pCtx->es.Attr.n.u2Dpl >= (pCtx->es.Sel & X86_SEL_RPL), VMX_IGS_DS_ATTR_DPL_RPL_UNEQUAL);
9532 HMVMX_CHECK_BREAK(!(pCtx->es.Attr.u & 0xf00), VMX_IGS_ES_ATTR_RESERVED);
9533 HMVMX_CHECK_BREAK(!(pCtx->es.Attr.u & 0xfffe0000), VMX_IGS_ES_ATTR_RESERVED);
9534 HMVMX_CHECK_BREAK( (pCtx->es.u32Limit & 0xfff) == 0xfff
9535 || !(pCtx->es.Attr.n.u1Granularity), VMX_IGS_ES_ATTR_G_INVALID);
9536 HMVMX_CHECK_BREAK( !(pCtx->es.u32Limit & 0xfff00000)
9537 || (pCtx->es.Attr.n.u1Granularity), VMX_IGS_ES_ATTR_G_INVALID);
9538 HMVMX_CHECK_BREAK( !(pCtx->es.Attr.n.u4Type & X86_SEL_TYPE_CODE)
9539 || (pCtx->es.Attr.n.u4Type & X86_SEL_TYPE_READ), VMX_IGS_ES_ATTR_TYPE_INVALID);
9540 }
9541 if (!(pCtx->fs.Attr.u & X86DESCATTR_UNUSABLE))
9542 {
9543 HMVMX_CHECK_BREAK(pCtx->fs.Attr.n.u4Type & X86_SEL_TYPE_ACCESSED, VMX_IGS_FS_ATTR_A_INVALID);
9544 HMVMX_CHECK_BREAK(pCtx->fs.Attr.n.u1Present, VMX_IGS_FS_ATTR_P_INVALID);
9545 HMVMX_CHECK_BREAK( pVM->hm.s.vmx.fUnrestrictedGuest
9546 || pCtx->fs.Attr.n.u4Type > 11
9547 || pCtx->fs.Attr.n.u2Dpl >= (pCtx->fs.Sel & X86_SEL_RPL), VMX_IGS_FS_ATTR_DPL_RPL_UNEQUAL);
9548 HMVMX_CHECK_BREAK(!(pCtx->fs.Attr.u & 0xf00), VMX_IGS_FS_ATTR_RESERVED);
9549 HMVMX_CHECK_BREAK(!(pCtx->fs.Attr.u & 0xfffe0000), VMX_IGS_FS_ATTR_RESERVED);
9550 HMVMX_CHECK_BREAK( (pCtx->fs.u32Limit & 0xfff) == 0xfff
9551 || !(pCtx->fs.Attr.n.u1Granularity), VMX_IGS_FS_ATTR_G_INVALID);
9552 HMVMX_CHECK_BREAK( !(pCtx->fs.u32Limit & 0xfff00000)
9553 || (pCtx->fs.Attr.n.u1Granularity), VMX_IGS_FS_ATTR_G_INVALID);
9554 HMVMX_CHECK_BREAK( !(pCtx->fs.Attr.n.u4Type & X86_SEL_TYPE_CODE)
9555 || (pCtx->fs.Attr.n.u4Type & X86_SEL_TYPE_READ), VMX_IGS_FS_ATTR_TYPE_INVALID);
9556 }
9557 if (!(pCtx->gs.Attr.u & X86DESCATTR_UNUSABLE))
9558 {
9559 HMVMX_CHECK_BREAK(pCtx->gs.Attr.n.u4Type & X86_SEL_TYPE_ACCESSED, VMX_IGS_GS_ATTR_A_INVALID);
9560 HMVMX_CHECK_BREAK(pCtx->gs.Attr.n.u1Present, VMX_IGS_GS_ATTR_P_INVALID);
9561 HMVMX_CHECK_BREAK( pVM->hm.s.vmx.fUnrestrictedGuest
9562 || pCtx->gs.Attr.n.u4Type > 11
9563 || pCtx->gs.Attr.n.u2Dpl >= (pCtx->gs.Sel & X86_SEL_RPL), VMX_IGS_GS_ATTR_DPL_RPL_UNEQUAL);
9564 HMVMX_CHECK_BREAK(!(pCtx->gs.Attr.u & 0xf00), VMX_IGS_GS_ATTR_RESERVED);
9565 HMVMX_CHECK_BREAK(!(pCtx->gs.Attr.u & 0xfffe0000), VMX_IGS_GS_ATTR_RESERVED);
9566 HMVMX_CHECK_BREAK( (pCtx->gs.u32Limit & 0xfff) == 0xfff
9567 || !(pCtx->gs.Attr.n.u1Granularity), VMX_IGS_GS_ATTR_G_INVALID);
9568 HMVMX_CHECK_BREAK( !(pCtx->gs.u32Limit & 0xfff00000)
9569 || (pCtx->gs.Attr.n.u1Granularity), VMX_IGS_GS_ATTR_G_INVALID);
9570 HMVMX_CHECK_BREAK( !(pCtx->gs.Attr.n.u4Type & X86_SEL_TYPE_CODE)
9571 || (pCtx->gs.Attr.n.u4Type & X86_SEL_TYPE_READ), VMX_IGS_GS_ATTR_TYPE_INVALID);
9572 }
9573 /* 64-bit capable CPUs. */
9574 HMVMX_CHECK_BREAK(X86_IS_CANONICAL(pCtx->fs.u64Base), VMX_IGS_FS_BASE_NOT_CANONICAL);
9575 HMVMX_CHECK_BREAK(X86_IS_CANONICAL(pCtx->gs.u64Base), VMX_IGS_GS_BASE_NOT_CANONICAL);
9576 HMVMX_CHECK_BREAK( (pCtx->ldtr.Attr.u & X86DESCATTR_UNUSABLE)
9577 || X86_IS_CANONICAL(pCtx->ldtr.u64Base), VMX_IGS_LDTR_BASE_NOT_CANONICAL);
9578 HMVMX_CHECK_BREAK(!RT_HI_U32(pCtx->cs.u64Base), VMX_IGS_LONGMODE_CS_BASE_INVALID);
9579 HMVMX_CHECK_BREAK((pCtx->ss.Attr.u & X86DESCATTR_UNUSABLE) || !RT_HI_U32(pCtx->ss.u64Base),
9580 VMX_IGS_LONGMODE_SS_BASE_INVALID);
9581 HMVMX_CHECK_BREAK((pCtx->ds.Attr.u & X86DESCATTR_UNUSABLE) || !RT_HI_U32(pCtx->ds.u64Base),
9582 VMX_IGS_LONGMODE_DS_BASE_INVALID);
9583 HMVMX_CHECK_BREAK((pCtx->es.Attr.u & X86DESCATTR_UNUSABLE) || !RT_HI_U32(pCtx->es.u64Base),
9584 VMX_IGS_LONGMODE_ES_BASE_INVALID);
9585 }
9586 else
9587 {
9588 /* V86 mode checks. */
9589 uint32_t u32CSAttr, u32SSAttr, u32DSAttr, u32ESAttr, u32FSAttr, u32GSAttr;
9590 if (pVmcsInfo->RealMode.fRealOnV86Active)
9591 {
9592 u32CSAttr = 0xf3; u32SSAttr = 0xf3;
9593 u32DSAttr = 0xf3; u32ESAttr = 0xf3;
9594 u32FSAttr = 0xf3; u32GSAttr = 0xf3;
9595 }
9596 else
9597 {
9598 u32CSAttr = pCtx->cs.Attr.u; u32SSAttr = pCtx->ss.Attr.u;
9599 u32DSAttr = pCtx->ds.Attr.u; u32ESAttr = pCtx->es.Attr.u;
9600 u32FSAttr = pCtx->fs.Attr.u; u32GSAttr = pCtx->gs.Attr.u;
9601 }
9602
9603 /* CS */
9604 HMVMX_CHECK_BREAK((pCtx->cs.u64Base == (uint64_t)pCtx->cs.Sel << 4), VMX_IGS_V86_CS_BASE_INVALID);
9605 HMVMX_CHECK_BREAK(pCtx->cs.u32Limit == 0xffff, VMX_IGS_V86_CS_LIMIT_INVALID);
9606 HMVMX_CHECK_BREAK(u32CSAttr == 0xf3, VMX_IGS_V86_CS_ATTR_INVALID);
9607 /* SS */
9608 HMVMX_CHECK_BREAK((pCtx->ss.u64Base == (uint64_t)pCtx->ss.Sel << 4), VMX_IGS_V86_SS_BASE_INVALID);
9609 HMVMX_CHECK_BREAK(pCtx->ss.u32Limit == 0xffff, VMX_IGS_V86_SS_LIMIT_INVALID);
9610 HMVMX_CHECK_BREAK(u32SSAttr == 0xf3, VMX_IGS_V86_SS_ATTR_INVALID);
9611 /* DS */
9612 HMVMX_CHECK_BREAK((pCtx->ds.u64Base == (uint64_t)pCtx->ds.Sel << 4), VMX_IGS_V86_DS_BASE_INVALID);
9613 HMVMX_CHECK_BREAK(pCtx->ds.u32Limit == 0xffff, VMX_IGS_V86_DS_LIMIT_INVALID);
9614 HMVMX_CHECK_BREAK(u32DSAttr == 0xf3, VMX_IGS_V86_DS_ATTR_INVALID);
9615 /* ES */
9616 HMVMX_CHECK_BREAK((pCtx->es.u64Base == (uint64_t)pCtx->es.Sel << 4), VMX_IGS_V86_ES_BASE_INVALID);
9617 HMVMX_CHECK_BREAK(pCtx->es.u32Limit == 0xffff, VMX_IGS_V86_ES_LIMIT_INVALID);
9618 HMVMX_CHECK_BREAK(u32ESAttr == 0xf3, VMX_IGS_V86_ES_ATTR_INVALID);
9619 /* FS */
9620 HMVMX_CHECK_BREAK((pCtx->fs.u64Base == (uint64_t)pCtx->fs.Sel << 4), VMX_IGS_V86_FS_BASE_INVALID);
9621 HMVMX_CHECK_BREAK(pCtx->fs.u32Limit == 0xffff, VMX_IGS_V86_FS_LIMIT_INVALID);
9622 HMVMX_CHECK_BREAK(u32FSAttr == 0xf3, VMX_IGS_V86_FS_ATTR_INVALID);
9623 /* GS */
9624 HMVMX_CHECK_BREAK((pCtx->gs.u64Base == (uint64_t)pCtx->gs.Sel << 4), VMX_IGS_V86_GS_BASE_INVALID);
9625 HMVMX_CHECK_BREAK(pCtx->gs.u32Limit == 0xffff, VMX_IGS_V86_GS_LIMIT_INVALID);
9626 HMVMX_CHECK_BREAK(u32GSAttr == 0xf3, VMX_IGS_V86_GS_ATTR_INVALID);
9627 /* 64-bit capable CPUs. */
9628 HMVMX_CHECK_BREAK(X86_IS_CANONICAL(pCtx->fs.u64Base), VMX_IGS_FS_BASE_NOT_CANONICAL);
9629 HMVMX_CHECK_BREAK(X86_IS_CANONICAL(pCtx->gs.u64Base), VMX_IGS_GS_BASE_NOT_CANONICAL);
9630 HMVMX_CHECK_BREAK( (pCtx->ldtr.Attr.u & X86DESCATTR_UNUSABLE)
9631 || X86_IS_CANONICAL(pCtx->ldtr.u64Base), VMX_IGS_LDTR_BASE_NOT_CANONICAL);
9632 HMVMX_CHECK_BREAK(!RT_HI_U32(pCtx->cs.u64Base), VMX_IGS_LONGMODE_CS_BASE_INVALID);
9633 HMVMX_CHECK_BREAK((pCtx->ss.Attr.u & X86DESCATTR_UNUSABLE) || !RT_HI_U32(pCtx->ss.u64Base),
9634 VMX_IGS_LONGMODE_SS_BASE_INVALID);
9635 HMVMX_CHECK_BREAK((pCtx->ds.Attr.u & X86DESCATTR_UNUSABLE) || !RT_HI_U32(pCtx->ds.u64Base),
9636 VMX_IGS_LONGMODE_DS_BASE_INVALID);
9637 HMVMX_CHECK_BREAK((pCtx->es.Attr.u & X86DESCATTR_UNUSABLE) || !RT_HI_U32(pCtx->es.u64Base),
9638 VMX_IGS_LONGMODE_ES_BASE_INVALID);
9639 }
9640
9641 /*
9642 * TR.
9643 */
9644 HMVMX_CHECK_BREAK(!(pCtx->tr.Sel & X86_SEL_LDT), VMX_IGS_TR_TI_INVALID);
9645 /* 64-bit capable CPUs. */
9646 HMVMX_CHECK_BREAK(X86_IS_CANONICAL(pCtx->tr.u64Base), VMX_IGS_TR_BASE_NOT_CANONICAL);
9647 if (fLongModeGuest)
9648 HMVMX_CHECK_BREAK(pCtx->tr.Attr.n.u4Type == 11, /* 64-bit busy TSS. */
9649 VMX_IGS_LONGMODE_TR_ATTR_TYPE_INVALID);
9650 else
9651 HMVMX_CHECK_BREAK( pCtx->tr.Attr.n.u4Type == 3 /* 16-bit busy TSS. */
9652 || pCtx->tr.Attr.n.u4Type == 11, /* 32-bit busy TSS.*/
9653 VMX_IGS_TR_ATTR_TYPE_INVALID);
9654 HMVMX_CHECK_BREAK(!pCtx->tr.Attr.n.u1DescType, VMX_IGS_TR_ATTR_S_INVALID);
9655 HMVMX_CHECK_BREAK(pCtx->tr.Attr.n.u1Present, VMX_IGS_TR_ATTR_P_INVALID);
9656 HMVMX_CHECK_BREAK(!(pCtx->tr.Attr.u & 0xf00), VMX_IGS_TR_ATTR_RESERVED); /* Bits 11:8 MBZ. */
9657 HMVMX_CHECK_BREAK( (pCtx->tr.u32Limit & 0xfff) == 0xfff
9658 || !(pCtx->tr.Attr.n.u1Granularity), VMX_IGS_TR_ATTR_G_INVALID);
9659 HMVMX_CHECK_BREAK( !(pCtx->tr.u32Limit & 0xfff00000)
9660 || (pCtx->tr.Attr.n.u1Granularity), VMX_IGS_TR_ATTR_G_INVALID);
9661 HMVMX_CHECK_BREAK(!(pCtx->tr.Attr.u & X86DESCATTR_UNUSABLE), VMX_IGS_TR_ATTR_UNUSABLE);
9662
9663 /*
9664 * GDTR and IDTR (64-bit capable checks).
9665 */
9666 rc = VMXReadVmcsNw(VMX_VMCS_GUEST_GDTR_BASE, &u64Val);
9667 AssertRC(rc);
9668 HMVMX_CHECK_BREAK(X86_IS_CANONICAL(u64Val), VMX_IGS_GDTR_BASE_NOT_CANONICAL);
9669
9670 rc = VMXReadVmcsNw(VMX_VMCS_GUEST_IDTR_BASE, &u64Val);
9671 AssertRC(rc);
9672 HMVMX_CHECK_BREAK(X86_IS_CANONICAL(u64Val), VMX_IGS_IDTR_BASE_NOT_CANONICAL);
9673
9674 rc = VMXReadVmcs32(VMX_VMCS32_GUEST_GDTR_LIMIT, &u32Val);
9675 AssertRC(rc);
9676 HMVMX_CHECK_BREAK(!(u32Val & 0xffff0000), VMX_IGS_GDTR_LIMIT_INVALID); /* Bits 31:16 MBZ. */
9677
9678 rc = VMXReadVmcs32(VMX_VMCS32_GUEST_IDTR_LIMIT, &u32Val);
9679 AssertRC(rc);
9680 HMVMX_CHECK_BREAK(!(u32Val & 0xffff0000), VMX_IGS_IDTR_LIMIT_INVALID); /* Bits 31:16 MBZ. */
9681
9682 /*
9683 * Guest Non-Register State.
9684 */
9685 /* Activity State. */
9686 uint32_t u32ActivityState;
9687 rc = VMXReadVmcs32(VMX_VMCS32_GUEST_ACTIVITY_STATE, &u32ActivityState);
9688 AssertRC(rc);
9689 HMVMX_CHECK_BREAK( !u32ActivityState
9690 || (u32ActivityState & RT_BF_GET(pVM->hm.s.vmx.Msrs.u64Misc, VMX_BF_MISC_ACTIVITY_STATES)),
9691 VMX_IGS_ACTIVITY_STATE_INVALID);
9692 HMVMX_CHECK_BREAK( !(pCtx->ss.Attr.n.u2Dpl)
9693 || u32ActivityState != VMX_VMCS_GUEST_ACTIVITY_HLT, VMX_IGS_ACTIVITY_STATE_HLT_INVALID);
9694
9695 if ( u32IntrState == VMX_VMCS_GUEST_INT_STATE_BLOCK_MOVSS
9696 || u32IntrState == VMX_VMCS_GUEST_INT_STATE_BLOCK_STI)
9697 HMVMX_CHECK_BREAK(u32ActivityState == VMX_VMCS_GUEST_ACTIVITY_ACTIVE, VMX_IGS_ACTIVITY_STATE_ACTIVE_INVALID);
9698
9699 /** @todo Activity state and injecting interrupts. Left as a todo since we
9700 * currently don't use activity states but ACTIVE. */
9701
9702 HMVMX_CHECK_BREAK( !(pVmcsInfo->u32EntryCtls & VMX_ENTRY_CTLS_ENTRY_TO_SMM)
9703 || u32ActivityState != VMX_VMCS_GUEST_ACTIVITY_SIPI_WAIT, VMX_IGS_ACTIVITY_STATE_SIPI_WAIT_INVALID);
9704
9705 /* Guest interruptibility-state. */
9706 HMVMX_CHECK_BREAK(!(u32IntrState & 0xffffffe0), VMX_IGS_INTERRUPTIBILITY_STATE_RESERVED);
9707 HMVMX_CHECK_BREAK((u32IntrState & (VMX_VMCS_GUEST_INT_STATE_BLOCK_STI | VMX_VMCS_GUEST_INT_STATE_BLOCK_MOVSS))
9708 != (VMX_VMCS_GUEST_INT_STATE_BLOCK_STI | VMX_VMCS_GUEST_INT_STATE_BLOCK_MOVSS),
9709 VMX_IGS_INTERRUPTIBILITY_STATE_STI_MOVSS_INVALID);
9710 HMVMX_CHECK_BREAK( (u32Eflags & X86_EFL_IF)
9711 || !(u32IntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_STI),
9712 VMX_IGS_INTERRUPTIBILITY_STATE_STI_EFL_INVALID);
9713 if (VMX_ENTRY_INT_INFO_IS_EXT_INT(u32EntryInfo))
9714 {
9715 HMVMX_CHECK_BREAK( !(u32IntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_STI)
9716 && !(u32IntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_MOVSS),
9717 VMX_IGS_INTERRUPTIBILITY_STATE_EXT_INT_INVALID);
9718 }
9719 else if (VMX_ENTRY_INT_INFO_IS_XCPT_NMI(u32EntryInfo))
9720 {
9721 HMVMX_CHECK_BREAK(!(u32IntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_MOVSS),
9722 VMX_IGS_INTERRUPTIBILITY_STATE_MOVSS_INVALID);
9723 HMVMX_CHECK_BREAK(!(u32IntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_STI),
9724 VMX_IGS_INTERRUPTIBILITY_STATE_STI_INVALID);
9725 }
9726 /** @todo Assumes the processor is not in SMM. */
9727 HMVMX_CHECK_BREAK(!(u32IntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_SMI),
9728 VMX_IGS_INTERRUPTIBILITY_STATE_SMI_INVALID);
9729 HMVMX_CHECK_BREAK( !(pVmcsInfo->u32EntryCtls & VMX_ENTRY_CTLS_ENTRY_TO_SMM)
9730 || (u32IntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_SMI),
9731 VMX_IGS_INTERRUPTIBILITY_STATE_SMI_SMM_INVALID);
9732 if ( (pVmcsInfo->u32PinCtls & VMX_PIN_CTLS_VIRT_NMI)
9733 && VMX_ENTRY_INT_INFO_IS_XCPT_NMI(u32EntryInfo))
9734 HMVMX_CHECK_BREAK(!(u32IntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_NMI), VMX_IGS_INTERRUPTIBILITY_STATE_NMI_INVALID);
9735
9736 /* Pending debug exceptions. */
9737 rc = VMXReadVmcsNw(VMX_VMCS_GUEST_PENDING_DEBUG_XCPTS, &u64Val);
9738 AssertRC(rc);
9739 /* Bits 63:15, Bit 13, Bits 11:4 MBZ. */
9740 HMVMX_CHECK_BREAK(!(u64Val & UINT64_C(0xffffffffffffaff0)), VMX_IGS_LONGMODE_PENDING_DEBUG_RESERVED);
9741 u32Val = u64Val; /* For pending debug exceptions checks below. */
9742
9743 if ( (u32IntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_STI)
9744 || (u32IntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_MOVSS)
9745 || u32ActivityState == VMX_VMCS_GUEST_ACTIVITY_HLT)
9746 {
9747 if ( (u32Eflags & X86_EFL_TF)
9748 && !(u64DebugCtlMsr & RT_BIT_64(1))) /* Bit 1 is IA32_DEBUGCTL.BTF. */
9749 {
9750 /* Bit 14 is PendingDebug.BS. */
9751 HMVMX_CHECK_BREAK(u32Val & RT_BIT(14), VMX_IGS_PENDING_DEBUG_XCPT_BS_NOT_SET);
9752 }
9753 if ( !(u32Eflags & X86_EFL_TF)
9754 || (u64DebugCtlMsr & RT_BIT_64(1))) /* Bit 1 is IA32_DEBUGCTL.BTF. */
9755 {
9756 /* Bit 14 is PendingDebug.BS. */
9757 HMVMX_CHECK_BREAK(!(u32Val & RT_BIT(14)), VMX_IGS_PENDING_DEBUG_XCPT_BS_NOT_CLEAR);
9758 }
9759 }
9760
9761 /* VMCS link pointer. */
9762 rc = VMXReadVmcs64(VMX_VMCS64_GUEST_VMCS_LINK_PTR_FULL, &u64Val);
9763 AssertRC(rc);
9764 if (u64Val != UINT64_C(0xffffffffffffffff))
9765 {
9766 HMVMX_CHECK_BREAK(!(u64Val & 0xfff), VMX_IGS_VMCS_LINK_PTR_RESERVED);
9767 /** @todo Bits beyond the processor's physical-address width MBZ. */
9768 /** @todo SMM checks. */
9769 Assert(pVmcsInfo->HCPhysShadowVmcs == u64Val);
9770 Assert(pVmcsInfo->pvShadowVmcs);
9771 VMXVMCSREVID VmcsRevId;
9772 VmcsRevId.u = *(uint32_t *)pVmcsInfo->pvShadowVmcs;
9773 HMVMX_CHECK_BREAK(VmcsRevId.n.u31RevisionId == RT_BF_GET(pVM->hm.s.vmx.Msrs.u64Basic, VMX_BF_BASIC_VMCS_ID),
9774 VMX_IGS_VMCS_LINK_PTR_SHADOW_VMCS_ID_INVALID);
9775 HMVMX_CHECK_BREAK(VmcsRevId.n.fIsShadowVmcs == (uint32_t)!!(pVmcsInfo->u32ProcCtls2 & VMX_PROC_CTLS2_VMCS_SHADOWING),
9776 VMX_IGS_VMCS_LINK_PTR_NOT_SHADOW);
9777 }
9778
9779 /** @todo Checks on Guest Page-Directory-Pointer-Table Entries when guest is
9780 * not using nested paging? */
9781 if ( pVM->hm.s.fNestedPaging
9782 && !fLongModeGuest
9783 && CPUMIsGuestInPAEModeEx(pCtx))
9784 {
9785 rc = VMXReadVmcs64(VMX_VMCS64_GUEST_PDPTE0_FULL, &u64Val);
9786 AssertRC(rc);
9787 HMVMX_CHECK_BREAK(!(u64Val & X86_PDPE_PAE_MBZ_MASK), VMX_IGS_PAE_PDPTE_RESERVED);
9788
9789 rc = VMXReadVmcs64(VMX_VMCS64_GUEST_PDPTE1_FULL, &u64Val);
9790 AssertRC(rc);
9791 HMVMX_CHECK_BREAK(!(u64Val & X86_PDPE_PAE_MBZ_MASK), VMX_IGS_PAE_PDPTE_RESERVED);
9792
9793 rc = VMXReadVmcs64(VMX_VMCS64_GUEST_PDPTE2_FULL, &u64Val);
9794 AssertRC(rc);
9795 HMVMX_CHECK_BREAK(!(u64Val & X86_PDPE_PAE_MBZ_MASK), VMX_IGS_PAE_PDPTE_RESERVED);
9796
9797 rc = VMXReadVmcs64(VMX_VMCS64_GUEST_PDPTE3_FULL, &u64Val);
9798 AssertRC(rc);
9799 HMVMX_CHECK_BREAK(!(u64Val & X86_PDPE_PAE_MBZ_MASK), VMX_IGS_PAE_PDPTE_RESERVED);
9800 }
9801
9802 /* Shouldn't happen but distinguish it from AssertRCBreak() errors. */
9803 if (uError == VMX_IGS_ERROR)
9804 uError = VMX_IGS_REASON_NOT_FOUND;
9805 } while (0);
9806
9807 pVCpu->hm.s.u32HMError = uError;
9808 pVCpu->hm.s.vmx.LastError.u32GuestIntrState = u32IntrState;
9809 return uError;
9810
9811#undef HMVMX_ERROR_BREAK
9812#undef HMVMX_CHECK_BREAK
9813}
9814
9815
9816/**
9817 * Map the APIC-access page for virtualizing APIC accesses.
9818 *
9819 * This can cause a longjumps to R3 due to the acquisition of the PGM lock. Hence,
9820 * this not done as part of exporting guest state, see @bugref{8721}.
9821 *
9822 * @returns VBox status code.
9823 * @param pVCpu The cross context virtual CPU structure.
9824 */
9825static int hmR0VmxMapHCApicAccessPage(PVMCPUCC pVCpu)
9826{
9827 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
9828 uint64_t const u64MsrApicBase = APICGetBaseMsrNoCheck(pVCpu);
9829
9830 Assert(PDMHasApic(pVM));
9831 Assert(u64MsrApicBase);
9832
9833 RTGCPHYS const GCPhysApicBase = u64MsrApicBase & PAGE_BASE_GC_MASK;
9834 Log4Func(("Mappping HC APIC-access page at %#RGp\n", GCPhysApicBase));
9835
9836 /* Unalias the existing mapping. */
9837 int rc = PGMHandlerPhysicalReset(pVM, GCPhysApicBase);
9838 AssertRCReturn(rc, rc);
9839
9840 /* Map the HC APIC-access page in place of the MMIO page, also updates the shadow page tables if necessary. */
9841 Assert(pVM->hm.s.vmx.HCPhysApicAccess != NIL_RTHCPHYS);
9842 rc = IOMMMIOMapMMIOHCPage(pVM, pVCpu, GCPhysApicBase, pVM->hm.s.vmx.HCPhysApicAccess, X86_PTE_RW | X86_PTE_P);
9843 AssertRCReturn(rc, rc);
9844
9845 /* Update the per-VCPU cache of the APIC base MSR. */
9846 pVCpu->hm.s.vmx.u64GstMsrApicBase = u64MsrApicBase;
9847 return VINF_SUCCESS;
9848}
9849
9850
9851/**
9852 * Worker function passed to RTMpOnSpecific() that is to be called on the target
9853 * CPU.
9854 *
9855 * @param idCpu The ID for the CPU the function is called on.
9856 * @param pvUser1 Null, not used.
9857 * @param pvUser2 Null, not used.
9858 */
9859static DECLCALLBACK(void) hmR0DispatchHostNmi(RTCPUID idCpu, void *pvUser1, void *pvUser2)
9860{
9861 RT_NOREF3(idCpu, pvUser1, pvUser2);
9862 VMXDispatchHostNmi();
9863}
9864
9865
9866/**
9867 * Dispatching an NMI on the host CPU that received it.
9868 *
9869 * @returns VBox status code.
9870 * @param pVCpu The cross context virtual CPU structure.
9871 * @param pVmcsInfo The VMCS info. object corresponding to the VMCS that was
9872 * executing when receiving the host NMI in VMX non-root
9873 * operation.
9874 */
9875static int hmR0VmxExitHostNmi(PVMCPUCC pVCpu, PCVMXVMCSINFO pVmcsInfo)
9876{
9877 RTCPUID const idCpu = pVmcsInfo->idHostCpuExec;
9878 Assert(idCpu != NIL_RTCPUID);
9879
9880 /*
9881 * We don't want to delay dispatching the NMI any more than we have to. However,
9882 * we have already chosen -not- to dispatch NMIs when interrupts were still disabled
9883 * after executing guest or nested-guest code for the following reasons:
9884 *
9885 * - We would need to perform VMREADs with interrupts disabled and is orders of
9886 * magnitude worse when we run as a nested hypervisor without VMCS shadowing
9887 * supported by the host hypervisor.
9888 *
9889 * - It affects the common VM-exit scenario and keeps interrupts disabled for a
9890 * longer period of time just for handling an edge case like host NMIs which do
9891 * not occur nearly as frequently as other VM-exits.
9892 *
9893 * Let's cover the most likely scenario first. Check if we are on the target CPU
9894 * and dispatch the NMI right away. This should be much faster than calling into
9895 * RTMpOnSpecific() machinery.
9896 */
9897 bool fDispatched = false;
9898 RTCCUINTREG const fEFlags = ASMIntDisableFlags();
9899 if (idCpu == RTMpCpuId())
9900 {
9901 VMXDispatchHostNmi();
9902 fDispatched = true;
9903 }
9904 ASMSetFlags(fEFlags);
9905 if (fDispatched)
9906 {
9907 STAM_REL_COUNTER_INC(&pVCpu->hm.s.StatExitHostNmiInGC);
9908 return VINF_SUCCESS;
9909 }
9910
9911 /*
9912 * RTMpOnSpecific() waits until the worker function has run on the target CPU. So
9913 * there should be no race or recursion even if we are unlucky enough to be preempted
9914 * (to the target CPU) without dispatching the host NMI above.
9915 */
9916 STAM_REL_COUNTER_INC(&pVCpu->hm.s.StatExitHostNmiInGCIpi);
9917 return RTMpOnSpecific(idCpu, &hmR0DispatchHostNmi, NULL /* pvUser1 */, NULL /* pvUser2 */);
9918}
9919
9920
9921#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
9922/**
9923 * Merges the guest with the nested-guest MSR bitmap in preparation of executing the
9924 * nested-guest using hardware-assisted VMX.
9925 *
9926 * @param pVCpu The cross context virtual CPU structure.
9927 * @param pVmcsInfoNstGst The nested-guest VMCS info. object.
9928 * @param pVmcsInfoGst The guest VMCS info. object.
9929 */
9930static void hmR0VmxMergeMsrBitmapNested(PCVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfoNstGst, PCVMXVMCSINFO pVmcsInfoGst)
9931{
9932 uint32_t const cbMsrBitmap = X86_PAGE_4K_SIZE;
9933 uint64_t *pu64MsrBitmap = (uint64_t *)pVmcsInfoNstGst->pvMsrBitmap;
9934 Assert(pu64MsrBitmap);
9935
9936 /*
9937 * We merge the guest MSR bitmap with the nested-guest MSR bitmap such that any
9938 * MSR that is intercepted by the guest is also intercepted while executing the
9939 * nested-guest using hardware-assisted VMX.
9940 *
9941 * Note! If the nested-guest is not using an MSR bitmap, ever MSR must cause a
9942 * nested-guest VM-exit even if the outer guest is not intercepting some
9943 * MSRs. We cannot assume the caller has initialized the nested-guest
9944 * MSR bitmap in this case.
9945 *
9946 * The nested hypervisor may also switch whether it uses MSR bitmaps for
9947 * each VM-entry, hence initializing it once per-VM while setting up the
9948 * nested-guest VMCS is not sufficient.
9949 */
9950 PCVMXVVMCS pVmcsNstGst = pVCpu->cpum.GstCtx.hwvirt.vmx.CTX_SUFF(pVmcs);
9951 if (pVmcsNstGst->u32ProcCtls & VMX_PROC_CTLS_USE_MSR_BITMAPS)
9952 {
9953 uint64_t const *pu64MsrBitmapNstGst = (uint64_t const *)pVCpu->cpum.GstCtx.hwvirt.vmx.CTX_SUFF(pvMsrBitmap);
9954 uint64_t const *pu64MsrBitmapGst = (uint64_t const *)pVmcsInfoGst->pvMsrBitmap;
9955 Assert(pu64MsrBitmapNstGst);
9956 Assert(pu64MsrBitmapGst);
9957
9958 uint32_t const cFrags = cbMsrBitmap / sizeof(uint64_t);
9959 for (uint32_t i = 0; i < cFrags; i++)
9960 pu64MsrBitmap[i] = pu64MsrBitmapNstGst[i] | pu64MsrBitmapGst[i];
9961 }
9962 else
9963 ASMMemFill32(pu64MsrBitmap, cbMsrBitmap, UINT32_C(0xffffffff));
9964}
9965
9966
9967/**
9968 * Merges the guest VMCS in to the nested-guest VMCS controls in preparation of
9969 * hardware-assisted VMX execution of the nested-guest.
9970 *
9971 * For a guest, we don't modify these controls once we set up the VMCS and hence
9972 * this function is never called.
9973 *
9974 * For nested-guests since the nested hypervisor provides these controls on every
9975 * nested-guest VM-entry and could potentially change them everytime we need to
9976 * merge them before every nested-guest VM-entry.
9977 *
9978 * @returns VBox status code.
9979 * @param pVCpu The cross context virtual CPU structure.
9980 */
9981static int hmR0VmxMergeVmcsNested(PVMCPUCC pVCpu)
9982{
9983 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
9984 PCVMXVMCSINFO pVmcsInfoGst = &pVCpu->hm.s.vmx.VmcsInfo;
9985 PCVMXVVMCS pVmcsNstGst = pVCpu->cpum.GstCtx.hwvirt.vmx.CTX_SUFF(pVmcs);
9986 Assert(pVmcsNstGst);
9987
9988 /*
9989 * Merge the controls with the requirements of the guest VMCS.
9990 *
9991 * We do not need to validate the nested-guest VMX features specified in the nested-guest
9992 * VMCS with the features supported by the physical CPU as it's already done by the
9993 * VMLAUNCH/VMRESUME instruction emulation.
9994 *
9995 * This is because the VMX features exposed by CPUM (through CPUID/MSRs) to the guest are
9996 * derived from the VMX features supported by the physical CPU.
9997 */
9998
9999 /* Pin-based VM-execution controls. */
10000 uint32_t const u32PinCtls = pVmcsNstGst->u32PinCtls | pVmcsInfoGst->u32PinCtls;
10001
10002 /* Processor-based VM-execution controls. */
10003 uint32_t u32ProcCtls = (pVmcsNstGst->u32ProcCtls & ~VMX_PROC_CTLS_USE_IO_BITMAPS)
10004 | (pVmcsInfoGst->u32ProcCtls & ~( VMX_PROC_CTLS_INT_WINDOW_EXIT
10005 | VMX_PROC_CTLS_NMI_WINDOW_EXIT
10006 | VMX_PROC_CTLS_USE_TPR_SHADOW
10007 | VMX_PROC_CTLS_MONITOR_TRAP_FLAG));
10008
10009 /* Secondary processor-based VM-execution controls. */
10010 uint32_t const u32ProcCtls2 = (pVmcsNstGst->u32ProcCtls2 & ~VMX_PROC_CTLS2_VPID)
10011 | (pVmcsInfoGst->u32ProcCtls2 & ~( VMX_PROC_CTLS2_VIRT_APIC_ACCESS
10012 | VMX_PROC_CTLS2_INVPCID
10013 | VMX_PROC_CTLS2_VMCS_SHADOWING
10014 | VMX_PROC_CTLS2_RDTSCP
10015 | VMX_PROC_CTLS2_XSAVES_XRSTORS
10016 | VMX_PROC_CTLS2_APIC_REG_VIRT
10017 | VMX_PROC_CTLS2_VIRT_INT_DELIVERY
10018 | VMX_PROC_CTLS2_VMFUNC));
10019
10020 /*
10021 * VM-entry controls:
10022 * These controls contains state that depends on the nested-guest state (primarily
10023 * EFER MSR) and is thus not constant between VMLAUNCH/VMRESUME and the nested-guest
10024 * VM-exit. Although the nested hypervisor cannot change it, we need to in order to
10025 * properly continue executing the nested-guest if the EFER MSR changes but does not
10026 * cause a nested-guest VM-exits.
10027 *
10028 * VM-exit controls:
10029 * These controls specify the host state on return. We cannot use the controls from
10030 * the nested hypervisor state as is as it would contain the guest state rather than
10031 * the host state. Since the host state is subject to change (e.g. preemption, trips
10032 * to ring-3, longjmp and rescheduling to a different host CPU) they are not constant
10033 * through VMLAUNCH/VMRESUME and the nested-guest VM-exit.
10034 *
10035 * VM-entry MSR-load:
10036 * The guest MSRs from the VM-entry MSR-load area are already loaded into the guest-CPU
10037 * context by the VMLAUNCH/VMRESUME instruction emulation.
10038 *
10039 * VM-exit MSR-store:
10040 * The VM-exit emulation will take care of populating the MSRs from the guest-CPU context
10041 * back into the VM-exit MSR-store area.
10042 *
10043 * VM-exit MSR-load areas:
10044 * This must contain the real host MSRs with hardware-assisted VMX execution. Hence, we
10045 * can entirely ignore what the nested hypervisor wants to load here.
10046 */
10047
10048 /*
10049 * Exception bitmap.
10050 *
10051 * We could remove #UD from the guest bitmap and merge it with the nested-guest bitmap
10052 * here (and avoid doing anything while exporting nested-guest state), but to keep the
10053 * code more flexible if intercepting exceptions become more dynamic in the future we do
10054 * it as part of exporting the nested-guest state.
10055 */
10056 uint32_t const u32XcptBitmap = pVmcsNstGst->u32XcptBitmap | pVmcsInfoGst->u32XcptBitmap;
10057
10058 /*
10059 * CR0/CR4 guest/host mask.
10060 *
10061 * Modifications by the nested-guest to CR0/CR4 bits owned by the host and the guest must
10062 * cause VM-exits, so we need to merge them here.
10063 */
10064 uint64_t const u64Cr0Mask = pVmcsNstGst->u64Cr0Mask.u | pVmcsInfoGst->u64Cr0Mask;
10065 uint64_t const u64Cr4Mask = pVmcsNstGst->u64Cr4Mask.u | pVmcsInfoGst->u64Cr4Mask;
10066
10067 /*
10068 * Page-fault error-code mask and match.
10069 *
10070 * Although we require unrestricted guest execution (and thereby nested-paging) for
10071 * hardware-assisted VMX execution of nested-guests and thus the outer guest doesn't
10072 * normally intercept #PFs, it might intercept them for debugging purposes.
10073 *
10074 * If the outer guest is not intercepting #PFs, we can use the nested-guest #PF filters.
10075 * If the outer guest is intercepting #PFs, we must intercept all #PFs.
10076 */
10077 uint32_t u32XcptPFMask;
10078 uint32_t u32XcptPFMatch;
10079 if (!(pVmcsInfoGst->u32XcptBitmap & RT_BIT(X86_XCPT_PF)))
10080 {
10081 u32XcptPFMask = pVmcsNstGst->u32XcptPFMask;
10082 u32XcptPFMatch = pVmcsNstGst->u32XcptPFMatch;
10083 }
10084 else
10085 {
10086 u32XcptPFMask = 0;
10087 u32XcptPFMatch = 0;
10088 }
10089
10090 /*
10091 * Pause-Loop exiting.
10092 */
10093 uint32_t const cPleGapTicks = RT_MIN(pVM->hm.s.vmx.cPleGapTicks, pVmcsNstGst->u32PleGap);
10094 uint32_t const cPleWindowTicks = RT_MIN(pVM->hm.s.vmx.cPleWindowTicks, pVmcsNstGst->u32PleWindow);
10095
10096 /*
10097 * Pending debug exceptions.
10098 * Currently just copy whatever the nested-guest provides us.
10099 */
10100 uint64_t const uPendingDbgXcpts = pVmcsNstGst->u64GuestPendingDbgXcpts.u;
10101
10102 /*
10103 * I/O Bitmap.
10104 *
10105 * We do not use the I/O bitmap that may be provided by the nested hypervisor as we always
10106 * intercept all I/O port accesses.
10107 */
10108 Assert(u32ProcCtls & VMX_PROC_CTLS_UNCOND_IO_EXIT);
10109 Assert(!(u32ProcCtls & VMX_PROC_CTLS_USE_IO_BITMAPS));
10110
10111 /*
10112 * VMCS shadowing.
10113 *
10114 * We do not yet expose VMCS shadowing to the guest and thus VMCS shadowing should not be
10115 * enabled while executing the nested-guest.
10116 */
10117 Assert(!(u32ProcCtls2 & VMX_PROC_CTLS2_VMCS_SHADOWING));
10118
10119 /*
10120 * APIC-access page.
10121 */
10122 RTHCPHYS HCPhysApicAccess;
10123 if (u32ProcCtls2 & VMX_PROC_CTLS2_VIRT_APIC_ACCESS)
10124 {
10125 Assert(pVM->hm.s.vmx.Msrs.ProcCtls2.n.allowed1 & VMX_PROC_CTLS2_VIRT_APIC_ACCESS);
10126 RTGCPHYS const GCPhysApicAccess = pVmcsNstGst->u64AddrApicAccess.u;
10127
10128 /** @todo NSTVMX: This is not really correct but currently is required to make
10129 * things work. We need to re-enable the page handler when we fallback to
10130 * IEM execution of the nested-guest! */
10131 PGMHandlerPhysicalPageTempOff(pVM, GCPhysApicAccess, GCPhysApicAccess);
10132
10133 void *pvPage;
10134 PGMPAGEMAPLOCK PgLockApicAccess;
10135 int rc = PGMPhysGCPhys2CCPtr(pVM, GCPhysApicAccess, &pvPage, &PgLockApicAccess);
10136 if (RT_SUCCESS(rc))
10137 {
10138 rc = PGMPhysGCPhys2HCPhys(pVM, GCPhysApicAccess, &HCPhysApicAccess);
10139 AssertMsgRCReturn(rc, ("Failed to get host-physical address for APIC-access page at %#RGp\n", GCPhysApicAccess), rc);
10140
10141 /** @todo Handle proper releasing of page-mapping lock later. */
10142 PGMPhysReleasePageMappingLock(pVCpu->CTX_SUFF(pVM), &PgLockApicAccess);
10143 }
10144 else
10145 return rc;
10146 }
10147 else
10148 HCPhysApicAccess = 0;
10149
10150 /*
10151 * Virtual-APIC page and TPR threshold.
10152 */
10153 PVMXVMCSINFO pVmcsInfoNstGst = &pVCpu->hm.s.vmx.VmcsInfoNstGst;
10154 RTHCPHYS HCPhysVirtApic;
10155 uint32_t u32TprThreshold;
10156 if (u32ProcCtls & VMX_PROC_CTLS_USE_TPR_SHADOW)
10157 {
10158 Assert(pVM->hm.s.vmx.Msrs.ProcCtls.n.allowed1 & VMX_PROC_CTLS_USE_TPR_SHADOW);
10159 RTGCPHYS const GCPhysVirtApic = pVmcsNstGst->u64AddrVirtApic.u;
10160
10161 void *pvPage;
10162 PGMPAGEMAPLOCK PgLockVirtApic;
10163 int rc = PGMPhysGCPhys2CCPtr(pVM, GCPhysVirtApic, &pvPage, &PgLockVirtApic);
10164 if (RT_SUCCESS(rc))
10165 {
10166 rc = PGMPhysGCPhys2HCPhys(pVM, GCPhysVirtApic, &HCPhysVirtApic);
10167 AssertMsgRCReturn(rc, ("Failed to get host-physical address for virtual-APIC page at %#RGp\n", GCPhysVirtApic), rc);
10168
10169 /** @todo Handle proper releasing of page-mapping lock later. */
10170 PGMPhysReleasePageMappingLock(pVCpu->CTX_SUFF(pVM), &PgLockVirtApic);
10171 }
10172 else
10173 return rc;
10174
10175 u32TprThreshold = pVmcsNstGst->u32TprThreshold;
10176 }
10177 else
10178 {
10179 HCPhysVirtApic = 0;
10180 u32TprThreshold = 0;
10181
10182 /*
10183 * We must make sure CR8 reads/write must cause VM-exits when TPR shadowing is not
10184 * used by the nested hypervisor. Preventing MMIO accesses to the physical APIC will
10185 * be taken care of by EPT/shadow paging.
10186 */
10187 if (pVM->hm.s.fAllow64BitGuests)
10188 {
10189 u32ProcCtls |= VMX_PROC_CTLS_CR8_STORE_EXIT
10190 | VMX_PROC_CTLS_CR8_LOAD_EXIT;
10191 }
10192 }
10193
10194 /*
10195 * Validate basic assumptions.
10196 */
10197 Assert(pVM->hm.s.vmx.fAllowUnrestricted);
10198 Assert(pVM->hm.s.vmx.Msrs.ProcCtls.n.allowed1 & VMX_PROC_CTLS_USE_SECONDARY_CTLS);
10199 Assert(hmGetVmxActiveVmcsInfo(pVCpu) == pVmcsInfoNstGst);
10200
10201 /*
10202 * Commit it to the nested-guest VMCS.
10203 */
10204 int rc = VINF_SUCCESS;
10205 if (pVmcsInfoNstGst->u32PinCtls != u32PinCtls)
10206 rc |= VMXWriteVmcs32(VMX_VMCS32_CTRL_PIN_EXEC, u32PinCtls);
10207 if (pVmcsInfoNstGst->u32ProcCtls != u32ProcCtls)
10208 rc |= VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, u32ProcCtls);
10209 if (pVmcsInfoNstGst->u32ProcCtls2 != u32ProcCtls2)
10210 rc |= VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC2, u32ProcCtls2);
10211 if (pVmcsInfoNstGst->u32XcptBitmap != u32XcptBitmap)
10212 rc |= VMXWriteVmcs32(VMX_VMCS32_CTRL_EXCEPTION_BITMAP, u32XcptBitmap);
10213 if (pVmcsInfoNstGst->u64Cr0Mask != u64Cr0Mask)
10214 rc |= VMXWriteVmcsNw(VMX_VMCS_CTRL_CR0_MASK, u64Cr0Mask);
10215 if (pVmcsInfoNstGst->u64Cr4Mask != u64Cr4Mask)
10216 rc |= VMXWriteVmcsNw(VMX_VMCS_CTRL_CR4_MASK, u64Cr4Mask);
10217 if (pVmcsInfoNstGst->u32XcptPFMask != u32XcptPFMask)
10218 rc |= VMXWriteVmcs32(VMX_VMCS32_CTRL_PAGEFAULT_ERROR_MASK, u32XcptPFMask);
10219 if (pVmcsInfoNstGst->u32XcptPFMatch != u32XcptPFMatch)
10220 rc |= VMXWriteVmcs32(VMX_VMCS32_CTRL_PAGEFAULT_ERROR_MATCH, u32XcptPFMatch);
10221 if ( !(u32ProcCtls & VMX_PROC_CTLS_PAUSE_EXIT)
10222 && (u32ProcCtls2 & VMX_PROC_CTLS2_PAUSE_LOOP_EXIT))
10223 {
10224 Assert(pVM->hm.s.vmx.Msrs.ProcCtls2.n.allowed1 & VMX_PROC_CTLS2_PAUSE_LOOP_EXIT);
10225 rc |= VMXWriteVmcs32(VMX_VMCS32_CTRL_PLE_GAP, cPleGapTicks);
10226 rc |= VMXWriteVmcs32(VMX_VMCS32_CTRL_PLE_WINDOW, cPleWindowTicks);
10227 }
10228 if (u32ProcCtls & VMX_PROC_CTLS_USE_TPR_SHADOW)
10229 {
10230 rc |= VMXWriteVmcs32(VMX_VMCS32_CTRL_TPR_THRESHOLD, u32TprThreshold);
10231 rc |= VMXWriteVmcs64(VMX_VMCS64_CTRL_VIRT_APIC_PAGEADDR_FULL, HCPhysVirtApic);
10232 }
10233 if (u32ProcCtls2 & VMX_PROC_CTLS2_VIRT_APIC_ACCESS)
10234 rc |= VMXWriteVmcs64(VMX_VMCS64_CTRL_APIC_ACCESSADDR_FULL, HCPhysApicAccess);
10235 rc |= VMXWriteVmcsNw(VMX_VMCS_GUEST_PENDING_DEBUG_XCPTS, uPendingDbgXcpts);
10236 AssertRC(rc);
10237
10238 /*
10239 * Update the nested-guest VMCS cache.
10240 */
10241 pVmcsInfoNstGst->u32PinCtls = u32PinCtls;
10242 pVmcsInfoNstGst->u32ProcCtls = u32ProcCtls;
10243 pVmcsInfoNstGst->u32ProcCtls2 = u32ProcCtls2;
10244 pVmcsInfoNstGst->u32XcptBitmap = u32XcptBitmap;
10245 pVmcsInfoNstGst->u64Cr0Mask = u64Cr0Mask;
10246 pVmcsInfoNstGst->u64Cr4Mask = u64Cr4Mask;
10247 pVmcsInfoNstGst->u32XcptPFMask = u32XcptPFMask;
10248 pVmcsInfoNstGst->u32XcptPFMatch = u32XcptPFMatch;
10249 pVmcsInfoNstGst->HCPhysVirtApic = HCPhysVirtApic;
10250
10251 /*
10252 * We need to flush the TLB if we are switching the APIC-access page address.
10253 * See Intel spec. 28.3.3.4 "Guidelines for Use of the INVEPT Instruction".
10254 */
10255 if (u32ProcCtls2 & VMX_PROC_CTLS2_VIRT_APIC_ACCESS)
10256 pVCpu->hm.s.vmx.fSwitchedNstGstFlushTlb = true;
10257
10258 /*
10259 * MSR bitmap.
10260 *
10261 * The MSR bitmap address has already been initialized while setting up the nested-guest
10262 * VMCS, here we need to merge the MSR bitmaps.
10263 */
10264 if (u32ProcCtls & VMX_PROC_CTLS_USE_MSR_BITMAPS)
10265 hmR0VmxMergeMsrBitmapNested(pVCpu, pVmcsInfoNstGst, pVmcsInfoGst);
10266
10267 return VINF_SUCCESS;
10268}
10269#endif /* VBOX_WITH_NESTED_HWVIRT_VMX */
10270
10271
10272/**
10273 * Does the preparations before executing guest code in VT-x.
10274 *
10275 * This may cause longjmps to ring-3 and may even result in rescheduling to the
10276 * recompiler/IEM. We must be cautious what we do here regarding committing
10277 * guest-state information into the VMCS assuming we assuredly execute the
10278 * guest in VT-x mode.
10279 *
10280 * If we fall back to the recompiler/IEM after updating the VMCS and clearing
10281 * the common-state (TRPM/forceflags), we must undo those changes so that the
10282 * recompiler/IEM can (and should) use them when it resumes guest execution.
10283 * Otherwise such operations must be done when we can no longer exit to ring-3.
10284 *
10285 * @returns Strict VBox status code (i.e. informational status codes too).
10286 * @retval VINF_SUCCESS if we can proceed with running the guest, interrupts
10287 * have been disabled.
10288 * @retval VINF_VMX_VMEXIT if a nested-guest VM-exit occurs (e.g., while evaluating
10289 * pending events).
10290 * @retval VINF_EM_RESET if a triple-fault occurs while injecting a
10291 * double-fault into the guest.
10292 * @retval VINF_EM_DBG_STEPPED if @a fStepping is true and an event was
10293 * dispatched directly.
10294 * @retval VINF_* scheduling changes, we have to go back to ring-3.
10295 *
10296 * @param pVCpu The cross context virtual CPU structure.
10297 * @param pVmxTransient The VMX-transient structure.
10298 * @param fStepping Whether we are single-stepping the guest in the
10299 * hypervisor debugger. Makes us ignore some of the reasons
10300 * for returning to ring-3, and return VINF_EM_DBG_STEPPED
10301 * if event dispatching took place.
10302 */
10303static VBOXSTRICTRC hmR0VmxPreRunGuest(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient, bool fStepping)
10304{
10305 Assert(VMMRZCallRing3IsEnabled(pVCpu));
10306
10307 Log4Func(("fIsNested=%RTbool fStepping=%RTbool\n", pVmxTransient->fIsNestedGuest, fStepping));
10308
10309#ifdef VBOX_WITH_NESTED_HWVIRT_ONLY_IN_IEM
10310 if (pVmxTransient->fIsNestedGuest)
10311 {
10312 RT_NOREF2(pVCpu, fStepping);
10313 Log2Func(("Rescheduling to IEM due to nested-hwvirt or forced IEM exec -> VINF_EM_RESCHEDULE_REM\n"));
10314 return VINF_EM_RESCHEDULE_REM;
10315 }
10316#endif
10317
10318#ifdef VBOX_WITH_2X_4GB_ADDR_SPACE_IN_R0
10319 PGMRZDynMapFlushAutoSet(pVCpu);
10320#endif
10321
10322 /*
10323 * Check and process force flag actions, some of which might require us to go back to ring-3.
10324 */
10325 VBOXSTRICTRC rcStrict = hmR0VmxCheckForceFlags(pVCpu, pVmxTransient, fStepping);
10326 if (rcStrict == VINF_SUCCESS)
10327 {
10328 /* FFs don't get set all the time. */
10329#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
10330 if ( pVmxTransient->fIsNestedGuest
10331 && !CPUMIsGuestInVmxNonRootMode(&pVCpu->cpum.GstCtx))
10332 {
10333 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchNstGstVmexit);
10334 return VINF_VMX_VMEXIT;
10335 }
10336#endif
10337 }
10338 else
10339 return rcStrict;
10340
10341 /*
10342 * Virtualize memory-mapped accesses to the physical APIC (may take locks).
10343 */
10344 /** @todo Doing this from ring-3 after VM setup phase causes a
10345 * VERR_IOM_MMIO_RANGE_NOT_FOUND guru while booting Visa 64 SMP VM. No
10346 * idea why atm. */
10347 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
10348 if ( !pVCpu->hm.s.vmx.u64GstMsrApicBase
10349 && (pVM->hm.s.vmx.Msrs.ProcCtls2.n.allowed1 & VMX_PROC_CTLS2_VIRT_APIC_ACCESS)
10350 && PDMHasApic(pVM))
10351 {
10352 int rc = hmR0VmxMapHCApicAccessPage(pVCpu);
10353 AssertRCReturn(rc, rc);
10354 }
10355
10356#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
10357 /*
10358 * Merge guest VMCS controls with the nested-guest VMCS controls.
10359 *
10360 * Even if we have not executed the guest prior to this (e.g. when resuming from a
10361 * saved state), we should be okay with merging controls as we initialize the
10362 * guest VMCS controls as part of VM setup phase.
10363 */
10364 if ( pVmxTransient->fIsNestedGuest
10365 && !pVCpu->hm.s.vmx.fMergedNstGstCtls)
10366 {
10367 int rc = hmR0VmxMergeVmcsNested(pVCpu);
10368 AssertRCReturn(rc, rc);
10369 pVCpu->hm.s.vmx.fMergedNstGstCtls = true;
10370 }
10371#endif
10372
10373 /*
10374 * Evaluate events to be injected into the guest.
10375 *
10376 * Events in TRPM can be injected without inspecting the guest state.
10377 * If any new events (interrupts/NMI) are pending currently, we try to set up the
10378 * guest to cause a VM-exit the next time they are ready to receive the event.
10379 *
10380 * With nested-guests, evaluating pending events may cause VM-exits. Also, verify
10381 * that the event in TRPM that we will inject using hardware-assisted VMX is -not-
10382 * subject to interecption. Otherwise, we should have checked and injected them
10383 * manually elsewhere (IEM).
10384 */
10385 if (TRPMHasTrap(pVCpu))
10386 {
10387 Assert(!pVmxTransient->fIsNestedGuest || !CPUMIsGuestVmxInterceptEvents(&pVCpu->cpum.GstCtx));
10388 hmR0VmxTrpmTrapToPendingEvent(pVCpu);
10389 }
10390
10391 uint32_t fIntrState;
10392 rcStrict = hmR0VmxEvaluatePendingEvent(pVCpu, pVmxTransient, &fIntrState);
10393
10394#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
10395 /*
10396 * While evaluating pending events if something failed (unlikely) or if we were
10397 * preparing to run a nested-guest but performed a nested-guest VM-exit, we should bail.
10398 */
10399 if (rcStrict != VINF_SUCCESS)
10400 return rcStrict;
10401 if ( pVmxTransient->fIsNestedGuest
10402 && !CPUMIsGuestInVmxNonRootMode(&pVCpu->cpum.GstCtx))
10403 {
10404 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchNstGstVmexit);
10405 return VINF_VMX_VMEXIT;
10406 }
10407#else
10408 Assert(rcStrict == VINF_SUCCESS);
10409#endif
10410
10411 /*
10412 * Event injection may take locks (currently the PGM lock for real-on-v86 case) and thus
10413 * needs to be done with longjmps or interrupts + preemption enabled. Event injection might
10414 * also result in triple-faulting the VM.
10415 *
10416 * With nested-guests, the above does not apply since unrestricted guest execution is a
10417 * requirement. Regardless, we do this here to avoid duplicating code elsewhere.
10418 */
10419 rcStrict = hmR0VmxInjectPendingEvent(pVCpu, pVmxTransient, fIntrState, fStepping);
10420 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
10421 { /* likely */ }
10422 else
10423 {
10424 AssertMsg(rcStrict == VINF_EM_RESET || (rcStrict == VINF_EM_DBG_STEPPED && fStepping),
10425 ("%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
10426 return rcStrict;
10427 }
10428
10429 /*
10430 * A longjump might result in importing CR3 even for VM-exits that don't necessarily
10431 * import CR3 themselves. We will need to update them here, as even as late as the above
10432 * hmR0VmxInjectPendingEvent() call may lazily import guest-CPU state on demand causing
10433 * the below force flags to be set.
10434 */
10435 if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_HM_UPDATE_CR3))
10436 {
10437 Assert(!(ASMAtomicUoReadU64(&pVCpu->cpum.GstCtx.fExtrn) & CPUMCTX_EXTRN_CR3));
10438 int rc2 = PGMUpdateCR3(pVCpu, CPUMGetGuestCR3(pVCpu));
10439 AssertMsgReturn(rc2 == VINF_SUCCESS || rc2 == VINF_PGM_SYNC_CR3,
10440 ("%Rrc\n", rc2), RT_FAILURE_NP(rc2) ? rc2 : VERR_IPE_UNEXPECTED_INFO_STATUS);
10441 Assert(!VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_HM_UPDATE_CR3));
10442 }
10443 if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_HM_UPDATE_PAE_PDPES))
10444 {
10445 PGMGstUpdatePaePdpes(pVCpu, &pVCpu->hm.s.aPdpes[0]);
10446 Assert(!VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_HM_UPDATE_PAE_PDPES));
10447 }
10448
10449#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
10450 /* Paranoia. */
10451 Assert(!pVmxTransient->fIsNestedGuest || CPUMIsGuestInVmxNonRootMode(&pVCpu->cpum.GstCtx));
10452#endif
10453
10454 /*
10455 * No longjmps to ring-3 from this point on!!!
10456 * Asserts() will still longjmp to ring-3 (but won't return), which is intentional, better than a kernel panic.
10457 * This also disables flushing of the R0-logger instance (if any).
10458 */
10459 VMMRZCallRing3Disable(pVCpu);
10460
10461 /*
10462 * Export the guest state bits.
10463 *
10464 * We cannot perform longjmps while loading the guest state because we do not preserve the
10465 * host/guest state (although the VMCS will be preserved) across longjmps which can cause
10466 * CPU migration.
10467 *
10468 * If we are injecting events to a real-on-v86 mode guest, we would have updated RIP and some segment
10469 * registers. Hence, exporting of the guest state needs to be done -after- injection of events.
10470 */
10471 rcStrict = hmR0VmxExportGuestStateOptimal(pVCpu, pVmxTransient);
10472 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
10473 { /* likely */ }
10474 else
10475 {
10476 VMMRZCallRing3Enable(pVCpu);
10477 return rcStrict;
10478 }
10479
10480 /*
10481 * We disable interrupts so that we don't miss any interrupts that would flag preemption
10482 * (IPI/timers etc.) when thread-context hooks aren't used and we've been running with
10483 * preemption disabled for a while. Since this is purely to aid the
10484 * RTThreadPreemptIsPending() code, it doesn't matter that it may temporarily reenable and
10485 * disable interrupt on NT.
10486 *
10487 * We need to check for force-flags that could've possible been altered since we last
10488 * checked them (e.g. by PDMGetInterrupt() leaving the PDM critical section,
10489 * see @bugref{6398}).
10490 *
10491 * We also check a couple of other force-flags as a last opportunity to get the EMT back
10492 * to ring-3 before executing guest code.
10493 */
10494 pVmxTransient->fEFlags = ASMIntDisableFlags();
10495
10496 if ( ( !VM_FF_IS_ANY_SET(pVM, VM_FF_EMT_RENDEZVOUS | VM_FF_TM_VIRTUAL_SYNC)
10497 && !VMCPU_FF_IS_ANY_SET(pVCpu, VMCPU_FF_HM_TO_R3_MASK))
10498 || ( fStepping /* Optimized for the non-stepping case, so a bit of unnecessary work when stepping. */
10499 && !VMCPU_FF_IS_ANY_SET(pVCpu, VMCPU_FF_HM_TO_R3_MASK & ~(VMCPU_FF_TIMER | VMCPU_FF_PDM_CRITSECT))) )
10500 {
10501 if (!RTThreadPreemptIsPending(NIL_RTTHREAD))
10502 {
10503#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
10504 /*
10505 * If we are executing a nested-guest make sure that we should intercept subsequent
10506 * events. The one we are injecting might be part of VM-entry. This is mainly to keep
10507 * the VM-exit instruction emulation happy.
10508 */
10509 if (pVmxTransient->fIsNestedGuest)
10510 CPUMSetGuestVmxInterceptEvents(&pVCpu->cpum.GstCtx, true);
10511#endif
10512
10513 /*
10514 * We've injected any pending events. This is really the point of no return (to ring-3).
10515 *
10516 * Note! The caller expects to continue with interrupts & longjmps disabled on successful
10517 * returns from this function, so do -not- enable them here.
10518 */
10519 pVCpu->hm.s.Event.fPending = false;
10520 return VINF_SUCCESS;
10521 }
10522
10523 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchPendingHostIrq);
10524 rcStrict = VINF_EM_RAW_INTERRUPT;
10525 }
10526 else
10527 {
10528 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchHmToR3FF);
10529 rcStrict = VINF_EM_RAW_TO_R3;
10530 }
10531
10532 ASMSetFlags(pVmxTransient->fEFlags);
10533 VMMRZCallRing3Enable(pVCpu);
10534
10535 return rcStrict;
10536}
10537
10538
10539/**
10540 * Final preparations before executing guest code using hardware-assisted VMX.
10541 *
10542 * We can no longer get preempted to a different host CPU and there are no returns
10543 * to ring-3. We ignore any errors that may happen from this point (e.g. VMWRITE
10544 * failures), this function is not intended to fail sans unrecoverable hardware
10545 * errors.
10546 *
10547 * @param pVCpu The cross context virtual CPU structure.
10548 * @param pVmxTransient The VMX-transient structure.
10549 *
10550 * @remarks Called with preemption disabled.
10551 * @remarks No-long-jump zone!!!
10552 */
10553static void hmR0VmxPreRunGuestCommitted(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
10554{
10555 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
10556 Assert(VMMR0IsLogFlushDisabled(pVCpu));
10557 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
10558 Assert(!pVCpu->hm.s.Event.fPending);
10559
10560 /*
10561 * Indicate start of guest execution and where poking EMT out of guest-context is recognized.
10562 */
10563 VMCPU_ASSERT_STATE(pVCpu, VMCPUSTATE_STARTED_HM);
10564 VMCPU_SET_STATE(pVCpu, VMCPUSTATE_STARTED_EXEC);
10565
10566 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
10567 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
10568 PHMPHYSCPU pHostCpu = hmR0GetCurrentCpu();
10569 RTCPUID const idCurrentCpu = pHostCpu->idCpu;
10570
10571 if (!CPUMIsGuestFPUStateActive(pVCpu))
10572 {
10573 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatLoadGuestFpuState, x);
10574 if (CPUMR0LoadGuestFPU(pVM, pVCpu) == VINF_CPUM_HOST_CR0_MODIFIED)
10575 pVCpu->hm.s.fCtxChanged |= HM_CHANGED_HOST_CONTEXT;
10576 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatLoadGuestFpuState, x);
10577 STAM_COUNTER_INC(&pVCpu->hm.s.StatLoadGuestFpu);
10578 }
10579
10580 /*
10581 * Re-export the host state bits as we may've been preempted (only happens when
10582 * thread-context hooks are used or when the VM start function changes) or if
10583 * the host CR0 is modified while loading the guest FPU state above.
10584 *
10585 * The 64-on-32 switcher saves the (64-bit) host state into the VMCS and if we
10586 * changed the switcher back to 32-bit, we *must* save the 32-bit host state here,
10587 * see @bugref{8432}.
10588 *
10589 * This may also happen when switching to/from a nested-guest VMCS without leaving
10590 * ring-0.
10591 */
10592 if (pVCpu->hm.s.fCtxChanged & HM_CHANGED_HOST_CONTEXT)
10593 {
10594 hmR0VmxExportHostState(pVCpu);
10595 STAM_COUNTER_INC(&pVCpu->hm.s.StatExportHostState);
10596 }
10597 Assert(!(pVCpu->hm.s.fCtxChanged & HM_CHANGED_HOST_CONTEXT));
10598
10599 /*
10600 * Export the state shared between host and guest (FPU, debug, lazy MSRs).
10601 */
10602 if (pVCpu->hm.s.fCtxChanged & HM_CHANGED_VMX_HOST_GUEST_SHARED_STATE)
10603 hmR0VmxExportSharedState(pVCpu, pVmxTransient);
10604 AssertMsg(!pVCpu->hm.s.fCtxChanged, ("fCtxChanged=%#RX64\n", pVCpu->hm.s.fCtxChanged));
10605
10606 /*
10607 * Store status of the shared guest/host debug state at the time of VM-entry.
10608 */
10609 pVmxTransient->fWasGuestDebugStateActive = CPUMIsGuestDebugStateActive(pVCpu);
10610 pVmxTransient->fWasHyperDebugStateActive = CPUMIsHyperDebugStateActive(pVCpu);
10611
10612 /*
10613 * Always cache the TPR-shadow if the virtual-APIC page exists, thereby skipping
10614 * more than one conditional check. The post-run side of our code shall determine
10615 * if it needs to sync. the virtual APIC TPR with the TPR-shadow.
10616 */
10617 if (pVmcsInfo->pbVirtApic)
10618 pVmxTransient->u8GuestTpr = pVmcsInfo->pbVirtApic[XAPIC_OFF_TPR];
10619
10620 /*
10621 * Update the host MSRs values in the VM-exit MSR-load area.
10622 */
10623 if (!pVCpu->hm.s.vmx.fUpdatedHostAutoMsrs)
10624 {
10625 if (pVmcsInfo->cExitMsrLoad > 0)
10626 hmR0VmxUpdateAutoLoadHostMsrs(pVCpu, pVmcsInfo);
10627 pVCpu->hm.s.vmx.fUpdatedHostAutoMsrs = true;
10628 }
10629
10630 /*
10631 * Evaluate if we need to intercept guest RDTSC/P accesses. Set up the
10632 * VMX-preemption timer based on the next virtual sync clock deadline.
10633 */
10634 if ( !pVmxTransient->fUpdatedTscOffsettingAndPreemptTimer
10635 || idCurrentCpu != pVCpu->hm.s.idLastCpu)
10636 {
10637 hmR0VmxUpdateTscOffsettingAndPreemptTimer(pVCpu, pVmxTransient);
10638 pVmxTransient->fUpdatedTscOffsettingAndPreemptTimer = true;
10639 }
10640
10641 /* Record statistics of how often we use TSC offsetting as opposed to intercepting RDTSC/P. */
10642 bool const fIsRdtscIntercepted = RT_BOOL(pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_RDTSC_EXIT);
10643 if (!fIsRdtscIntercepted)
10644 STAM_COUNTER_INC(&pVCpu->hm.s.StatTscOffset);
10645 else
10646 STAM_COUNTER_INC(&pVCpu->hm.s.StatTscIntercept);
10647
10648 ASMAtomicWriteBool(&pVCpu->hm.s.fCheckedTLBFlush, true); /* Used for TLB flushing, set this across the world switch. */
10649 hmR0VmxFlushTaggedTlb(pHostCpu, pVCpu, pVmcsInfo); /* Invalidate the appropriate guest entries from the TLB. */
10650 Assert(idCurrentCpu == pVCpu->hm.s.idLastCpu);
10651 pVCpu->hm.s.vmx.LastError.idCurrentCpu = idCurrentCpu; /* Record the error reporting info. with the current host CPU. */
10652 pVmcsInfo->idHostCpuState = idCurrentCpu; /* Record the CPU for which the host-state has been exported. */
10653 pVmcsInfo->idHostCpuExec = idCurrentCpu; /* Record the CPU on which we shall execute. */
10654
10655 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatEntry, &pVCpu->hm.s.StatInGC, x);
10656
10657 TMNotifyStartOfExecution(pVM, pVCpu); /* Notify TM to resume its clocks when TSC is tied to execution,
10658 as we're about to start executing the guest. */
10659
10660 /*
10661 * Load the guest TSC_AUX MSR when we are not intercepting RDTSCP.
10662 *
10663 * This is done this late as updating the TSC offsetting/preemption timer above
10664 * figures out if we can skip intercepting RDTSCP by calculating the number of
10665 * host CPU ticks till the next virtual sync deadline (for the dynamic case).
10666 */
10667 if ( (pVmcsInfo->u32ProcCtls2 & VMX_PROC_CTLS2_RDTSCP)
10668 && !fIsRdtscIntercepted)
10669 {
10670 hmR0VmxImportGuestState(pVCpu, pVmcsInfo, CPUMCTX_EXTRN_TSC_AUX);
10671
10672 /* NB: Because we call hmR0VmxAddAutoLoadStoreMsr with fUpdateHostMsr=true,
10673 it's safe even after hmR0VmxUpdateAutoLoadHostMsrs has already been done. */
10674 int rc = hmR0VmxAddAutoLoadStoreMsr(pVCpu, pVmxTransient, MSR_K8_TSC_AUX, CPUMGetGuestTscAux(pVCpu),
10675 true /* fSetReadWrite */, true /* fUpdateHostMsr */);
10676 AssertRC(rc);
10677 Assert(!pVmxTransient->fRemoveTscAuxMsr);
10678 pVmxTransient->fRemoveTscAuxMsr = true;
10679 }
10680
10681#ifdef VBOX_STRICT
10682 Assert(pVCpu->hm.s.vmx.fUpdatedHostAutoMsrs);
10683 hmR0VmxCheckAutoLoadStoreMsrs(pVCpu, pVmcsInfo, pVmxTransient->fIsNestedGuest);
10684 hmR0VmxCheckHostEferMsr(pVCpu, pVmcsInfo);
10685 AssertRC(hmR0VmxCheckCachedVmcsCtls(pVCpu, pVmcsInfo, pVmxTransient->fIsNestedGuest));
10686#endif
10687
10688#ifdef HMVMX_ALWAYS_CHECK_GUEST_STATE
10689 /** @todo r=ramshankar: We can now probably use iemVmxVmentryCheckGuestState here.
10690 * Add a PVMXMSRS parameter to it, so that IEM can look at the host MSRs,
10691 * see @bugref{9180#c54}. */
10692 uint32_t const uInvalidReason = hmR0VmxCheckGuestState(pVCpu, pVmcsInfo);
10693 if (uInvalidReason != VMX_IGS_REASON_NOT_FOUND)
10694 Log4(("hmR0VmxCheckGuestState returned %#x\n", uInvalidReason));
10695#endif
10696}
10697
10698
10699/**
10700 * First C routine invoked after running guest code using hardware-assisted VMX.
10701 *
10702 * @param pVCpu The cross context virtual CPU structure.
10703 * @param pVmxTransient The VMX-transient structure.
10704 * @param rcVMRun Return code of VMLAUNCH/VMRESUME.
10705 *
10706 * @remarks Called with interrupts disabled, and returns with interrupts enabled!
10707 *
10708 * @remarks No-long-jump zone!!! This function will however re-enable longjmps
10709 * unconditionally when it is safe to do so.
10710 */
10711static void hmR0VmxPostRunGuest(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient, int rcVMRun)
10712{
10713 uint64_t const uHostTsc = ASMReadTSC(); /** @todo We can do a lot better here, see @bugref{9180#c38}. */
10714
10715 ASMAtomicWriteBool(&pVCpu->hm.s.fCheckedTLBFlush, false); /* See HMInvalidatePageOnAllVCpus(): used for TLB flushing. */
10716 ASMAtomicIncU32(&pVCpu->hm.s.cWorldSwitchExits); /* Initialized in vmR3CreateUVM(): used for EMT poking. */
10717 pVCpu->hm.s.fCtxChanged = 0; /* Exits/longjmps to ring-3 requires saving the guest state. */
10718 pVmxTransient->fVmcsFieldsRead = 0; /* Transient fields need to be read from the VMCS. */
10719 pVmxTransient->fVectoringPF = false; /* Vectoring page-fault needs to be determined later. */
10720 pVmxTransient->fVectoringDoublePF = false; /* Vectoring double page-fault needs to be determined later. */
10721
10722 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
10723 if (!(pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_RDTSC_EXIT))
10724 {
10725 uint64_t uGstTsc;
10726 if (!pVmxTransient->fIsNestedGuest)
10727 uGstTsc = uHostTsc + pVmcsInfo->u64TscOffset;
10728 else
10729 {
10730 uint64_t const uNstGstTsc = uHostTsc + pVmcsInfo->u64TscOffset;
10731 uGstTsc = CPUMRemoveNestedGuestTscOffset(pVCpu, uNstGstTsc);
10732 }
10733 TMCpuTickSetLastSeen(pVCpu, uGstTsc); /* Update TM with the guest TSC. */
10734 }
10735
10736 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatInGC, &pVCpu->hm.s.StatPreExit, x);
10737 TMNotifyEndOfExecution(pVCpu->CTX_SUFF(pVM), pVCpu); /* Notify TM that the guest is no longer running. */
10738 VMCPU_SET_STATE(pVCpu, VMCPUSTATE_STARTED_HM);
10739
10740 pVCpu->hm.s.vmx.fRestoreHostFlags |= VMX_RESTORE_HOST_REQUIRED; /* Some host state messed up by VMX needs restoring. */
10741 pVmcsInfo->fVmcsState |= VMX_V_VMCS_LAUNCH_STATE_LAUNCHED; /* Use VMRESUME instead of VMLAUNCH in the next run. */
10742#ifdef VBOX_STRICT
10743 hmR0VmxCheckHostEferMsr(pVCpu, pVmcsInfo); /* Verify that the host EFER MSR wasn't modified. */
10744#endif
10745 Assert(!ASMIntAreEnabled());
10746 ASMSetFlags(pVmxTransient->fEFlags); /* Enable interrupts. */
10747 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
10748
10749#ifdef HMVMX_ALWAYS_CLEAN_TRANSIENT
10750 /*
10751 * Clean all the VMCS fields in the transient structure before reading
10752 * anything from the VMCS.
10753 */
10754 pVmxTransient->uExitReason = 0;
10755 pVmxTransient->uExitIntErrorCode = 0;
10756 pVmxTransient->uExitQual = 0;
10757 pVmxTransient->uGuestLinearAddr = 0;
10758 pVmxTransient->uExitIntInfo = 0;
10759 pVmxTransient->cbExitInstr = 0;
10760 pVmxTransient->ExitInstrInfo.u = 0;
10761 pVmxTransient->uEntryIntInfo = 0;
10762 pVmxTransient->uEntryXcptErrorCode = 0;
10763 pVmxTransient->cbEntryInstr = 0;
10764 pVmxTransient->uIdtVectoringInfo = 0;
10765 pVmxTransient->uIdtVectoringErrorCode = 0;
10766#endif
10767
10768 /*
10769 * Save the basic VM-exit reason and check if the VM-entry failed.
10770 * See Intel spec. 24.9.1 "Basic VM-exit Information".
10771 */
10772 uint32_t uExitReason;
10773 int rc = VMXReadVmcs32(VMX_VMCS32_RO_EXIT_REASON, &uExitReason);
10774 AssertRC(rc);
10775 pVmxTransient->uExitReason = VMX_EXIT_REASON_BASIC(uExitReason);
10776 pVmxTransient->fVMEntryFailed = VMX_EXIT_REASON_HAS_ENTRY_FAILED(uExitReason);
10777
10778 /*
10779 * Log the VM-exit before logging anything else as otherwise it might be a
10780 * tad confusing what happens before and after the world-switch.
10781 */
10782 HMVMX_LOG_EXIT(pVCpu, uExitReason);
10783
10784 /*
10785 * Remove the TSC_AUX MSR from the auto-load/store MSR area and reset any MSR
10786 * bitmap permissions, if it was added before VM-entry.
10787 */
10788 if (pVmxTransient->fRemoveTscAuxMsr)
10789 {
10790 hmR0VmxRemoveAutoLoadStoreMsr(pVCpu, pVmxTransient, MSR_K8_TSC_AUX);
10791 pVmxTransient->fRemoveTscAuxMsr = false;
10792 }
10793
10794 /*
10795 * Check if VMLAUNCH/VMRESUME succeeded.
10796 * If this failed, we cause a guru meditation and cease further execution.
10797 *
10798 * However, if we are executing a nested-guest we might fail if we use the
10799 * fast path rather than fully emulating VMLAUNCH/VMRESUME instruction in IEM.
10800 */
10801 if (RT_LIKELY(rcVMRun == VINF_SUCCESS))
10802 {
10803 /*
10804 * Update the VM-exit history array here even if the VM-entry failed due to:
10805 * - Invalid guest state.
10806 * - MSR loading.
10807 * - Machine-check event.
10808 *
10809 * In any of the above cases we will still have a "valid" VM-exit reason
10810 * despite @a fVMEntryFailed being false.
10811 *
10812 * See Intel spec. 26.7 "VM-Entry failures during or after loading guest state".
10813 *
10814 * Note! We don't have CS or RIP at this point. Will probably address that later
10815 * by amending the history entry added here.
10816 */
10817 EMHistoryAddExit(pVCpu, EMEXIT_MAKE_FT(EMEXIT_F_KIND_VMX, pVmxTransient->uExitReason & EMEXIT_F_TYPE_MASK),
10818 UINT64_MAX, uHostTsc);
10819
10820 if (RT_LIKELY(!pVmxTransient->fVMEntryFailed))
10821 {
10822 VMMRZCallRing3Enable(pVCpu);
10823
10824 Assert(!VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_HM_UPDATE_CR3));
10825 Assert(!VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_HM_UPDATE_PAE_PDPES));
10826
10827#ifdef HMVMX_ALWAYS_SAVE_RO_GUEST_STATE
10828 hmR0VmxReadAllRoFieldsVmcs(pVmxTransient);
10829#endif
10830#if defined(HMVMX_ALWAYS_SYNC_FULL_GUEST_STATE) || defined(HMVMX_ALWAYS_SAVE_FULL_GUEST_STATE)
10831 rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, HMVMX_CPUMCTX_EXTRN_ALL);
10832 AssertRC(rc);
10833#elif defined(HMVMX_ALWAYS_SAVE_GUEST_RFLAGS)
10834 rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, HMVMX_CPUMCTX_EXTRN_RFLAGS);
10835 AssertRC(rc);
10836#else
10837 /*
10838 * Import the guest-interruptibility state always as we need it while evaluating
10839 * injecting events on re-entry.
10840 *
10841 * We don't import CR0 (when unrestricted guest execution is unavailable) despite
10842 * checking for real-mode while exporting the state because all bits that cause
10843 * mode changes wrt CR0 are intercepted.
10844 */
10845 rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, CPUMCTX_EXTRN_HM_VMX_INT_STATE);
10846 AssertRC(rc);
10847#endif
10848
10849 /*
10850 * Sync the TPR shadow with our APIC state.
10851 */
10852 if ( !pVmxTransient->fIsNestedGuest
10853 && (pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_USE_TPR_SHADOW))
10854 {
10855 Assert(pVmcsInfo->pbVirtApic);
10856 if (pVmxTransient->u8GuestTpr != pVmcsInfo->pbVirtApic[XAPIC_OFF_TPR])
10857 {
10858 rc = APICSetTpr(pVCpu, pVmcsInfo->pbVirtApic[XAPIC_OFF_TPR]);
10859 AssertRC(rc);
10860 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_APIC_TPR);
10861 }
10862 }
10863
10864 Assert(VMMRZCallRing3IsEnabled(pVCpu));
10865 return;
10866 }
10867 }
10868#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
10869 else if (pVmxTransient->fIsNestedGuest)
10870 AssertMsgFailed(("VMLAUNCH/VMRESUME failed but shouldn't happen when VMLAUNCH/VMRESUME was emulated in IEM!\n"));
10871#endif
10872 else
10873 Log4Func(("VM-entry failure: rcVMRun=%Rrc fVMEntryFailed=%RTbool\n", rcVMRun, pVmxTransient->fVMEntryFailed));
10874
10875 VMMRZCallRing3Enable(pVCpu);
10876}
10877
10878
10879/**
10880 * Runs the guest code using hardware-assisted VMX the normal way.
10881 *
10882 * @returns VBox status code.
10883 * @param pVCpu The cross context virtual CPU structure.
10884 * @param pcLoops Pointer to the number of executed loops.
10885 */
10886static VBOXSTRICTRC hmR0VmxRunGuestCodeNormal(PVMCPUCC pVCpu, uint32_t *pcLoops)
10887{
10888 uint32_t const cMaxResumeLoops = pVCpu->CTX_SUFF(pVM)->hm.s.cMaxResumeLoops;
10889 Assert(pcLoops);
10890 Assert(*pcLoops <= cMaxResumeLoops);
10891 Assert(!CPUMIsGuestInVmxNonRootMode(&pVCpu->cpum.GstCtx));
10892
10893#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
10894 /*
10895 * Switch to the guest VMCS as we may have transitioned from executing the nested-guest
10896 * without leaving ring-0. Otherwise, if we came from ring-3 we would have loaded the
10897 * guest VMCS while entering the VMX ring-0 session.
10898 */
10899 if (pVCpu->hm.s.vmx.fSwitchedToNstGstVmcs)
10900 {
10901 int rc = hmR0VmxSwitchToGstOrNstGstVmcs(pVCpu, false /* fSwitchToNstGstVmcs */);
10902 if (RT_SUCCESS(rc))
10903 { /* likely */ }
10904 else
10905 {
10906 LogRelFunc(("Failed to switch to the guest VMCS. rc=%Rrc\n", rc));
10907 return rc;
10908 }
10909 }
10910#endif
10911
10912 VMXTRANSIENT VmxTransient;
10913 RT_ZERO(VmxTransient);
10914 VmxTransient.pVmcsInfo = hmGetVmxActiveVmcsInfo(pVCpu);
10915
10916 /* Paranoia. */
10917 Assert(VmxTransient.pVmcsInfo == &pVCpu->hm.s.vmx.VmcsInfo);
10918
10919 VBOXSTRICTRC rcStrict = VERR_INTERNAL_ERROR_5;
10920 for (;;)
10921 {
10922 Assert(!HMR0SuspendPending());
10923 HMVMX_ASSERT_CPU_SAFE(pVCpu);
10924 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatEntry, x);
10925
10926 /*
10927 * Preparatory work for running nested-guest code, this may force us to
10928 * return to ring-3.
10929 *
10930 * Warning! This bugger disables interrupts on VINF_SUCCESS!
10931 */
10932 rcStrict = hmR0VmxPreRunGuest(pVCpu, &VmxTransient, false /* fStepping */);
10933 if (rcStrict != VINF_SUCCESS)
10934 break;
10935
10936 /* Interrupts are disabled at this point! */
10937 hmR0VmxPreRunGuestCommitted(pVCpu, &VmxTransient);
10938 int rcRun = hmR0VmxRunGuest(pVCpu, &VmxTransient);
10939 hmR0VmxPostRunGuest(pVCpu, &VmxTransient, rcRun);
10940 /* Interrupts are re-enabled at this point! */
10941
10942 /*
10943 * Check for errors with running the VM (VMLAUNCH/VMRESUME).
10944 */
10945 if (RT_SUCCESS(rcRun))
10946 { /* very likely */ }
10947 else
10948 {
10949 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatPreExit, x);
10950 hmR0VmxReportWorldSwitchError(pVCpu, rcRun, &VmxTransient);
10951 return rcRun;
10952 }
10953
10954 /*
10955 * Profile the VM-exit.
10956 */
10957 AssertMsg(VmxTransient.uExitReason <= VMX_EXIT_MAX, ("%#x\n", VmxTransient.uExitReason));
10958 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitAll);
10959 STAM_COUNTER_INC(&pVCpu->hm.s.paStatExitReasonR0[VmxTransient.uExitReason & MASK_EXITREASON_STAT]);
10960 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatPreExit, &pVCpu->hm.s.StatExitHandling, x);
10961 HMVMX_START_EXIT_DISPATCH_PROF();
10962
10963 VBOXVMM_R0_HMVMX_VMEXIT_NOCTX(pVCpu, &pVCpu->cpum.GstCtx, VmxTransient.uExitReason);
10964
10965 /*
10966 * Handle the VM-exit.
10967 */
10968#ifdef HMVMX_USE_FUNCTION_TABLE
10969 rcStrict = g_apfnVMExitHandlers[VmxTransient.uExitReason](pVCpu, &VmxTransient);
10970#else
10971 rcStrict = hmR0VmxHandleExit(pVCpu, &VmxTransient);
10972#endif
10973 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExitHandling, x);
10974 if (rcStrict == VINF_SUCCESS)
10975 {
10976 if (++(*pcLoops) <= cMaxResumeLoops)
10977 continue;
10978 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchMaxResumeLoops);
10979 rcStrict = VINF_EM_RAW_INTERRUPT;
10980 }
10981 break;
10982 }
10983
10984 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatEntry, x);
10985 return rcStrict;
10986}
10987
10988
10989#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
10990/**
10991 * Runs the nested-guest code using hardware-assisted VMX.
10992 *
10993 * @returns VBox status code.
10994 * @param pVCpu The cross context virtual CPU structure.
10995 * @param pcLoops Pointer to the number of executed loops.
10996 *
10997 * @sa hmR0VmxRunGuestCodeNormal.
10998 */
10999static VBOXSTRICTRC hmR0VmxRunGuestCodeNested(PVMCPUCC pVCpu, uint32_t *pcLoops)
11000{
11001 uint32_t const cMaxResumeLoops = pVCpu->CTX_SUFF(pVM)->hm.s.cMaxResumeLoops;
11002 Assert(pcLoops);
11003 Assert(*pcLoops <= cMaxResumeLoops);
11004 Assert(CPUMIsGuestInVmxNonRootMode(&pVCpu->cpum.GstCtx));
11005
11006 /*
11007 * Switch to the nested-guest VMCS as we may have transitioned from executing the
11008 * guest without leaving ring-0. Otherwise, if we came from ring-3 we would have
11009 * loaded the nested-guest VMCS while entering the VMX ring-0 session.
11010 */
11011 if (!pVCpu->hm.s.vmx.fSwitchedToNstGstVmcs)
11012 {
11013 int rc = hmR0VmxSwitchToGstOrNstGstVmcs(pVCpu, true /* fSwitchToNstGstVmcs */);
11014 if (RT_SUCCESS(rc))
11015 { /* likely */ }
11016 else
11017 {
11018 LogRelFunc(("Failed to switch to the nested-guest VMCS. rc=%Rrc\n", rc));
11019 return rc;
11020 }
11021 }
11022
11023 VMXTRANSIENT VmxTransient;
11024 RT_ZERO(VmxTransient);
11025 VmxTransient.pVmcsInfo = hmGetVmxActiveVmcsInfo(pVCpu);
11026 VmxTransient.fIsNestedGuest = true;
11027
11028 /* Paranoia. */
11029 Assert(VmxTransient.pVmcsInfo == &pVCpu->hm.s.vmx.VmcsInfoNstGst);
11030
11031 VBOXSTRICTRC rcStrict = VERR_INTERNAL_ERROR_5;
11032 for (;;)
11033 {
11034 Assert(!HMR0SuspendPending());
11035 HMVMX_ASSERT_CPU_SAFE(pVCpu);
11036 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatEntry, x);
11037
11038 /*
11039 * Preparatory work for running guest code, this may force us to
11040 * return to ring-3.
11041 *
11042 * Warning! This bugger disables interrupts on VINF_SUCCESS!
11043 */
11044 rcStrict = hmR0VmxPreRunGuest(pVCpu, &VmxTransient, false /* fStepping */);
11045 if (rcStrict != VINF_SUCCESS)
11046 break;
11047
11048 /* Interrupts are disabled at this point! */
11049 hmR0VmxPreRunGuestCommitted(pVCpu, &VmxTransient);
11050 int rcRun = hmR0VmxRunGuest(pVCpu, &VmxTransient);
11051 hmR0VmxPostRunGuest(pVCpu, &VmxTransient, rcRun);
11052 /* Interrupts are re-enabled at this point! */
11053
11054 /*
11055 * Check for errors with running the VM (VMLAUNCH/VMRESUME).
11056 */
11057 if (RT_SUCCESS(rcRun))
11058 { /* very likely */ }
11059 else
11060 {
11061 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatPreExit, x);
11062 hmR0VmxReportWorldSwitchError(pVCpu, rcRun, &VmxTransient);
11063 return rcRun;
11064 }
11065
11066 /*
11067 * Profile the VM-exit.
11068 */
11069 AssertMsg(VmxTransient.uExitReason <= VMX_EXIT_MAX, ("%#x\n", VmxTransient.uExitReason));
11070 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitAll);
11071 STAM_COUNTER_INC(&pVCpu->hm.s.StatNestedExitAll);
11072 STAM_COUNTER_INC(&pVCpu->hm.s.paStatNestedExitReasonR0[VmxTransient.uExitReason & MASK_EXITREASON_STAT]);
11073 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatPreExit, &pVCpu->hm.s.StatExitHandling, x);
11074 HMVMX_START_EXIT_DISPATCH_PROF();
11075
11076 VBOXVMM_R0_HMVMX_VMEXIT_NOCTX(pVCpu, &pVCpu->cpum.GstCtx, VmxTransient.uExitReason);
11077
11078 /*
11079 * Handle the VM-exit.
11080 */
11081 rcStrict = hmR0VmxHandleExitNested(pVCpu, &VmxTransient);
11082 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExitHandling, x);
11083 if (rcStrict == VINF_SUCCESS)
11084 {
11085 if (!CPUMIsGuestInVmxNonRootMode(&pVCpu->cpum.GstCtx))
11086 {
11087 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchNstGstVmexit);
11088 rcStrict = VINF_VMX_VMEXIT;
11089 }
11090 else
11091 {
11092 if (++(*pcLoops) <= cMaxResumeLoops)
11093 continue;
11094 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchMaxResumeLoops);
11095 rcStrict = VINF_EM_RAW_INTERRUPT;
11096 }
11097 }
11098 else
11099 Assert(rcStrict != VINF_VMX_VMEXIT);
11100 break;
11101 }
11102
11103 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatEntry, x);
11104 return rcStrict;
11105}
11106#endif /* VBOX_WITH_NESTED_HWVIRT_VMX */
11107
11108
11109/** @name Execution loop for single stepping, DBGF events and expensive Dtrace
11110 * probes.
11111 *
11112 * The following few functions and associated structure contains the bloat
11113 * necessary for providing detailed debug events and dtrace probes as well as
11114 * reliable host side single stepping. This works on the principle of
11115 * "subclassing" the normal execution loop and workers. We replace the loop
11116 * method completely and override selected helpers to add necessary adjustments
11117 * to their core operation.
11118 *
11119 * The goal is to keep the "parent" code lean and mean, so as not to sacrifice
11120 * any performance for debug and analysis features.
11121 *
11122 * @{
11123 */
11124
11125/**
11126 * Transient per-VCPU debug state of VMCS and related info. we save/restore in
11127 * the debug run loop.
11128 */
11129typedef struct VMXRUNDBGSTATE
11130{
11131 /** The RIP we started executing at. This is for detecting that we stepped. */
11132 uint64_t uRipStart;
11133 /** The CS we started executing with. */
11134 uint16_t uCsStart;
11135
11136 /** Whether we've actually modified the 1st execution control field. */
11137 bool fModifiedProcCtls : 1;
11138 /** Whether we've actually modified the 2nd execution control field. */
11139 bool fModifiedProcCtls2 : 1;
11140 /** Whether we've actually modified the exception bitmap. */
11141 bool fModifiedXcptBitmap : 1;
11142
11143 /** We desire the modified the CR0 mask to be cleared. */
11144 bool fClearCr0Mask : 1;
11145 /** We desire the modified the CR4 mask to be cleared. */
11146 bool fClearCr4Mask : 1;
11147 /** Stuff we need in VMX_VMCS32_CTRL_PROC_EXEC. */
11148 uint32_t fCpe1Extra;
11149 /** Stuff we do not want in VMX_VMCS32_CTRL_PROC_EXEC. */
11150 uint32_t fCpe1Unwanted;
11151 /** Stuff we need in VMX_VMCS32_CTRL_PROC_EXEC2. */
11152 uint32_t fCpe2Extra;
11153 /** Extra stuff we need in VMX_VMCS32_CTRL_EXCEPTION_BITMAP. */
11154 uint32_t bmXcptExtra;
11155 /** The sequence number of the Dtrace provider settings the state was
11156 * configured against. */
11157 uint32_t uDtraceSettingsSeqNo;
11158 /** VM-exits to check (one bit per VM-exit). */
11159 uint32_t bmExitsToCheck[3];
11160
11161 /** The initial VMX_VMCS32_CTRL_PROC_EXEC value (helps with restore). */
11162 uint32_t fProcCtlsInitial;
11163 /** The initial VMX_VMCS32_CTRL_PROC_EXEC2 value (helps with restore). */
11164 uint32_t fProcCtls2Initial;
11165 /** The initial VMX_VMCS32_CTRL_EXCEPTION_BITMAP value (helps with restore). */
11166 uint32_t bmXcptInitial;
11167} VMXRUNDBGSTATE;
11168AssertCompileMemberSize(VMXRUNDBGSTATE, bmExitsToCheck, (VMX_EXIT_MAX + 1 + 31) / 32 * 4);
11169typedef VMXRUNDBGSTATE *PVMXRUNDBGSTATE;
11170
11171
11172/**
11173 * Initializes the VMXRUNDBGSTATE structure.
11174 *
11175 * @param pVCpu The cross context virtual CPU structure of the
11176 * calling EMT.
11177 * @param pVmxTransient The VMX-transient structure.
11178 * @param pDbgState The debug state to initialize.
11179 */
11180static void hmR0VmxRunDebugStateInit(PVMCPUCC pVCpu, PCVMXTRANSIENT pVmxTransient, PVMXRUNDBGSTATE pDbgState)
11181{
11182 pDbgState->uRipStart = pVCpu->cpum.GstCtx.rip;
11183 pDbgState->uCsStart = pVCpu->cpum.GstCtx.cs.Sel;
11184
11185 pDbgState->fModifiedProcCtls = false;
11186 pDbgState->fModifiedProcCtls2 = false;
11187 pDbgState->fModifiedXcptBitmap = false;
11188 pDbgState->fClearCr0Mask = false;
11189 pDbgState->fClearCr4Mask = false;
11190 pDbgState->fCpe1Extra = 0;
11191 pDbgState->fCpe1Unwanted = 0;
11192 pDbgState->fCpe2Extra = 0;
11193 pDbgState->bmXcptExtra = 0;
11194 pDbgState->fProcCtlsInitial = pVmxTransient->pVmcsInfo->u32ProcCtls;
11195 pDbgState->fProcCtls2Initial = pVmxTransient->pVmcsInfo->u32ProcCtls2;
11196 pDbgState->bmXcptInitial = pVmxTransient->pVmcsInfo->u32XcptBitmap;
11197}
11198
11199
11200/**
11201 * Updates the VMSC fields with changes requested by @a pDbgState.
11202 *
11203 * This is performed after hmR0VmxPreRunGuestDebugStateUpdate as well
11204 * immediately before executing guest code, i.e. when interrupts are disabled.
11205 * We don't check status codes here as we cannot easily assert or return in the
11206 * latter case.
11207 *
11208 * @param pVCpu The cross context virtual CPU structure.
11209 * @param pVmxTransient The VMX-transient structure.
11210 * @param pDbgState The debug state.
11211 */
11212static void hmR0VmxPreRunGuestDebugStateApply(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient, PVMXRUNDBGSTATE pDbgState)
11213{
11214 /*
11215 * Ensure desired flags in VMCS control fields are set.
11216 * (Ignoring write failure here, as we're committed and it's just debug extras.)
11217 *
11218 * Note! We load the shadow CR0 & CR4 bits when we flag the clearing, so
11219 * there should be no stale data in pCtx at this point.
11220 */
11221 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
11222 if ( (pVmcsInfo->u32ProcCtls & pDbgState->fCpe1Extra) != pDbgState->fCpe1Extra
11223 || (pVmcsInfo->u32ProcCtls & pDbgState->fCpe1Unwanted))
11224 {
11225 pVmcsInfo->u32ProcCtls |= pDbgState->fCpe1Extra;
11226 pVmcsInfo->u32ProcCtls &= ~pDbgState->fCpe1Unwanted;
11227 VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, pVmcsInfo->u32ProcCtls);
11228 Log6Func(("VMX_VMCS32_CTRL_PROC_EXEC: %#RX32\n", pVmcsInfo->u32ProcCtls));
11229 pDbgState->fModifiedProcCtls = true;
11230 }
11231
11232 if ((pVmcsInfo->u32ProcCtls2 & pDbgState->fCpe2Extra) != pDbgState->fCpe2Extra)
11233 {
11234 pVmcsInfo->u32ProcCtls2 |= pDbgState->fCpe2Extra;
11235 VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC2, pVmcsInfo->u32ProcCtls2);
11236 Log6Func(("VMX_VMCS32_CTRL_PROC_EXEC2: %#RX32\n", pVmcsInfo->u32ProcCtls2));
11237 pDbgState->fModifiedProcCtls2 = true;
11238 }
11239
11240 if ((pVmcsInfo->u32XcptBitmap & pDbgState->bmXcptExtra) != pDbgState->bmXcptExtra)
11241 {
11242 pVmcsInfo->u32XcptBitmap |= pDbgState->bmXcptExtra;
11243 VMXWriteVmcs32(VMX_VMCS32_CTRL_EXCEPTION_BITMAP, pVmcsInfo->u32XcptBitmap);
11244 Log6Func(("VMX_VMCS32_CTRL_EXCEPTION_BITMAP: %#RX32\n", pVmcsInfo->u32XcptBitmap));
11245 pDbgState->fModifiedXcptBitmap = true;
11246 }
11247
11248 if (pDbgState->fClearCr0Mask && pVmcsInfo->u64Cr0Mask != 0)
11249 {
11250 pVmcsInfo->u64Cr0Mask = 0;
11251 VMXWriteVmcsNw(VMX_VMCS_CTRL_CR0_MASK, 0);
11252 Log6Func(("VMX_VMCS_CTRL_CR0_MASK: 0\n"));
11253 }
11254
11255 if (pDbgState->fClearCr4Mask && pVmcsInfo->u64Cr4Mask != 0)
11256 {
11257 pVmcsInfo->u64Cr4Mask = 0;
11258 VMXWriteVmcsNw(VMX_VMCS_CTRL_CR4_MASK, 0);
11259 Log6Func(("VMX_VMCS_CTRL_CR4_MASK: 0\n"));
11260 }
11261
11262 NOREF(pVCpu);
11263}
11264
11265
11266/**
11267 * Restores VMCS fields that were changed by hmR0VmxPreRunGuestDebugStateApply for
11268 * re-entry next time around.
11269 *
11270 * @returns Strict VBox status code (i.e. informational status codes too).
11271 * @param pVCpu The cross context virtual CPU structure.
11272 * @param pVmxTransient The VMX-transient structure.
11273 * @param pDbgState The debug state.
11274 * @param rcStrict The return code from executing the guest using single
11275 * stepping.
11276 */
11277static VBOXSTRICTRC hmR0VmxRunDebugStateRevert(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient, PVMXRUNDBGSTATE pDbgState,
11278 VBOXSTRICTRC rcStrict)
11279{
11280 /*
11281 * Restore VM-exit control settings as we may not reenter this function the
11282 * next time around.
11283 */
11284 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
11285
11286 /* We reload the initial value, trigger what we can of recalculations the
11287 next time around. From the looks of things, that's all that's required atm. */
11288 if (pDbgState->fModifiedProcCtls)
11289 {
11290 if (!(pDbgState->fProcCtlsInitial & VMX_PROC_CTLS_MOV_DR_EXIT) && CPUMIsHyperDebugStateActive(pVCpu))
11291 pDbgState->fProcCtlsInitial |= VMX_PROC_CTLS_MOV_DR_EXIT; /* Avoid assertion in hmR0VmxLeave */
11292 int rc2 = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, pDbgState->fProcCtlsInitial);
11293 AssertRC(rc2);
11294 pVmcsInfo->u32ProcCtls = pDbgState->fProcCtlsInitial;
11295 }
11296
11297 /* We're currently the only ones messing with this one, so just restore the
11298 cached value and reload the field. */
11299 if ( pDbgState->fModifiedProcCtls2
11300 && pVmcsInfo->u32ProcCtls2 != pDbgState->fProcCtls2Initial)
11301 {
11302 int rc2 = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC2, pDbgState->fProcCtls2Initial);
11303 AssertRC(rc2);
11304 pVmcsInfo->u32ProcCtls2 = pDbgState->fProcCtls2Initial;
11305 }
11306
11307 /* If we've modified the exception bitmap, we restore it and trigger
11308 reloading and partial recalculation the next time around. */
11309 if (pDbgState->fModifiedXcptBitmap)
11310 pVmcsInfo->u32XcptBitmap = pDbgState->bmXcptInitial;
11311
11312 return rcStrict;
11313}
11314
11315
11316/**
11317 * Configures VM-exit controls for current DBGF and DTrace settings.
11318 *
11319 * This updates @a pDbgState and the VMCS execution control fields to reflect
11320 * the necessary VM-exits demanded by DBGF and DTrace.
11321 *
11322 * @param pVCpu The cross context virtual CPU structure.
11323 * @param pVmxTransient The VMX-transient structure. May update
11324 * fUpdatedTscOffsettingAndPreemptTimer.
11325 * @param pDbgState The debug state.
11326 */
11327static void hmR0VmxPreRunGuestDebugStateUpdate(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient, PVMXRUNDBGSTATE pDbgState)
11328{
11329 /*
11330 * Take down the dtrace serial number so we can spot changes.
11331 */
11332 pDbgState->uDtraceSettingsSeqNo = VBOXVMM_GET_SETTINGS_SEQ_NO();
11333 ASMCompilerBarrier();
11334
11335 /*
11336 * We'll rebuild most of the middle block of data members (holding the
11337 * current settings) as we go along here, so start by clearing it all.
11338 */
11339 pDbgState->bmXcptExtra = 0;
11340 pDbgState->fCpe1Extra = 0;
11341 pDbgState->fCpe1Unwanted = 0;
11342 pDbgState->fCpe2Extra = 0;
11343 for (unsigned i = 0; i < RT_ELEMENTS(pDbgState->bmExitsToCheck); i++)
11344 pDbgState->bmExitsToCheck[i] = 0;
11345
11346 /*
11347 * Software interrupts (INT XXh) - no idea how to trigger these...
11348 */
11349 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
11350 if ( DBGF_IS_EVENT_ENABLED(pVM, DBGFEVENT_INTERRUPT_SOFTWARE)
11351 || VBOXVMM_INT_SOFTWARE_ENABLED())
11352 {
11353 ASMBitSet(pDbgState->bmExitsToCheck, VMX_EXIT_XCPT_OR_NMI);
11354 }
11355
11356 /*
11357 * INT3 breakpoints - triggered by #BP exceptions.
11358 */
11359 if (pVM->dbgf.ro.cEnabledInt3Breakpoints > 0)
11360 pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_BP);
11361
11362 /*
11363 * Exception bitmap and XCPT events+probes.
11364 */
11365 for (int iXcpt = 0; iXcpt < (DBGFEVENT_XCPT_LAST - DBGFEVENT_XCPT_FIRST + 1); iXcpt++)
11366 if (DBGF_IS_EVENT_ENABLED(pVM, (DBGFEVENTTYPE)(DBGFEVENT_XCPT_FIRST + iXcpt)))
11367 pDbgState->bmXcptExtra |= RT_BIT_32(iXcpt);
11368
11369 if (VBOXVMM_XCPT_DE_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_DE);
11370 if (VBOXVMM_XCPT_DB_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_DB);
11371 if (VBOXVMM_XCPT_BP_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_BP);
11372 if (VBOXVMM_XCPT_OF_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_OF);
11373 if (VBOXVMM_XCPT_BR_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_BR);
11374 if (VBOXVMM_XCPT_UD_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_UD);
11375 if (VBOXVMM_XCPT_NM_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_NM);
11376 if (VBOXVMM_XCPT_DF_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_DF);
11377 if (VBOXVMM_XCPT_TS_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_TS);
11378 if (VBOXVMM_XCPT_NP_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_NP);
11379 if (VBOXVMM_XCPT_SS_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_SS);
11380 if (VBOXVMM_XCPT_GP_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_GP);
11381 if (VBOXVMM_XCPT_PF_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_PF);
11382 if (VBOXVMM_XCPT_MF_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_MF);
11383 if (VBOXVMM_XCPT_AC_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_AC);
11384 if (VBOXVMM_XCPT_XF_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_XF);
11385 if (VBOXVMM_XCPT_VE_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_VE);
11386 if (VBOXVMM_XCPT_SX_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_SX);
11387
11388 if (pDbgState->bmXcptExtra)
11389 ASMBitSet(pDbgState->bmExitsToCheck, VMX_EXIT_XCPT_OR_NMI);
11390
11391 /*
11392 * Process events and probes for VM-exits, making sure we get the wanted VM-exits.
11393 *
11394 * Note! This is the reverse of what hmR0VmxHandleExitDtraceEvents does.
11395 * So, when adding/changing/removing please don't forget to update it.
11396 *
11397 * Some of the macros are picking up local variables to save horizontal space,
11398 * (being able to see it in a table is the lesser evil here).
11399 */
11400#define IS_EITHER_ENABLED(a_pVM, a_EventSubName) \
11401 ( DBGF_IS_EVENT_ENABLED(a_pVM, RT_CONCAT(DBGFEVENT_, a_EventSubName)) \
11402 || RT_CONCAT3(VBOXVMM_, a_EventSubName, _ENABLED)() )
11403#define SET_ONLY_XBM_IF_EITHER_EN(a_EventSubName, a_uExit) \
11404 if (IS_EITHER_ENABLED(pVM, a_EventSubName)) \
11405 { AssertCompile((unsigned)(a_uExit) < sizeof(pDbgState->bmExitsToCheck) * 8); \
11406 ASMBitSet((pDbgState)->bmExitsToCheck, a_uExit); \
11407 } else do { } while (0)
11408#define SET_CPE1_XBM_IF_EITHER_EN(a_EventSubName, a_uExit, a_fCtrlProcExec) \
11409 if (IS_EITHER_ENABLED(pVM, a_EventSubName)) \
11410 { \
11411 (pDbgState)->fCpe1Extra |= (a_fCtrlProcExec); \
11412 AssertCompile((unsigned)(a_uExit) < sizeof(pDbgState->bmExitsToCheck) * 8); \
11413 ASMBitSet((pDbgState)->bmExitsToCheck, a_uExit); \
11414 } else do { } while (0)
11415#define SET_CPEU_XBM_IF_EITHER_EN(a_EventSubName, a_uExit, a_fUnwantedCtrlProcExec) \
11416 if (IS_EITHER_ENABLED(pVM, a_EventSubName)) \
11417 { \
11418 (pDbgState)->fCpe1Unwanted |= (a_fUnwantedCtrlProcExec); \
11419 AssertCompile((unsigned)(a_uExit) < sizeof(pDbgState->bmExitsToCheck) * 8); \
11420 ASMBitSet((pDbgState)->bmExitsToCheck, a_uExit); \
11421 } else do { } while (0)
11422#define SET_CPE2_XBM_IF_EITHER_EN(a_EventSubName, a_uExit, a_fCtrlProcExec2) \
11423 if (IS_EITHER_ENABLED(pVM, a_EventSubName)) \
11424 { \
11425 (pDbgState)->fCpe2Extra |= (a_fCtrlProcExec2); \
11426 AssertCompile((unsigned)(a_uExit) < sizeof(pDbgState->bmExitsToCheck) * 8); \
11427 ASMBitSet((pDbgState)->bmExitsToCheck, a_uExit); \
11428 } else do { } while (0)
11429
11430 SET_ONLY_XBM_IF_EITHER_EN(EXIT_TASK_SWITCH, VMX_EXIT_TASK_SWITCH); /* unconditional */
11431 SET_ONLY_XBM_IF_EITHER_EN(EXIT_VMX_EPT_VIOLATION, VMX_EXIT_EPT_VIOLATION); /* unconditional */
11432 SET_ONLY_XBM_IF_EITHER_EN(EXIT_VMX_EPT_MISCONFIG, VMX_EXIT_EPT_MISCONFIG); /* unconditional (unless #VE) */
11433 SET_ONLY_XBM_IF_EITHER_EN(EXIT_VMX_VAPIC_ACCESS, VMX_EXIT_APIC_ACCESS); /* feature dependent, nothing to enable here */
11434 SET_ONLY_XBM_IF_EITHER_EN(EXIT_VMX_VAPIC_WRITE, VMX_EXIT_APIC_WRITE); /* feature dependent, nothing to enable here */
11435
11436 SET_ONLY_XBM_IF_EITHER_EN(INSTR_CPUID, VMX_EXIT_CPUID); /* unconditional */
11437 SET_ONLY_XBM_IF_EITHER_EN( EXIT_CPUID, VMX_EXIT_CPUID);
11438 SET_ONLY_XBM_IF_EITHER_EN(INSTR_GETSEC, VMX_EXIT_GETSEC); /* unconditional */
11439 SET_ONLY_XBM_IF_EITHER_EN( EXIT_GETSEC, VMX_EXIT_GETSEC);
11440 SET_CPE1_XBM_IF_EITHER_EN(INSTR_HALT, VMX_EXIT_HLT, VMX_PROC_CTLS_HLT_EXIT); /* paranoia */
11441 SET_ONLY_XBM_IF_EITHER_EN( EXIT_HALT, VMX_EXIT_HLT);
11442 SET_ONLY_XBM_IF_EITHER_EN(INSTR_INVD, VMX_EXIT_INVD); /* unconditional */
11443 SET_ONLY_XBM_IF_EITHER_EN( EXIT_INVD, VMX_EXIT_INVD);
11444 SET_CPE1_XBM_IF_EITHER_EN(INSTR_INVLPG, VMX_EXIT_INVLPG, VMX_PROC_CTLS_INVLPG_EXIT);
11445 SET_ONLY_XBM_IF_EITHER_EN( EXIT_INVLPG, VMX_EXIT_INVLPG);
11446 SET_CPE1_XBM_IF_EITHER_EN(INSTR_RDPMC, VMX_EXIT_RDPMC, VMX_PROC_CTLS_RDPMC_EXIT);
11447 SET_ONLY_XBM_IF_EITHER_EN( EXIT_RDPMC, VMX_EXIT_RDPMC);
11448 SET_CPE1_XBM_IF_EITHER_EN(INSTR_RDTSC, VMX_EXIT_RDTSC, VMX_PROC_CTLS_RDTSC_EXIT);
11449 SET_ONLY_XBM_IF_EITHER_EN( EXIT_RDTSC, VMX_EXIT_RDTSC);
11450 SET_ONLY_XBM_IF_EITHER_EN(INSTR_RSM, VMX_EXIT_RSM); /* unconditional */
11451 SET_ONLY_XBM_IF_EITHER_EN( EXIT_RSM, VMX_EXIT_RSM);
11452 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMM_CALL, VMX_EXIT_VMCALL); /* unconditional */
11453 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMM_CALL, VMX_EXIT_VMCALL);
11454 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMX_VMCLEAR, VMX_EXIT_VMCLEAR); /* unconditional */
11455 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_VMCLEAR, VMX_EXIT_VMCLEAR);
11456 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMX_VMLAUNCH, VMX_EXIT_VMLAUNCH); /* unconditional */
11457 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_VMLAUNCH, VMX_EXIT_VMLAUNCH);
11458 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMX_VMPTRLD, VMX_EXIT_VMPTRLD); /* unconditional */
11459 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_VMPTRLD, VMX_EXIT_VMPTRLD);
11460 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMX_VMPTRST, VMX_EXIT_VMPTRST); /* unconditional */
11461 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_VMPTRST, VMX_EXIT_VMPTRST);
11462 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMX_VMREAD, VMX_EXIT_VMREAD); /* unconditional */
11463 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_VMREAD, VMX_EXIT_VMREAD);
11464 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMX_VMRESUME, VMX_EXIT_VMRESUME); /* unconditional */
11465 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_VMRESUME, VMX_EXIT_VMRESUME);
11466 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMX_VMWRITE, VMX_EXIT_VMWRITE); /* unconditional */
11467 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_VMWRITE, VMX_EXIT_VMWRITE);
11468 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMX_VMXOFF, VMX_EXIT_VMXOFF); /* unconditional */
11469 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_VMXOFF, VMX_EXIT_VMXOFF);
11470 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMX_VMXON, VMX_EXIT_VMXON); /* unconditional */
11471 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_VMXON, VMX_EXIT_VMXON);
11472
11473 if ( IS_EITHER_ENABLED(pVM, INSTR_CRX_READ)
11474 || IS_EITHER_ENABLED(pVM, INSTR_CRX_WRITE))
11475 {
11476 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, CPUMCTX_EXTRN_CR0 | CPUMCTX_EXTRN_CR4
11477 | CPUMCTX_EXTRN_APIC_TPR);
11478 AssertRC(rc);
11479
11480#if 0 /** @todo fix me */
11481 pDbgState->fClearCr0Mask = true;
11482 pDbgState->fClearCr4Mask = true;
11483#endif
11484 if (IS_EITHER_ENABLED(pVM, INSTR_CRX_READ))
11485 pDbgState->fCpe1Extra |= VMX_PROC_CTLS_CR3_STORE_EXIT | VMX_PROC_CTLS_CR8_STORE_EXIT;
11486 if (IS_EITHER_ENABLED(pVM, INSTR_CRX_WRITE))
11487 pDbgState->fCpe1Extra |= VMX_PROC_CTLS_CR3_LOAD_EXIT | VMX_PROC_CTLS_CR8_LOAD_EXIT;
11488 pDbgState->fCpe1Unwanted |= VMX_PROC_CTLS_USE_TPR_SHADOW; /* risky? */
11489 /* Note! We currently don't use VMX_VMCS32_CTRL_CR3_TARGET_COUNT. It would
11490 require clearing here and in the loop if we start using it. */
11491 ASMBitSet(pDbgState->bmExitsToCheck, VMX_EXIT_MOV_CRX);
11492 }
11493 else
11494 {
11495 if (pDbgState->fClearCr0Mask)
11496 {
11497 pDbgState->fClearCr0Mask = false;
11498 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_CR0);
11499 }
11500 if (pDbgState->fClearCr4Mask)
11501 {
11502 pDbgState->fClearCr4Mask = false;
11503 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_CR4);
11504 }
11505 }
11506 SET_ONLY_XBM_IF_EITHER_EN( EXIT_CRX_READ, VMX_EXIT_MOV_CRX);
11507 SET_ONLY_XBM_IF_EITHER_EN( EXIT_CRX_WRITE, VMX_EXIT_MOV_CRX);
11508
11509 if ( IS_EITHER_ENABLED(pVM, INSTR_DRX_READ)
11510 || IS_EITHER_ENABLED(pVM, INSTR_DRX_WRITE))
11511 {
11512 /** @todo later, need to fix handler as it assumes this won't usually happen. */
11513 ASMBitSet(pDbgState->bmExitsToCheck, VMX_EXIT_MOV_DRX);
11514 }
11515 SET_ONLY_XBM_IF_EITHER_EN( EXIT_DRX_READ, VMX_EXIT_MOV_DRX);
11516 SET_ONLY_XBM_IF_EITHER_EN( EXIT_DRX_WRITE, VMX_EXIT_MOV_DRX);
11517
11518 SET_CPEU_XBM_IF_EITHER_EN(INSTR_RDMSR, VMX_EXIT_RDMSR, VMX_PROC_CTLS_USE_MSR_BITMAPS); /* risky clearing this? */
11519 SET_ONLY_XBM_IF_EITHER_EN( EXIT_RDMSR, VMX_EXIT_RDMSR);
11520 SET_CPEU_XBM_IF_EITHER_EN(INSTR_WRMSR, VMX_EXIT_WRMSR, VMX_PROC_CTLS_USE_MSR_BITMAPS);
11521 SET_ONLY_XBM_IF_EITHER_EN( EXIT_WRMSR, VMX_EXIT_WRMSR);
11522 SET_CPE1_XBM_IF_EITHER_EN(INSTR_MWAIT, VMX_EXIT_MWAIT, VMX_PROC_CTLS_MWAIT_EXIT); /* paranoia */
11523 SET_ONLY_XBM_IF_EITHER_EN( EXIT_MWAIT, VMX_EXIT_MWAIT);
11524 SET_CPE1_XBM_IF_EITHER_EN(INSTR_MONITOR, VMX_EXIT_MONITOR, VMX_PROC_CTLS_MONITOR_EXIT); /* paranoia */
11525 SET_ONLY_XBM_IF_EITHER_EN( EXIT_MONITOR, VMX_EXIT_MONITOR);
11526#if 0 /** @todo too slow, fix handler. */
11527 SET_CPE1_XBM_IF_EITHER_EN(INSTR_PAUSE, VMX_EXIT_PAUSE, VMX_PROC_CTLS_PAUSE_EXIT);
11528#endif
11529 SET_ONLY_XBM_IF_EITHER_EN( EXIT_PAUSE, VMX_EXIT_PAUSE);
11530
11531 if ( IS_EITHER_ENABLED(pVM, INSTR_SGDT)
11532 || IS_EITHER_ENABLED(pVM, INSTR_SIDT)
11533 || IS_EITHER_ENABLED(pVM, INSTR_LGDT)
11534 || IS_EITHER_ENABLED(pVM, INSTR_LIDT))
11535 {
11536 pDbgState->fCpe2Extra |= VMX_PROC_CTLS2_DESC_TABLE_EXIT;
11537 ASMBitSet(pDbgState->bmExitsToCheck, VMX_EXIT_GDTR_IDTR_ACCESS);
11538 }
11539 SET_ONLY_XBM_IF_EITHER_EN( EXIT_SGDT, VMX_EXIT_GDTR_IDTR_ACCESS);
11540 SET_ONLY_XBM_IF_EITHER_EN( EXIT_SIDT, VMX_EXIT_GDTR_IDTR_ACCESS);
11541 SET_ONLY_XBM_IF_EITHER_EN( EXIT_LGDT, VMX_EXIT_GDTR_IDTR_ACCESS);
11542 SET_ONLY_XBM_IF_EITHER_EN( EXIT_LIDT, VMX_EXIT_GDTR_IDTR_ACCESS);
11543
11544 if ( IS_EITHER_ENABLED(pVM, INSTR_SLDT)
11545 || IS_EITHER_ENABLED(pVM, INSTR_STR)
11546 || IS_EITHER_ENABLED(pVM, INSTR_LLDT)
11547 || IS_EITHER_ENABLED(pVM, INSTR_LTR))
11548 {
11549 pDbgState->fCpe2Extra |= VMX_PROC_CTLS2_DESC_TABLE_EXIT;
11550 ASMBitSet(pDbgState->bmExitsToCheck, VMX_EXIT_LDTR_TR_ACCESS);
11551 }
11552 SET_ONLY_XBM_IF_EITHER_EN( EXIT_SLDT, VMX_EXIT_LDTR_TR_ACCESS);
11553 SET_ONLY_XBM_IF_EITHER_EN( EXIT_STR, VMX_EXIT_LDTR_TR_ACCESS);
11554 SET_ONLY_XBM_IF_EITHER_EN( EXIT_LLDT, VMX_EXIT_LDTR_TR_ACCESS);
11555 SET_ONLY_XBM_IF_EITHER_EN( EXIT_LTR, VMX_EXIT_LDTR_TR_ACCESS);
11556
11557 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMX_INVEPT, VMX_EXIT_INVEPT); /* unconditional */
11558 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_INVEPT, VMX_EXIT_INVEPT);
11559 SET_CPE1_XBM_IF_EITHER_EN(INSTR_RDTSCP, VMX_EXIT_RDTSCP, VMX_PROC_CTLS_RDTSC_EXIT);
11560 SET_ONLY_XBM_IF_EITHER_EN( EXIT_RDTSCP, VMX_EXIT_RDTSCP);
11561 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMX_INVVPID, VMX_EXIT_INVVPID); /* unconditional */
11562 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_INVVPID, VMX_EXIT_INVVPID);
11563 SET_CPE2_XBM_IF_EITHER_EN(INSTR_WBINVD, VMX_EXIT_WBINVD, VMX_PROC_CTLS2_WBINVD_EXIT);
11564 SET_ONLY_XBM_IF_EITHER_EN( EXIT_WBINVD, VMX_EXIT_WBINVD);
11565 SET_ONLY_XBM_IF_EITHER_EN(INSTR_XSETBV, VMX_EXIT_XSETBV); /* unconditional */
11566 SET_ONLY_XBM_IF_EITHER_EN( EXIT_XSETBV, VMX_EXIT_XSETBV);
11567 SET_CPE2_XBM_IF_EITHER_EN(INSTR_RDRAND, VMX_EXIT_RDRAND, VMX_PROC_CTLS2_RDRAND_EXIT);
11568 SET_ONLY_XBM_IF_EITHER_EN( EXIT_RDRAND, VMX_EXIT_RDRAND);
11569 SET_CPE1_XBM_IF_EITHER_EN(INSTR_VMX_INVPCID, VMX_EXIT_INVPCID, VMX_PROC_CTLS_INVLPG_EXIT);
11570 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_INVPCID, VMX_EXIT_INVPCID);
11571 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMX_VMFUNC, VMX_EXIT_VMFUNC); /* unconditional for the current setup */
11572 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_VMFUNC, VMX_EXIT_VMFUNC);
11573 SET_CPE2_XBM_IF_EITHER_EN(INSTR_RDSEED, VMX_EXIT_RDSEED, VMX_PROC_CTLS2_RDSEED_EXIT);
11574 SET_ONLY_XBM_IF_EITHER_EN( EXIT_RDSEED, VMX_EXIT_RDSEED);
11575 SET_ONLY_XBM_IF_EITHER_EN(INSTR_XSAVES, VMX_EXIT_XSAVES); /* unconditional (enabled by host, guest cfg) */
11576 SET_ONLY_XBM_IF_EITHER_EN(EXIT_XSAVES, VMX_EXIT_XSAVES);
11577 SET_ONLY_XBM_IF_EITHER_EN(INSTR_XRSTORS, VMX_EXIT_XRSTORS); /* unconditional (enabled by host, guest cfg) */
11578 SET_ONLY_XBM_IF_EITHER_EN( EXIT_XRSTORS, VMX_EXIT_XRSTORS);
11579
11580#undef IS_EITHER_ENABLED
11581#undef SET_ONLY_XBM_IF_EITHER_EN
11582#undef SET_CPE1_XBM_IF_EITHER_EN
11583#undef SET_CPEU_XBM_IF_EITHER_EN
11584#undef SET_CPE2_XBM_IF_EITHER_EN
11585
11586 /*
11587 * Sanitize the control stuff.
11588 */
11589 pDbgState->fCpe2Extra &= pVM->hm.s.vmx.Msrs.ProcCtls2.n.allowed1;
11590 if (pDbgState->fCpe2Extra)
11591 pDbgState->fCpe1Extra |= VMX_PROC_CTLS_USE_SECONDARY_CTLS;
11592 pDbgState->fCpe1Extra &= pVM->hm.s.vmx.Msrs.ProcCtls.n.allowed1;
11593 pDbgState->fCpe1Unwanted &= ~pVM->hm.s.vmx.Msrs.ProcCtls.n.allowed0;
11594 if (pVCpu->hm.s.fDebugWantRdTscExit != RT_BOOL(pDbgState->fCpe1Extra & VMX_PROC_CTLS_RDTSC_EXIT))
11595 {
11596 pVCpu->hm.s.fDebugWantRdTscExit ^= true;
11597 pVmxTransient->fUpdatedTscOffsettingAndPreemptTimer = false;
11598 }
11599
11600 Log6(("HM: debug state: cpe1=%#RX32 cpeu=%#RX32 cpe2=%#RX32%s%s\n",
11601 pDbgState->fCpe1Extra, pDbgState->fCpe1Unwanted, pDbgState->fCpe2Extra,
11602 pDbgState->fClearCr0Mask ? " clr-cr0" : "",
11603 pDbgState->fClearCr4Mask ? " clr-cr4" : ""));
11604}
11605
11606
11607/**
11608 * Fires off DBGF events and dtrace probes for a VM-exit, when it's
11609 * appropriate.
11610 *
11611 * The caller has checked the VM-exit against the
11612 * VMXRUNDBGSTATE::bmExitsToCheck bitmap. The caller has checked for NMIs
11613 * already, so we don't have to do that either.
11614 *
11615 * @returns Strict VBox status code (i.e. informational status codes too).
11616 * @param pVCpu The cross context virtual CPU structure.
11617 * @param pVmxTransient The VMX-transient structure.
11618 * @param uExitReason The VM-exit reason.
11619 *
11620 * @remarks The name of this function is displayed by dtrace, so keep it short
11621 * and to the point. No longer than 33 chars long, please.
11622 */
11623static VBOXSTRICTRC hmR0VmxHandleExitDtraceEvents(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient, uint32_t uExitReason)
11624{
11625 /*
11626 * Translate the event into a DBGF event (enmEvent + uEventArg) and at the
11627 * same time check whether any corresponding Dtrace event is enabled (fDtrace).
11628 *
11629 * Note! This is the reverse operation of what hmR0VmxPreRunGuestDebugStateUpdate
11630 * does. Must add/change/remove both places. Same ordering, please.
11631 *
11632 * Added/removed events must also be reflected in the next section
11633 * where we dispatch dtrace events.
11634 */
11635 bool fDtrace1 = false;
11636 bool fDtrace2 = false;
11637 DBGFEVENTTYPE enmEvent1 = DBGFEVENT_END;
11638 DBGFEVENTTYPE enmEvent2 = DBGFEVENT_END;
11639 uint32_t uEventArg = 0;
11640#define SET_EXIT(a_EventSubName) \
11641 do { \
11642 enmEvent2 = RT_CONCAT(DBGFEVENT_EXIT_, a_EventSubName); \
11643 fDtrace2 = RT_CONCAT3(VBOXVMM_EXIT_, a_EventSubName, _ENABLED)(); \
11644 } while (0)
11645#define SET_BOTH(a_EventSubName) \
11646 do { \
11647 enmEvent1 = RT_CONCAT(DBGFEVENT_INSTR_, a_EventSubName); \
11648 enmEvent2 = RT_CONCAT(DBGFEVENT_EXIT_, a_EventSubName); \
11649 fDtrace1 = RT_CONCAT3(VBOXVMM_INSTR_, a_EventSubName, _ENABLED)(); \
11650 fDtrace2 = RT_CONCAT3(VBOXVMM_EXIT_, a_EventSubName, _ENABLED)(); \
11651 } while (0)
11652 switch (uExitReason)
11653 {
11654 case VMX_EXIT_MTF:
11655 return hmR0VmxExitMtf(pVCpu, pVmxTransient);
11656
11657 case VMX_EXIT_XCPT_OR_NMI:
11658 {
11659 uint8_t const idxVector = VMX_EXIT_INT_INFO_VECTOR(pVmxTransient->uExitIntInfo);
11660 switch (VMX_EXIT_INT_INFO_TYPE(pVmxTransient->uExitIntInfo))
11661 {
11662 case VMX_EXIT_INT_INFO_TYPE_HW_XCPT:
11663 case VMX_EXIT_INT_INFO_TYPE_SW_XCPT:
11664 case VMX_EXIT_INT_INFO_TYPE_PRIV_SW_XCPT:
11665 if (idxVector <= (unsigned)(DBGFEVENT_XCPT_LAST - DBGFEVENT_XCPT_FIRST))
11666 {
11667 if (VMX_EXIT_INT_INFO_IS_ERROR_CODE_VALID(pVmxTransient->uExitIntInfo))
11668 {
11669 hmR0VmxReadExitIntErrorCodeVmcs(pVmxTransient);
11670 uEventArg = pVmxTransient->uExitIntErrorCode;
11671 }
11672 enmEvent1 = (DBGFEVENTTYPE)(DBGFEVENT_XCPT_FIRST + idxVector);
11673 switch (enmEvent1)
11674 {
11675 case DBGFEVENT_XCPT_DE: fDtrace1 = VBOXVMM_XCPT_DE_ENABLED(); break;
11676 case DBGFEVENT_XCPT_DB: fDtrace1 = VBOXVMM_XCPT_DB_ENABLED(); break;
11677 case DBGFEVENT_XCPT_BP: fDtrace1 = VBOXVMM_XCPT_BP_ENABLED(); break;
11678 case DBGFEVENT_XCPT_OF: fDtrace1 = VBOXVMM_XCPT_OF_ENABLED(); break;
11679 case DBGFEVENT_XCPT_BR: fDtrace1 = VBOXVMM_XCPT_BR_ENABLED(); break;
11680 case DBGFEVENT_XCPT_UD: fDtrace1 = VBOXVMM_XCPT_UD_ENABLED(); break;
11681 case DBGFEVENT_XCPT_NM: fDtrace1 = VBOXVMM_XCPT_NM_ENABLED(); break;
11682 case DBGFEVENT_XCPT_DF: fDtrace1 = VBOXVMM_XCPT_DF_ENABLED(); break;
11683 case DBGFEVENT_XCPT_TS: fDtrace1 = VBOXVMM_XCPT_TS_ENABLED(); break;
11684 case DBGFEVENT_XCPT_NP: fDtrace1 = VBOXVMM_XCPT_NP_ENABLED(); break;
11685 case DBGFEVENT_XCPT_SS: fDtrace1 = VBOXVMM_XCPT_SS_ENABLED(); break;
11686 case DBGFEVENT_XCPT_GP: fDtrace1 = VBOXVMM_XCPT_GP_ENABLED(); break;
11687 case DBGFEVENT_XCPT_PF: fDtrace1 = VBOXVMM_XCPT_PF_ENABLED(); break;
11688 case DBGFEVENT_XCPT_MF: fDtrace1 = VBOXVMM_XCPT_MF_ENABLED(); break;
11689 case DBGFEVENT_XCPT_AC: fDtrace1 = VBOXVMM_XCPT_AC_ENABLED(); break;
11690 case DBGFEVENT_XCPT_XF: fDtrace1 = VBOXVMM_XCPT_XF_ENABLED(); break;
11691 case DBGFEVENT_XCPT_VE: fDtrace1 = VBOXVMM_XCPT_VE_ENABLED(); break;
11692 case DBGFEVENT_XCPT_SX: fDtrace1 = VBOXVMM_XCPT_SX_ENABLED(); break;
11693 default: break;
11694 }
11695 }
11696 else
11697 AssertFailed();
11698 break;
11699
11700 case VMX_EXIT_INT_INFO_TYPE_SW_INT:
11701 uEventArg = idxVector;
11702 enmEvent1 = DBGFEVENT_INTERRUPT_SOFTWARE;
11703 fDtrace1 = VBOXVMM_INT_SOFTWARE_ENABLED();
11704 break;
11705 }
11706 break;
11707 }
11708
11709 case VMX_EXIT_TRIPLE_FAULT:
11710 enmEvent1 = DBGFEVENT_TRIPLE_FAULT;
11711 //fDtrace1 = VBOXVMM_EXIT_TRIPLE_FAULT_ENABLED();
11712 break;
11713 case VMX_EXIT_TASK_SWITCH: SET_EXIT(TASK_SWITCH); break;
11714 case VMX_EXIT_EPT_VIOLATION: SET_EXIT(VMX_EPT_VIOLATION); break;
11715 case VMX_EXIT_EPT_MISCONFIG: SET_EXIT(VMX_EPT_MISCONFIG); break;
11716 case VMX_EXIT_APIC_ACCESS: SET_EXIT(VMX_VAPIC_ACCESS); break;
11717 case VMX_EXIT_APIC_WRITE: SET_EXIT(VMX_VAPIC_WRITE); break;
11718
11719 /* Instruction specific VM-exits: */
11720 case VMX_EXIT_CPUID: SET_BOTH(CPUID); break;
11721 case VMX_EXIT_GETSEC: SET_BOTH(GETSEC); break;
11722 case VMX_EXIT_HLT: SET_BOTH(HALT); break;
11723 case VMX_EXIT_INVD: SET_BOTH(INVD); break;
11724 case VMX_EXIT_INVLPG: SET_BOTH(INVLPG); break;
11725 case VMX_EXIT_RDPMC: SET_BOTH(RDPMC); break;
11726 case VMX_EXIT_RDTSC: SET_BOTH(RDTSC); break;
11727 case VMX_EXIT_RSM: SET_BOTH(RSM); break;
11728 case VMX_EXIT_VMCALL: SET_BOTH(VMM_CALL); break;
11729 case VMX_EXIT_VMCLEAR: SET_BOTH(VMX_VMCLEAR); break;
11730 case VMX_EXIT_VMLAUNCH: SET_BOTH(VMX_VMLAUNCH); break;
11731 case VMX_EXIT_VMPTRLD: SET_BOTH(VMX_VMPTRLD); break;
11732 case VMX_EXIT_VMPTRST: SET_BOTH(VMX_VMPTRST); break;
11733 case VMX_EXIT_VMREAD: SET_BOTH(VMX_VMREAD); break;
11734 case VMX_EXIT_VMRESUME: SET_BOTH(VMX_VMRESUME); break;
11735 case VMX_EXIT_VMWRITE: SET_BOTH(VMX_VMWRITE); break;
11736 case VMX_EXIT_VMXOFF: SET_BOTH(VMX_VMXOFF); break;
11737 case VMX_EXIT_VMXON: SET_BOTH(VMX_VMXON); break;
11738 case VMX_EXIT_MOV_CRX:
11739 hmR0VmxReadExitQualVmcs(pVmxTransient);
11740 if (VMX_EXIT_QUAL_CRX_ACCESS(pVmxTransient->uExitQual) == VMX_EXIT_QUAL_CRX_ACCESS_READ)
11741 SET_BOTH(CRX_READ);
11742 else
11743 SET_BOTH(CRX_WRITE);
11744 uEventArg = VMX_EXIT_QUAL_CRX_REGISTER(pVmxTransient->uExitQual);
11745 break;
11746 case VMX_EXIT_MOV_DRX:
11747 hmR0VmxReadExitQualVmcs(pVmxTransient);
11748 if ( VMX_EXIT_QUAL_DRX_DIRECTION(pVmxTransient->uExitQual)
11749 == VMX_EXIT_QUAL_DRX_DIRECTION_READ)
11750 SET_BOTH(DRX_READ);
11751 else
11752 SET_BOTH(DRX_WRITE);
11753 uEventArg = VMX_EXIT_QUAL_DRX_REGISTER(pVmxTransient->uExitQual);
11754 break;
11755 case VMX_EXIT_RDMSR: SET_BOTH(RDMSR); break;
11756 case VMX_EXIT_WRMSR: SET_BOTH(WRMSR); break;
11757 case VMX_EXIT_MWAIT: SET_BOTH(MWAIT); break;
11758 case VMX_EXIT_MONITOR: SET_BOTH(MONITOR); break;
11759 case VMX_EXIT_PAUSE: SET_BOTH(PAUSE); break;
11760 case VMX_EXIT_GDTR_IDTR_ACCESS:
11761 hmR0VmxReadExitInstrInfoVmcs(pVmxTransient);
11762 switch (RT_BF_GET(pVmxTransient->ExitInstrInfo.u, VMX_BF_XDTR_INSINFO_INSTR_ID))
11763 {
11764 case VMX_XDTR_INSINFO_II_SGDT: SET_BOTH(SGDT); break;
11765 case VMX_XDTR_INSINFO_II_SIDT: SET_BOTH(SIDT); break;
11766 case VMX_XDTR_INSINFO_II_LGDT: SET_BOTH(LGDT); break;
11767 case VMX_XDTR_INSINFO_II_LIDT: SET_BOTH(LIDT); break;
11768 }
11769 break;
11770
11771 case VMX_EXIT_LDTR_TR_ACCESS:
11772 hmR0VmxReadExitInstrInfoVmcs(pVmxTransient);
11773 switch (RT_BF_GET(pVmxTransient->ExitInstrInfo.u, VMX_BF_YYTR_INSINFO_INSTR_ID))
11774 {
11775 case VMX_YYTR_INSINFO_II_SLDT: SET_BOTH(SLDT); break;
11776 case VMX_YYTR_INSINFO_II_STR: SET_BOTH(STR); break;
11777 case VMX_YYTR_INSINFO_II_LLDT: SET_BOTH(LLDT); break;
11778 case VMX_YYTR_INSINFO_II_LTR: SET_BOTH(LTR); break;
11779 }
11780 break;
11781
11782 case VMX_EXIT_INVEPT: SET_BOTH(VMX_INVEPT); break;
11783 case VMX_EXIT_RDTSCP: SET_BOTH(RDTSCP); break;
11784 case VMX_EXIT_INVVPID: SET_BOTH(VMX_INVVPID); break;
11785 case VMX_EXIT_WBINVD: SET_BOTH(WBINVD); break;
11786 case VMX_EXIT_XSETBV: SET_BOTH(XSETBV); break;
11787 case VMX_EXIT_RDRAND: SET_BOTH(RDRAND); break;
11788 case VMX_EXIT_INVPCID: SET_BOTH(VMX_INVPCID); break;
11789 case VMX_EXIT_VMFUNC: SET_BOTH(VMX_VMFUNC); break;
11790 case VMX_EXIT_RDSEED: SET_BOTH(RDSEED); break;
11791 case VMX_EXIT_XSAVES: SET_BOTH(XSAVES); break;
11792 case VMX_EXIT_XRSTORS: SET_BOTH(XRSTORS); break;
11793
11794 /* Events that aren't relevant at this point. */
11795 case VMX_EXIT_EXT_INT:
11796 case VMX_EXIT_INT_WINDOW:
11797 case VMX_EXIT_NMI_WINDOW:
11798 case VMX_EXIT_TPR_BELOW_THRESHOLD:
11799 case VMX_EXIT_PREEMPT_TIMER:
11800 case VMX_EXIT_IO_INSTR:
11801 break;
11802
11803 /* Errors and unexpected events. */
11804 case VMX_EXIT_INIT_SIGNAL:
11805 case VMX_EXIT_SIPI:
11806 case VMX_EXIT_IO_SMI:
11807 case VMX_EXIT_SMI:
11808 case VMX_EXIT_ERR_INVALID_GUEST_STATE:
11809 case VMX_EXIT_ERR_MSR_LOAD:
11810 case VMX_EXIT_ERR_MACHINE_CHECK:
11811 case VMX_EXIT_PML_FULL:
11812 case VMX_EXIT_VIRTUALIZED_EOI:
11813 break;
11814
11815 default:
11816 AssertMsgFailed(("Unexpected VM-exit=%#x\n", uExitReason));
11817 break;
11818 }
11819#undef SET_BOTH
11820#undef SET_EXIT
11821
11822 /*
11823 * Dtrace tracepoints go first. We do them here at once so we don't
11824 * have to copy the guest state saving and stuff a few dozen times.
11825 * Down side is that we've got to repeat the switch, though this time
11826 * we use enmEvent since the probes are a subset of what DBGF does.
11827 */
11828 if (fDtrace1 || fDtrace2)
11829 {
11830 hmR0VmxReadExitQualVmcs(pVmxTransient);
11831 hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, HMVMX_CPUMCTX_EXTRN_ALL);
11832 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
11833 switch (enmEvent1)
11834 {
11835 /** @todo consider which extra parameters would be helpful for each probe. */
11836 case DBGFEVENT_END: break;
11837 case DBGFEVENT_XCPT_DE: VBOXVMM_XCPT_DE(pVCpu, pCtx); break;
11838 case DBGFEVENT_XCPT_DB: VBOXVMM_XCPT_DB(pVCpu, pCtx, pCtx->dr[6]); break;
11839 case DBGFEVENT_XCPT_BP: VBOXVMM_XCPT_BP(pVCpu, pCtx); break;
11840 case DBGFEVENT_XCPT_OF: VBOXVMM_XCPT_OF(pVCpu, pCtx); break;
11841 case DBGFEVENT_XCPT_BR: VBOXVMM_XCPT_BR(pVCpu, pCtx); break;
11842 case DBGFEVENT_XCPT_UD: VBOXVMM_XCPT_UD(pVCpu, pCtx); break;
11843 case DBGFEVENT_XCPT_NM: VBOXVMM_XCPT_NM(pVCpu, pCtx); break;
11844 case DBGFEVENT_XCPT_DF: VBOXVMM_XCPT_DF(pVCpu, pCtx); break;
11845 case DBGFEVENT_XCPT_TS: VBOXVMM_XCPT_TS(pVCpu, pCtx, uEventArg); break;
11846 case DBGFEVENT_XCPT_NP: VBOXVMM_XCPT_NP(pVCpu, pCtx, uEventArg); break;
11847 case DBGFEVENT_XCPT_SS: VBOXVMM_XCPT_SS(pVCpu, pCtx, uEventArg); break;
11848 case DBGFEVENT_XCPT_GP: VBOXVMM_XCPT_GP(pVCpu, pCtx, uEventArg); break;
11849 case DBGFEVENT_XCPT_PF: VBOXVMM_XCPT_PF(pVCpu, pCtx, uEventArg, pCtx->cr2); break;
11850 case DBGFEVENT_XCPT_MF: VBOXVMM_XCPT_MF(pVCpu, pCtx); break;
11851 case DBGFEVENT_XCPT_AC: VBOXVMM_XCPT_AC(pVCpu, pCtx); break;
11852 case DBGFEVENT_XCPT_XF: VBOXVMM_XCPT_XF(pVCpu, pCtx); break;
11853 case DBGFEVENT_XCPT_VE: VBOXVMM_XCPT_VE(pVCpu, pCtx); break;
11854 case DBGFEVENT_XCPT_SX: VBOXVMM_XCPT_SX(pVCpu, pCtx, uEventArg); break;
11855 case DBGFEVENT_INTERRUPT_SOFTWARE: VBOXVMM_INT_SOFTWARE(pVCpu, pCtx, (uint8_t)uEventArg); break;
11856 case DBGFEVENT_INSTR_CPUID: VBOXVMM_INSTR_CPUID(pVCpu, pCtx, pCtx->eax, pCtx->ecx); break;
11857 case DBGFEVENT_INSTR_GETSEC: VBOXVMM_INSTR_GETSEC(pVCpu, pCtx); break;
11858 case DBGFEVENT_INSTR_HALT: VBOXVMM_INSTR_HALT(pVCpu, pCtx); break;
11859 case DBGFEVENT_INSTR_INVD: VBOXVMM_INSTR_INVD(pVCpu, pCtx); break;
11860 case DBGFEVENT_INSTR_INVLPG: VBOXVMM_INSTR_INVLPG(pVCpu, pCtx); break;
11861 case DBGFEVENT_INSTR_RDPMC: VBOXVMM_INSTR_RDPMC(pVCpu, pCtx); break;
11862 case DBGFEVENT_INSTR_RDTSC: VBOXVMM_INSTR_RDTSC(pVCpu, pCtx); break;
11863 case DBGFEVENT_INSTR_RSM: VBOXVMM_INSTR_RSM(pVCpu, pCtx); break;
11864 case DBGFEVENT_INSTR_CRX_READ: VBOXVMM_INSTR_CRX_READ(pVCpu, pCtx, (uint8_t)uEventArg); break;
11865 case DBGFEVENT_INSTR_CRX_WRITE: VBOXVMM_INSTR_CRX_WRITE(pVCpu, pCtx, (uint8_t)uEventArg); break;
11866 case DBGFEVENT_INSTR_DRX_READ: VBOXVMM_INSTR_DRX_READ(pVCpu, pCtx, (uint8_t)uEventArg); break;
11867 case DBGFEVENT_INSTR_DRX_WRITE: VBOXVMM_INSTR_DRX_WRITE(pVCpu, pCtx, (uint8_t)uEventArg); break;
11868 case DBGFEVENT_INSTR_RDMSR: VBOXVMM_INSTR_RDMSR(pVCpu, pCtx, pCtx->ecx); break;
11869 case DBGFEVENT_INSTR_WRMSR: VBOXVMM_INSTR_WRMSR(pVCpu, pCtx, pCtx->ecx,
11870 RT_MAKE_U64(pCtx->eax, pCtx->edx)); break;
11871 case DBGFEVENT_INSTR_MWAIT: VBOXVMM_INSTR_MWAIT(pVCpu, pCtx); break;
11872 case DBGFEVENT_INSTR_MONITOR: VBOXVMM_INSTR_MONITOR(pVCpu, pCtx); break;
11873 case DBGFEVENT_INSTR_PAUSE: VBOXVMM_INSTR_PAUSE(pVCpu, pCtx); break;
11874 case DBGFEVENT_INSTR_SGDT: VBOXVMM_INSTR_SGDT(pVCpu, pCtx); break;
11875 case DBGFEVENT_INSTR_SIDT: VBOXVMM_INSTR_SIDT(pVCpu, pCtx); break;
11876 case DBGFEVENT_INSTR_LGDT: VBOXVMM_INSTR_LGDT(pVCpu, pCtx); break;
11877 case DBGFEVENT_INSTR_LIDT: VBOXVMM_INSTR_LIDT(pVCpu, pCtx); break;
11878 case DBGFEVENT_INSTR_SLDT: VBOXVMM_INSTR_SLDT(pVCpu, pCtx); break;
11879 case DBGFEVENT_INSTR_STR: VBOXVMM_INSTR_STR(pVCpu, pCtx); break;
11880 case DBGFEVENT_INSTR_LLDT: VBOXVMM_INSTR_LLDT(pVCpu, pCtx); break;
11881 case DBGFEVENT_INSTR_LTR: VBOXVMM_INSTR_LTR(pVCpu, pCtx); break;
11882 case DBGFEVENT_INSTR_RDTSCP: VBOXVMM_INSTR_RDTSCP(pVCpu, pCtx); break;
11883 case DBGFEVENT_INSTR_WBINVD: VBOXVMM_INSTR_WBINVD(pVCpu, pCtx); break;
11884 case DBGFEVENT_INSTR_XSETBV: VBOXVMM_INSTR_XSETBV(pVCpu, pCtx); break;
11885 case DBGFEVENT_INSTR_RDRAND: VBOXVMM_INSTR_RDRAND(pVCpu, pCtx); break;
11886 case DBGFEVENT_INSTR_RDSEED: VBOXVMM_INSTR_RDSEED(pVCpu, pCtx); break;
11887 case DBGFEVENT_INSTR_XSAVES: VBOXVMM_INSTR_XSAVES(pVCpu, pCtx); break;
11888 case DBGFEVENT_INSTR_XRSTORS: VBOXVMM_INSTR_XRSTORS(pVCpu, pCtx); break;
11889 case DBGFEVENT_INSTR_VMM_CALL: VBOXVMM_INSTR_VMM_CALL(pVCpu, pCtx); break;
11890 case DBGFEVENT_INSTR_VMX_VMCLEAR: VBOXVMM_INSTR_VMX_VMCLEAR(pVCpu, pCtx); break;
11891 case DBGFEVENT_INSTR_VMX_VMLAUNCH: VBOXVMM_INSTR_VMX_VMLAUNCH(pVCpu, pCtx); break;
11892 case DBGFEVENT_INSTR_VMX_VMPTRLD: VBOXVMM_INSTR_VMX_VMPTRLD(pVCpu, pCtx); break;
11893 case DBGFEVENT_INSTR_VMX_VMPTRST: VBOXVMM_INSTR_VMX_VMPTRST(pVCpu, pCtx); break;
11894 case DBGFEVENT_INSTR_VMX_VMREAD: VBOXVMM_INSTR_VMX_VMREAD(pVCpu, pCtx); break;
11895 case DBGFEVENT_INSTR_VMX_VMRESUME: VBOXVMM_INSTR_VMX_VMRESUME(pVCpu, pCtx); break;
11896 case DBGFEVENT_INSTR_VMX_VMWRITE: VBOXVMM_INSTR_VMX_VMWRITE(pVCpu, pCtx); break;
11897 case DBGFEVENT_INSTR_VMX_VMXOFF: VBOXVMM_INSTR_VMX_VMXOFF(pVCpu, pCtx); break;
11898 case DBGFEVENT_INSTR_VMX_VMXON: VBOXVMM_INSTR_VMX_VMXON(pVCpu, pCtx); break;
11899 case DBGFEVENT_INSTR_VMX_INVEPT: VBOXVMM_INSTR_VMX_INVEPT(pVCpu, pCtx); break;
11900 case DBGFEVENT_INSTR_VMX_INVVPID: VBOXVMM_INSTR_VMX_INVVPID(pVCpu, pCtx); break;
11901 case DBGFEVENT_INSTR_VMX_INVPCID: VBOXVMM_INSTR_VMX_INVPCID(pVCpu, pCtx); break;
11902 case DBGFEVENT_INSTR_VMX_VMFUNC: VBOXVMM_INSTR_VMX_VMFUNC(pVCpu, pCtx); break;
11903 default: AssertMsgFailed(("enmEvent1=%d uExitReason=%d\n", enmEvent1, uExitReason)); break;
11904 }
11905 switch (enmEvent2)
11906 {
11907 /** @todo consider which extra parameters would be helpful for each probe. */
11908 case DBGFEVENT_END: break;
11909 case DBGFEVENT_EXIT_TASK_SWITCH: VBOXVMM_EXIT_TASK_SWITCH(pVCpu, pCtx); break;
11910 case DBGFEVENT_EXIT_CPUID: VBOXVMM_EXIT_CPUID(pVCpu, pCtx, pCtx->eax, pCtx->ecx); break;
11911 case DBGFEVENT_EXIT_GETSEC: VBOXVMM_EXIT_GETSEC(pVCpu, pCtx); break;
11912 case DBGFEVENT_EXIT_HALT: VBOXVMM_EXIT_HALT(pVCpu, pCtx); break;
11913 case DBGFEVENT_EXIT_INVD: VBOXVMM_EXIT_INVD(pVCpu, pCtx); break;
11914 case DBGFEVENT_EXIT_INVLPG: VBOXVMM_EXIT_INVLPG(pVCpu, pCtx); break;
11915 case DBGFEVENT_EXIT_RDPMC: VBOXVMM_EXIT_RDPMC(pVCpu, pCtx); break;
11916 case DBGFEVENT_EXIT_RDTSC: VBOXVMM_EXIT_RDTSC(pVCpu, pCtx); break;
11917 case DBGFEVENT_EXIT_RSM: VBOXVMM_EXIT_RSM(pVCpu, pCtx); break;
11918 case DBGFEVENT_EXIT_CRX_READ: VBOXVMM_EXIT_CRX_READ(pVCpu, pCtx, (uint8_t)uEventArg); break;
11919 case DBGFEVENT_EXIT_CRX_WRITE: VBOXVMM_EXIT_CRX_WRITE(pVCpu, pCtx, (uint8_t)uEventArg); break;
11920 case DBGFEVENT_EXIT_DRX_READ: VBOXVMM_EXIT_DRX_READ(pVCpu, pCtx, (uint8_t)uEventArg); break;
11921 case DBGFEVENT_EXIT_DRX_WRITE: VBOXVMM_EXIT_DRX_WRITE(pVCpu, pCtx, (uint8_t)uEventArg); break;
11922 case DBGFEVENT_EXIT_RDMSR: VBOXVMM_EXIT_RDMSR(pVCpu, pCtx, pCtx->ecx); break;
11923 case DBGFEVENT_EXIT_WRMSR: VBOXVMM_EXIT_WRMSR(pVCpu, pCtx, pCtx->ecx,
11924 RT_MAKE_U64(pCtx->eax, pCtx->edx)); break;
11925 case DBGFEVENT_EXIT_MWAIT: VBOXVMM_EXIT_MWAIT(pVCpu, pCtx); break;
11926 case DBGFEVENT_EXIT_MONITOR: VBOXVMM_EXIT_MONITOR(pVCpu, pCtx); break;
11927 case DBGFEVENT_EXIT_PAUSE: VBOXVMM_EXIT_PAUSE(pVCpu, pCtx); break;
11928 case DBGFEVENT_EXIT_SGDT: VBOXVMM_EXIT_SGDT(pVCpu, pCtx); break;
11929 case DBGFEVENT_EXIT_SIDT: VBOXVMM_EXIT_SIDT(pVCpu, pCtx); break;
11930 case DBGFEVENT_EXIT_LGDT: VBOXVMM_EXIT_LGDT(pVCpu, pCtx); break;
11931 case DBGFEVENT_EXIT_LIDT: VBOXVMM_EXIT_LIDT(pVCpu, pCtx); break;
11932 case DBGFEVENT_EXIT_SLDT: VBOXVMM_EXIT_SLDT(pVCpu, pCtx); break;
11933 case DBGFEVENT_EXIT_STR: VBOXVMM_EXIT_STR(pVCpu, pCtx); break;
11934 case DBGFEVENT_EXIT_LLDT: VBOXVMM_EXIT_LLDT(pVCpu, pCtx); break;
11935 case DBGFEVENT_EXIT_LTR: VBOXVMM_EXIT_LTR(pVCpu, pCtx); break;
11936 case DBGFEVENT_EXIT_RDTSCP: VBOXVMM_EXIT_RDTSCP(pVCpu, pCtx); break;
11937 case DBGFEVENT_EXIT_WBINVD: VBOXVMM_EXIT_WBINVD(pVCpu, pCtx); break;
11938 case DBGFEVENT_EXIT_XSETBV: VBOXVMM_EXIT_XSETBV(pVCpu, pCtx); break;
11939 case DBGFEVENT_EXIT_RDRAND: VBOXVMM_EXIT_RDRAND(pVCpu, pCtx); break;
11940 case DBGFEVENT_EXIT_RDSEED: VBOXVMM_EXIT_RDSEED(pVCpu, pCtx); break;
11941 case DBGFEVENT_EXIT_XSAVES: VBOXVMM_EXIT_XSAVES(pVCpu, pCtx); break;
11942 case DBGFEVENT_EXIT_XRSTORS: VBOXVMM_EXIT_XRSTORS(pVCpu, pCtx); break;
11943 case DBGFEVENT_EXIT_VMM_CALL: VBOXVMM_EXIT_VMM_CALL(pVCpu, pCtx); break;
11944 case DBGFEVENT_EXIT_VMX_VMCLEAR: VBOXVMM_EXIT_VMX_VMCLEAR(pVCpu, pCtx); break;
11945 case DBGFEVENT_EXIT_VMX_VMLAUNCH: VBOXVMM_EXIT_VMX_VMLAUNCH(pVCpu, pCtx); break;
11946 case DBGFEVENT_EXIT_VMX_VMPTRLD: VBOXVMM_EXIT_VMX_VMPTRLD(pVCpu, pCtx); break;
11947 case DBGFEVENT_EXIT_VMX_VMPTRST: VBOXVMM_EXIT_VMX_VMPTRST(pVCpu, pCtx); break;
11948 case DBGFEVENT_EXIT_VMX_VMREAD: VBOXVMM_EXIT_VMX_VMREAD(pVCpu, pCtx); break;
11949 case DBGFEVENT_EXIT_VMX_VMRESUME: VBOXVMM_EXIT_VMX_VMRESUME(pVCpu, pCtx); break;
11950 case DBGFEVENT_EXIT_VMX_VMWRITE: VBOXVMM_EXIT_VMX_VMWRITE(pVCpu, pCtx); break;
11951 case DBGFEVENT_EXIT_VMX_VMXOFF: VBOXVMM_EXIT_VMX_VMXOFF(pVCpu, pCtx); break;
11952 case DBGFEVENT_EXIT_VMX_VMXON: VBOXVMM_EXIT_VMX_VMXON(pVCpu, pCtx); break;
11953 case DBGFEVENT_EXIT_VMX_INVEPT: VBOXVMM_EXIT_VMX_INVEPT(pVCpu, pCtx); break;
11954 case DBGFEVENT_EXIT_VMX_INVVPID: VBOXVMM_EXIT_VMX_INVVPID(pVCpu, pCtx); break;
11955 case DBGFEVENT_EXIT_VMX_INVPCID: VBOXVMM_EXIT_VMX_INVPCID(pVCpu, pCtx); break;
11956 case DBGFEVENT_EXIT_VMX_VMFUNC: VBOXVMM_EXIT_VMX_VMFUNC(pVCpu, pCtx); break;
11957 case DBGFEVENT_EXIT_VMX_EPT_MISCONFIG: VBOXVMM_EXIT_VMX_EPT_MISCONFIG(pVCpu, pCtx); break;
11958 case DBGFEVENT_EXIT_VMX_EPT_VIOLATION: VBOXVMM_EXIT_VMX_EPT_VIOLATION(pVCpu, pCtx); break;
11959 case DBGFEVENT_EXIT_VMX_VAPIC_ACCESS: VBOXVMM_EXIT_VMX_VAPIC_ACCESS(pVCpu, pCtx); break;
11960 case DBGFEVENT_EXIT_VMX_VAPIC_WRITE: VBOXVMM_EXIT_VMX_VAPIC_WRITE(pVCpu, pCtx); break;
11961 default: AssertMsgFailed(("enmEvent2=%d uExitReason=%d\n", enmEvent2, uExitReason)); break;
11962 }
11963 }
11964
11965 /*
11966 * Fire of the DBGF event, if enabled (our check here is just a quick one,
11967 * the DBGF call will do a full check).
11968 *
11969 * Note! DBGF sets DBGFEVENT_INTERRUPT_SOFTWARE in the bitmap.
11970 * Note! If we have to events, we prioritize the first, i.e. the instruction
11971 * one, in order to avoid event nesting.
11972 */
11973 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
11974 if ( enmEvent1 != DBGFEVENT_END
11975 && DBGF_IS_EVENT_ENABLED(pVM, enmEvent1))
11976 {
11977 hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, CPUMCTX_EXTRN_CS | CPUMCTX_EXTRN_RIP);
11978 VBOXSTRICTRC rcStrict = DBGFEventGenericWithArgs(pVM, pVCpu, enmEvent1, DBGFEVENTCTX_HM, 1, uEventArg);
11979 if (rcStrict != VINF_SUCCESS)
11980 return rcStrict;
11981 }
11982 else if ( enmEvent2 != DBGFEVENT_END
11983 && DBGF_IS_EVENT_ENABLED(pVM, enmEvent2))
11984 {
11985 hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, CPUMCTX_EXTRN_CS | CPUMCTX_EXTRN_RIP);
11986 VBOXSTRICTRC rcStrict = DBGFEventGenericWithArgs(pVM, pVCpu, enmEvent2, DBGFEVENTCTX_HM, 1, uEventArg);
11987 if (rcStrict != VINF_SUCCESS)
11988 return rcStrict;
11989 }
11990
11991 return VINF_SUCCESS;
11992}
11993
11994
11995/**
11996 * Single-stepping VM-exit filtering.
11997 *
11998 * This is preprocessing the VM-exits and deciding whether we've gotten far
11999 * enough to return VINF_EM_DBG_STEPPED already. If not, normal VM-exit
12000 * handling is performed.
12001 *
12002 * @returns Strict VBox status code (i.e. informational status codes too).
12003 * @param pVCpu The cross context virtual CPU structure of the calling EMT.
12004 * @param pVmxTransient The VMX-transient structure.
12005 * @param pDbgState The debug state.
12006 */
12007DECLINLINE(VBOXSTRICTRC) hmR0VmxRunDebugHandleExit(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient, PVMXRUNDBGSTATE pDbgState)
12008{
12009 /*
12010 * Expensive (saves context) generic dtrace VM-exit probe.
12011 */
12012 uint32_t const uExitReason = pVmxTransient->uExitReason;
12013 if (!VBOXVMM_R0_HMVMX_VMEXIT_ENABLED())
12014 { /* more likely */ }
12015 else
12016 {
12017 hmR0VmxReadExitQualVmcs(pVmxTransient);
12018 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, HMVMX_CPUMCTX_EXTRN_ALL);
12019 AssertRC(rc);
12020 VBOXVMM_R0_HMVMX_VMEXIT(pVCpu, &pVCpu->cpum.GstCtx, pVmxTransient->uExitReason, pVmxTransient->uExitQual);
12021 }
12022
12023 /*
12024 * Check for host NMI, just to get that out of the way.
12025 */
12026 if (uExitReason != VMX_EXIT_XCPT_OR_NMI)
12027 { /* normally likely */ }
12028 else
12029 {
12030 hmR0VmxReadExitIntInfoVmcs(pVmxTransient);
12031 uint32_t const uIntType = VMX_EXIT_INT_INFO_TYPE(pVmxTransient->uExitIntInfo);
12032 if (uIntType == VMX_EXIT_INT_INFO_TYPE_NMI)
12033 return hmR0VmxExitHostNmi(pVCpu, pVmxTransient->pVmcsInfo);
12034 }
12035
12036 /*
12037 * Check for single stepping event if we're stepping.
12038 */
12039 if (pVCpu->hm.s.fSingleInstruction)
12040 {
12041 switch (uExitReason)
12042 {
12043 case VMX_EXIT_MTF:
12044 return hmR0VmxExitMtf(pVCpu, pVmxTransient);
12045
12046 /* Various events: */
12047 case VMX_EXIT_XCPT_OR_NMI:
12048 case VMX_EXIT_EXT_INT:
12049 case VMX_EXIT_TRIPLE_FAULT:
12050 case VMX_EXIT_INT_WINDOW:
12051 case VMX_EXIT_NMI_WINDOW:
12052 case VMX_EXIT_TASK_SWITCH:
12053 case VMX_EXIT_TPR_BELOW_THRESHOLD:
12054 case VMX_EXIT_APIC_ACCESS:
12055 case VMX_EXIT_EPT_VIOLATION:
12056 case VMX_EXIT_EPT_MISCONFIG:
12057 case VMX_EXIT_PREEMPT_TIMER:
12058
12059 /* Instruction specific VM-exits: */
12060 case VMX_EXIT_CPUID:
12061 case VMX_EXIT_GETSEC:
12062 case VMX_EXIT_HLT:
12063 case VMX_EXIT_INVD:
12064 case VMX_EXIT_INVLPG:
12065 case VMX_EXIT_RDPMC:
12066 case VMX_EXIT_RDTSC:
12067 case VMX_EXIT_RSM:
12068 case VMX_EXIT_VMCALL:
12069 case VMX_EXIT_VMCLEAR:
12070 case VMX_EXIT_VMLAUNCH:
12071 case VMX_EXIT_VMPTRLD:
12072 case VMX_EXIT_VMPTRST:
12073 case VMX_EXIT_VMREAD:
12074 case VMX_EXIT_VMRESUME:
12075 case VMX_EXIT_VMWRITE:
12076 case VMX_EXIT_VMXOFF:
12077 case VMX_EXIT_VMXON:
12078 case VMX_EXIT_MOV_CRX:
12079 case VMX_EXIT_MOV_DRX:
12080 case VMX_EXIT_IO_INSTR:
12081 case VMX_EXIT_RDMSR:
12082 case VMX_EXIT_WRMSR:
12083 case VMX_EXIT_MWAIT:
12084 case VMX_EXIT_MONITOR:
12085 case VMX_EXIT_PAUSE:
12086 case VMX_EXIT_GDTR_IDTR_ACCESS:
12087 case VMX_EXIT_LDTR_TR_ACCESS:
12088 case VMX_EXIT_INVEPT:
12089 case VMX_EXIT_RDTSCP:
12090 case VMX_EXIT_INVVPID:
12091 case VMX_EXIT_WBINVD:
12092 case VMX_EXIT_XSETBV:
12093 case VMX_EXIT_RDRAND:
12094 case VMX_EXIT_INVPCID:
12095 case VMX_EXIT_VMFUNC:
12096 case VMX_EXIT_RDSEED:
12097 case VMX_EXIT_XSAVES:
12098 case VMX_EXIT_XRSTORS:
12099 {
12100 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, CPUMCTX_EXTRN_CS | CPUMCTX_EXTRN_RIP);
12101 AssertRCReturn(rc, rc);
12102 if ( pVCpu->cpum.GstCtx.rip != pDbgState->uRipStart
12103 || pVCpu->cpum.GstCtx.cs.Sel != pDbgState->uCsStart)
12104 return VINF_EM_DBG_STEPPED;
12105 break;
12106 }
12107
12108 /* Errors and unexpected events: */
12109 case VMX_EXIT_INIT_SIGNAL:
12110 case VMX_EXIT_SIPI:
12111 case VMX_EXIT_IO_SMI:
12112 case VMX_EXIT_SMI:
12113 case VMX_EXIT_ERR_INVALID_GUEST_STATE:
12114 case VMX_EXIT_ERR_MSR_LOAD:
12115 case VMX_EXIT_ERR_MACHINE_CHECK:
12116 case VMX_EXIT_PML_FULL:
12117 case VMX_EXIT_VIRTUALIZED_EOI:
12118 case VMX_EXIT_APIC_WRITE: /* Some talk about this being fault like, so I guess we must process it? */
12119 break;
12120
12121 default:
12122 AssertMsgFailed(("Unexpected VM-exit=%#x\n", uExitReason));
12123 break;
12124 }
12125 }
12126
12127 /*
12128 * Check for debugger event breakpoints and dtrace probes.
12129 */
12130 if ( uExitReason < RT_ELEMENTS(pDbgState->bmExitsToCheck) * 32U
12131 && ASMBitTest(pDbgState->bmExitsToCheck, uExitReason) )
12132 {
12133 VBOXSTRICTRC rcStrict = hmR0VmxHandleExitDtraceEvents(pVCpu, pVmxTransient, uExitReason);
12134 if (rcStrict != VINF_SUCCESS)
12135 return rcStrict;
12136 }
12137
12138 /*
12139 * Normal processing.
12140 */
12141#ifdef HMVMX_USE_FUNCTION_TABLE
12142 return g_apfnVMExitHandlers[uExitReason](pVCpu, pVmxTransient);
12143#else
12144 return hmR0VmxHandleExit(pVCpu, pVmxTransient, uExitReason);
12145#endif
12146}
12147
12148
12149/**
12150 * Single steps guest code using hardware-assisted VMX.
12151 *
12152 * This is -not- the same as the guest single-stepping itself (say using EFLAGS.TF)
12153 * but single-stepping through the hypervisor debugger.
12154 *
12155 * @returns Strict VBox status code (i.e. informational status codes too).
12156 * @param pVCpu The cross context virtual CPU structure.
12157 * @param pcLoops Pointer to the number of executed loops.
12158 *
12159 * @note Mostly the same as hmR0VmxRunGuestCodeNormal().
12160 */
12161static VBOXSTRICTRC hmR0VmxRunGuestCodeDebug(PVMCPUCC pVCpu, uint32_t *pcLoops)
12162{
12163 uint32_t const cMaxResumeLoops = pVCpu->CTX_SUFF(pVM)->hm.s.cMaxResumeLoops;
12164 Assert(pcLoops);
12165 Assert(*pcLoops <= cMaxResumeLoops);
12166
12167 VMXTRANSIENT VmxTransient;
12168 RT_ZERO(VmxTransient);
12169 VmxTransient.pVmcsInfo = hmGetVmxActiveVmcsInfo(pVCpu);
12170
12171 /* Set HMCPU indicators. */
12172 bool const fSavedSingleInstruction = pVCpu->hm.s.fSingleInstruction;
12173 pVCpu->hm.s.fSingleInstruction = pVCpu->hm.s.fSingleInstruction || DBGFIsStepping(pVCpu);
12174 pVCpu->hm.s.fDebugWantRdTscExit = false;
12175 pVCpu->hm.s.fUsingDebugLoop = true;
12176
12177 /* State we keep to help modify and later restore the VMCS fields we alter, and for detecting steps. */
12178 VMXRUNDBGSTATE DbgState;
12179 hmR0VmxRunDebugStateInit(pVCpu, &VmxTransient, &DbgState);
12180 hmR0VmxPreRunGuestDebugStateUpdate(pVCpu, &VmxTransient, &DbgState);
12181
12182 /*
12183 * The loop.
12184 */
12185 VBOXSTRICTRC rcStrict = VERR_INTERNAL_ERROR_5;
12186 for (;;)
12187 {
12188 Assert(!HMR0SuspendPending());
12189 HMVMX_ASSERT_CPU_SAFE(pVCpu);
12190 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatEntry, x);
12191 bool fStepping = pVCpu->hm.s.fSingleInstruction;
12192
12193 /* Set up VM-execution controls the next two can respond to. */
12194 hmR0VmxPreRunGuestDebugStateApply(pVCpu, &VmxTransient, &DbgState);
12195
12196 /*
12197 * Preparatory work for running guest code, this may force us to
12198 * return to ring-3.
12199 *
12200 * Warning! This bugger disables interrupts on VINF_SUCCESS!
12201 */
12202 rcStrict = hmR0VmxPreRunGuest(pVCpu, &VmxTransient, fStepping);
12203 if (rcStrict != VINF_SUCCESS)
12204 break;
12205
12206 /* Interrupts are disabled at this point! */
12207 hmR0VmxPreRunGuestCommitted(pVCpu, &VmxTransient);
12208
12209 /* Override any obnoxious code in the above two calls. */
12210 hmR0VmxPreRunGuestDebugStateApply(pVCpu, &VmxTransient, &DbgState);
12211
12212 /*
12213 * Finally execute the guest.
12214 */
12215 int rcRun = hmR0VmxRunGuest(pVCpu, &VmxTransient);
12216
12217 hmR0VmxPostRunGuest(pVCpu, &VmxTransient, rcRun);
12218 /* Interrupts are re-enabled at this point! */
12219
12220 /* Check for errors with running the VM (VMLAUNCH/VMRESUME). */
12221 if (RT_SUCCESS(rcRun))
12222 { /* very likely */ }
12223 else
12224 {
12225 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatPreExit, x);
12226 hmR0VmxReportWorldSwitchError(pVCpu, rcRun, &VmxTransient);
12227 return rcRun;
12228 }
12229
12230 /* Profile the VM-exit. */
12231 AssertMsg(VmxTransient.uExitReason <= VMX_EXIT_MAX, ("%#x\n", VmxTransient.uExitReason));
12232 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitAll);
12233 STAM_COUNTER_INC(&pVCpu->hm.s.paStatExitReasonR0[VmxTransient.uExitReason & MASK_EXITREASON_STAT]);
12234 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatPreExit, &pVCpu->hm.s.StatExitHandling, x);
12235 HMVMX_START_EXIT_DISPATCH_PROF();
12236
12237 VBOXVMM_R0_HMVMX_VMEXIT_NOCTX(pVCpu, &pVCpu->cpum.GstCtx, VmxTransient.uExitReason);
12238
12239 /*
12240 * Handle the VM-exit - we quit earlier on certain VM-exits, see hmR0VmxHandleExitDebug().
12241 */
12242 rcStrict = hmR0VmxRunDebugHandleExit(pVCpu, &VmxTransient, &DbgState);
12243 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExitHandling, x);
12244 if (rcStrict != VINF_SUCCESS)
12245 break;
12246 if (++(*pcLoops) > cMaxResumeLoops)
12247 {
12248 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchMaxResumeLoops);
12249 rcStrict = VINF_EM_RAW_INTERRUPT;
12250 break;
12251 }
12252
12253 /*
12254 * Stepping: Did the RIP change, if so, consider it a single step.
12255 * Otherwise, make sure one of the TFs gets set.
12256 */
12257 if (fStepping)
12258 {
12259 int rc = hmR0VmxImportGuestState(pVCpu, VmxTransient.pVmcsInfo, CPUMCTX_EXTRN_CS | CPUMCTX_EXTRN_RIP);
12260 AssertRC(rc);
12261 if ( pVCpu->cpum.GstCtx.rip != DbgState.uRipStart
12262 || pVCpu->cpum.GstCtx.cs.Sel != DbgState.uCsStart)
12263 {
12264 rcStrict = VINF_EM_DBG_STEPPED;
12265 break;
12266 }
12267 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_DR7);
12268 }
12269
12270 /*
12271 * Update when dtrace settings changes (DBGF kicks us, so no need to check).
12272 */
12273 if (VBOXVMM_GET_SETTINGS_SEQ_NO() != DbgState.uDtraceSettingsSeqNo)
12274 hmR0VmxPreRunGuestDebugStateUpdate(pVCpu, &VmxTransient, &DbgState);
12275 }
12276
12277 /*
12278 * Clear the X86_EFL_TF if necessary.
12279 */
12280 if (pVCpu->hm.s.fClearTrapFlag)
12281 {
12282 int rc = hmR0VmxImportGuestState(pVCpu, VmxTransient.pVmcsInfo, CPUMCTX_EXTRN_RFLAGS);
12283 AssertRC(rc);
12284 pVCpu->hm.s.fClearTrapFlag = false;
12285 pVCpu->cpum.GstCtx.eflags.Bits.u1TF = 0;
12286 }
12287 /** @todo there seems to be issues with the resume flag when the monitor trap
12288 * flag is pending without being used. Seen early in bios init when
12289 * accessing APIC page in protected mode. */
12290
12291 /*
12292 * Restore VM-exit control settings as we may not re-enter this function the
12293 * next time around.
12294 */
12295 rcStrict = hmR0VmxRunDebugStateRevert(pVCpu, &VmxTransient, &DbgState, rcStrict);
12296
12297 /* Restore HMCPU indicators. */
12298 pVCpu->hm.s.fUsingDebugLoop = false;
12299 pVCpu->hm.s.fDebugWantRdTscExit = false;
12300 pVCpu->hm.s.fSingleInstruction = fSavedSingleInstruction;
12301
12302 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatEntry, x);
12303 return rcStrict;
12304}
12305
12306
12307/** @} */
12308
12309
12310/**
12311 * Checks if any expensive dtrace probes are enabled and we should go to the
12312 * debug loop.
12313 *
12314 * @returns true if we should use debug loop, false if not.
12315 */
12316static bool hmR0VmxAnyExpensiveProbesEnabled(void)
12317{
12318 /* It's probably faster to OR the raw 32-bit counter variables together.
12319 Since the variables are in an array and the probes are next to one
12320 another (more or less), we have good locality. So, better read
12321 eight-nine cache lines ever time and only have one conditional, than
12322 128+ conditionals, right? */
12323 return ( VBOXVMM_R0_HMVMX_VMEXIT_ENABLED_RAW() /* expensive too due to context */
12324 | VBOXVMM_XCPT_DE_ENABLED_RAW()
12325 | VBOXVMM_XCPT_DB_ENABLED_RAW()
12326 | VBOXVMM_XCPT_BP_ENABLED_RAW()
12327 | VBOXVMM_XCPT_OF_ENABLED_RAW()
12328 | VBOXVMM_XCPT_BR_ENABLED_RAW()
12329 | VBOXVMM_XCPT_UD_ENABLED_RAW()
12330 | VBOXVMM_XCPT_NM_ENABLED_RAW()
12331 | VBOXVMM_XCPT_DF_ENABLED_RAW()
12332 | VBOXVMM_XCPT_TS_ENABLED_RAW()
12333 | VBOXVMM_XCPT_NP_ENABLED_RAW()
12334 | VBOXVMM_XCPT_SS_ENABLED_RAW()
12335 | VBOXVMM_XCPT_GP_ENABLED_RAW()
12336 | VBOXVMM_XCPT_PF_ENABLED_RAW()
12337 | VBOXVMM_XCPT_MF_ENABLED_RAW()
12338 | VBOXVMM_XCPT_AC_ENABLED_RAW()
12339 | VBOXVMM_XCPT_XF_ENABLED_RAW()
12340 | VBOXVMM_XCPT_VE_ENABLED_RAW()
12341 | VBOXVMM_XCPT_SX_ENABLED_RAW()
12342 | VBOXVMM_INT_SOFTWARE_ENABLED_RAW()
12343 | VBOXVMM_INT_HARDWARE_ENABLED_RAW()
12344 ) != 0
12345 || ( VBOXVMM_INSTR_HALT_ENABLED_RAW()
12346 | VBOXVMM_INSTR_MWAIT_ENABLED_RAW()
12347 | VBOXVMM_INSTR_MONITOR_ENABLED_RAW()
12348 | VBOXVMM_INSTR_CPUID_ENABLED_RAW()
12349 | VBOXVMM_INSTR_INVD_ENABLED_RAW()
12350 | VBOXVMM_INSTR_WBINVD_ENABLED_RAW()
12351 | VBOXVMM_INSTR_INVLPG_ENABLED_RAW()
12352 | VBOXVMM_INSTR_RDTSC_ENABLED_RAW()
12353 | VBOXVMM_INSTR_RDTSCP_ENABLED_RAW()
12354 | VBOXVMM_INSTR_RDPMC_ENABLED_RAW()
12355 | VBOXVMM_INSTR_RDMSR_ENABLED_RAW()
12356 | VBOXVMM_INSTR_WRMSR_ENABLED_RAW()
12357 | VBOXVMM_INSTR_CRX_READ_ENABLED_RAW()
12358 | VBOXVMM_INSTR_CRX_WRITE_ENABLED_RAW()
12359 | VBOXVMM_INSTR_DRX_READ_ENABLED_RAW()
12360 | VBOXVMM_INSTR_DRX_WRITE_ENABLED_RAW()
12361 | VBOXVMM_INSTR_PAUSE_ENABLED_RAW()
12362 | VBOXVMM_INSTR_XSETBV_ENABLED_RAW()
12363 | VBOXVMM_INSTR_SIDT_ENABLED_RAW()
12364 | VBOXVMM_INSTR_LIDT_ENABLED_RAW()
12365 | VBOXVMM_INSTR_SGDT_ENABLED_RAW()
12366 | VBOXVMM_INSTR_LGDT_ENABLED_RAW()
12367 | VBOXVMM_INSTR_SLDT_ENABLED_RAW()
12368 | VBOXVMM_INSTR_LLDT_ENABLED_RAW()
12369 | VBOXVMM_INSTR_STR_ENABLED_RAW()
12370 | VBOXVMM_INSTR_LTR_ENABLED_RAW()
12371 | VBOXVMM_INSTR_GETSEC_ENABLED_RAW()
12372 | VBOXVMM_INSTR_RSM_ENABLED_RAW()
12373 | VBOXVMM_INSTR_RDRAND_ENABLED_RAW()
12374 | VBOXVMM_INSTR_RDSEED_ENABLED_RAW()
12375 | VBOXVMM_INSTR_XSAVES_ENABLED_RAW()
12376 | VBOXVMM_INSTR_XRSTORS_ENABLED_RAW()
12377 | VBOXVMM_INSTR_VMM_CALL_ENABLED_RAW()
12378 | VBOXVMM_INSTR_VMX_VMCLEAR_ENABLED_RAW()
12379 | VBOXVMM_INSTR_VMX_VMLAUNCH_ENABLED_RAW()
12380 | VBOXVMM_INSTR_VMX_VMPTRLD_ENABLED_RAW()
12381 | VBOXVMM_INSTR_VMX_VMPTRST_ENABLED_RAW()
12382 | VBOXVMM_INSTR_VMX_VMREAD_ENABLED_RAW()
12383 | VBOXVMM_INSTR_VMX_VMRESUME_ENABLED_RAW()
12384 | VBOXVMM_INSTR_VMX_VMWRITE_ENABLED_RAW()
12385 | VBOXVMM_INSTR_VMX_VMXOFF_ENABLED_RAW()
12386 | VBOXVMM_INSTR_VMX_VMXON_ENABLED_RAW()
12387 | VBOXVMM_INSTR_VMX_VMFUNC_ENABLED_RAW()
12388 | VBOXVMM_INSTR_VMX_INVEPT_ENABLED_RAW()
12389 | VBOXVMM_INSTR_VMX_INVVPID_ENABLED_RAW()
12390 | VBOXVMM_INSTR_VMX_INVPCID_ENABLED_RAW()
12391 ) != 0
12392 || ( VBOXVMM_EXIT_TASK_SWITCH_ENABLED_RAW()
12393 | VBOXVMM_EXIT_HALT_ENABLED_RAW()
12394 | VBOXVMM_EXIT_MWAIT_ENABLED_RAW()
12395 | VBOXVMM_EXIT_MONITOR_ENABLED_RAW()
12396 | VBOXVMM_EXIT_CPUID_ENABLED_RAW()
12397 | VBOXVMM_EXIT_INVD_ENABLED_RAW()
12398 | VBOXVMM_EXIT_WBINVD_ENABLED_RAW()
12399 | VBOXVMM_EXIT_INVLPG_ENABLED_RAW()
12400 | VBOXVMM_EXIT_RDTSC_ENABLED_RAW()
12401 | VBOXVMM_EXIT_RDTSCP_ENABLED_RAW()
12402 | VBOXVMM_EXIT_RDPMC_ENABLED_RAW()
12403 | VBOXVMM_EXIT_RDMSR_ENABLED_RAW()
12404 | VBOXVMM_EXIT_WRMSR_ENABLED_RAW()
12405 | VBOXVMM_EXIT_CRX_READ_ENABLED_RAW()
12406 | VBOXVMM_EXIT_CRX_WRITE_ENABLED_RAW()
12407 | VBOXVMM_EXIT_DRX_READ_ENABLED_RAW()
12408 | VBOXVMM_EXIT_DRX_WRITE_ENABLED_RAW()
12409 | VBOXVMM_EXIT_PAUSE_ENABLED_RAW()
12410 | VBOXVMM_EXIT_XSETBV_ENABLED_RAW()
12411 | VBOXVMM_EXIT_SIDT_ENABLED_RAW()
12412 | VBOXVMM_EXIT_LIDT_ENABLED_RAW()
12413 | VBOXVMM_EXIT_SGDT_ENABLED_RAW()
12414 | VBOXVMM_EXIT_LGDT_ENABLED_RAW()
12415 | VBOXVMM_EXIT_SLDT_ENABLED_RAW()
12416 | VBOXVMM_EXIT_LLDT_ENABLED_RAW()
12417 | VBOXVMM_EXIT_STR_ENABLED_RAW()
12418 | VBOXVMM_EXIT_LTR_ENABLED_RAW()
12419 | VBOXVMM_EXIT_GETSEC_ENABLED_RAW()
12420 | VBOXVMM_EXIT_RSM_ENABLED_RAW()
12421 | VBOXVMM_EXIT_RDRAND_ENABLED_RAW()
12422 | VBOXVMM_EXIT_RDSEED_ENABLED_RAW()
12423 | VBOXVMM_EXIT_XSAVES_ENABLED_RAW()
12424 | VBOXVMM_EXIT_XRSTORS_ENABLED_RAW()
12425 | VBOXVMM_EXIT_VMM_CALL_ENABLED_RAW()
12426 | VBOXVMM_EXIT_VMX_VMCLEAR_ENABLED_RAW()
12427 | VBOXVMM_EXIT_VMX_VMLAUNCH_ENABLED_RAW()
12428 | VBOXVMM_EXIT_VMX_VMPTRLD_ENABLED_RAW()
12429 | VBOXVMM_EXIT_VMX_VMPTRST_ENABLED_RAW()
12430 | VBOXVMM_EXIT_VMX_VMREAD_ENABLED_RAW()
12431 | VBOXVMM_EXIT_VMX_VMRESUME_ENABLED_RAW()
12432 | VBOXVMM_EXIT_VMX_VMWRITE_ENABLED_RAW()
12433 | VBOXVMM_EXIT_VMX_VMXOFF_ENABLED_RAW()
12434 | VBOXVMM_EXIT_VMX_VMXON_ENABLED_RAW()
12435 | VBOXVMM_EXIT_VMX_VMFUNC_ENABLED_RAW()
12436 | VBOXVMM_EXIT_VMX_INVEPT_ENABLED_RAW()
12437 | VBOXVMM_EXIT_VMX_INVVPID_ENABLED_RAW()
12438 | VBOXVMM_EXIT_VMX_INVPCID_ENABLED_RAW()
12439 | VBOXVMM_EXIT_VMX_EPT_VIOLATION_ENABLED_RAW()
12440 | VBOXVMM_EXIT_VMX_EPT_MISCONFIG_ENABLED_RAW()
12441 | VBOXVMM_EXIT_VMX_VAPIC_ACCESS_ENABLED_RAW()
12442 | VBOXVMM_EXIT_VMX_VAPIC_WRITE_ENABLED_RAW()
12443 ) != 0;
12444}
12445
12446
12447/**
12448 * Runs the guest using hardware-assisted VMX.
12449 *
12450 * @returns Strict VBox status code (i.e. informational status codes too).
12451 * @param pVCpu The cross context virtual CPU structure.
12452 */
12453VMMR0DECL(VBOXSTRICTRC) VMXR0RunGuestCode(PVMCPUCC pVCpu)
12454{
12455 AssertPtr(pVCpu);
12456 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
12457 Assert(VMMRZCallRing3IsEnabled(pVCpu));
12458 Assert(!ASMAtomicUoReadU64(&pCtx->fExtrn));
12459 HMVMX_ASSERT_PREEMPT_SAFE(pVCpu);
12460
12461 VBOXSTRICTRC rcStrict;
12462 uint32_t cLoops = 0;
12463 for (;;)
12464 {
12465#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
12466 bool const fInNestedGuestMode = CPUMIsGuestInVmxNonRootMode(pCtx);
12467#else
12468 NOREF(pCtx);
12469 bool const fInNestedGuestMode = false;
12470#endif
12471 if (!fInNestedGuestMode)
12472 {
12473 if ( !pVCpu->hm.s.fUseDebugLoop
12474 && (!VBOXVMM_ANY_PROBES_ENABLED() || !hmR0VmxAnyExpensiveProbesEnabled())
12475 && !DBGFIsStepping(pVCpu)
12476 && !pVCpu->CTX_SUFF(pVM)->dbgf.ro.cEnabledInt3Breakpoints)
12477 rcStrict = hmR0VmxRunGuestCodeNormal(pVCpu, &cLoops);
12478 else
12479 rcStrict = hmR0VmxRunGuestCodeDebug(pVCpu, &cLoops);
12480 }
12481#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
12482 else
12483 rcStrict = hmR0VmxRunGuestCodeNested(pVCpu, &cLoops);
12484
12485 if (rcStrict == VINF_VMX_VMLAUNCH_VMRESUME)
12486 {
12487 Assert(CPUMIsGuestInVmxNonRootMode(pCtx));
12488 continue;
12489 }
12490 if (rcStrict == VINF_VMX_VMEXIT)
12491 {
12492 Assert(!CPUMIsGuestInVmxNonRootMode(pCtx));
12493 continue;
12494 }
12495#endif
12496 break;
12497 }
12498
12499 int const rcLoop = VBOXSTRICTRC_VAL(rcStrict);
12500 switch (rcLoop)
12501 {
12502 case VERR_EM_INTERPRETER: rcStrict = VINF_EM_RAW_EMULATE_INSTR; break;
12503 case VINF_EM_RESET: rcStrict = VINF_EM_TRIPLE_FAULT; break;
12504 }
12505
12506 int rc2 = hmR0VmxExitToRing3(pVCpu, rcStrict);
12507 if (RT_FAILURE(rc2))
12508 {
12509 pVCpu->hm.s.u32HMError = (uint32_t)VBOXSTRICTRC_VAL(rcStrict);
12510 rcStrict = rc2;
12511 }
12512 Assert(!ASMAtomicUoReadU64(&pCtx->fExtrn));
12513 Assert(!VMMRZCallRing3IsNotificationSet(pVCpu));
12514 return rcStrict;
12515}
12516
12517
12518#ifndef HMVMX_USE_FUNCTION_TABLE
12519/**
12520 * Handles a guest VM-exit from hardware-assisted VMX execution.
12521 *
12522 * @returns Strict VBox status code (i.e. informational status codes too).
12523 * @param pVCpu The cross context virtual CPU structure.
12524 * @param pVmxTransient The VMX-transient structure.
12525 */
12526DECLINLINE(VBOXSTRICTRC) hmR0VmxHandleExit(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
12527{
12528#ifdef DEBUG_ramshankar
12529# define VMEXIT_CALL_RET(a_fSave, a_CallExpr) \
12530 do { \
12531 if (a_fSave != 0) \
12532 hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, HMVMX_CPUMCTX_EXTRN_ALL); \
12533 VBOXSTRICTRC rcStrict = a_CallExpr; \
12534 if (a_fSave != 0) \
12535 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_ALL_GUEST); \
12536 return rcStrict; \
12537 } while (0)
12538#else
12539# define VMEXIT_CALL_RET(a_fSave, a_CallExpr) return a_CallExpr
12540#endif
12541 uint32_t const uExitReason = pVmxTransient->uExitReason;
12542 switch (uExitReason)
12543 {
12544 case VMX_EXIT_EPT_MISCONFIG: VMEXIT_CALL_RET(0, hmR0VmxExitEptMisconfig(pVCpu, pVmxTransient));
12545 case VMX_EXIT_EPT_VIOLATION: VMEXIT_CALL_RET(0, hmR0VmxExitEptViolation(pVCpu, pVmxTransient));
12546 case VMX_EXIT_IO_INSTR: VMEXIT_CALL_RET(0, hmR0VmxExitIoInstr(pVCpu, pVmxTransient));
12547 case VMX_EXIT_CPUID: VMEXIT_CALL_RET(0, hmR0VmxExitCpuid(pVCpu, pVmxTransient));
12548 case VMX_EXIT_RDTSC: VMEXIT_CALL_RET(0, hmR0VmxExitRdtsc(pVCpu, pVmxTransient));
12549 case VMX_EXIT_RDTSCP: VMEXIT_CALL_RET(0, hmR0VmxExitRdtscp(pVCpu, pVmxTransient));
12550 case VMX_EXIT_APIC_ACCESS: VMEXIT_CALL_RET(0, hmR0VmxExitApicAccess(pVCpu, pVmxTransient));
12551 case VMX_EXIT_XCPT_OR_NMI: VMEXIT_CALL_RET(0, hmR0VmxExitXcptOrNmi(pVCpu, pVmxTransient));
12552 case VMX_EXIT_MOV_CRX: VMEXIT_CALL_RET(0, hmR0VmxExitMovCRx(pVCpu, pVmxTransient));
12553 case VMX_EXIT_EXT_INT: VMEXIT_CALL_RET(0, hmR0VmxExitExtInt(pVCpu, pVmxTransient));
12554 case VMX_EXIT_INT_WINDOW: VMEXIT_CALL_RET(0, hmR0VmxExitIntWindow(pVCpu, pVmxTransient));
12555 case VMX_EXIT_TPR_BELOW_THRESHOLD: VMEXIT_CALL_RET(0, hmR0VmxExitTprBelowThreshold(pVCpu, pVmxTransient));
12556 case VMX_EXIT_MWAIT: VMEXIT_CALL_RET(0, hmR0VmxExitMwait(pVCpu, pVmxTransient));
12557 case VMX_EXIT_MONITOR: VMEXIT_CALL_RET(0, hmR0VmxExitMonitor(pVCpu, pVmxTransient));
12558 case VMX_EXIT_TASK_SWITCH: VMEXIT_CALL_RET(0, hmR0VmxExitTaskSwitch(pVCpu, pVmxTransient));
12559 case VMX_EXIT_PREEMPT_TIMER: VMEXIT_CALL_RET(0, hmR0VmxExitPreemptTimer(pVCpu, pVmxTransient));
12560 case VMX_EXIT_RDMSR: VMEXIT_CALL_RET(0, hmR0VmxExitRdmsr(pVCpu, pVmxTransient));
12561 case VMX_EXIT_WRMSR: VMEXIT_CALL_RET(0, hmR0VmxExitWrmsr(pVCpu, pVmxTransient));
12562 case VMX_EXIT_VMCALL: VMEXIT_CALL_RET(0, hmR0VmxExitVmcall(pVCpu, pVmxTransient));
12563 case VMX_EXIT_MOV_DRX: VMEXIT_CALL_RET(0, hmR0VmxExitMovDRx(pVCpu, pVmxTransient));
12564 case VMX_EXIT_HLT: VMEXIT_CALL_RET(0, hmR0VmxExitHlt(pVCpu, pVmxTransient));
12565 case VMX_EXIT_INVD: VMEXIT_CALL_RET(0, hmR0VmxExitInvd(pVCpu, pVmxTransient));
12566 case VMX_EXIT_INVLPG: VMEXIT_CALL_RET(0, hmR0VmxExitInvlpg(pVCpu, pVmxTransient));
12567 case VMX_EXIT_MTF: VMEXIT_CALL_RET(0, hmR0VmxExitMtf(pVCpu, pVmxTransient));
12568 case VMX_EXIT_PAUSE: VMEXIT_CALL_RET(0, hmR0VmxExitPause(pVCpu, pVmxTransient));
12569 case VMX_EXIT_WBINVD: VMEXIT_CALL_RET(0, hmR0VmxExitWbinvd(pVCpu, pVmxTransient));
12570 case VMX_EXIT_XSETBV: VMEXIT_CALL_RET(0, hmR0VmxExitXsetbv(pVCpu, pVmxTransient));
12571 case VMX_EXIT_INVPCID: VMEXIT_CALL_RET(0, hmR0VmxExitInvpcid(pVCpu, pVmxTransient));
12572 case VMX_EXIT_GETSEC: VMEXIT_CALL_RET(0, hmR0VmxExitGetsec(pVCpu, pVmxTransient));
12573 case VMX_EXIT_RDPMC: VMEXIT_CALL_RET(0, hmR0VmxExitRdpmc(pVCpu, pVmxTransient));
12574#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
12575 case VMX_EXIT_VMCLEAR: VMEXIT_CALL_RET(0, hmR0VmxExitVmclear(pVCpu, pVmxTransient));
12576 case VMX_EXIT_VMLAUNCH: VMEXIT_CALL_RET(0, hmR0VmxExitVmlaunch(pVCpu, pVmxTransient));
12577 case VMX_EXIT_VMPTRLD: VMEXIT_CALL_RET(0, hmR0VmxExitVmptrld(pVCpu, pVmxTransient));
12578 case VMX_EXIT_VMPTRST: VMEXIT_CALL_RET(0, hmR0VmxExitVmptrst(pVCpu, pVmxTransient));
12579 case VMX_EXIT_VMREAD: VMEXIT_CALL_RET(0, hmR0VmxExitVmread(pVCpu, pVmxTransient));
12580 case VMX_EXIT_VMRESUME: VMEXIT_CALL_RET(0, hmR0VmxExitVmwrite(pVCpu, pVmxTransient));
12581 case VMX_EXIT_VMWRITE: VMEXIT_CALL_RET(0, hmR0VmxExitVmresume(pVCpu, pVmxTransient));
12582 case VMX_EXIT_VMXOFF: VMEXIT_CALL_RET(0, hmR0VmxExitVmxoff(pVCpu, pVmxTransient));
12583 case VMX_EXIT_VMXON: VMEXIT_CALL_RET(0, hmR0VmxExitVmxon(pVCpu, pVmxTransient));
12584 case VMX_EXIT_INVVPID: VMEXIT_CALL_RET(0, hmR0VmxExitInvvpid(pVCpu, pVmxTransient));
12585 case VMX_EXIT_INVEPT: VMEXIT_CALL_RET(0, hmR0VmxExitSetPendingXcptUD(pVCpu, pVmxTransient));
12586#else
12587 case VMX_EXIT_VMCLEAR:
12588 case VMX_EXIT_VMLAUNCH:
12589 case VMX_EXIT_VMPTRLD:
12590 case VMX_EXIT_VMPTRST:
12591 case VMX_EXIT_VMREAD:
12592 case VMX_EXIT_VMRESUME:
12593 case VMX_EXIT_VMWRITE:
12594 case VMX_EXIT_VMXOFF:
12595 case VMX_EXIT_VMXON:
12596 case VMX_EXIT_INVVPID:
12597 case VMX_EXIT_INVEPT:
12598 return hmR0VmxExitSetPendingXcptUD(pVCpu, pVmxTransient);
12599#endif
12600
12601 case VMX_EXIT_TRIPLE_FAULT: return hmR0VmxExitTripleFault(pVCpu, pVmxTransient);
12602 case VMX_EXIT_NMI_WINDOW: return hmR0VmxExitNmiWindow(pVCpu, pVmxTransient);
12603 case VMX_EXIT_ERR_INVALID_GUEST_STATE: return hmR0VmxExitErrInvalidGuestState(pVCpu, pVmxTransient);
12604
12605 case VMX_EXIT_INIT_SIGNAL:
12606 case VMX_EXIT_SIPI:
12607 case VMX_EXIT_IO_SMI:
12608 case VMX_EXIT_SMI:
12609 case VMX_EXIT_ERR_MSR_LOAD:
12610 case VMX_EXIT_ERR_MACHINE_CHECK:
12611 case VMX_EXIT_PML_FULL:
12612 case VMX_EXIT_VIRTUALIZED_EOI:
12613 case VMX_EXIT_GDTR_IDTR_ACCESS:
12614 case VMX_EXIT_LDTR_TR_ACCESS:
12615 case VMX_EXIT_APIC_WRITE:
12616 case VMX_EXIT_RDRAND:
12617 case VMX_EXIT_RSM:
12618 case VMX_EXIT_VMFUNC:
12619 case VMX_EXIT_ENCLS:
12620 case VMX_EXIT_RDSEED:
12621 case VMX_EXIT_XSAVES:
12622 case VMX_EXIT_XRSTORS:
12623 case VMX_EXIT_UMWAIT:
12624 case VMX_EXIT_TPAUSE:
12625 default:
12626 return hmR0VmxExitErrUnexpected(pVCpu, pVmxTransient);
12627 }
12628#undef VMEXIT_CALL_RET
12629}
12630#endif /* !HMVMX_USE_FUNCTION_TABLE */
12631
12632
12633#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
12634/**
12635 * Handles a nested-guest VM-exit from hardware-assisted VMX execution.
12636 *
12637 * @returns Strict VBox status code (i.e. informational status codes too).
12638 * @param pVCpu The cross context virtual CPU structure.
12639 * @param pVmxTransient The VMX-transient structure.
12640 */
12641DECLINLINE(VBOXSTRICTRC) hmR0VmxHandleExitNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
12642{
12643 /** @todo NSTVMX: Remove after debugging page-fault issue. */
12644#ifdef DEBUG_ramshankar
12645 hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, HMVMX_CPUMCTX_EXTRN_ALL);
12646 Log4Func(("cs:rip=%#04x:%#RX64 rsp=%#RX64 eflags=%#RX32 cr3=%#RX64\n", pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip,
12647 pVCpu->cpum.GstCtx.rsp, pVCpu->cpum.GstCtx.eflags.u32, pVCpu->cpum.GstCtx.cr3));
12648#endif
12649
12650 uint32_t const uExitReason = pVmxTransient->uExitReason;
12651 switch (uExitReason)
12652 {
12653 case VMX_EXIT_EPT_MISCONFIG: return hmR0VmxExitEptMisconfig(pVCpu, pVmxTransient);
12654 case VMX_EXIT_EPT_VIOLATION: return hmR0VmxExitEptViolation(pVCpu, pVmxTransient);
12655 case VMX_EXIT_XCPT_OR_NMI: return hmR0VmxExitXcptOrNmiNested(pVCpu, pVmxTransient);
12656 case VMX_EXIT_IO_INSTR: return hmR0VmxExitIoInstrNested(pVCpu, pVmxTransient);
12657 case VMX_EXIT_HLT: return hmR0VmxExitHltNested(pVCpu, pVmxTransient);
12658
12659 /*
12660 * We shouldn't direct host physical interrupts to the nested-guest.
12661 */
12662 case VMX_EXIT_EXT_INT:
12663 return hmR0VmxExitExtInt(pVCpu, pVmxTransient);
12664
12665 /*
12666 * Instructions that cause VM-exits unconditionally or the condition is
12667 * always is taken solely from the nested hypervisor (meaning if the VM-exit
12668 * happens, it's guaranteed to be a nested-guest VM-exit).
12669 *
12670 * - Provides VM-exit instruction length ONLY.
12671 */
12672 case VMX_EXIT_CPUID: /* Unconditional. */
12673 case VMX_EXIT_VMCALL:
12674 case VMX_EXIT_GETSEC:
12675 case VMX_EXIT_INVD:
12676 case VMX_EXIT_XSETBV:
12677 case VMX_EXIT_VMLAUNCH:
12678 case VMX_EXIT_VMRESUME:
12679 case VMX_EXIT_VMXOFF:
12680 case VMX_EXIT_ENCLS: /* Condition specified solely by nested hypervisor. */
12681 case VMX_EXIT_VMFUNC:
12682 return hmR0VmxExitInstrNested(pVCpu, pVmxTransient);
12683
12684 /*
12685 * Instructions that cause VM-exits unconditionally or the condition is
12686 * always is taken solely from the nested hypervisor (meaning if the VM-exit
12687 * happens, it's guaranteed to be a nested-guest VM-exit).
12688 *
12689 * - Provides VM-exit instruction length.
12690 * - Provides VM-exit information.
12691 * - Optionally provides Exit qualification.
12692 *
12693 * Since Exit qualification is 0 for all VM-exits where it is not
12694 * applicable, reading and passing it to the guest should produce
12695 * defined behavior.
12696 *
12697 * See Intel spec. 27.2.1 "Basic VM-Exit Information".
12698 */
12699 case VMX_EXIT_INVEPT: /* Unconditional. */
12700 case VMX_EXIT_INVVPID:
12701 case VMX_EXIT_VMCLEAR:
12702 case VMX_EXIT_VMPTRLD:
12703 case VMX_EXIT_VMPTRST:
12704 case VMX_EXIT_VMXON:
12705 case VMX_EXIT_GDTR_IDTR_ACCESS: /* Condition specified solely by nested hypervisor. */
12706 case VMX_EXIT_LDTR_TR_ACCESS:
12707 case VMX_EXIT_RDRAND:
12708 case VMX_EXIT_RDSEED:
12709 case VMX_EXIT_XSAVES:
12710 case VMX_EXIT_XRSTORS:
12711 case VMX_EXIT_UMWAIT:
12712 case VMX_EXIT_TPAUSE:
12713 return hmR0VmxExitInstrWithInfoNested(pVCpu, pVmxTransient);
12714
12715 case VMX_EXIT_RDTSC: return hmR0VmxExitRdtscNested(pVCpu, pVmxTransient);
12716 case VMX_EXIT_RDTSCP: return hmR0VmxExitRdtscpNested(pVCpu, pVmxTransient);
12717 case VMX_EXIT_RDMSR: return hmR0VmxExitRdmsrNested(pVCpu, pVmxTransient);
12718 case VMX_EXIT_WRMSR: return hmR0VmxExitWrmsrNested(pVCpu, pVmxTransient);
12719 case VMX_EXIT_INVLPG: return hmR0VmxExitInvlpgNested(pVCpu, pVmxTransient);
12720 case VMX_EXIT_INVPCID: return hmR0VmxExitInvpcidNested(pVCpu, pVmxTransient);
12721 case VMX_EXIT_TASK_SWITCH: return hmR0VmxExitTaskSwitchNested(pVCpu, pVmxTransient);
12722 case VMX_EXIT_WBINVD: return hmR0VmxExitWbinvdNested(pVCpu, pVmxTransient);
12723 case VMX_EXIT_MTF: return hmR0VmxExitMtfNested(pVCpu, pVmxTransient);
12724 case VMX_EXIT_APIC_ACCESS: return hmR0VmxExitApicAccessNested(pVCpu, pVmxTransient);
12725 case VMX_EXIT_APIC_WRITE: return hmR0VmxExitApicWriteNested(pVCpu, pVmxTransient);
12726 case VMX_EXIT_VIRTUALIZED_EOI: return hmR0VmxExitVirtEoiNested(pVCpu, pVmxTransient);
12727 case VMX_EXIT_MOV_CRX: return hmR0VmxExitMovCRxNested(pVCpu, pVmxTransient);
12728 case VMX_EXIT_INT_WINDOW: return hmR0VmxExitIntWindowNested(pVCpu, pVmxTransient);
12729 case VMX_EXIT_NMI_WINDOW: return hmR0VmxExitNmiWindowNested(pVCpu, pVmxTransient);
12730 case VMX_EXIT_TPR_BELOW_THRESHOLD: return hmR0VmxExitTprBelowThresholdNested(pVCpu, pVmxTransient);
12731 case VMX_EXIT_MWAIT: return hmR0VmxExitMwaitNested(pVCpu, pVmxTransient);
12732 case VMX_EXIT_MONITOR: return hmR0VmxExitMonitorNested(pVCpu, pVmxTransient);
12733 case VMX_EXIT_PAUSE: return hmR0VmxExitPauseNested(pVCpu, pVmxTransient);
12734
12735 case VMX_EXIT_PREEMPT_TIMER:
12736 {
12737 /** @todo NSTVMX: Preempt timer. */
12738 return hmR0VmxExitPreemptTimer(pVCpu, pVmxTransient);
12739 }
12740
12741 case VMX_EXIT_MOV_DRX: return hmR0VmxExitMovDRxNested(pVCpu, pVmxTransient);
12742 case VMX_EXIT_RDPMC: return hmR0VmxExitRdpmcNested(pVCpu, pVmxTransient);
12743
12744 case VMX_EXIT_VMREAD:
12745 case VMX_EXIT_VMWRITE: return hmR0VmxExitVmreadVmwriteNested(pVCpu, pVmxTransient);
12746
12747 case VMX_EXIT_TRIPLE_FAULT: return hmR0VmxExitTripleFaultNested(pVCpu, pVmxTransient);
12748 case VMX_EXIT_ERR_INVALID_GUEST_STATE: return hmR0VmxExitErrInvalidGuestStateNested(pVCpu, pVmxTransient);
12749
12750 case VMX_EXIT_INIT_SIGNAL:
12751 case VMX_EXIT_SIPI:
12752 case VMX_EXIT_IO_SMI:
12753 case VMX_EXIT_SMI:
12754 case VMX_EXIT_ERR_MSR_LOAD:
12755 case VMX_EXIT_ERR_MACHINE_CHECK:
12756 case VMX_EXIT_PML_FULL:
12757 case VMX_EXIT_RSM:
12758 default:
12759 return hmR0VmxExitErrUnexpected(pVCpu, pVmxTransient);
12760 }
12761}
12762#endif /* VBOX_WITH_NESTED_HWVIRT_VMX */
12763
12764
12765/** @name VM-exit helpers.
12766 * @{
12767 */
12768/* -=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= */
12769/* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= VM-exit helpers -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- */
12770/* -=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= */
12771
12772/** Macro for VM-exits called unexpectedly. */
12773#define HMVMX_UNEXPECTED_EXIT_RET(a_pVCpu, a_HmError) \
12774 do { \
12775 (a_pVCpu)->hm.s.u32HMError = (a_HmError); \
12776 return VERR_VMX_UNEXPECTED_EXIT; \
12777 } while (0)
12778
12779#ifdef VBOX_STRICT
12780/* Is there some generic IPRT define for this that are not in Runtime/internal/\* ?? */
12781# define HMVMX_ASSERT_PREEMPT_CPUID_VAR() \
12782 RTCPUID const idAssertCpu = RTThreadPreemptIsEnabled(NIL_RTTHREAD) ? NIL_RTCPUID : RTMpCpuId()
12783
12784# define HMVMX_ASSERT_PREEMPT_CPUID() \
12785 do { \
12786 RTCPUID const idAssertCpuNow = RTThreadPreemptIsEnabled(NIL_RTTHREAD) ? NIL_RTCPUID : RTMpCpuId(); \
12787 AssertMsg(idAssertCpu == idAssertCpuNow, ("VMX %#x, %#x\n", idAssertCpu, idAssertCpuNow)); \
12788 } while (0)
12789
12790# define HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(a_pVCpu, a_pVmxTransient) \
12791 do { \
12792 AssertPtr((a_pVCpu)); \
12793 AssertPtr((a_pVmxTransient)); \
12794 Assert((a_pVmxTransient)->fVMEntryFailed == false); \
12795 Assert((a_pVmxTransient)->pVmcsInfo); \
12796 Assert(ASMIntAreEnabled()); \
12797 HMVMX_ASSERT_PREEMPT_SAFE(a_pVCpu); \
12798 HMVMX_ASSERT_PREEMPT_CPUID_VAR(); \
12799 Log4Func(("vcpu[%RU32]\n", (a_pVCpu)->idCpu)); \
12800 HMVMX_ASSERT_PREEMPT_SAFE(a_pVCpu); \
12801 if (VMMR0IsLogFlushDisabled((a_pVCpu))) \
12802 HMVMX_ASSERT_PREEMPT_CPUID(); \
12803 HMVMX_STOP_EXIT_DISPATCH_PROF(); \
12804 } while (0)
12805
12806# define HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(a_pVCpu, a_pVmxTransient) \
12807 do { \
12808 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(a_pVCpu, a_pVmxTransient); \
12809 Assert((a_pVmxTransient)->fIsNestedGuest); \
12810 } while (0)
12811
12812# define HMVMX_VALIDATE_EXIT_XCPT_HANDLER_PARAMS(a_pVCpu, a_pVmxTransient) \
12813 do { \
12814 Log4Func(("\n")); \
12815 } while (0)
12816#else
12817# define HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(a_pVCpu, a_pVmxTransient) \
12818 do { \
12819 HMVMX_STOP_EXIT_DISPATCH_PROF(); \
12820 NOREF((a_pVCpu)); NOREF((a_pVmxTransient)); \
12821 } while (0)
12822
12823# define HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(a_pVCpu, a_pVmxTransient) \
12824 do { HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(a_pVCpu, a_pVmxTransient); } while (0)
12825
12826# define HMVMX_VALIDATE_EXIT_XCPT_HANDLER_PARAMS(a_pVCpu, a_pVmxTransient) do { } while (0)
12827#endif
12828
12829#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
12830/** Macro that does the necessary privilege checks and intercepted VM-exits for
12831 * guests that attempted to execute a VMX instruction. */
12832# define HMVMX_CHECK_EXIT_DUE_TO_VMX_INSTR(a_pVCpu, a_uExitReason) \
12833 do \
12834 { \
12835 VBOXSTRICTRC rcStrictTmp = hmR0VmxCheckExitDueToVmxInstr((a_pVCpu), (a_uExitReason)); \
12836 if (rcStrictTmp == VINF_SUCCESS) \
12837 { /* likely */ } \
12838 else if (rcStrictTmp == VINF_HM_PENDING_XCPT) \
12839 { \
12840 Assert((a_pVCpu)->hm.s.Event.fPending); \
12841 Log4Func(("Privilege checks failed -> %#x\n", VMX_ENTRY_INT_INFO_VECTOR((a_pVCpu)->hm.s.Event.u64IntInfo))); \
12842 return VINF_SUCCESS; \
12843 } \
12844 else \
12845 { \
12846 int rcTmp = VBOXSTRICTRC_VAL(rcStrictTmp); \
12847 AssertMsgFailedReturn(("Unexpected failure. rc=%Rrc", rcTmp), rcTmp); \
12848 } \
12849 } while (0)
12850
12851/** Macro that decodes a memory operand for an VM-exit caused by an instruction. */
12852# define HMVMX_DECODE_MEM_OPERAND(a_pVCpu, a_uExitInstrInfo, a_uExitQual, a_enmMemAccess, a_pGCPtrEffAddr) \
12853 do \
12854 { \
12855 VBOXSTRICTRC rcStrictTmp = hmR0VmxDecodeMemOperand((a_pVCpu), (a_uExitInstrInfo), (a_uExitQual), (a_enmMemAccess), \
12856 (a_pGCPtrEffAddr)); \
12857 if (rcStrictTmp == VINF_SUCCESS) \
12858 { /* likely */ } \
12859 else if (rcStrictTmp == VINF_HM_PENDING_XCPT) \
12860 { \
12861 uint8_t const uXcptTmp = VMX_ENTRY_INT_INFO_VECTOR((a_pVCpu)->hm.s.Event.u64IntInfo); \
12862 Log4Func(("Memory operand decoding failed, raising xcpt %#x\n", uXcptTmp)); \
12863 NOREF(uXcptTmp); \
12864 return VINF_SUCCESS; \
12865 } \
12866 else \
12867 { \
12868 Log4Func(("hmR0VmxDecodeMemOperand failed. rc=%Rrc\n", VBOXSTRICTRC_VAL(rcStrictTmp))); \
12869 return rcStrictTmp; \
12870 } \
12871 } while (0)
12872#endif /* VBOX_WITH_NESTED_HWVIRT_VMX */
12873
12874
12875/**
12876 * Advances the guest RIP by the specified number of bytes.
12877 *
12878 * @param pVCpu The cross context virtual CPU structure.
12879 * @param cbInstr Number of bytes to advance the RIP by.
12880 *
12881 * @remarks No-long-jump zone!!!
12882 */
12883DECLINLINE(void) hmR0VmxAdvanceGuestRipBy(PVMCPUCC pVCpu, uint32_t cbInstr)
12884{
12885 /* Advance the RIP. */
12886 pVCpu->cpum.GstCtx.rip += cbInstr;
12887 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP);
12888
12889 /* Update interrupt inhibition. */
12890 if ( VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS)
12891 && pVCpu->cpum.GstCtx.rip != EMGetInhibitInterruptsPC(pVCpu))
12892 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS);
12893}
12894
12895
12896/**
12897 * Advances the guest RIP after reading it from the VMCS.
12898 *
12899 * @returns VBox status code, no informational status codes.
12900 * @param pVCpu The cross context virtual CPU structure.
12901 * @param pVmxTransient The VMX-transient structure.
12902 *
12903 * @remarks No-long-jump zone!!!
12904 */
12905static int hmR0VmxAdvanceGuestRip(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
12906{
12907 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
12908 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, CPUMCTX_EXTRN_RIP | CPUMCTX_EXTRN_RFLAGS);
12909 AssertRCReturn(rc, rc);
12910
12911 hmR0VmxAdvanceGuestRipBy(pVCpu, pVmxTransient->cbExitInstr);
12912 return VINF_SUCCESS;
12913}
12914
12915
12916/**
12917 * Handle a condition that occurred while delivering an event through the guest or
12918 * nested-guest IDT.
12919 *
12920 * @returns Strict VBox status code (i.e. informational status codes too).
12921 * @retval VINF_SUCCESS if we should continue handling the VM-exit.
12922 * @retval VINF_HM_DOUBLE_FAULT if a \#DF condition was detected and we ought
12923 * to continue execution of the guest which will delivery the \#DF.
12924 * @retval VINF_EM_RESET if we detected a triple-fault condition.
12925 * @retval VERR_EM_GUEST_CPU_HANG if we detected a guest CPU hang.
12926 *
12927 * @param pVCpu The cross context virtual CPU structure.
12928 * @param pVmxTransient The VMX-transient structure.
12929 *
12930 * @remarks Requires all fields in HMVMX_READ_XCPT_INFO to be read from the VMCS.
12931 * Additionally, HMVMX_READ_EXIT_QUALIFICATION is required if the VM-exit
12932 * is due to an EPT violation, PML full or SPP-related event.
12933 *
12934 * @remarks No-long-jump zone!!!
12935 */
12936static VBOXSTRICTRC hmR0VmxCheckExitDueToEventDelivery(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
12937{
12938 Assert(!pVCpu->hm.s.Event.fPending);
12939 HMVMX_ASSERT_READ(pVmxTransient, HMVMX_READ_XCPT_INFO);
12940 if ( pVmxTransient->uExitReason == VMX_EXIT_EPT_VIOLATION
12941 || pVmxTransient->uExitReason == VMX_EXIT_PML_FULL
12942 || pVmxTransient->uExitReason == VMX_EXIT_SPP_EVENT)
12943 HMVMX_ASSERT_READ(pVmxTransient, HMVMX_READ_EXIT_QUALIFICATION);
12944
12945 VBOXSTRICTRC rcStrict = VINF_SUCCESS;
12946 PCVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
12947 uint32_t const uIdtVectorInfo = pVmxTransient->uIdtVectoringInfo;
12948 uint32_t const uExitIntInfo = pVmxTransient->uExitIntInfo;
12949 if (VMX_IDT_VECTORING_INFO_IS_VALID(uIdtVectorInfo))
12950 {
12951 uint32_t const uIdtVector = VMX_IDT_VECTORING_INFO_VECTOR(uIdtVectorInfo);
12952 uint32_t const uIdtVectorType = VMX_IDT_VECTORING_INFO_TYPE(uIdtVectorInfo);
12953
12954 /*
12955 * If the event was a software interrupt (generated with INT n) or a software exception
12956 * (generated by INT3/INTO) or a privileged software exception (generated by INT1), we
12957 * can handle the VM-exit and continue guest execution which will re-execute the
12958 * instruction rather than re-injecting the exception, as that can cause premature
12959 * trips to ring-3 before injection and involve TRPM which currently has no way of
12960 * storing that these exceptions were caused by these instructions (ICEBP's #DB poses
12961 * the problem).
12962 */
12963 IEMXCPTRAISE enmRaise;
12964 IEMXCPTRAISEINFO fRaiseInfo;
12965 if ( uIdtVectorType == VMX_IDT_VECTORING_INFO_TYPE_SW_INT
12966 || uIdtVectorType == VMX_IDT_VECTORING_INFO_TYPE_SW_XCPT
12967 || uIdtVectorType == VMX_IDT_VECTORING_INFO_TYPE_PRIV_SW_XCPT)
12968 {
12969 enmRaise = IEMXCPTRAISE_REEXEC_INSTR;
12970 fRaiseInfo = IEMXCPTRAISEINFO_NONE;
12971 }
12972 else if (VMX_EXIT_INT_INFO_IS_VALID(uExitIntInfo))
12973 {
12974 uint32_t const uExitVectorType = VMX_EXIT_INT_INFO_TYPE(uExitIntInfo);
12975 uint8_t const uExitVector = VMX_EXIT_INT_INFO_VECTOR(uExitIntInfo);
12976 Assert(uExitVectorType == VMX_EXIT_INT_INFO_TYPE_HW_XCPT);
12977
12978 uint32_t const fIdtVectorFlags = hmR0VmxGetIemXcptFlags(uIdtVector, uIdtVectorType);
12979 uint32_t const fExitVectorFlags = hmR0VmxGetIemXcptFlags(uExitVector, uExitVectorType);
12980
12981 enmRaise = IEMEvaluateRecursiveXcpt(pVCpu, fIdtVectorFlags, uIdtVector, fExitVectorFlags, uExitVector, &fRaiseInfo);
12982
12983 /* Determine a vectoring #PF condition, see comment in hmR0VmxExitXcptPF(). */
12984 if (fRaiseInfo & (IEMXCPTRAISEINFO_EXT_INT_PF | IEMXCPTRAISEINFO_NMI_PF))
12985 {
12986 pVmxTransient->fVectoringPF = true;
12987 enmRaise = IEMXCPTRAISE_PREV_EVENT;
12988 }
12989 }
12990 else
12991 {
12992 /*
12993 * If an exception or hardware interrupt delivery caused an EPT violation/misconfig or APIC access
12994 * VM-exit, then the VM-exit interruption-information will not be valid and we end up here.
12995 * It is sufficient to reflect the original event to the guest after handling the VM-exit.
12996 */
12997 Assert( uIdtVectorType == VMX_IDT_VECTORING_INFO_TYPE_HW_XCPT
12998 || uIdtVectorType == VMX_IDT_VECTORING_INFO_TYPE_NMI
12999 || uIdtVectorType == VMX_IDT_VECTORING_INFO_TYPE_EXT_INT);
13000 enmRaise = IEMXCPTRAISE_PREV_EVENT;
13001 fRaiseInfo = IEMXCPTRAISEINFO_NONE;
13002 }
13003
13004 /*
13005 * On CPUs that support Virtual NMIs, if this VM-exit (be it an exception or EPT violation/misconfig
13006 * etc.) occurred while delivering the NMI, we need to clear the block-by-NMI field in the guest
13007 * interruptibility-state before re-delivering the NMI after handling the VM-exit. Otherwise the
13008 * subsequent VM-entry would fail, see @bugref{7445}.
13009 *
13010 * See Intel spec. 30.7.1.2 "Resuming Guest Software after Handling an Exception".
13011 */
13012 if ( uIdtVectorType == VMX_IDT_VECTORING_INFO_TYPE_NMI
13013 && enmRaise == IEMXCPTRAISE_PREV_EVENT
13014 && (pVmcsInfo->u32PinCtls & VMX_PIN_CTLS_VIRT_NMI)
13015 && CPUMIsGuestNmiBlocking(pVCpu))
13016 {
13017 CPUMSetGuestNmiBlocking(pVCpu, false);
13018 }
13019
13020 switch (enmRaise)
13021 {
13022 case IEMXCPTRAISE_CURRENT_XCPT:
13023 {
13024 Log4Func(("IDT: Pending secondary Xcpt: idtinfo=%#RX64 exitinfo=%#RX64\n", uIdtVectorInfo, uExitIntInfo));
13025 Assert(rcStrict == VINF_SUCCESS);
13026 break;
13027 }
13028
13029 case IEMXCPTRAISE_PREV_EVENT:
13030 {
13031 uint32_t u32ErrCode;
13032 if (VMX_IDT_VECTORING_INFO_IS_ERROR_CODE_VALID(uIdtVectorInfo))
13033 u32ErrCode = pVmxTransient->uIdtVectoringErrorCode;
13034 else
13035 u32ErrCode = 0;
13036
13037 /* If uExitVector is #PF, CR2 value will be updated from the VMCS if it's a guest #PF, see hmR0VmxExitXcptPF(). */
13038 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectReflect);
13039 hmR0VmxSetPendingEvent(pVCpu, VMX_ENTRY_INT_INFO_FROM_EXIT_IDT_INFO(uIdtVectorInfo), 0 /* cbInstr */,
13040 u32ErrCode, pVCpu->cpum.GstCtx.cr2);
13041
13042 Log4Func(("IDT: Pending vectoring event %#RX64 Err=%#RX32\n", pVCpu->hm.s.Event.u64IntInfo,
13043 pVCpu->hm.s.Event.u32ErrCode));
13044 Assert(rcStrict == VINF_SUCCESS);
13045 break;
13046 }
13047
13048 case IEMXCPTRAISE_REEXEC_INSTR:
13049 Assert(rcStrict == VINF_SUCCESS);
13050 break;
13051
13052 case IEMXCPTRAISE_DOUBLE_FAULT:
13053 {
13054 /*
13055 * Determing a vectoring double #PF condition. Used later, when PGM evaluates the
13056 * second #PF as a guest #PF (and not a shadow #PF) and needs to be converted into a #DF.
13057 */
13058 if (fRaiseInfo & IEMXCPTRAISEINFO_PF_PF)
13059 {
13060 pVmxTransient->fVectoringDoublePF = true;
13061 Log4Func(("IDT: Vectoring double #PF %#RX64 cr2=%#RX64\n", pVCpu->hm.s.Event.u64IntInfo,
13062 pVCpu->cpum.GstCtx.cr2));
13063 rcStrict = VINF_SUCCESS;
13064 }
13065 else
13066 {
13067 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectConvertDF);
13068 hmR0VmxSetPendingXcptDF(pVCpu);
13069 Log4Func(("IDT: Pending vectoring #DF %#RX64 uIdtVector=%#x uExitVector=%#x\n", pVCpu->hm.s.Event.u64IntInfo,
13070 uIdtVector, VMX_EXIT_INT_INFO_VECTOR(uExitIntInfo)));
13071 rcStrict = VINF_HM_DOUBLE_FAULT;
13072 }
13073 break;
13074 }
13075
13076 case IEMXCPTRAISE_TRIPLE_FAULT:
13077 {
13078 Log4Func(("IDT: Pending vectoring triple-fault uIdt=%#x uExit=%#x\n", uIdtVector,
13079 VMX_EXIT_INT_INFO_VECTOR(uExitIntInfo)));
13080 rcStrict = VINF_EM_RESET;
13081 break;
13082 }
13083
13084 case IEMXCPTRAISE_CPU_HANG:
13085 {
13086 Log4Func(("IDT: Bad guest! Entering CPU hang. fRaiseInfo=%#x\n", fRaiseInfo));
13087 rcStrict = VERR_EM_GUEST_CPU_HANG;
13088 break;
13089 }
13090
13091 default:
13092 {
13093 AssertMsgFailed(("IDT: vcpu[%RU32] Unexpected/invalid value! enmRaise=%#x\n", pVCpu->idCpu, enmRaise));
13094 rcStrict = VERR_VMX_IPE_2;
13095 break;
13096 }
13097 }
13098 }
13099 else if ( (pVmcsInfo->u32PinCtls & VMX_PIN_CTLS_VIRT_NMI)
13100 && !CPUMIsGuestNmiBlocking(pVCpu))
13101 {
13102 if ( VMX_EXIT_INT_INFO_IS_VALID(uExitIntInfo)
13103 && VMX_EXIT_INT_INFO_VECTOR(uExitIntInfo) != X86_XCPT_DF
13104 && VMX_EXIT_INT_INFO_IS_NMI_UNBLOCK_IRET(uExitIntInfo))
13105 {
13106 /*
13107 * Execution of IRET caused a fault when NMI blocking was in effect (i.e we're in
13108 * the guest or nested-guest NMI handler). We need to set the block-by-NMI field so
13109 * that virtual NMIs remain blocked until the IRET execution is completed.
13110 *
13111 * See Intel spec. 31.7.1.2 "Resuming Guest Software After Handling An Exception".
13112 */
13113 CPUMSetGuestNmiBlocking(pVCpu, true);
13114 Log4Func(("Set NMI blocking. uExitReason=%u\n", pVmxTransient->uExitReason));
13115 }
13116 else if ( pVmxTransient->uExitReason == VMX_EXIT_EPT_VIOLATION
13117 || pVmxTransient->uExitReason == VMX_EXIT_PML_FULL
13118 || pVmxTransient->uExitReason == VMX_EXIT_SPP_EVENT)
13119 {
13120 /*
13121 * Execution of IRET caused an EPT violation, page-modification log-full event or
13122 * SPP-related event VM-exit when NMI blocking was in effect (i.e. we're in the
13123 * guest or nested-guest NMI handler). We need to set the block-by-NMI field so
13124 * that virtual NMIs remain blocked until the IRET execution is completed.
13125 *
13126 * See Intel spec. 27.2.3 "Information about NMI unblocking due to IRET"
13127 */
13128 if (VMX_EXIT_QUAL_EPT_IS_NMI_UNBLOCK_IRET(pVmxTransient->uExitQual))
13129 {
13130 CPUMSetGuestNmiBlocking(pVCpu, true);
13131 Log4Func(("Set NMI blocking. uExitReason=%u\n", pVmxTransient->uExitReason));
13132 }
13133 }
13134 }
13135
13136 Assert( rcStrict == VINF_SUCCESS || rcStrict == VINF_HM_DOUBLE_FAULT
13137 || rcStrict == VINF_EM_RESET || rcStrict == VERR_EM_GUEST_CPU_HANG);
13138 return rcStrict;
13139}
13140
13141
13142#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
13143/**
13144 * Perform the relevant VMX instruction checks for VM-exits that occurred due to the
13145 * guest attempting to execute a VMX instruction.
13146 *
13147 * @returns Strict VBox status code (i.e. informational status codes too).
13148 * @retval VINF_SUCCESS if we should continue handling the VM-exit.
13149 * @retval VINF_HM_PENDING_XCPT if an exception was raised.
13150 *
13151 * @param pVCpu The cross context virtual CPU structure.
13152 * @param uExitReason The VM-exit reason.
13153 *
13154 * @todo NSTVMX: Document other error codes when VM-exit is implemented.
13155 * @remarks No-long-jump zone!!!
13156 */
13157static VBOXSTRICTRC hmR0VmxCheckExitDueToVmxInstr(PVMCPUCC pVCpu, uint32_t uExitReason)
13158{
13159 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_CR0 | CPUMCTX_EXTRN_RFLAGS | CPUMCTX_EXTRN_SS
13160 | CPUMCTX_EXTRN_CS | CPUMCTX_EXTRN_EFER);
13161
13162 /*
13163 * The physical CPU would have already checked the CPU mode/code segment.
13164 * We shall just assert here for paranoia.
13165 * See Intel spec. 25.1.1 "Relative Priority of Faults and VM Exits".
13166 */
13167 Assert(!CPUMIsGuestInRealOrV86ModeEx(&pVCpu->cpum.GstCtx));
13168 Assert( !CPUMIsGuestInLongModeEx(&pVCpu->cpum.GstCtx)
13169 || CPUMIsGuestIn64BitCodeEx(&pVCpu->cpum.GstCtx));
13170
13171 if (uExitReason == VMX_EXIT_VMXON)
13172 {
13173 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_CR4);
13174
13175 /*
13176 * We check CR4.VMXE because it is required to be always set while in VMX operation
13177 * by physical CPUs and our CR4 read-shadow is only consulted when executing specific
13178 * instructions (CLTS, LMSW, MOV CR, and SMSW) and thus doesn't affect CPU operation
13179 * otherwise (i.e. physical CPU won't automatically #UD if Cr4Shadow.VMXE is 0).
13180 */
13181 if (!CPUMIsGuestVmxEnabled(&pVCpu->cpum.GstCtx))
13182 {
13183 Log4Func(("CR4.VMXE is not set -> #UD\n"));
13184 hmR0VmxSetPendingXcptUD(pVCpu);
13185 return VINF_HM_PENDING_XCPT;
13186 }
13187 }
13188 else if (!CPUMIsGuestInVmxRootMode(&pVCpu->cpum.GstCtx))
13189 {
13190 /*
13191 * The guest has not entered VMX operation but attempted to execute a VMX instruction
13192 * (other than VMXON), we need to raise a #UD.
13193 */
13194 Log4Func(("Not in VMX root mode -> #UD\n"));
13195 hmR0VmxSetPendingXcptUD(pVCpu);
13196 return VINF_HM_PENDING_XCPT;
13197 }
13198
13199 /* All other checks (including VM-exit intercepts) are handled by IEM instruction emulation. */
13200 return VINF_SUCCESS;
13201}
13202
13203
13204/**
13205 * Decodes the memory operand of an instruction that caused a VM-exit.
13206 *
13207 * The Exit qualification field provides the displacement field for memory
13208 * operand instructions, if any.
13209 *
13210 * @returns Strict VBox status code (i.e. informational status codes too).
13211 * @retval VINF_SUCCESS if the operand was successfully decoded.
13212 * @retval VINF_HM_PENDING_XCPT if an exception was raised while decoding the
13213 * operand.
13214 * @param pVCpu The cross context virtual CPU structure.
13215 * @param uExitInstrInfo The VM-exit instruction information field.
13216 * @param enmMemAccess The memory operand's access type (read or write).
13217 * @param GCPtrDisp The instruction displacement field, if any. For
13218 * RIP-relative addressing pass RIP + displacement here.
13219 * @param pGCPtrMem Where to store the effective destination memory address.
13220 *
13221 * @remarks Warning! This function ASSUMES the instruction cannot be used in real or
13222 * virtual-8086 mode hence skips those checks while verifying if the
13223 * segment is valid.
13224 */
13225static VBOXSTRICTRC hmR0VmxDecodeMemOperand(PVMCPUCC pVCpu, uint32_t uExitInstrInfo, RTGCPTR GCPtrDisp, VMXMEMACCESS enmMemAccess,
13226 PRTGCPTR pGCPtrMem)
13227{
13228 Assert(pGCPtrMem);
13229 Assert(!CPUMIsGuestInRealOrV86Mode(pVCpu));
13230 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_RIP | CPUMCTX_EXTRN_RSP | CPUMCTX_EXTRN_SREG_MASK | CPUMCTX_EXTRN_EFER
13231 | CPUMCTX_EXTRN_CR0);
13232
13233 static uint64_t const s_auAddrSizeMasks[] = { UINT64_C(0xffff), UINT64_C(0xffffffff), UINT64_C(0xffffffffffffffff) };
13234 static uint64_t const s_auAccessSizeMasks[] = { sizeof(uint16_t), sizeof(uint32_t), sizeof(uint64_t) };
13235 AssertCompile(RT_ELEMENTS(s_auAccessSizeMasks) == RT_ELEMENTS(s_auAddrSizeMasks));
13236
13237 VMXEXITINSTRINFO ExitInstrInfo;
13238 ExitInstrInfo.u = uExitInstrInfo;
13239 uint8_t const uAddrSize = ExitInstrInfo.All.u3AddrSize;
13240 uint8_t const iSegReg = ExitInstrInfo.All.iSegReg;
13241 bool const fIdxRegValid = !ExitInstrInfo.All.fIdxRegInvalid;
13242 uint8_t const iIdxReg = ExitInstrInfo.All.iIdxReg;
13243 uint8_t const uScale = ExitInstrInfo.All.u2Scaling;
13244 bool const fBaseRegValid = !ExitInstrInfo.All.fBaseRegInvalid;
13245 uint8_t const iBaseReg = ExitInstrInfo.All.iBaseReg;
13246 bool const fIsMemOperand = !ExitInstrInfo.All.fIsRegOperand;
13247 bool const fIsLongMode = CPUMIsGuestInLongModeEx(&pVCpu->cpum.GstCtx);
13248
13249 /*
13250 * Validate instruction information.
13251 * This shouldn't happen on real hardware but useful while testing our nested hardware-virtualization code.
13252 */
13253 AssertLogRelMsgReturn(uAddrSize < RT_ELEMENTS(s_auAddrSizeMasks),
13254 ("Invalid address size. ExitInstrInfo=%#RX32\n", ExitInstrInfo.u), VERR_VMX_IPE_1);
13255 AssertLogRelMsgReturn(iSegReg < X86_SREG_COUNT,
13256 ("Invalid segment register. ExitInstrInfo=%#RX32\n", ExitInstrInfo.u), VERR_VMX_IPE_2);
13257 AssertLogRelMsgReturn(fIsMemOperand,
13258 ("Expected memory operand. ExitInstrInfo=%#RX32\n", ExitInstrInfo.u), VERR_VMX_IPE_3);
13259
13260 /*
13261 * Compute the complete effective address.
13262 *
13263 * See AMD instruction spec. 1.4.2 "SIB Byte Format"
13264 * See AMD spec. 4.5.2 "Segment Registers".
13265 */
13266 RTGCPTR GCPtrMem = GCPtrDisp;
13267 if (fBaseRegValid)
13268 GCPtrMem += pVCpu->cpum.GstCtx.aGRegs[iBaseReg].u64;
13269 if (fIdxRegValid)
13270 GCPtrMem += pVCpu->cpum.GstCtx.aGRegs[iIdxReg].u64 << uScale;
13271
13272 RTGCPTR const GCPtrOff = GCPtrMem;
13273 if ( !fIsLongMode
13274 || iSegReg >= X86_SREG_FS)
13275 GCPtrMem += pVCpu->cpum.GstCtx.aSRegs[iSegReg].u64Base;
13276 GCPtrMem &= s_auAddrSizeMasks[uAddrSize];
13277
13278 /*
13279 * Validate effective address.
13280 * See AMD spec. 4.5.3 "Segment Registers in 64-Bit Mode".
13281 */
13282 uint8_t const cbAccess = s_auAccessSizeMasks[uAddrSize];
13283 Assert(cbAccess > 0);
13284 if (fIsLongMode)
13285 {
13286 if (X86_IS_CANONICAL(GCPtrMem))
13287 {
13288 *pGCPtrMem = GCPtrMem;
13289 return VINF_SUCCESS;
13290 }
13291
13292 /** @todo r=ramshankar: We should probably raise \#SS or \#GP. See AMD spec. 4.12.2
13293 * "Data Limit Checks in 64-bit Mode". */
13294 Log4Func(("Long mode effective address is not canonical GCPtrMem=%#RX64\n", GCPtrMem));
13295 hmR0VmxSetPendingXcptGP(pVCpu, 0);
13296 return VINF_HM_PENDING_XCPT;
13297 }
13298
13299 /*
13300 * This is a watered down version of iemMemApplySegment().
13301 * Parts that are not applicable for VMX instructions like real-or-v8086 mode
13302 * and segment CPL/DPL checks are skipped.
13303 */
13304 RTGCPTR32 const GCPtrFirst32 = (RTGCPTR32)GCPtrOff;
13305 RTGCPTR32 const GCPtrLast32 = GCPtrFirst32 + cbAccess - 1;
13306 PCCPUMSELREG pSel = &pVCpu->cpum.GstCtx.aSRegs[iSegReg];
13307
13308 /* Check if the segment is present and usable. */
13309 if ( pSel->Attr.n.u1Present
13310 && !pSel->Attr.n.u1Unusable)
13311 {
13312 Assert(pSel->Attr.n.u1DescType);
13313 if (!(pSel->Attr.n.u4Type & X86_SEL_TYPE_CODE))
13314 {
13315 /* Check permissions for the data segment. */
13316 if ( enmMemAccess == VMXMEMACCESS_WRITE
13317 && !(pSel->Attr.n.u4Type & X86_SEL_TYPE_WRITE))
13318 {
13319 Log4Func(("Data segment access invalid. iSegReg=%#x Attr=%#RX32\n", iSegReg, pSel->Attr.u));
13320 hmR0VmxSetPendingXcptGP(pVCpu, iSegReg);
13321 return VINF_HM_PENDING_XCPT;
13322 }
13323
13324 /* Check limits if it's a normal data segment. */
13325 if (!(pSel->Attr.n.u4Type & X86_SEL_TYPE_DOWN))
13326 {
13327 if ( GCPtrFirst32 > pSel->u32Limit
13328 || GCPtrLast32 > pSel->u32Limit)
13329 {
13330 Log4Func(("Data segment limit exceeded. "
13331 "iSegReg=%#x GCPtrFirst32=%#RX32 GCPtrLast32=%#RX32 u32Limit=%#RX32\n", iSegReg, GCPtrFirst32,
13332 GCPtrLast32, pSel->u32Limit));
13333 if (iSegReg == X86_SREG_SS)
13334 hmR0VmxSetPendingXcptSS(pVCpu, 0);
13335 else
13336 hmR0VmxSetPendingXcptGP(pVCpu, 0);
13337 return VINF_HM_PENDING_XCPT;
13338 }
13339 }
13340 else
13341 {
13342 /* Check limits if it's an expand-down data segment.
13343 Note! The upper boundary is defined by the B bit, not the G bit! */
13344 if ( GCPtrFirst32 < pSel->u32Limit + UINT32_C(1)
13345 || GCPtrLast32 > (pSel->Attr.n.u1DefBig ? UINT32_MAX : UINT32_C(0xffff)))
13346 {
13347 Log4Func(("Expand-down data segment limit exceeded. "
13348 "iSegReg=%#x GCPtrFirst32=%#RX32 GCPtrLast32=%#RX32 u32Limit=%#RX32\n", iSegReg, GCPtrFirst32,
13349 GCPtrLast32, pSel->u32Limit));
13350 if (iSegReg == X86_SREG_SS)
13351 hmR0VmxSetPendingXcptSS(pVCpu, 0);
13352 else
13353 hmR0VmxSetPendingXcptGP(pVCpu, 0);
13354 return VINF_HM_PENDING_XCPT;
13355 }
13356 }
13357 }
13358 else
13359 {
13360 /* Check permissions for the code segment. */
13361 if ( enmMemAccess == VMXMEMACCESS_WRITE
13362 || ( enmMemAccess == VMXMEMACCESS_READ
13363 && !(pSel->Attr.n.u4Type & X86_SEL_TYPE_READ)))
13364 {
13365 Log4Func(("Code segment access invalid. Attr=%#RX32\n", pSel->Attr.u));
13366 Assert(!CPUMIsGuestInRealOrV86ModeEx(&pVCpu->cpum.GstCtx));
13367 hmR0VmxSetPendingXcptGP(pVCpu, 0);
13368 return VINF_HM_PENDING_XCPT;
13369 }
13370
13371 /* Check limits for the code segment (normal/expand-down not applicable for code segments). */
13372 if ( GCPtrFirst32 > pSel->u32Limit
13373 || GCPtrLast32 > pSel->u32Limit)
13374 {
13375 Log4Func(("Code segment limit exceeded. GCPtrFirst32=%#RX32 GCPtrLast32=%#RX32 u32Limit=%#RX32\n",
13376 GCPtrFirst32, GCPtrLast32, pSel->u32Limit));
13377 if (iSegReg == X86_SREG_SS)
13378 hmR0VmxSetPendingXcptSS(pVCpu, 0);
13379 else
13380 hmR0VmxSetPendingXcptGP(pVCpu, 0);
13381 return VINF_HM_PENDING_XCPT;
13382 }
13383 }
13384 }
13385 else
13386 {
13387 Log4Func(("Not present or unusable segment. iSegReg=%#x Attr=%#RX32\n", iSegReg, pSel->Attr.u));
13388 hmR0VmxSetPendingXcptGP(pVCpu, 0);
13389 return VINF_HM_PENDING_XCPT;
13390 }
13391
13392 *pGCPtrMem = GCPtrMem;
13393 return VINF_SUCCESS;
13394}
13395#endif /* VBOX_WITH_NESTED_HWVIRT_VMX */
13396
13397
13398/**
13399 * VM-exit helper for LMSW.
13400 */
13401static VBOXSTRICTRC hmR0VmxExitLmsw(PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo, uint8_t cbInstr, uint16_t uMsw, RTGCPTR GCPtrEffDst)
13402{
13403 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, IEM_CPUMCTX_EXTRN_MUST_MASK);
13404 AssertRCReturn(rc, rc);
13405
13406 VBOXSTRICTRC rcStrict = IEMExecDecodedLmsw(pVCpu, cbInstr, uMsw, GCPtrEffDst);
13407 AssertMsg( rcStrict == VINF_SUCCESS
13408 || rcStrict == VINF_IEM_RAISED_XCPT, ("%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
13409
13410 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS | HM_CHANGED_GUEST_CR0);
13411 if (rcStrict == VINF_IEM_RAISED_XCPT)
13412 {
13413 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
13414 rcStrict = VINF_SUCCESS;
13415 }
13416
13417 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitLmsw);
13418 Log4Func(("rcStrict=%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
13419 return rcStrict;
13420}
13421
13422
13423/**
13424 * VM-exit helper for CLTS.
13425 */
13426static VBOXSTRICTRC hmR0VmxExitClts(PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo, uint8_t cbInstr)
13427{
13428 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, IEM_CPUMCTX_EXTRN_MUST_MASK);
13429 AssertRCReturn(rc, rc);
13430
13431 VBOXSTRICTRC rcStrict = IEMExecDecodedClts(pVCpu, cbInstr);
13432 AssertMsg( rcStrict == VINF_SUCCESS
13433 || rcStrict == VINF_IEM_RAISED_XCPT, ("%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
13434
13435 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS | HM_CHANGED_GUEST_CR0);
13436 if (rcStrict == VINF_IEM_RAISED_XCPT)
13437 {
13438 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
13439 rcStrict = VINF_SUCCESS;
13440 }
13441
13442 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitClts);
13443 Log4Func(("rcStrict=%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
13444 return rcStrict;
13445}
13446
13447
13448/**
13449 * VM-exit helper for MOV from CRx (CRx read).
13450 */
13451static VBOXSTRICTRC hmR0VmxExitMovFromCrX(PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo, uint8_t cbInstr, uint8_t iGReg, uint8_t iCrReg)
13452{
13453 Assert(iCrReg < 16);
13454 Assert(iGReg < RT_ELEMENTS(pVCpu->cpum.GstCtx.aGRegs));
13455
13456 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, IEM_CPUMCTX_EXTRN_MUST_MASK);
13457 AssertRCReturn(rc, rc);
13458
13459 VBOXSTRICTRC rcStrict = IEMExecDecodedMovCRxRead(pVCpu, cbInstr, iGReg, iCrReg);
13460 AssertMsg( rcStrict == VINF_SUCCESS
13461 || rcStrict == VINF_IEM_RAISED_XCPT, ("%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
13462
13463 if (iGReg == X86_GREG_xSP)
13464 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS | HM_CHANGED_GUEST_RSP);
13465 else
13466 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS);
13467#ifdef VBOX_WITH_STATISTICS
13468 switch (iCrReg)
13469 {
13470 case 0: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCR0Read); break;
13471 case 2: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCR2Read); break;
13472 case 3: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCR3Read); break;
13473 case 4: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCR4Read); break;
13474 case 8: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCR8Read); break;
13475 }
13476#endif
13477 Log4Func(("CR%d Read access rcStrict=%Rrc\n", iCrReg, VBOXSTRICTRC_VAL(rcStrict)));
13478 return rcStrict;
13479}
13480
13481
13482/**
13483 * VM-exit helper for MOV to CRx (CRx write).
13484 */
13485static VBOXSTRICTRC hmR0VmxExitMovToCrX(PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo, uint8_t cbInstr, uint8_t iGReg, uint8_t iCrReg)
13486{
13487 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, IEM_CPUMCTX_EXTRN_MUST_MASK);
13488 AssertRCReturn(rc, rc);
13489
13490 VBOXSTRICTRC rcStrict = IEMExecDecodedMovCRxWrite(pVCpu, cbInstr, iCrReg, iGReg);
13491 AssertMsg( rcStrict == VINF_SUCCESS
13492 || rcStrict == VINF_IEM_RAISED_XCPT
13493 || rcStrict == VINF_PGM_SYNC_CR3, ("%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
13494
13495 switch (iCrReg)
13496 {
13497 case 0:
13498 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS | HM_CHANGED_GUEST_CR0
13499 | HM_CHANGED_GUEST_EFER_MSR | HM_CHANGED_VMX_ENTRY_EXIT_CTLS);
13500 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCR0Write);
13501 Log4Func(("CR0 write. rcStrict=%Rrc CR0=%#RX64\n", VBOXSTRICTRC_VAL(rcStrict), pVCpu->cpum.GstCtx.cr0));
13502 break;
13503
13504 case 2:
13505 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCR2Write);
13506 /* Nothing to do here, CR2 it's not part of the VMCS. */
13507 break;
13508
13509 case 3:
13510 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS | HM_CHANGED_GUEST_CR3);
13511 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCR3Write);
13512 Log4Func(("CR3 write. rcStrict=%Rrc CR3=%#RX64\n", VBOXSTRICTRC_VAL(rcStrict), pVCpu->cpum.GstCtx.cr3));
13513 break;
13514
13515 case 4:
13516 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS | HM_CHANGED_GUEST_CR4);
13517 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCR4Write);
13518 Log4Func(("CR4 write. rc=%Rrc CR4=%#RX64 fLoadSaveGuestXcr0=%u\n", VBOXSTRICTRC_VAL(rcStrict),
13519 pVCpu->cpum.GstCtx.cr4, pVCpu->hm.s.fLoadSaveGuestXcr0));
13520 break;
13521
13522 case 8:
13523 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged,
13524 HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS | HM_CHANGED_GUEST_APIC_TPR);
13525 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCR8Write);
13526 break;
13527
13528 default:
13529 AssertMsgFailed(("Invalid CRx register %#x\n", iCrReg));
13530 break;
13531 }
13532
13533 if (rcStrict == VINF_IEM_RAISED_XCPT)
13534 {
13535 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
13536 rcStrict = VINF_SUCCESS;
13537 }
13538 return rcStrict;
13539}
13540
13541
13542/**
13543 * VM-exit exception handler for \#PF (Page-fault exception).
13544 *
13545 * @remarks Requires all fields in HMVMX_READ_XCPT_INFO to be read from the VMCS.
13546 */
13547static VBOXSTRICTRC hmR0VmxExitXcptPF(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
13548{
13549 HMVMX_VALIDATE_EXIT_XCPT_HANDLER_PARAMS(pVCpu, pVmxTransient);
13550 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
13551 hmR0VmxReadExitQualVmcs(pVmxTransient);
13552
13553 if (!pVM->hm.s.fNestedPaging)
13554 { /* likely */ }
13555 else
13556 {
13557#if !defined(HMVMX_ALWAYS_TRAP_ALL_XCPTS) && !defined(HMVMX_ALWAYS_TRAP_PF)
13558 Assert(pVmxTransient->fIsNestedGuest || pVCpu->hm.s.fUsingDebugLoop);
13559#endif
13560 pVCpu->hm.s.Event.fPending = false; /* In case it's a contributory or vectoring #PF. */
13561 if (!pVmxTransient->fVectoringDoublePF)
13562 {
13563 hmR0VmxSetPendingEvent(pVCpu, VMX_ENTRY_INT_INFO_FROM_EXIT_INT_INFO(pVmxTransient->uExitIntInfo), 0 /* cbInstr */,
13564 pVmxTransient->uExitIntErrorCode, pVmxTransient->uExitQual);
13565 }
13566 else
13567 {
13568 /* A guest page-fault occurred during delivery of a page-fault. Inject #DF. */
13569 Assert(!pVmxTransient->fIsNestedGuest);
13570 hmR0VmxSetPendingXcptDF(pVCpu);
13571 Log4Func(("Pending #DF due to vectoring #PF w/ NestedPaging\n"));
13572 }
13573 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestPF);
13574 return VINF_SUCCESS;
13575 }
13576
13577 Assert(!pVmxTransient->fIsNestedGuest);
13578
13579 /* If it's a vectoring #PF, emulate injecting the original event injection as PGMTrap0eHandler() is incapable
13580 of differentiating between instruction emulation and event injection that caused a #PF. See @bugref{6607}. */
13581 if (pVmxTransient->fVectoringPF)
13582 {
13583 Assert(pVCpu->hm.s.Event.fPending);
13584 return VINF_EM_RAW_INJECT_TRPM_EVENT;
13585 }
13586
13587 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
13588 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, HMVMX_CPUMCTX_EXTRN_ALL);
13589 AssertRCReturn(rc, rc);
13590
13591 Log4Func(("#PF: cs:rip=%#04x:%#RX64 err_code=%#RX32 exit_qual=%#RX64 cr3=%#RX64\n", pCtx->cs.Sel, pCtx->rip,
13592 pVmxTransient->uExitIntErrorCode, pVmxTransient->uExitQual, pCtx->cr3));
13593
13594 TRPMAssertXcptPF(pVCpu, pVmxTransient->uExitQual, (RTGCUINT)pVmxTransient->uExitIntErrorCode);
13595 rc = PGMTrap0eHandler(pVCpu, pVmxTransient->uExitIntErrorCode, CPUMCTX2CORE(pCtx), (RTGCPTR)pVmxTransient->uExitQual);
13596
13597 Log4Func(("#PF: rc=%Rrc\n", rc));
13598 if (rc == VINF_SUCCESS)
13599 {
13600 /*
13601 * This is typically a shadow page table sync or a MMIO instruction. But we may have
13602 * emulated something like LTR or a far jump. Any part of the CPU context may have changed.
13603 */
13604 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_ALL_GUEST);
13605 TRPMResetTrap(pVCpu);
13606 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitShadowPF);
13607 return rc;
13608 }
13609
13610 if (rc == VINF_EM_RAW_GUEST_TRAP)
13611 {
13612 if (!pVmxTransient->fVectoringDoublePF)
13613 {
13614 /* It's a guest page fault and needs to be reflected to the guest. */
13615 uint32_t const uGstErrorCode = TRPMGetErrorCode(pVCpu);
13616 TRPMResetTrap(pVCpu);
13617 pVCpu->hm.s.Event.fPending = false; /* In case it's a contributory #PF. */
13618 hmR0VmxSetPendingEvent(pVCpu, VMX_ENTRY_INT_INFO_FROM_EXIT_INT_INFO(pVmxTransient->uExitIntInfo), 0 /* cbInstr */,
13619 uGstErrorCode, pVmxTransient->uExitQual);
13620 }
13621 else
13622 {
13623 /* A guest page-fault occurred during delivery of a page-fault. Inject #DF. */
13624 TRPMResetTrap(pVCpu);
13625 pVCpu->hm.s.Event.fPending = false; /* Clear pending #PF to replace it with #DF. */
13626 hmR0VmxSetPendingXcptDF(pVCpu);
13627 Log4Func(("#PF: Pending #DF due to vectoring #PF\n"));
13628 }
13629
13630 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestPF);
13631 return VINF_SUCCESS;
13632 }
13633
13634 TRPMResetTrap(pVCpu);
13635 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitShadowPFEM);
13636 return rc;
13637}
13638
13639
13640/**
13641 * VM-exit exception handler for \#MF (Math Fault: floating point exception).
13642 *
13643 * @remarks Requires all fields in HMVMX_READ_XCPT_INFO to be read from the VMCS.
13644 */
13645static VBOXSTRICTRC hmR0VmxExitXcptMF(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
13646{
13647 HMVMX_VALIDATE_EXIT_XCPT_HANDLER_PARAMS(pVCpu, pVmxTransient);
13648 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestMF);
13649
13650 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, CPUMCTX_EXTRN_CR0);
13651 AssertRCReturn(rc, rc);
13652
13653 if (!(pVCpu->cpum.GstCtx.cr0 & X86_CR0_NE))
13654 {
13655 /* Convert a #MF into a FERR -> IRQ 13. See @bugref{6117}. */
13656 rc = PDMIsaSetIrq(pVCpu->CTX_SUFF(pVM), 13, 1, 0 /* uTagSrc */);
13657
13658 /** @todo r=ramshankar: The Intel spec. does -not- specify that this VM-exit
13659 * provides VM-exit instruction length. If this causes problem later,
13660 * disassemble the instruction like it's done on AMD-V. */
13661 int rc2 = hmR0VmxAdvanceGuestRip(pVCpu, pVmxTransient);
13662 AssertRCReturn(rc2, rc2);
13663 return rc;
13664 }
13665
13666 hmR0VmxSetPendingEvent(pVCpu, VMX_ENTRY_INT_INFO_FROM_EXIT_INT_INFO(pVmxTransient->uExitIntInfo), pVmxTransient->cbExitInstr,
13667 pVmxTransient->uExitIntErrorCode, 0 /* GCPtrFaultAddress */);
13668 return VINF_SUCCESS;
13669}
13670
13671
13672/**
13673 * VM-exit exception handler for \#BP (Breakpoint exception).
13674 *
13675 * @remarks Requires all fields in HMVMX_READ_XCPT_INFO to be read from the VMCS.
13676 */
13677static VBOXSTRICTRC hmR0VmxExitXcptBP(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
13678{
13679 HMVMX_VALIDATE_EXIT_XCPT_HANDLER_PARAMS(pVCpu, pVmxTransient);
13680 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestBP);
13681
13682 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, HMVMX_CPUMCTX_EXTRN_ALL);
13683 AssertRCReturn(rc, rc);
13684
13685 if (!pVmxTransient->fIsNestedGuest)
13686 rc = DBGFRZTrap03Handler(pVCpu->CTX_SUFF(pVM), pVCpu, CPUMCTX2CORE(&pVCpu->cpum.GstCtx));
13687 else
13688 rc = VINF_EM_RAW_GUEST_TRAP;
13689
13690 if (rc == VINF_EM_RAW_GUEST_TRAP)
13691 {
13692 hmR0VmxSetPendingEvent(pVCpu, VMX_ENTRY_INT_INFO_FROM_EXIT_INT_INFO(pVmxTransient->uExitIntInfo),
13693 pVmxTransient->cbExitInstr, pVmxTransient->uExitIntErrorCode, 0 /* GCPtrFaultAddress */);
13694 rc = VINF_SUCCESS;
13695 }
13696
13697 Assert(rc == VINF_SUCCESS || rc == VINF_EM_DBG_BREAKPOINT);
13698 return rc;
13699}
13700
13701
13702/**
13703 * VM-exit exception handler for \#AC (Alignment-check exception).
13704 *
13705 * @remarks Requires all fields in HMVMX_READ_XCPT_INFO to be read from the VMCS.
13706 */
13707static VBOXSTRICTRC hmR0VmxExitXcptAC(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
13708{
13709 HMVMX_VALIDATE_EXIT_XCPT_HANDLER_PARAMS(pVCpu, pVmxTransient);
13710 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestAC);
13711
13712 /* Re-inject it. We'll detect any nesting before getting here. */
13713 hmR0VmxSetPendingEvent(pVCpu, VMX_ENTRY_INT_INFO_FROM_EXIT_INT_INFO(pVmxTransient->uExitIntInfo),
13714 pVmxTransient->cbExitInstr, pVmxTransient->uExitIntErrorCode, 0 /* GCPtrFaultAddress */);
13715 return VINF_SUCCESS;
13716}
13717
13718
13719/**
13720 * VM-exit exception handler for \#DB (Debug exception).
13721 *
13722 * @remarks Requires all fields in HMVMX_READ_XCPT_INFO to be read from the VMCS.
13723 */
13724static VBOXSTRICTRC hmR0VmxExitXcptDB(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
13725{
13726 HMVMX_VALIDATE_EXIT_XCPT_HANDLER_PARAMS(pVCpu, pVmxTransient);
13727 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestDB);
13728
13729 /*
13730 * Get the DR6-like values from the Exit qualification and pass it to DBGF for processing.
13731 */
13732 hmR0VmxReadExitQualVmcs(pVmxTransient);
13733
13734 /* Refer Intel spec. Table 27-1. "Exit Qualifications for debug exceptions" for the format. */
13735 uint64_t const uDR6 = X86_DR6_INIT_VAL
13736 | (pVmxTransient->uExitQual & ( X86_DR6_B0 | X86_DR6_B1 | X86_DR6_B2 | X86_DR6_B3
13737 | X86_DR6_BD | X86_DR6_BS));
13738
13739 int rc;
13740 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
13741 if (!pVmxTransient->fIsNestedGuest)
13742 rc = DBGFRZTrap01Handler(pVCpu->CTX_SUFF(pVM), pVCpu, CPUMCTX2CORE(pCtx), uDR6, pVCpu->hm.s.fSingleInstruction);
13743 else
13744 rc = VINF_EM_RAW_GUEST_TRAP;
13745 Log6Func(("rc=%Rrc\n", rc));
13746 if (rc == VINF_EM_RAW_GUEST_TRAP)
13747 {
13748 /*
13749 * The exception was for the guest. Update DR6, DR7.GD and
13750 * IA32_DEBUGCTL.LBR before forwarding it.
13751 * See Intel spec. 27.1 "Architectural State before a VM-Exit".
13752 */
13753 VMMRZCallRing3Disable(pVCpu);
13754 HM_DISABLE_PREEMPT(pVCpu);
13755
13756 pCtx->dr[6] &= ~X86_DR6_B_MASK;
13757 pCtx->dr[6] |= uDR6;
13758 if (CPUMIsGuestDebugStateActive(pVCpu))
13759 ASMSetDR6(pCtx->dr[6]);
13760
13761 HM_RESTORE_PREEMPT();
13762 VMMRZCallRing3Enable(pVCpu);
13763
13764 rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, CPUMCTX_EXTRN_DR7);
13765 AssertRCReturn(rc, rc);
13766
13767 /* X86_DR7_GD will be cleared if DRx accesses should be trapped inside the guest. */
13768 pCtx->dr[7] &= ~(uint64_t)X86_DR7_GD;
13769
13770 /* Paranoia. */
13771 pCtx->dr[7] &= ~(uint64_t)X86_DR7_RAZ_MASK;
13772 pCtx->dr[7] |= X86_DR7_RA1_MASK;
13773
13774 rc = VMXWriteVmcsNw(VMX_VMCS_GUEST_DR7, pCtx->dr[7]);
13775 AssertRC(rc);
13776
13777 /*
13778 * Raise #DB in the guest.
13779 *
13780 * It is important to reflect exactly what the VM-exit gave us (preserving the
13781 * interruption-type) rather than use hmR0VmxSetPendingXcptDB() as the #DB could've
13782 * been raised while executing ICEBP (INT1) and not the regular #DB. Thus it may
13783 * trigger different handling in the CPU (like skipping DPL checks), see @bugref{6398}.
13784 *
13785 * Intel re-documented ICEBP/INT1 on May 2018 previously documented as part of
13786 * Intel 386, see Intel spec. 24.8.3 "VM-Entry Controls for Event Injection".
13787 */
13788 hmR0VmxSetPendingEvent(pVCpu, VMX_ENTRY_INT_INFO_FROM_EXIT_INT_INFO(pVmxTransient->uExitIntInfo),
13789 pVmxTransient->cbExitInstr, pVmxTransient->uExitIntErrorCode, 0 /* GCPtrFaultAddress */);
13790 return VINF_SUCCESS;
13791 }
13792
13793 /*
13794 * Not a guest trap, must be a hypervisor related debug event then.
13795 * Update DR6 in case someone is interested in it.
13796 */
13797 AssertMsg(rc == VINF_EM_DBG_STEPPED || rc == VINF_EM_DBG_BREAKPOINT, ("%Rrc\n", rc));
13798 AssertReturn(pVmxTransient->fWasHyperDebugStateActive, VERR_HM_IPE_5);
13799 CPUMSetHyperDR6(pVCpu, uDR6);
13800
13801 return rc;
13802}
13803
13804
13805/**
13806 * Hacks its way around the lovely mesa driver's backdoor accesses.
13807 *
13808 * @sa hmR0SvmHandleMesaDrvGp.
13809 */
13810static int hmR0VmxHandleMesaDrvGp(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient, PCPUMCTX pCtx)
13811{
13812 LogFunc(("cs:rip=%#04x:%#RX64 rcx=%#RX64 rbx=%#RX64\n", pCtx->cs.Sel, pCtx->rip, pCtx->rcx, pCtx->rbx));
13813 RT_NOREF(pCtx);
13814
13815 /* For now we'll just skip the instruction. */
13816 return hmR0VmxAdvanceGuestRip(pVCpu, pVmxTransient);
13817}
13818
13819
13820/**
13821 * Checks if the \#GP'ing instruction is the mesa driver doing it's lovely
13822 * backdoor logging w/o checking what it is running inside.
13823 *
13824 * This recognizes an "IN EAX,DX" instruction executed in flat ring-3, with the
13825 * backdoor port and magic numbers loaded in registers.
13826 *
13827 * @returns true if it is, false if it isn't.
13828 * @sa hmR0SvmIsMesaDrvGp.
13829 */
13830DECLINLINE(bool) hmR0VmxIsMesaDrvGp(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient, PCPUMCTX pCtx)
13831{
13832 /* 0xed: IN eAX,dx */
13833 uint8_t abInstr[1];
13834 if (pVmxTransient->cbExitInstr != sizeof(abInstr))
13835 return false;
13836
13837 /* Check that it is #GP(0). */
13838 if (pVmxTransient->uExitIntErrorCode != 0)
13839 return false;
13840
13841 /* Check magic and port. */
13842 Assert(!(pCtx->fExtrn & (CPUMCTX_EXTRN_RAX | CPUMCTX_EXTRN_RDX | CPUMCTX_EXTRN_RCX)));
13843 /*Log(("hmR0VmxIsMesaDrvGp: rax=%RX64 rdx=%RX64\n", pCtx->rax, pCtx->rdx));*/
13844 if (pCtx->rax != UINT32_C(0x564d5868))
13845 return false;
13846 if (pCtx->dx != UINT32_C(0x5658))
13847 return false;
13848
13849 /* Flat ring-3 CS. */
13850 AssertCompile(HMVMX_CPUMCTX_EXTRN_ALL & CPUMCTX_EXTRN_CS);
13851 Assert(!(pCtx->fExtrn & CPUMCTX_EXTRN_CS));
13852 /*Log(("hmR0VmxIsMesaDrvGp: cs.Attr.n.u2Dpl=%d base=%Rx64\n", pCtx->cs.Attr.n.u2Dpl, pCtx->cs.u64Base));*/
13853 if (pCtx->cs.Attr.n.u2Dpl != 3)
13854 return false;
13855 if (pCtx->cs.u64Base != 0)
13856 return false;
13857
13858 /* Check opcode. */
13859 AssertCompile(HMVMX_CPUMCTX_EXTRN_ALL & CPUMCTX_EXTRN_RIP);
13860 Assert(!(pCtx->fExtrn & CPUMCTX_EXTRN_RIP));
13861 int rc = PGMPhysSimpleReadGCPtr(pVCpu, abInstr, pCtx->rip, sizeof(abInstr));
13862 /*Log(("hmR0VmxIsMesaDrvGp: PGMPhysSimpleReadGCPtr -> %Rrc %#x\n", rc, abInstr[0]));*/
13863 if (RT_FAILURE(rc))
13864 return false;
13865 if (abInstr[0] != 0xed)
13866 return false;
13867
13868 return true;
13869}
13870
13871
13872/**
13873 * VM-exit exception handler for \#GP (General-protection exception).
13874 *
13875 * @remarks Requires all fields in HMVMX_READ_XCPT_INFO to be read from the VMCS.
13876 */
13877static VBOXSTRICTRC hmR0VmxExitXcptGP(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
13878{
13879 HMVMX_VALIDATE_EXIT_XCPT_HANDLER_PARAMS(pVCpu, pVmxTransient);
13880 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestGP);
13881
13882 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
13883 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
13884 if (pVmcsInfo->RealMode.fRealOnV86Active)
13885 { /* likely */ }
13886 else
13887 {
13888#ifndef HMVMX_ALWAYS_TRAP_ALL_XCPTS
13889 Assert(pVCpu->hm.s.fUsingDebugLoop || pVCpu->hm.s.fTrapXcptGpForLovelyMesaDrv || pVmxTransient->fIsNestedGuest);
13890#endif
13891 /*
13892 * If the guest is not in real-mode or we have unrestricted guest execution support, or if we are
13893 * executing a nested-guest, reflect #GP to the guest or nested-guest.
13894 */
13895 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, HMVMX_CPUMCTX_EXTRN_ALL);
13896 AssertRCReturn(rc, rc);
13897 Log4Func(("Gst: cs:rip=%#04x:%#RX64 ErrorCode=%#x cr0=%#RX64 cpl=%u tr=%#04x\n", pCtx->cs.Sel, pCtx->rip,
13898 pVmxTransient->uExitIntErrorCode, pCtx->cr0, CPUMGetGuestCPL(pVCpu), pCtx->tr.Sel));
13899
13900 if ( pVmxTransient->fIsNestedGuest
13901 || !pVCpu->hm.s.fTrapXcptGpForLovelyMesaDrv
13902 || !hmR0VmxIsMesaDrvGp(pVCpu, pVmxTransient, pCtx))
13903 hmR0VmxSetPendingEvent(pVCpu, VMX_ENTRY_INT_INFO_FROM_EXIT_INT_INFO(pVmxTransient->uExitIntInfo),
13904 pVmxTransient->cbExitInstr, pVmxTransient->uExitIntErrorCode, 0 /* GCPtrFaultAddress */);
13905 else
13906 rc = hmR0VmxHandleMesaDrvGp(pVCpu, pVmxTransient, pCtx);
13907 return rc;
13908 }
13909
13910 Assert(CPUMIsGuestInRealModeEx(pCtx));
13911 Assert(!pVCpu->CTX_SUFF(pVM)->hm.s.vmx.fUnrestrictedGuest);
13912 Assert(!pVmxTransient->fIsNestedGuest);
13913
13914 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, HMVMX_CPUMCTX_EXTRN_ALL);
13915 AssertRCReturn(rc, rc);
13916
13917 VBOXSTRICTRC rcStrict = IEMExecOne(pVCpu);
13918 if (rcStrict == VINF_SUCCESS)
13919 {
13920 if (!CPUMIsGuestInRealModeEx(pCtx))
13921 {
13922 /*
13923 * The guest is no longer in real-mode, check if we can continue executing the
13924 * guest using hardware-assisted VMX. Otherwise, fall back to emulation.
13925 */
13926 pVmcsInfo->RealMode.fRealOnV86Active = false;
13927 if (HMCanExecuteVmxGuest(pVCpu->pVMR0, pVCpu, pCtx))
13928 {
13929 Log4Func(("Mode changed but guest still suitable for executing using hardware-assisted VMX\n"));
13930 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_ALL_GUEST);
13931 }
13932 else
13933 {
13934 Log4Func(("Mode changed -> VINF_EM_RESCHEDULE\n"));
13935 rcStrict = VINF_EM_RESCHEDULE;
13936 }
13937 }
13938 else
13939 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_ALL_GUEST);
13940 }
13941 else if (rcStrict == VINF_IEM_RAISED_XCPT)
13942 {
13943 rcStrict = VINF_SUCCESS;
13944 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
13945 }
13946 return VBOXSTRICTRC_VAL(rcStrict);
13947}
13948
13949
13950/**
13951 * VM-exit exception handler wrapper for all other exceptions that are not handled
13952 * by a specific handler.
13953 *
13954 * This simply re-injects the exception back into the VM without any special
13955 * processing.
13956 *
13957 * @remarks Requires all fields in HMVMX_READ_XCPT_INFO to be read from the VMCS.
13958 */
13959static VBOXSTRICTRC hmR0VmxExitXcptOthers(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
13960{
13961 HMVMX_VALIDATE_EXIT_XCPT_HANDLER_PARAMS(pVCpu, pVmxTransient);
13962
13963#ifndef HMVMX_ALWAYS_TRAP_ALL_XCPTS
13964 PCVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
13965 AssertMsg(pVCpu->hm.s.fUsingDebugLoop || pVmcsInfo->RealMode.fRealOnV86Active || pVmxTransient->fIsNestedGuest,
13966 ("uVector=%#x u32XcptBitmap=%#X32\n",
13967 VMX_EXIT_INT_INFO_VECTOR(pVmxTransient->uExitIntInfo), pVmcsInfo->u32XcptBitmap));
13968 NOREF(pVmcsInfo);
13969#endif
13970
13971 /*
13972 * Re-inject the exception into the guest. This cannot be a double-fault condition which
13973 * would have been handled while checking exits due to event delivery.
13974 */
13975 uint8_t const uVector = VMX_EXIT_INT_INFO_VECTOR(pVmxTransient->uExitIntInfo);
13976
13977#ifdef HMVMX_ALWAYS_TRAP_ALL_XCPTS
13978 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, CPUMCTX_EXTRN_CS | CPUMCTX_EXTRN_RIP);
13979 AssertRCReturn(rc, rc);
13980 Log4Func(("Reinjecting Xcpt. uVector=%#x cs:rip=%#04x:%#RX64\n", uVector, pCtx->cs.Sel, pCtx->rip));
13981#endif
13982
13983#ifdef VBOX_WITH_STATISTICS
13984 switch (uVector)
13985 {
13986 case X86_XCPT_DE: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestDE); break;
13987 case X86_XCPT_DB: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestDB); break;
13988 case X86_XCPT_BP: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestBP); break;
13989 case X86_XCPT_OF: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestOF); break;
13990 case X86_XCPT_BR: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestBR); break;
13991 case X86_XCPT_UD: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestUD); break;
13992 case X86_XCPT_NM: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestOF); break;
13993 case X86_XCPT_DF: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestDF); break;
13994 case X86_XCPT_TS: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestTS); break;
13995 case X86_XCPT_NP: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestNP); break;
13996 case X86_XCPT_SS: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestSS); break;
13997 case X86_XCPT_GP: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestGP); break;
13998 case X86_XCPT_PF: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestPF); break;
13999 case X86_XCPT_MF: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestMF); break;
14000 case X86_XCPT_AC: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestAC); break;
14001 case X86_XCPT_XF: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestXF); break;
14002 default:
14003 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestXcpUnk);
14004 break;
14005 }
14006#endif
14007
14008 /* We should never call this function for a page-fault, we'd need to pass on the fault address below otherwise. */
14009 Assert(!VMX_EXIT_INT_INFO_IS_XCPT_PF(pVmxTransient->uExitIntInfo));
14010 NOREF(uVector);
14011
14012 /* Re-inject the original exception into the guest. */
14013 hmR0VmxSetPendingEvent(pVCpu, VMX_ENTRY_INT_INFO_FROM_EXIT_INT_INFO(pVmxTransient->uExitIntInfo),
14014 pVmxTransient->cbExitInstr, pVmxTransient->uExitIntErrorCode, 0 /* GCPtrFaultAddress */);
14015 return VINF_SUCCESS;
14016}
14017
14018
14019/**
14020 * VM-exit exception handler for all exceptions (except NMIs!).
14021 *
14022 * @remarks This may be called for both guests and nested-guests. Take care to not
14023 * make assumptions and avoid doing anything that is not relevant when
14024 * executing a nested-guest (e.g., Mesa driver hacks).
14025 */
14026static VBOXSTRICTRC hmR0VmxExitXcpt(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14027{
14028 HMVMX_ASSERT_READ(pVmxTransient, HMVMX_READ_XCPT_INFO);
14029
14030 /*
14031 * If this VM-exit occurred while delivering an event through the guest IDT, take
14032 * action based on the return code and additional hints (e.g. for page-faults)
14033 * that will be updated in the VMX transient structure.
14034 */
14035 VBOXSTRICTRC rcStrict = hmR0VmxCheckExitDueToEventDelivery(pVCpu, pVmxTransient);
14036 if (rcStrict == VINF_SUCCESS)
14037 {
14038 /*
14039 * If an exception caused a VM-exit due to delivery of an event, the original
14040 * event may have to be re-injected into the guest. We shall reinject it and
14041 * continue guest execution. However, page-fault is a complicated case and
14042 * needs additional processing done in hmR0VmxExitXcptPF().
14043 */
14044 Assert(VMX_EXIT_INT_INFO_IS_VALID(pVmxTransient->uExitIntInfo));
14045 uint8_t const uVector = VMX_EXIT_INT_INFO_VECTOR(pVmxTransient->uExitIntInfo);
14046 if ( !pVCpu->hm.s.Event.fPending
14047 || uVector == X86_XCPT_PF)
14048 {
14049 switch (uVector)
14050 {
14051 case X86_XCPT_PF: return hmR0VmxExitXcptPF(pVCpu, pVmxTransient);
14052 case X86_XCPT_GP: return hmR0VmxExitXcptGP(pVCpu, pVmxTransient);
14053 case X86_XCPT_MF: return hmR0VmxExitXcptMF(pVCpu, pVmxTransient);
14054 case X86_XCPT_DB: return hmR0VmxExitXcptDB(pVCpu, pVmxTransient);
14055 case X86_XCPT_BP: return hmR0VmxExitXcptBP(pVCpu, pVmxTransient);
14056 case X86_XCPT_AC: return hmR0VmxExitXcptAC(pVCpu, pVmxTransient);
14057 default:
14058 return hmR0VmxExitXcptOthers(pVCpu, pVmxTransient);
14059 }
14060 }
14061 /* else: inject pending event before resuming guest execution. */
14062 }
14063 else if (rcStrict == VINF_HM_DOUBLE_FAULT)
14064 {
14065 Assert(pVCpu->hm.s.Event.fPending);
14066 rcStrict = VINF_SUCCESS;
14067 }
14068
14069 return rcStrict;
14070}
14071/** @} */
14072
14073
14074/** @name VM-exit handlers.
14075 * @{
14076 */
14077/* -=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= */
14078/* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- VM-exit handlers -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- */
14079/* -=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= */
14080
14081/**
14082 * VM-exit handler for external interrupts (VMX_EXIT_EXT_INT).
14083 */
14084HMVMX_EXIT_DECL hmR0VmxExitExtInt(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14085{
14086 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14087 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitExtInt);
14088 /* Windows hosts (32-bit and 64-bit) have DPC latency issues. See @bugref{6853}. */
14089 if (VMMR0ThreadCtxHookIsEnabled(pVCpu))
14090 return VINF_SUCCESS;
14091 return VINF_EM_RAW_INTERRUPT;
14092}
14093
14094
14095/**
14096 * VM-exit handler for exceptions or NMIs (VMX_EXIT_XCPT_OR_NMI). Conditional
14097 * VM-exit.
14098 */
14099HMVMX_EXIT_DECL hmR0VmxExitXcptOrNmi(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14100{
14101 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14102 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatExitXcptNmi, y3);
14103
14104 hmR0VmxReadExitIntInfoVmcs(pVmxTransient);
14105
14106 uint32_t const uExitIntType = VMX_EXIT_INT_INFO_TYPE(pVmxTransient->uExitIntInfo);
14107 uint8_t const uVector = VMX_EXIT_INT_INFO_VECTOR(pVmxTransient->uExitIntInfo);
14108 Assert(VMX_EXIT_INT_INFO_IS_VALID(pVmxTransient->uExitIntInfo));
14109
14110 PCVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
14111 Assert( !(pVmcsInfo->u32ExitCtls & VMX_EXIT_CTLS_ACK_EXT_INT)
14112 && uExitIntType != VMX_EXIT_INT_INFO_TYPE_EXT_INT);
14113 NOREF(pVmcsInfo);
14114
14115 VBOXSTRICTRC rcStrict;
14116 switch (uExitIntType)
14117 {
14118 /*
14119 * Host physical NMIs:
14120 * This cannot be a guest NMI as the only way for the guest to receive an NMI is if we
14121 * injected it ourselves and anything we inject is not going to cause a VM-exit directly
14122 * for the event being injected[1]. Go ahead and dispatch the NMI to the host[2].
14123 *
14124 * See Intel spec. 27.2.3 "Information for VM Exits During Event Delivery".
14125 * See Intel spec. 27.5.5 "Updating Non-Register State".
14126 */
14127 case VMX_EXIT_INT_INFO_TYPE_NMI:
14128 {
14129 rcStrict = hmR0VmxExitHostNmi(pVCpu, pVmcsInfo);
14130 break;
14131 }
14132
14133 /*
14134 * Privileged software exceptions (#DB from ICEBP),
14135 * Software exceptions (#BP and #OF),
14136 * Hardware exceptions:
14137 * Process the required exceptions and resume guest execution if possible.
14138 */
14139 case VMX_EXIT_INT_INFO_TYPE_PRIV_SW_XCPT:
14140 Assert(uVector == X86_XCPT_DB);
14141 RT_FALL_THRU();
14142 case VMX_EXIT_INT_INFO_TYPE_SW_XCPT:
14143 Assert(uVector == X86_XCPT_BP || uVector == X86_XCPT_OF || uExitIntType == VMX_EXIT_INT_INFO_TYPE_PRIV_SW_XCPT);
14144 RT_FALL_THRU();
14145 case VMX_EXIT_INT_INFO_TYPE_HW_XCPT:
14146 {
14147 NOREF(uVector);
14148 hmR0VmxReadExitIntErrorCodeVmcs(pVmxTransient);
14149 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
14150 hmR0VmxReadIdtVectoringInfoVmcs(pVmxTransient);
14151 hmR0VmxReadIdtVectoringErrorCodeVmcs(pVmxTransient);
14152
14153 rcStrict = hmR0VmxExitXcpt(pVCpu, pVmxTransient);
14154 break;
14155 }
14156
14157 default:
14158 {
14159 pVCpu->hm.s.u32HMError = pVmxTransient->uExitIntInfo;
14160 rcStrict = VERR_VMX_UNEXPECTED_INTERRUPTION_EXIT_TYPE;
14161 AssertMsgFailed(("Invalid/unexpected VM-exit interruption info %#x\n", pVmxTransient->uExitIntInfo));
14162 break;
14163 }
14164 }
14165
14166 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExitXcptNmi, y3);
14167 return rcStrict;
14168}
14169
14170
14171/**
14172 * VM-exit handler for interrupt-window exiting (VMX_EXIT_INT_WINDOW).
14173 */
14174HMVMX_EXIT_NSRC_DECL hmR0VmxExitIntWindow(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14175{
14176 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14177
14178 /* Indicate that we no longer need to VM-exit when the guest is ready to receive interrupts, it is now ready. */
14179 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
14180 hmR0VmxClearIntWindowExitVmcs(pVmcsInfo);
14181
14182 /* Evaluate and deliver pending events and resume guest execution. */
14183 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIntWindow);
14184 return VINF_SUCCESS;
14185}
14186
14187
14188/**
14189 * VM-exit handler for NMI-window exiting (VMX_EXIT_NMI_WINDOW).
14190 */
14191HMVMX_EXIT_NSRC_DECL hmR0VmxExitNmiWindow(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14192{
14193 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14194
14195 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
14196 if (RT_UNLIKELY(!(pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_NMI_WINDOW_EXIT))) /** @todo NSTVMX: Turn this into an assertion. */
14197 {
14198 AssertMsgFailed(("Unexpected NMI-window exit.\n"));
14199 HMVMX_UNEXPECTED_EXIT_RET(pVCpu, pVmxTransient->uExitReason);
14200 }
14201
14202 Assert(!CPUMIsGuestNmiBlocking(pVCpu));
14203
14204 /*
14205 * If block-by-STI is set when we get this VM-exit, it means the CPU doesn't block NMIs following STI.
14206 * It is therefore safe to unblock STI and deliver the NMI ourselves. See @bugref{7445}.
14207 */
14208 uint32_t fIntrState;
14209 int rc = VMXReadVmcs32(VMX_VMCS32_GUEST_INT_STATE, &fIntrState);
14210 AssertRC(rc);
14211 Assert(!(fIntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_MOVSS));
14212 if (fIntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_STI)
14213 {
14214 if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS))
14215 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS);
14216
14217 fIntrState &= ~VMX_VMCS_GUEST_INT_STATE_BLOCK_STI;
14218 rc = VMXWriteVmcs32(VMX_VMCS32_GUEST_INT_STATE, fIntrState);
14219 AssertRC(rc);
14220 }
14221
14222 /* Indicate that we no longer need to VM-exit when the guest is ready to receive NMIs, it is now ready */
14223 hmR0VmxClearNmiWindowExitVmcs(pVmcsInfo);
14224
14225 /* Evaluate and deliver pending events and resume guest execution. */
14226 return VINF_SUCCESS;
14227}
14228
14229
14230/**
14231 * VM-exit handler for WBINVD (VMX_EXIT_WBINVD). Conditional VM-exit.
14232 */
14233HMVMX_EXIT_NSRC_DECL hmR0VmxExitWbinvd(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14234{
14235 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14236 return hmR0VmxAdvanceGuestRip(pVCpu, pVmxTransient);
14237}
14238
14239
14240/**
14241 * VM-exit handler for INVD (VMX_EXIT_INVD). Unconditional VM-exit.
14242 */
14243HMVMX_EXIT_NSRC_DECL hmR0VmxExitInvd(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14244{
14245 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14246 return hmR0VmxAdvanceGuestRip(pVCpu, pVmxTransient);
14247}
14248
14249
14250/**
14251 * VM-exit handler for CPUID (VMX_EXIT_CPUID). Unconditional VM-exit.
14252 */
14253HMVMX_EXIT_DECL hmR0VmxExitCpuid(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14254{
14255 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14256
14257 /*
14258 * Get the state we need and update the exit history entry.
14259 */
14260 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
14261 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
14262
14263 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, IEM_CPUMCTX_EXTRN_EXEC_DECODED_NO_MEM_MASK);
14264 AssertRCReturn(rc, rc);
14265
14266 VBOXSTRICTRC rcStrict;
14267 PCEMEXITREC pExitRec = EMHistoryUpdateFlagsAndTypeAndPC(pVCpu,
14268 EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM | EMEXIT_F_HM, EMEXITTYPE_CPUID),
14269 pVCpu->cpum.GstCtx.rip + pVCpu->cpum.GstCtx.cs.u64Base);
14270 if (!pExitRec)
14271 {
14272 /*
14273 * Regular CPUID instruction execution.
14274 */
14275 rcStrict = IEMExecDecodedCpuid(pVCpu, pVmxTransient->cbExitInstr);
14276 if (rcStrict == VINF_SUCCESS)
14277 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS);
14278 else if (rcStrict == VINF_IEM_RAISED_XCPT)
14279 {
14280 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
14281 rcStrict = VINF_SUCCESS;
14282 }
14283 }
14284 else
14285 {
14286 /*
14287 * Frequent exit or something needing probing. Get state and call EMHistoryExec.
14288 */
14289 int rc2 = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, HMVMX_CPUMCTX_EXTRN_ALL);
14290 AssertRCReturn(rc2, rc2);
14291
14292 Log4(("CpuIdExit/%u: %04x:%08RX64: %#x/%#x -> EMHistoryExec\n",
14293 pVCpu->idCpu, pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip, pVCpu->cpum.GstCtx.eax, pVCpu->cpum.GstCtx.ecx));
14294
14295 rcStrict = EMHistoryExec(pVCpu, pExitRec, 0);
14296 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_ALL_GUEST);
14297
14298 Log4(("CpuIdExit/%u: %04x:%08RX64: EMHistoryExec -> %Rrc + %04x:%08RX64\n",
14299 pVCpu->idCpu, pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip,
14300 VBOXSTRICTRC_VAL(rcStrict), pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip));
14301 }
14302 return rcStrict;
14303}
14304
14305
14306/**
14307 * VM-exit handler for GETSEC (VMX_EXIT_GETSEC). Unconditional VM-exit.
14308 */
14309HMVMX_EXIT_DECL hmR0VmxExitGetsec(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14310{
14311 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14312
14313 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
14314 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, CPUMCTX_EXTRN_CR4);
14315 AssertRCReturn(rc, rc);
14316
14317 if (pVCpu->cpum.GstCtx.cr4 & X86_CR4_SMXE)
14318 return VINF_EM_RAW_EMULATE_INSTR;
14319
14320 AssertMsgFailed(("hmR0VmxExitGetsec: Unexpected VM-exit when CR4.SMXE is 0.\n"));
14321 HMVMX_UNEXPECTED_EXIT_RET(pVCpu, pVmxTransient->uExitReason);
14322}
14323
14324
14325/**
14326 * VM-exit handler for RDTSC (VMX_EXIT_RDTSC). Conditional VM-exit.
14327 */
14328HMVMX_EXIT_DECL hmR0VmxExitRdtsc(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14329{
14330 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14331
14332 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
14333 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
14334 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, IEM_CPUMCTX_EXTRN_MUST_MASK);
14335 AssertRCReturn(rc, rc);
14336
14337 VBOXSTRICTRC rcStrict = IEMExecDecodedRdtsc(pVCpu, pVmxTransient->cbExitInstr);
14338 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
14339 {
14340 /* If we get a spurious VM-exit when TSC offsetting is enabled,
14341 we must reset offsetting on VM-entry. See @bugref{6634}. */
14342 if (pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_USE_TSC_OFFSETTING)
14343 pVmxTransient->fUpdatedTscOffsettingAndPreemptTimer = false;
14344 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS);
14345 }
14346 else if (rcStrict == VINF_IEM_RAISED_XCPT)
14347 {
14348 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
14349 rcStrict = VINF_SUCCESS;
14350 }
14351 return rcStrict;
14352}
14353
14354
14355/**
14356 * VM-exit handler for RDTSCP (VMX_EXIT_RDTSCP). Conditional VM-exit.
14357 */
14358HMVMX_EXIT_DECL hmR0VmxExitRdtscp(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14359{
14360 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14361
14362 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
14363 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
14364 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, IEM_CPUMCTX_EXTRN_MUST_MASK | CPUMCTX_EXTRN_TSC_AUX);
14365 AssertRCReturn(rc, rc);
14366
14367 VBOXSTRICTRC rcStrict = IEMExecDecodedRdtscp(pVCpu, pVmxTransient->cbExitInstr);
14368 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
14369 {
14370 /* If we get a spurious VM-exit when TSC offsetting is enabled,
14371 we must reset offsetting on VM-reentry. See @bugref{6634}. */
14372 if (pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_USE_TSC_OFFSETTING)
14373 pVmxTransient->fUpdatedTscOffsettingAndPreemptTimer = false;
14374 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS);
14375 }
14376 else if (rcStrict == VINF_IEM_RAISED_XCPT)
14377 {
14378 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
14379 rcStrict = VINF_SUCCESS;
14380 }
14381 return rcStrict;
14382}
14383
14384
14385/**
14386 * VM-exit handler for RDPMC (VMX_EXIT_RDPMC). Conditional VM-exit.
14387 */
14388HMVMX_EXIT_DECL hmR0VmxExitRdpmc(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14389{
14390 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14391
14392 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
14393 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, CPUMCTX_EXTRN_CR4 | CPUMCTX_EXTRN_CR0
14394 | CPUMCTX_EXTRN_RFLAGS | CPUMCTX_EXTRN_SS);
14395 AssertRCReturn(rc, rc);
14396
14397 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
14398 rc = EMInterpretRdpmc(pVCpu->CTX_SUFF(pVM), pVCpu, CPUMCTX2CORE(pCtx));
14399 if (RT_LIKELY(rc == VINF_SUCCESS))
14400 {
14401 rc = hmR0VmxAdvanceGuestRip(pVCpu, pVmxTransient);
14402 Assert(pVmxTransient->cbExitInstr == 2);
14403 }
14404 else
14405 {
14406 AssertMsgFailed(("hmR0VmxExitRdpmc: EMInterpretRdpmc failed with %Rrc\n", rc));
14407 rc = VERR_EM_INTERPRETER;
14408 }
14409 return rc;
14410}
14411
14412
14413/**
14414 * VM-exit handler for VMCALL (VMX_EXIT_VMCALL). Unconditional VM-exit.
14415 */
14416HMVMX_EXIT_DECL hmR0VmxExitVmcall(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14417{
14418 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14419
14420 VBOXSTRICTRC rcStrict = VERR_VMX_IPE_3;
14421 if (EMAreHypercallInstructionsEnabled(pVCpu))
14422 {
14423 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
14424 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, CPUMCTX_EXTRN_RIP | CPUMCTX_EXTRN_RFLAGS | CPUMCTX_EXTRN_CR0
14425 | CPUMCTX_EXTRN_SS | CPUMCTX_EXTRN_CS | CPUMCTX_EXTRN_EFER);
14426 AssertRCReturn(rc, rc);
14427
14428 /* Perform the hypercall. */
14429 rcStrict = GIMHypercall(pVCpu, &pVCpu->cpum.GstCtx);
14430 if (rcStrict == VINF_SUCCESS)
14431 {
14432 rc = hmR0VmxAdvanceGuestRip(pVCpu, pVmxTransient);
14433 AssertRCReturn(rc, rc);
14434 }
14435 else
14436 Assert( rcStrict == VINF_GIM_R3_HYPERCALL
14437 || rcStrict == VINF_GIM_HYPERCALL_CONTINUING
14438 || RT_FAILURE(rcStrict));
14439
14440 /* If the hypercall changes anything other than guest's general-purpose registers,
14441 we would need to reload the guest changed bits here before VM-entry. */
14442 }
14443 else
14444 Log4Func(("Hypercalls not enabled\n"));
14445
14446 /* If hypercalls are disabled or the hypercall failed for some reason, raise #UD and continue. */
14447 if (RT_FAILURE(rcStrict))
14448 {
14449 hmR0VmxSetPendingXcptUD(pVCpu);
14450 rcStrict = VINF_SUCCESS;
14451 }
14452
14453 return rcStrict;
14454}
14455
14456
14457/**
14458 * VM-exit handler for INVLPG (VMX_EXIT_INVLPG). Conditional VM-exit.
14459 */
14460HMVMX_EXIT_DECL hmR0VmxExitInvlpg(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14461{
14462 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14463 Assert(!pVCpu->CTX_SUFF(pVM)->hm.s.fNestedPaging || pVCpu->hm.s.fUsingDebugLoop);
14464
14465 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
14466 hmR0VmxReadExitQualVmcs(pVmxTransient);
14467 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
14468 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, IEM_CPUMCTX_EXTRN_EXEC_DECODED_MEM_MASK);
14469 AssertRCReturn(rc, rc);
14470
14471 VBOXSTRICTRC rcStrict = IEMExecDecodedInvlpg(pVCpu, pVmxTransient->cbExitInstr, pVmxTransient->uExitQual);
14472
14473 if (rcStrict == VINF_SUCCESS || rcStrict == VINF_PGM_SYNC_CR3)
14474 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS);
14475 else if (rcStrict == VINF_IEM_RAISED_XCPT)
14476 {
14477 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
14478 rcStrict = VINF_SUCCESS;
14479 }
14480 else
14481 AssertMsgFailed(("Unexpected IEMExecDecodedInvlpg(%#RX64) status: %Rrc\n", pVmxTransient->uExitQual,
14482 VBOXSTRICTRC_VAL(rcStrict)));
14483 return rcStrict;
14484}
14485
14486
14487/**
14488 * VM-exit handler for MONITOR (VMX_EXIT_MONITOR). Conditional VM-exit.
14489 */
14490HMVMX_EXIT_DECL hmR0VmxExitMonitor(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14491{
14492 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14493
14494 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
14495 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
14496 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, IEM_CPUMCTX_EXTRN_EXEC_DECODED_MEM_MASK | CPUMCTX_EXTRN_DS);
14497 AssertRCReturn(rc, rc);
14498
14499 VBOXSTRICTRC rcStrict = IEMExecDecodedMonitor(pVCpu, pVmxTransient->cbExitInstr);
14500 if (rcStrict == VINF_SUCCESS)
14501 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS);
14502 else if (rcStrict == VINF_IEM_RAISED_XCPT)
14503 {
14504 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
14505 rcStrict = VINF_SUCCESS;
14506 }
14507
14508 return rcStrict;
14509}
14510
14511
14512/**
14513 * VM-exit handler for MWAIT (VMX_EXIT_MWAIT). Conditional VM-exit.
14514 */
14515HMVMX_EXIT_DECL hmR0VmxExitMwait(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14516{
14517 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14518
14519 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
14520 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
14521 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, IEM_CPUMCTX_EXTRN_EXEC_DECODED_NO_MEM_MASK);
14522 AssertRCReturn(rc, rc);
14523
14524 VBOXSTRICTRC rcStrict = IEMExecDecodedMwait(pVCpu, pVmxTransient->cbExitInstr);
14525 if (RT_SUCCESS(rcStrict))
14526 {
14527 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS);
14528 if (EMMonitorWaitShouldContinue(pVCpu, &pVCpu->cpum.GstCtx))
14529 rcStrict = VINF_SUCCESS;
14530 }
14531
14532 return rcStrict;
14533}
14534
14535
14536/**
14537 * VM-exit handler for triple faults (VMX_EXIT_TRIPLE_FAULT). Unconditional
14538 * VM-exit.
14539 */
14540HMVMX_EXIT_DECL hmR0VmxExitTripleFault(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14541{
14542 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14543 return VINF_EM_RESET;
14544}
14545
14546
14547/**
14548 * VM-exit handler for HLT (VMX_EXIT_HLT). Conditional VM-exit.
14549 */
14550HMVMX_EXIT_DECL hmR0VmxExitHlt(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14551{
14552 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14553
14554 int rc = hmR0VmxAdvanceGuestRip(pVCpu, pVmxTransient);
14555 AssertRCReturn(rc, rc);
14556
14557 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_RFLAGS); /* Advancing the RIP above should've imported eflags. */
14558 if (EMShouldContinueAfterHalt(pVCpu, &pVCpu->cpum.GstCtx)) /* Requires eflags. */
14559 rc = VINF_SUCCESS;
14560 else
14561 rc = VINF_EM_HALT;
14562
14563 if (rc != VINF_SUCCESS)
14564 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchHltToR3);
14565 return rc;
14566}
14567
14568
14569/**
14570 * VM-exit handler for instructions that result in a \#UD exception delivered to
14571 * the guest.
14572 */
14573HMVMX_EXIT_NSRC_DECL hmR0VmxExitSetPendingXcptUD(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14574{
14575 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14576 hmR0VmxSetPendingXcptUD(pVCpu);
14577 return VINF_SUCCESS;
14578}
14579
14580
14581/**
14582 * VM-exit handler for expiry of the VMX-preemption timer.
14583 */
14584HMVMX_EXIT_DECL hmR0VmxExitPreemptTimer(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14585{
14586 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14587
14588 /* If the VMX-preemption timer has expired, reinitialize the preemption timer on next VM-entry. */
14589 pVmxTransient->fUpdatedTscOffsettingAndPreemptTimer = false;
14590
14591 /* If there are any timer events pending, fall back to ring-3, otherwise resume guest execution. */
14592 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
14593 bool fTimersPending = TMTimerPollBool(pVM, pVCpu);
14594 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitPreemptTimer);
14595 return fTimersPending ? VINF_EM_RAW_TIMER_PENDING : VINF_SUCCESS;
14596}
14597
14598
14599/**
14600 * VM-exit handler for XSETBV (VMX_EXIT_XSETBV). Unconditional VM-exit.
14601 */
14602HMVMX_EXIT_DECL hmR0VmxExitXsetbv(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14603{
14604 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14605
14606 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
14607 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
14608 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, IEM_CPUMCTX_EXTRN_MUST_MASK | CPUMCTX_EXTRN_CR4);
14609 AssertRCReturn(rc, rc);
14610
14611 VBOXSTRICTRC rcStrict = IEMExecDecodedXsetbv(pVCpu, pVmxTransient->cbExitInstr);
14612 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, rcStrict != VINF_IEM_RAISED_XCPT ? HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS
14613 : HM_CHANGED_RAISED_XCPT_MASK);
14614
14615 PCCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
14616 pVCpu->hm.s.fLoadSaveGuestXcr0 = (pCtx->cr4 & X86_CR4_OSXSAVE) && pCtx->aXcr[0] != ASMGetXcr0();
14617
14618 return rcStrict;
14619}
14620
14621
14622/**
14623 * VM-exit handler for INVPCID (VMX_EXIT_INVPCID). Conditional VM-exit.
14624 */
14625HMVMX_EXIT_DECL hmR0VmxExitInvpcid(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14626{
14627 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14628
14629#if 1
14630 /** @todo Use VM-exit instruction information. */
14631 return VERR_EM_INTERPRETER;
14632#else
14633 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
14634 hmR0VmxReadExitInstrInfoVmcs(pVmxTransient);
14635 hmR0VmxReadExitQualVmcs(pVmxTransient);
14636 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, CPUMCTX_EXTRN_RSP | CPUMCTX_EXTRN_SREG_MASK
14637 | IEM_CPUMCTX_EXTRN_EXEC_DECODED_MEM_MASK);
14638 AssertRCReturn(rc, rc);
14639
14640 /* Paranoia. Ensure this has a memory operand. */
14641 Assert(!pVmxTransient->ExitInstrInfo.Inv.u1Cleared0);
14642
14643 uint8_t const iGReg = pVmxTransient->ExitInstrInfo.VmreadVmwrite.iReg2;
14644 Assert(iGReg < RT_ELEMENTS(pVCpu->cpum.GstCtx.aGRegs));
14645 uint64_t const uType = CPUMIsGuestIn64BitCode(pVCpu) ? pVCpu->cpum.GstCtx.aGRegs[iGReg].u64
14646 : pVCpu->cpum.GstCtx.aGRegs[iGReg].u32;
14647
14648 RTGCPTR GCPtrDesc;
14649 HMVMX_DECODE_MEM_OPERAND(pVCpu, pVmxTransient->ExitInstrInfo.u, pVmxTransient->uExitQual, VMXMEMACCESS_READ, &GCPtrDesc);
14650
14651 VBOXSTRICTRC rcStrict = IEMExecDecodedInvpcid(pVCpu, pVmxTransient->cbExitInstr, pVmxTransient->ExitInstrInfo.Inv.iSegReg,
14652 GCPtrDesc, uType);
14653 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
14654 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS);
14655 else if (rcStrict == VINF_IEM_RAISED_XCPT)
14656 {
14657 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
14658 rcStrict = VINF_SUCCESS;
14659 }
14660 return rcStrict;
14661#endif
14662}
14663
14664
14665/**
14666 * VM-exit handler for invalid-guest-state (VMX_EXIT_ERR_INVALID_GUEST_STATE). Error
14667 * VM-exit.
14668 */
14669HMVMX_EXIT_NSRC_DECL hmR0VmxExitErrInvalidGuestState(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14670{
14671 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
14672 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, HMVMX_CPUMCTX_EXTRN_ALL);
14673 AssertRCReturn(rc, rc);
14674
14675 rc = hmR0VmxCheckCachedVmcsCtls(pVCpu, pVmcsInfo, pVmxTransient->fIsNestedGuest);
14676 if (RT_FAILURE(rc))
14677 return rc;
14678
14679 uint32_t const uInvalidReason = hmR0VmxCheckGuestState(pVCpu, pVmcsInfo);
14680 NOREF(uInvalidReason);
14681
14682#ifdef VBOX_STRICT
14683 uint32_t fIntrState;
14684 uint64_t u64Val;
14685 hmR0VmxReadEntryIntInfoVmcs(pVmxTransient);
14686 hmR0VmxReadEntryXcptErrorCodeVmcs(pVmxTransient);
14687 hmR0VmxReadEntryInstrLenVmcs(pVmxTransient);
14688
14689 Log4(("uInvalidReason %u\n", uInvalidReason));
14690 Log4(("VMX_VMCS32_CTRL_ENTRY_INTERRUPTION_INFO %#RX32\n", pVmxTransient->uEntryIntInfo));
14691 Log4(("VMX_VMCS32_CTRL_ENTRY_EXCEPTION_ERRCODE %#RX32\n", pVmxTransient->uEntryXcptErrorCode));
14692 Log4(("VMX_VMCS32_CTRL_ENTRY_INSTR_LENGTH %#RX32\n", pVmxTransient->cbEntryInstr));
14693
14694 rc = VMXReadVmcs32(VMX_VMCS32_GUEST_INT_STATE, &fIntrState); AssertRC(rc);
14695 Log4(("VMX_VMCS32_GUEST_INT_STATE %#RX32\n", fIntrState));
14696 rc = VMXReadVmcsNw(VMX_VMCS_GUEST_CR0, &u64Val); AssertRC(rc);
14697 Log4(("VMX_VMCS_GUEST_CR0 %#RX64\n", u64Val));
14698 rc = VMXReadVmcsNw(VMX_VMCS_CTRL_CR0_MASK, &u64Val); AssertRC(rc);
14699 Log4(("VMX_VMCS_CTRL_CR0_MASK %#RX64\n", u64Val));
14700 rc = VMXReadVmcsNw(VMX_VMCS_CTRL_CR0_READ_SHADOW, &u64Val); AssertRC(rc);
14701 Log4(("VMX_VMCS_CTRL_CR4_READ_SHADOW %#RX64\n", u64Val));
14702 rc = VMXReadVmcsNw(VMX_VMCS_CTRL_CR4_MASK, &u64Val); AssertRC(rc);
14703 Log4(("VMX_VMCS_CTRL_CR4_MASK %#RX64\n", u64Val));
14704 rc = VMXReadVmcsNw(VMX_VMCS_CTRL_CR4_READ_SHADOW, &u64Val); AssertRC(rc);
14705 Log4(("VMX_VMCS_CTRL_CR4_READ_SHADOW %#RX64\n", u64Val));
14706 if (pVCpu->CTX_SUFF(pVM)->hm.s.fNestedPaging)
14707 {
14708 rc = VMXReadVmcs64(VMX_VMCS64_CTRL_EPTP_FULL, &u64Val); AssertRC(rc);
14709 Log4(("VMX_VMCS64_CTRL_EPTP_FULL %#RX64\n", u64Val));
14710 }
14711 hmR0DumpRegs(pVCpu, HM_DUMP_REG_FLAGS_ALL);
14712#endif
14713
14714 return VERR_VMX_INVALID_GUEST_STATE;
14715}
14716
14717/**
14718 * VM-exit handler for all undefined/unexpected reasons. Should never happen.
14719 */
14720HMVMX_EXIT_NSRC_DECL hmR0VmxExitErrUnexpected(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14721{
14722 /*
14723 * Cumulative notes of all recognized but unexpected VM-exits.
14724 *
14725 * 1. This does -not- cover scenarios like a page-fault VM-exit occurring when
14726 * nested-paging is used.
14727 *
14728 * 2. Any instruction that causes a VM-exit unconditionally (for e.g. VMXON) must be
14729 * emulated or a #UD must be raised in the guest. Therefore, we should -not- be using
14730 * this function (and thereby stop VM execution) for handling such instructions.
14731 *
14732 *
14733 * VMX_EXIT_INIT_SIGNAL:
14734 * INIT signals are blocked in VMX root operation by VMXON and by SMI in SMM.
14735 * It is -NOT- blocked in VMX non-root operation so we can, in theory, still get these
14736 * VM-exits. However, we should not receive INIT signals VM-exit while executing a VM.
14737 *
14738 * See Intel spec. 33.14.1 Default Treatment of SMI Delivery"
14739 * See Intel spec. 29.3 "VMX Instructions" for "VMXON".
14740 * See Intel spec. "23.8 Restrictions on VMX operation".
14741 *
14742 * VMX_EXIT_SIPI:
14743 * SIPI exits can only occur in VMX non-root operation when the "wait-for-SIPI" guest
14744 * activity state is used. We don't make use of it as our guests don't have direct
14745 * access to the host local APIC.
14746 *
14747 * See Intel spec. 25.3 "Other Causes of VM-exits".
14748 *
14749 * VMX_EXIT_IO_SMI:
14750 * VMX_EXIT_SMI:
14751 * This can only happen if we support dual-monitor treatment of SMI, which can be
14752 * activated by executing VMCALL in VMX root operation. Only an STM (SMM transfer
14753 * monitor) would get this VM-exit when we (the executive monitor) execute a VMCALL in
14754 * VMX root mode or receive an SMI. If we get here, something funny is going on.
14755 *
14756 * See Intel spec. 33.15.6 "Activating the Dual-Monitor Treatment"
14757 * See Intel spec. 25.3 "Other Causes of VM-Exits"
14758 *
14759 * VMX_EXIT_ERR_MSR_LOAD:
14760 * Failures while loading MSRs are part of the VM-entry MSR-load area are unexpected
14761 * and typically indicates a bug in the hypervisor code. We thus cannot not resume
14762 * execution.
14763 *
14764 * See Intel spec. 26.7 "VM-Entry Failures During Or After Loading Guest State".
14765 *
14766 * VMX_EXIT_ERR_MACHINE_CHECK:
14767 * Machine check exceptions indicates a fatal/unrecoverable hardware condition
14768 * including but not limited to system bus, ECC, parity, cache and TLB errors. A
14769 * #MC exception abort class exception is raised. We thus cannot assume a
14770 * reasonable chance of continuing any sort of execution and we bail.
14771 *
14772 * See Intel spec. 15.1 "Machine-check Architecture".
14773 * See Intel spec. 27.1 "Architectural State Before A VM Exit".
14774 *
14775 * VMX_EXIT_PML_FULL:
14776 * VMX_EXIT_VIRTUALIZED_EOI:
14777 * VMX_EXIT_APIC_WRITE:
14778 * We do not currently support any of these features and thus they are all unexpected
14779 * VM-exits.
14780 *
14781 * VMX_EXIT_GDTR_IDTR_ACCESS:
14782 * VMX_EXIT_LDTR_TR_ACCESS:
14783 * VMX_EXIT_RDRAND:
14784 * VMX_EXIT_RSM:
14785 * VMX_EXIT_VMFUNC:
14786 * VMX_EXIT_ENCLS:
14787 * VMX_EXIT_RDSEED:
14788 * VMX_EXIT_XSAVES:
14789 * VMX_EXIT_XRSTORS:
14790 * VMX_EXIT_UMWAIT:
14791 * VMX_EXIT_TPAUSE:
14792 * These VM-exits are -not- caused unconditionally by execution of the corresponding
14793 * instruction. Any VM-exit for these instructions indicate a hardware problem,
14794 * unsupported CPU modes (like SMM) or potentially corrupt VMCS controls.
14795 *
14796 * See Intel spec. 25.1.3 "Instructions That Cause VM Exits Conditionally".
14797 */
14798 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14799 AssertMsgFailed(("Unexpected VM-exit %u\n", pVmxTransient->uExitReason));
14800 HMVMX_UNEXPECTED_EXIT_RET(pVCpu, pVmxTransient->uExitReason);
14801}
14802
14803
14804/**
14805 * VM-exit handler for RDMSR (VMX_EXIT_RDMSR).
14806 */
14807HMVMX_EXIT_DECL hmR0VmxExitRdmsr(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14808{
14809 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14810
14811 /** @todo Optimize this: We currently drag in the whole MSR state
14812 * (CPUMCTX_EXTRN_ALL_MSRS) here. We should optimize this to only get
14813 * MSRs required. That would require changes to IEM and possibly CPUM too.
14814 * (Should probably do it lazy fashion from CPUMAllMsrs.cpp). */
14815 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
14816 uint32_t const idMsr = pVCpu->cpum.GstCtx.ecx;
14817 uint64_t fImport = IEM_CPUMCTX_EXTRN_EXEC_DECODED_NO_MEM_MASK | CPUMCTX_EXTRN_ALL_MSRS;
14818 switch (idMsr)
14819 {
14820 case MSR_K8_FS_BASE: fImport |= CPUMCTX_EXTRN_FS; break;
14821 case MSR_K8_GS_BASE: fImport |= CPUMCTX_EXTRN_GS; break;
14822 }
14823
14824 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
14825 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, fImport);
14826 AssertRCReturn(rc, rc);
14827
14828 Log4Func(("ecx=%#RX32\n", idMsr));
14829
14830#ifdef VBOX_STRICT
14831 Assert(!pVmxTransient->fIsNestedGuest);
14832 if (pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_USE_MSR_BITMAPS)
14833 {
14834 if ( hmR0VmxIsAutoLoadGuestMsr(pVmcsInfo, idMsr)
14835 && idMsr != MSR_K6_EFER)
14836 {
14837 AssertMsgFailed(("Unexpected RDMSR for an MSR in the auto-load/store area in the VMCS. ecx=%#RX32\n", idMsr));
14838 HMVMX_UNEXPECTED_EXIT_RET(pVCpu, idMsr);
14839 }
14840 if (hmR0VmxIsLazyGuestMsr(pVCpu, idMsr))
14841 {
14842 Assert(pVmcsInfo->pvMsrBitmap);
14843 uint32_t fMsrpm = CPUMGetVmxMsrPermission(pVmcsInfo->pvMsrBitmap, idMsr);
14844 if (fMsrpm & VMXMSRPM_ALLOW_RD)
14845 {
14846 AssertMsgFailed(("Unexpected RDMSR for a passthru lazy-restore MSR. ecx=%#RX32\n", idMsr));
14847 HMVMX_UNEXPECTED_EXIT_RET(pVCpu, idMsr);
14848 }
14849 }
14850 }
14851#endif
14852
14853 VBOXSTRICTRC rcStrict = IEMExecDecodedRdmsr(pVCpu, pVmxTransient->cbExitInstr);
14854 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitRdmsr);
14855 if (rcStrict == VINF_SUCCESS)
14856 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS);
14857 else if (rcStrict == VINF_IEM_RAISED_XCPT)
14858 {
14859 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
14860 rcStrict = VINF_SUCCESS;
14861 }
14862 else
14863 AssertMsg(rcStrict == VINF_CPUM_R3_MSR_READ, ("Unexpected IEMExecDecodedRdmsr rc (%Rrc)\n", VBOXSTRICTRC_VAL(rcStrict)));
14864
14865 return rcStrict;
14866}
14867
14868
14869/**
14870 * VM-exit handler for WRMSR (VMX_EXIT_WRMSR).
14871 */
14872HMVMX_EXIT_DECL hmR0VmxExitWrmsr(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14873{
14874 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14875
14876 /** @todo Optimize this: We currently drag in the whole MSR state
14877 * (CPUMCTX_EXTRN_ALL_MSRS) here. We should optimize this to only get
14878 * MSRs required. That would require changes to IEM and possibly CPUM too.
14879 * (Should probably do it lazy fashion from CPUMAllMsrs.cpp). */
14880 uint32_t const idMsr = pVCpu->cpum.GstCtx.ecx;
14881 uint64_t fImport = IEM_CPUMCTX_EXTRN_EXEC_DECODED_NO_MEM_MASK | CPUMCTX_EXTRN_ALL_MSRS;
14882
14883 /*
14884 * The FS and GS base MSRs are not part of the above all-MSRs mask.
14885 * Although we don't need to fetch the base as it will be overwritten shortly, while
14886 * loading guest-state we would also load the entire segment register including limit
14887 * and attributes and thus we need to load them here.
14888 */
14889 switch (idMsr)
14890 {
14891 case MSR_K8_FS_BASE: fImport |= CPUMCTX_EXTRN_FS; break;
14892 case MSR_K8_GS_BASE: fImport |= CPUMCTX_EXTRN_GS; break;
14893 }
14894
14895 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
14896 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
14897 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, fImport);
14898 AssertRCReturn(rc, rc);
14899
14900 Log4Func(("ecx=%#RX32 edx:eax=%#RX32:%#RX32\n", idMsr, pVCpu->cpum.GstCtx.edx, pVCpu->cpum.GstCtx.eax));
14901
14902 VBOXSTRICTRC rcStrict = IEMExecDecodedWrmsr(pVCpu, pVmxTransient->cbExitInstr);
14903 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitWrmsr);
14904
14905 if (rcStrict == VINF_SUCCESS)
14906 {
14907 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS);
14908
14909 /* If this is an X2APIC WRMSR access, update the APIC state as well. */
14910 if ( idMsr == MSR_IA32_APICBASE
14911 || ( idMsr >= MSR_IA32_X2APIC_START
14912 && idMsr <= MSR_IA32_X2APIC_END))
14913 {
14914 /*
14915 * We've already saved the APIC related guest-state (TPR) in post-run phase.
14916 * When full APIC register virtualization is implemented we'll have to make
14917 * sure APIC state is saved from the VMCS before IEM changes it.
14918 */
14919 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_APIC_TPR);
14920 }
14921 else if (idMsr == MSR_IA32_TSC) /* Windows 7 does this during bootup. See @bugref{6398}. */
14922 pVmxTransient->fUpdatedTscOffsettingAndPreemptTimer = false;
14923 else if (idMsr == MSR_K6_EFER)
14924 {
14925 /*
14926 * If the guest touches the EFER MSR we need to update the VM-Entry and VM-Exit controls
14927 * as well, even if it is -not- touching bits that cause paging mode changes (LMA/LME).
14928 * We care about the other bits as well, SCE and NXE. See @bugref{7368}.
14929 */
14930 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_EFER_MSR | HM_CHANGED_VMX_ENTRY_EXIT_CTLS);
14931 }
14932
14933 /* Update MSRs that are part of the VMCS and auto-load/store area when MSR-bitmaps are not used. */
14934 if (!(pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_USE_MSR_BITMAPS))
14935 {
14936 switch (idMsr)
14937 {
14938 case MSR_IA32_SYSENTER_CS: ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_SYSENTER_CS_MSR); break;
14939 case MSR_IA32_SYSENTER_EIP: ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_SYSENTER_EIP_MSR); break;
14940 case MSR_IA32_SYSENTER_ESP: ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_SYSENTER_ESP_MSR); break;
14941 case MSR_K8_FS_BASE: ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_FS); break;
14942 case MSR_K8_GS_BASE: ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_GS); break;
14943 case MSR_K6_EFER: /* Nothing to do, already handled above. */ break;
14944 default:
14945 {
14946 if (hmR0VmxIsLazyGuestMsr(pVCpu, idMsr))
14947 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_VMX_GUEST_LAZY_MSRS);
14948 else if (hmR0VmxIsAutoLoadGuestMsr(pVmcsInfo, idMsr))
14949 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_VMX_GUEST_AUTO_MSRS);
14950 break;
14951 }
14952 }
14953 }
14954#ifdef VBOX_STRICT
14955 else
14956 {
14957 /* Paranoia. Validate that MSRs in the MSR-bitmaps with write-passthru are not intercepted. */
14958 switch (idMsr)
14959 {
14960 case MSR_IA32_SYSENTER_CS:
14961 case MSR_IA32_SYSENTER_EIP:
14962 case MSR_IA32_SYSENTER_ESP:
14963 case MSR_K8_FS_BASE:
14964 case MSR_K8_GS_BASE:
14965 {
14966 AssertMsgFailed(("Unexpected WRMSR for an MSR in the VMCS. ecx=%#RX32\n", idMsr));
14967 HMVMX_UNEXPECTED_EXIT_RET(pVCpu, idMsr);
14968 }
14969
14970 /* Writes to MSRs in auto-load/store area/swapped MSRs, shouldn't cause VM-exits with MSR-bitmaps. */
14971 default:
14972 {
14973 if (hmR0VmxIsAutoLoadGuestMsr(pVmcsInfo, idMsr))
14974 {
14975 /* EFER MSR writes are always intercepted. */
14976 if (idMsr != MSR_K6_EFER)
14977 {
14978 AssertMsgFailed(("Unexpected WRMSR for an MSR in the auto-load/store area in the VMCS. ecx=%#RX32\n",
14979 idMsr));
14980 HMVMX_UNEXPECTED_EXIT_RET(pVCpu, idMsr);
14981 }
14982 }
14983
14984 if (hmR0VmxIsLazyGuestMsr(pVCpu, idMsr))
14985 {
14986 Assert(pVmcsInfo->pvMsrBitmap);
14987 uint32_t fMsrpm = CPUMGetVmxMsrPermission(pVmcsInfo->pvMsrBitmap, idMsr);
14988 if (fMsrpm & VMXMSRPM_ALLOW_WR)
14989 {
14990 AssertMsgFailed(("Unexpected WRMSR for passthru, lazy-restore MSR. ecx=%#RX32\n", idMsr));
14991 HMVMX_UNEXPECTED_EXIT_RET(pVCpu, idMsr);
14992 }
14993 }
14994 break;
14995 }
14996 }
14997 }
14998#endif /* VBOX_STRICT */
14999 }
15000 else if (rcStrict == VINF_IEM_RAISED_XCPT)
15001 {
15002 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
15003 rcStrict = VINF_SUCCESS;
15004 }
15005 else
15006 AssertMsg(rcStrict == VINF_CPUM_R3_MSR_WRITE, ("Unexpected IEMExecDecodedWrmsr rc (%Rrc)\n", VBOXSTRICTRC_VAL(rcStrict)));
15007
15008 return rcStrict;
15009}
15010
15011
15012/**
15013 * VM-exit handler for PAUSE (VMX_EXIT_PAUSE). Conditional VM-exit.
15014 */
15015HMVMX_EXIT_DECL hmR0VmxExitPause(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
15016{
15017 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
15018
15019 /** @todo The guest has likely hit a contended spinlock. We might want to
15020 * poke a schedule different guest VCPU. */
15021 int rc = hmR0VmxAdvanceGuestRip(pVCpu, pVmxTransient);
15022 if (RT_SUCCESS(rc))
15023 return VINF_EM_RAW_INTERRUPT;
15024
15025 AssertMsgFailed(("hmR0VmxExitPause: Failed to increment RIP. rc=%Rrc\n", rc));
15026 return rc;
15027}
15028
15029
15030/**
15031 * VM-exit handler for when the TPR value is lowered below the specified
15032 * threshold (VMX_EXIT_TPR_BELOW_THRESHOLD). Conditional VM-exit.
15033 */
15034HMVMX_EXIT_NSRC_DECL hmR0VmxExitTprBelowThreshold(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
15035{
15036 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
15037 Assert(pVmxTransient->pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_USE_TPR_SHADOW);
15038
15039 /*
15040 * The TPR shadow would've been synced with the APIC TPR in the post-run phase.
15041 * We'll re-evaluate pending interrupts and inject them before the next VM
15042 * entry so we can just continue execution here.
15043 */
15044 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitTprBelowThreshold);
15045 return VINF_SUCCESS;
15046}
15047
15048
15049/**
15050 * VM-exit handler for control-register accesses (VMX_EXIT_MOV_CRX). Conditional
15051 * VM-exit.
15052 *
15053 * @retval VINF_SUCCESS when guest execution can continue.
15054 * @retval VINF_PGM_SYNC_CR3 CR3 sync is required, back to ring-3.
15055 * @retval VERR_EM_RESCHEDULE_REM when we need to return to ring-3 due to
15056 * incompatible guest state for VMX execution (real-on-v86 case).
15057 */
15058HMVMX_EXIT_DECL hmR0VmxExitMovCRx(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
15059{
15060 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
15061 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatExitMovCRx, y2);
15062
15063 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
15064 hmR0VmxReadExitQualVmcs(pVmxTransient);
15065 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
15066
15067 VBOXSTRICTRC rcStrict;
15068 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
15069 uint64_t const uExitQual = pVmxTransient->uExitQual;
15070 uint32_t const uAccessType = VMX_EXIT_QUAL_CRX_ACCESS(uExitQual);
15071 switch (uAccessType)
15072 {
15073 /*
15074 * MOV to CRx.
15075 */
15076 case VMX_EXIT_QUAL_CRX_ACCESS_WRITE:
15077 {
15078 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, IEM_CPUMCTX_EXTRN_MUST_MASK);
15079 AssertRCReturn(rc, rc);
15080
15081 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_CR0);
15082 uint32_t const uOldCr0 = pVCpu->cpum.GstCtx.cr0;
15083 uint8_t const iGReg = VMX_EXIT_QUAL_CRX_GENREG(uExitQual);
15084 uint8_t const iCrReg = VMX_EXIT_QUAL_CRX_REGISTER(uExitQual);
15085
15086 /*
15087 * MOV to CR3 only cause a VM-exit when one or more of the following are true:
15088 * - When nested paging isn't used.
15089 * - If the guest doesn't have paging enabled (intercept CR3 to update shadow page tables).
15090 * - We are executing in the VM debug loop.
15091 */
15092 Assert( iCrReg != 3
15093 || !pVM->hm.s.fNestedPaging
15094 || !CPUMIsGuestPagingEnabledEx(&pVCpu->cpum.GstCtx)
15095 || pVCpu->hm.s.fUsingDebugLoop);
15096
15097 /* MOV to CR8 writes only cause VM-exits when TPR shadow is not used. */
15098 Assert( iCrReg != 8
15099 || !(pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_USE_TPR_SHADOW));
15100
15101 rcStrict = hmR0VmxExitMovToCrX(pVCpu, pVmcsInfo, pVmxTransient->cbExitInstr, iGReg, iCrReg);
15102 AssertMsg( rcStrict == VINF_SUCCESS
15103 || rcStrict == VINF_PGM_SYNC_CR3, ("%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
15104
15105 /*
15106 * This is a kludge for handling switches back to real mode when we try to use
15107 * V86 mode to run real mode code directly. Problem is that V86 mode cannot
15108 * deal with special selector values, so we have to return to ring-3 and run
15109 * there till the selector values are V86 mode compatible.
15110 *
15111 * Note! Using VINF_EM_RESCHEDULE_REM here rather than VINF_EM_RESCHEDULE since the
15112 * latter is an alias for VINF_IEM_RAISED_XCPT which is asserted at the end of
15113 * this function.
15114 */
15115 if ( iCrReg == 0
15116 && rcStrict == VINF_SUCCESS
15117 && !pVM->hm.s.vmx.fUnrestrictedGuest
15118 && CPUMIsGuestInRealModeEx(&pVCpu->cpum.GstCtx)
15119 && (uOldCr0 & X86_CR0_PE)
15120 && !(pVCpu->cpum.GstCtx.cr0 & X86_CR0_PE))
15121 {
15122 /** @todo Check selectors rather than returning all the time. */
15123 Assert(!pVmxTransient->fIsNestedGuest);
15124 Log4Func(("CR0 write, back to real mode -> VINF_EM_RESCHEDULE_REM\n"));
15125 rcStrict = VINF_EM_RESCHEDULE_REM;
15126 }
15127 break;
15128 }
15129
15130 /*
15131 * MOV from CRx.
15132 */
15133 case VMX_EXIT_QUAL_CRX_ACCESS_READ:
15134 {
15135 uint8_t const iGReg = VMX_EXIT_QUAL_CRX_GENREG(uExitQual);
15136 uint8_t const iCrReg = VMX_EXIT_QUAL_CRX_REGISTER(uExitQual);
15137
15138 /*
15139 * MOV from CR3 only cause a VM-exit when one or more of the following are true:
15140 * - When nested paging isn't used.
15141 * - If the guest doesn't have paging enabled (pass guest's CR3 rather than our identity mapped CR3).
15142 * - We are executing in the VM debug loop.
15143 */
15144 Assert( iCrReg != 3
15145 || !pVM->hm.s.fNestedPaging
15146 || !CPUMIsGuestPagingEnabledEx(&pVCpu->cpum.GstCtx)
15147 || pVCpu->hm.s.fUsingDebugLoop);
15148
15149 /* MOV from CR8 reads only cause a VM-exit when the TPR shadow feature isn't enabled. */
15150 Assert( iCrReg != 8
15151 || !(pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_USE_TPR_SHADOW));
15152
15153 rcStrict = hmR0VmxExitMovFromCrX(pVCpu, pVmcsInfo, pVmxTransient->cbExitInstr, iGReg, iCrReg);
15154 break;
15155 }
15156
15157 /*
15158 * CLTS (Clear Task-Switch Flag in CR0).
15159 */
15160 case VMX_EXIT_QUAL_CRX_ACCESS_CLTS:
15161 {
15162 rcStrict = hmR0VmxExitClts(pVCpu, pVmcsInfo, pVmxTransient->cbExitInstr);
15163 break;
15164 }
15165
15166 /*
15167 * LMSW (Load Machine-Status Word into CR0).
15168 * LMSW cannot clear CR0.PE, so no fRealOnV86Active kludge needed here.
15169 */
15170 case VMX_EXIT_QUAL_CRX_ACCESS_LMSW:
15171 {
15172 RTGCPTR GCPtrEffDst;
15173 uint8_t const cbInstr = pVmxTransient->cbExitInstr;
15174 uint16_t const uMsw = VMX_EXIT_QUAL_CRX_LMSW_DATA(uExitQual);
15175 bool const fMemOperand = VMX_EXIT_QUAL_CRX_LMSW_OP_MEM(uExitQual);
15176 if (fMemOperand)
15177 {
15178 hmR0VmxReadGuestLinearAddrVmcs(pVmxTransient);
15179 GCPtrEffDst = pVmxTransient->uGuestLinearAddr;
15180 }
15181 else
15182 GCPtrEffDst = NIL_RTGCPTR;
15183 rcStrict = hmR0VmxExitLmsw(pVCpu, pVmcsInfo, cbInstr, uMsw, GCPtrEffDst);
15184 break;
15185 }
15186
15187 default:
15188 {
15189 AssertMsgFailed(("Unrecognized Mov CRX access type %#x\n", uAccessType));
15190 HMVMX_UNEXPECTED_EXIT_RET(pVCpu, uAccessType);
15191 }
15192 }
15193
15194 Assert((pVCpu->hm.s.fCtxChanged & (HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS))
15195 == (HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS));
15196 Assert(rcStrict != VINF_IEM_RAISED_XCPT);
15197
15198 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExitMovCRx, y2);
15199 NOREF(pVM);
15200 return rcStrict;
15201}
15202
15203
15204/**
15205 * VM-exit handler for I/O instructions (VMX_EXIT_IO_INSTR). Conditional
15206 * VM-exit.
15207 */
15208HMVMX_EXIT_DECL hmR0VmxExitIoInstr(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
15209{
15210 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
15211 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatExitIO, y1);
15212
15213 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
15214 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
15215 hmR0VmxReadExitQualVmcs(pVmxTransient);
15216 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
15217 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, IEM_CPUMCTX_EXTRN_MUST_MASK | CPUMCTX_EXTRN_SREG_MASK
15218 | CPUMCTX_EXTRN_EFER);
15219 /* EFER MSR also required for longmode checks in EMInterpretDisasCurrent(), but it's always up-to-date. */
15220 AssertRCReturn(rc, rc);
15221
15222 /* Refer Intel spec. 27-5. "Exit Qualifications for I/O Instructions" for the format. */
15223 uint32_t const uIOPort = VMX_EXIT_QUAL_IO_PORT(pVmxTransient->uExitQual);
15224 uint8_t const uIOSize = VMX_EXIT_QUAL_IO_SIZE(pVmxTransient->uExitQual);
15225 bool const fIOWrite = (VMX_EXIT_QUAL_IO_DIRECTION(pVmxTransient->uExitQual) == VMX_EXIT_QUAL_IO_DIRECTION_OUT);
15226 bool const fIOString = VMX_EXIT_QUAL_IO_IS_STRING(pVmxTransient->uExitQual);
15227 bool const fGstStepping = RT_BOOL(pCtx->eflags.Bits.u1TF);
15228 bool const fDbgStepping = pVCpu->hm.s.fSingleInstruction;
15229 AssertReturn(uIOSize <= 3 && uIOSize != 2, VERR_VMX_IPE_1);
15230
15231 /*
15232 * Update exit history to see if this exit can be optimized.
15233 */
15234 VBOXSTRICTRC rcStrict;
15235 PCEMEXITREC pExitRec = NULL;
15236 if ( !fGstStepping
15237 && !fDbgStepping)
15238 pExitRec = EMHistoryUpdateFlagsAndTypeAndPC(pVCpu,
15239 !fIOString
15240 ? !fIOWrite
15241 ? EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM | EMEXIT_F_HM, EMEXITTYPE_IO_PORT_READ)
15242 : EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM | EMEXIT_F_HM, EMEXITTYPE_IO_PORT_WRITE)
15243 : !fIOWrite
15244 ? EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM | EMEXIT_F_HM, EMEXITTYPE_IO_PORT_STR_READ)
15245 : EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM | EMEXIT_F_HM, EMEXITTYPE_IO_PORT_STR_WRITE),
15246 pVCpu->cpum.GstCtx.rip + pVCpu->cpum.GstCtx.cs.u64Base);
15247 if (!pExitRec)
15248 {
15249 static uint32_t const s_aIOSizes[4] = { 1, 2, 0, 4 }; /* Size of the I/O accesses in bytes. */
15250 static uint32_t const s_aIOOpAnd[4] = { 0xff, 0xffff, 0, 0xffffffff }; /* AND masks for saving result in AL/AX/EAX. */
15251
15252 uint32_t const cbValue = s_aIOSizes[uIOSize];
15253 uint32_t const cbInstr = pVmxTransient->cbExitInstr;
15254 bool fUpdateRipAlready = false; /* ugly hack, should be temporary. */
15255 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
15256 if (fIOString)
15257 {
15258 /*
15259 * INS/OUTS - I/O String instruction.
15260 *
15261 * Use instruction-information if available, otherwise fall back on
15262 * interpreting the instruction.
15263 */
15264 Log4Func(("cs:rip=%#04x:%#RX64 %#06x/%u %c str\n", pCtx->cs.Sel, pCtx->rip, uIOPort, cbValue, fIOWrite ? 'w' : 'r'));
15265 AssertReturn(pCtx->dx == uIOPort, VERR_VMX_IPE_2);
15266 bool const fInsOutsInfo = RT_BF_GET(pVM->hm.s.vmx.Msrs.u64Basic, VMX_BF_BASIC_VMCS_INS_OUTS);
15267 if (fInsOutsInfo)
15268 {
15269 hmR0VmxReadExitInstrInfoVmcs(pVmxTransient);
15270 AssertReturn(pVmxTransient->ExitInstrInfo.StrIo.u3AddrSize <= 2, VERR_VMX_IPE_3);
15271 AssertCompile(IEMMODE_16BIT == 0 && IEMMODE_32BIT == 1 && IEMMODE_64BIT == 2);
15272 IEMMODE const enmAddrMode = (IEMMODE)pVmxTransient->ExitInstrInfo.StrIo.u3AddrSize;
15273 bool const fRep = VMX_EXIT_QUAL_IO_IS_REP(pVmxTransient->uExitQual);
15274 if (fIOWrite)
15275 rcStrict = IEMExecStringIoWrite(pVCpu, cbValue, enmAddrMode, fRep, cbInstr,
15276 pVmxTransient->ExitInstrInfo.StrIo.iSegReg, true /*fIoChecked*/);
15277 else
15278 {
15279 /*
15280 * The segment prefix for INS cannot be overridden and is always ES. We can safely assume X86_SREG_ES.
15281 * Hence "iSegReg" field is undefined in the instruction-information field in VT-x for INS.
15282 * See Intel Instruction spec. for "INS".
15283 * See Intel spec. Table 27-8 "Format of the VM-Exit Instruction-Information Field as Used for INS and OUTS".
15284 */
15285 rcStrict = IEMExecStringIoRead(pVCpu, cbValue, enmAddrMode, fRep, cbInstr, true /*fIoChecked*/);
15286 }
15287 }
15288 else
15289 rcStrict = IEMExecOne(pVCpu);
15290
15291 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP);
15292 fUpdateRipAlready = true;
15293 }
15294 else
15295 {
15296 /*
15297 * IN/OUT - I/O instruction.
15298 */
15299 Log4Func(("cs:rip=%04x:%08RX64 %#06x/%u %c\n", pCtx->cs.Sel, pCtx->rip, uIOPort, cbValue, fIOWrite ? 'w' : 'r'));
15300 uint32_t const uAndVal = s_aIOOpAnd[uIOSize];
15301 Assert(!VMX_EXIT_QUAL_IO_IS_REP(pVmxTransient->uExitQual));
15302 if (fIOWrite)
15303 {
15304 rcStrict = IOMIOPortWrite(pVM, pVCpu, uIOPort, pCtx->eax & uAndVal, cbValue);
15305 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIOWrite);
15306 if ( rcStrict == VINF_IOM_R3_IOPORT_WRITE
15307 && !pCtx->eflags.Bits.u1TF)
15308 rcStrict = EMRZSetPendingIoPortWrite(pVCpu, uIOPort, cbInstr, cbValue, pCtx->eax & uAndVal);
15309 }
15310 else
15311 {
15312 uint32_t u32Result = 0;
15313 rcStrict = IOMIOPortRead(pVM, pVCpu, uIOPort, &u32Result, cbValue);
15314 if (IOM_SUCCESS(rcStrict))
15315 {
15316 /* Save result of I/O IN instr. in AL/AX/EAX. */
15317 pCtx->eax = (pCtx->eax & ~uAndVal) | (u32Result & uAndVal);
15318 }
15319 if ( rcStrict == VINF_IOM_R3_IOPORT_READ
15320 && !pCtx->eflags.Bits.u1TF)
15321 rcStrict = EMRZSetPendingIoPortRead(pVCpu, uIOPort, cbInstr, cbValue);
15322 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIORead);
15323 }
15324 }
15325
15326 if (IOM_SUCCESS(rcStrict))
15327 {
15328 if (!fUpdateRipAlready)
15329 {
15330 hmR0VmxAdvanceGuestRipBy(pVCpu, cbInstr);
15331 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP);
15332 }
15333
15334 /*
15335 * INS/OUTS with REP prefix updates RFLAGS, can be observed with triple-fault guru
15336 * while booting Fedora 17 64-bit guest.
15337 *
15338 * See Intel Instruction reference for REP/REPE/REPZ/REPNE/REPNZ.
15339 */
15340 if (fIOString)
15341 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RFLAGS);
15342
15343 /*
15344 * If any I/O breakpoints are armed, we need to check if one triggered
15345 * and take appropriate action.
15346 * Note that the I/O breakpoint type is undefined if CR4.DE is 0.
15347 */
15348 rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, CPUMCTX_EXTRN_DR7);
15349 AssertRCReturn(rc, rc);
15350
15351 /** @todo Optimize away the DBGFBpIsHwIoArmed call by having DBGF tell the
15352 * execution engines about whether hyper BPs and such are pending. */
15353 uint32_t const uDr7 = pCtx->dr[7];
15354 if (RT_UNLIKELY( ( (uDr7 & X86_DR7_ENABLED_MASK)
15355 && X86_DR7_ANY_RW_IO(uDr7)
15356 && (pCtx->cr4 & X86_CR4_DE))
15357 || DBGFBpIsHwIoArmed(pVM)))
15358 {
15359 STAM_COUNTER_INC(&pVCpu->hm.s.StatDRxIoCheck);
15360
15361 /* We're playing with the host CPU state here, make sure we don't preempt or longjmp. */
15362 VMMRZCallRing3Disable(pVCpu);
15363 HM_DISABLE_PREEMPT(pVCpu);
15364
15365 bool fIsGuestDbgActive = CPUMR0DebugStateMaybeSaveGuest(pVCpu, true /* fDr6 */);
15366
15367 VBOXSTRICTRC rcStrict2 = DBGFBpCheckIo(pVM, pVCpu, pCtx, uIOPort, cbValue);
15368 if (rcStrict2 == VINF_EM_RAW_GUEST_TRAP)
15369 {
15370 /* Raise #DB. */
15371 if (fIsGuestDbgActive)
15372 ASMSetDR6(pCtx->dr[6]);
15373 if (pCtx->dr[7] != uDr7)
15374 pVCpu->hm.s.fCtxChanged |= HM_CHANGED_GUEST_DR7;
15375
15376 hmR0VmxSetPendingXcptDB(pVCpu);
15377 }
15378 /* rcStrict is VINF_SUCCESS, VINF_IOM_R3_IOPORT_COMMIT_WRITE, or in [VINF_EM_FIRST..VINF_EM_LAST],
15379 however we can ditch VINF_IOM_R3_IOPORT_COMMIT_WRITE as it has VMCPU_FF_IOM as backup. */
15380 else if ( rcStrict2 != VINF_SUCCESS
15381 && (rcStrict == VINF_SUCCESS || rcStrict2 < rcStrict))
15382 rcStrict = rcStrict2;
15383 AssertCompile(VINF_EM_LAST < VINF_IOM_R3_IOPORT_COMMIT_WRITE);
15384
15385 HM_RESTORE_PREEMPT();
15386 VMMRZCallRing3Enable(pVCpu);
15387 }
15388 }
15389
15390#ifdef VBOX_STRICT
15391 if ( rcStrict == VINF_IOM_R3_IOPORT_READ
15392 || rcStrict == VINF_EM_PENDING_R3_IOPORT_READ)
15393 Assert(!fIOWrite);
15394 else if ( rcStrict == VINF_IOM_R3_IOPORT_WRITE
15395 || rcStrict == VINF_IOM_R3_IOPORT_COMMIT_WRITE
15396 || rcStrict == VINF_EM_PENDING_R3_IOPORT_WRITE)
15397 Assert(fIOWrite);
15398 else
15399 {
15400# if 0 /** @todo r=bird: This is missing a bunch of VINF_EM_FIRST..VINF_EM_LAST
15401 * statuses, that the VMM device and some others may return. See
15402 * IOM_SUCCESS() for guidance. */
15403 AssertMsg( RT_FAILURE(rcStrict)
15404 || rcStrict == VINF_SUCCESS
15405 || rcStrict == VINF_EM_RAW_EMULATE_INSTR
15406 || rcStrict == VINF_EM_DBG_BREAKPOINT
15407 || rcStrict == VINF_EM_RAW_GUEST_TRAP
15408 || rcStrict == VINF_EM_RAW_TO_R3
15409 || rcStrict == VINF_TRPM_XCPT_DISPATCHED, ("%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
15410# endif
15411 }
15412#endif
15413 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExitIO, y1);
15414 }
15415 else
15416 {
15417 /*
15418 * Frequent exit or something needing probing. Get state and call EMHistoryExec.
15419 */
15420 int rc2 = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, HMVMX_CPUMCTX_EXTRN_ALL);
15421 AssertRCReturn(rc2, rc2);
15422 STAM_COUNTER_INC(!fIOString ? fIOWrite ? &pVCpu->hm.s.StatExitIOWrite : &pVCpu->hm.s.StatExitIORead
15423 : fIOWrite ? &pVCpu->hm.s.StatExitIOStringWrite : &pVCpu->hm.s.StatExitIOStringRead);
15424 Log4(("IOExit/%u: %04x:%08RX64: %s%s%s %#x LB %u -> EMHistoryExec\n",
15425 pVCpu->idCpu, pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip,
15426 VMX_EXIT_QUAL_IO_IS_REP(pVmxTransient->uExitQual) ? "REP " : "",
15427 fIOWrite ? "OUT" : "IN", fIOString ? "S" : "", uIOPort, uIOSize));
15428
15429 rcStrict = EMHistoryExec(pVCpu, pExitRec, 0);
15430 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_ALL_GUEST);
15431
15432 Log4(("IOExit/%u: %04x:%08RX64: EMHistoryExec -> %Rrc + %04x:%08RX64\n",
15433 pVCpu->idCpu, pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip,
15434 VBOXSTRICTRC_VAL(rcStrict), pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip));
15435 }
15436 return rcStrict;
15437}
15438
15439
15440/**
15441 * VM-exit handler for task switches (VMX_EXIT_TASK_SWITCH). Unconditional
15442 * VM-exit.
15443 */
15444HMVMX_EXIT_DECL hmR0VmxExitTaskSwitch(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
15445{
15446 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
15447
15448 /* Check if this task-switch occurred while delivery an event through the guest IDT. */
15449 hmR0VmxReadExitQualVmcs(pVmxTransient);
15450 if (VMX_EXIT_QUAL_TASK_SWITCH_TYPE(pVmxTransient->uExitQual) == VMX_EXIT_QUAL_TASK_SWITCH_TYPE_IDT)
15451 {
15452 hmR0VmxReadIdtVectoringInfoVmcs(pVmxTransient);
15453 if (VMX_IDT_VECTORING_INFO_IS_VALID(pVmxTransient->uIdtVectoringInfo))
15454 {
15455 uint32_t uErrCode;
15456 if (VMX_IDT_VECTORING_INFO_IS_ERROR_CODE_VALID(pVmxTransient->uIdtVectoringInfo))
15457 {
15458 hmR0VmxReadIdtVectoringErrorCodeVmcs(pVmxTransient);
15459 uErrCode = pVmxTransient->uIdtVectoringErrorCode;
15460 }
15461 else
15462 uErrCode = 0;
15463
15464 RTGCUINTPTR GCPtrFaultAddress;
15465 if (VMX_IDT_VECTORING_INFO_IS_XCPT_PF(pVmxTransient->uIdtVectoringInfo))
15466 GCPtrFaultAddress = pVCpu->cpum.GstCtx.cr2;
15467 else
15468 GCPtrFaultAddress = 0;
15469
15470 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
15471
15472 hmR0VmxSetPendingEvent(pVCpu, VMX_ENTRY_INT_INFO_FROM_EXIT_IDT_INFO(pVmxTransient->uIdtVectoringInfo),
15473 pVmxTransient->cbExitInstr, uErrCode, GCPtrFaultAddress);
15474
15475 Log4Func(("Pending event. uIntType=%#x uVector=%#x\n", VMX_IDT_VECTORING_INFO_TYPE(pVmxTransient->uIdtVectoringInfo),
15476 VMX_IDT_VECTORING_INFO_VECTOR(pVmxTransient->uIdtVectoringInfo)));
15477 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitTaskSwitch);
15478 return VINF_EM_RAW_INJECT_TRPM_EVENT;
15479 }
15480 }
15481
15482 /* Fall back to the interpreter to emulate the task-switch. */
15483 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitTaskSwitch);
15484 return VERR_EM_INTERPRETER;
15485}
15486
15487
15488/**
15489 * VM-exit handler for monitor-trap-flag (VMX_EXIT_MTF). Conditional VM-exit.
15490 */
15491HMVMX_EXIT_DECL hmR0VmxExitMtf(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
15492{
15493 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
15494
15495 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
15496 pVmcsInfo->u32ProcCtls &= ~VMX_PROC_CTLS_MONITOR_TRAP_FLAG;
15497 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, pVmcsInfo->u32ProcCtls);
15498 AssertRC(rc);
15499 return VINF_EM_DBG_STEPPED;
15500}
15501
15502
15503/**
15504 * VM-exit handler for APIC access (VMX_EXIT_APIC_ACCESS). Conditional VM-exit.
15505 */
15506HMVMX_EXIT_DECL hmR0VmxExitApicAccess(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
15507{
15508 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
15509 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitApicAccess);
15510
15511 hmR0VmxReadExitIntInfoVmcs(pVmxTransient);
15512 hmR0VmxReadExitIntErrorCodeVmcs(pVmxTransient);
15513 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
15514 hmR0VmxReadIdtVectoringInfoVmcs(pVmxTransient);
15515 hmR0VmxReadIdtVectoringErrorCodeVmcs(pVmxTransient);
15516
15517 /*
15518 * If this VM-exit occurred while delivering an event through the guest IDT, handle it accordingly.
15519 */
15520 VBOXSTRICTRC rcStrict = hmR0VmxCheckExitDueToEventDelivery(pVCpu, pVmxTransient);
15521 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
15522 {
15523 /* For some crazy guest, if an event delivery causes an APIC-access VM-exit, go to instruction emulation. */
15524 if (RT_UNLIKELY(pVCpu->hm.s.Event.fPending))
15525 {
15526 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectInterpret);
15527 return VINF_EM_RAW_INJECT_TRPM_EVENT;
15528 }
15529 }
15530 else
15531 {
15532 Assert(rcStrict != VINF_HM_DOUBLE_FAULT);
15533 return rcStrict;
15534 }
15535
15536 /* IOMMIOPhysHandler() below may call into IEM, save the necessary state. */
15537 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
15538 hmR0VmxReadExitQualVmcs(pVmxTransient);
15539 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, IEM_CPUMCTX_EXTRN_MUST_MASK);
15540 AssertRCReturn(rc, rc);
15541
15542 /* See Intel spec. 27-6 "Exit Qualifications for APIC-access VM-exits from Linear Accesses & Guest-Phyiscal Addresses" */
15543 uint32_t const uAccessType = VMX_EXIT_QUAL_APIC_ACCESS_TYPE(pVmxTransient->uExitQual);
15544 switch (uAccessType)
15545 {
15546 case VMX_APIC_ACCESS_TYPE_LINEAR_WRITE:
15547 case VMX_APIC_ACCESS_TYPE_LINEAR_READ:
15548 {
15549 AssertMsg( !(pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_USE_TPR_SHADOW)
15550 || VMX_EXIT_QUAL_APIC_ACCESS_OFFSET(pVmxTransient->uExitQual) != XAPIC_OFF_TPR,
15551 ("hmR0VmxExitApicAccess: can't access TPR offset while using TPR shadowing.\n"));
15552
15553 RTGCPHYS GCPhys = pVCpu->hm.s.vmx.u64GstMsrApicBase; /* Always up-to-date, as it is not part of the VMCS. */
15554 GCPhys &= PAGE_BASE_GC_MASK;
15555 GCPhys += VMX_EXIT_QUAL_APIC_ACCESS_OFFSET(pVmxTransient->uExitQual);
15556 Log4Func(("Linear access uAccessType=%#x GCPhys=%#RGp Off=%#x\n", uAccessType, GCPhys,
15557 VMX_EXIT_QUAL_APIC_ACCESS_OFFSET(pVmxTransient->uExitQual)));
15558
15559 rcStrict = IOMR0MmioPhysHandler(pVCpu->CTX_SUFF(pVM), pVCpu,
15560 uAccessType == VMX_APIC_ACCESS_TYPE_LINEAR_READ ? 0 : X86_TRAP_PF_RW, GCPhys);
15561 Log4Func(("IOMMMIOPhysHandler returned %Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
15562 if ( rcStrict == VINF_SUCCESS
15563 || rcStrict == VERR_PAGE_TABLE_NOT_PRESENT
15564 || rcStrict == VERR_PAGE_NOT_PRESENT)
15565 {
15566 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RSP | HM_CHANGED_GUEST_RFLAGS
15567 | HM_CHANGED_GUEST_APIC_TPR);
15568 rcStrict = VINF_SUCCESS;
15569 }
15570 break;
15571 }
15572
15573 default:
15574 {
15575 Log4Func(("uAccessType=%#x\n", uAccessType));
15576 rcStrict = VINF_EM_RAW_EMULATE_INSTR;
15577 break;
15578 }
15579 }
15580
15581 if (rcStrict != VINF_SUCCESS)
15582 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchApicAccessToR3);
15583 return rcStrict;
15584}
15585
15586
15587/**
15588 * VM-exit handler for debug-register accesses (VMX_EXIT_MOV_DRX). Conditional
15589 * VM-exit.
15590 */
15591HMVMX_EXIT_DECL hmR0VmxExitMovDRx(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
15592{
15593 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
15594 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
15595
15596 /* We might get this VM-exit if the nested-guest is not intercepting MOV DRx accesses. */
15597 if (!pVmxTransient->fIsNestedGuest)
15598 {
15599 /* We should -not- get this VM-exit if the guest's debug registers were active. */
15600 if (pVmxTransient->fWasGuestDebugStateActive)
15601 {
15602 AssertMsgFailed(("Unexpected MOV DRx exit\n"));
15603 HMVMX_UNEXPECTED_EXIT_RET(pVCpu, pVmxTransient->uExitReason);
15604 }
15605
15606 if ( !pVCpu->hm.s.fSingleInstruction
15607 && !pVmxTransient->fWasHyperDebugStateActive)
15608 {
15609 Assert(!DBGFIsStepping(pVCpu));
15610 Assert(pVmcsInfo->u32XcptBitmap & RT_BIT(X86_XCPT_DB));
15611
15612 /* Don't intercept MOV DRx any more. */
15613 pVmcsInfo->u32ProcCtls &= ~VMX_PROC_CTLS_MOV_DR_EXIT;
15614 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, pVmcsInfo->u32ProcCtls);
15615 AssertRC(rc);
15616
15617 /* We're playing with the host CPU state here, make sure we can't preempt or longjmp. */
15618 VMMRZCallRing3Disable(pVCpu);
15619 HM_DISABLE_PREEMPT(pVCpu);
15620
15621 /* Save the host & load the guest debug state, restart execution of the MOV DRx instruction. */
15622 CPUMR0LoadGuestDebugState(pVCpu, true /* include DR6 */);
15623 Assert(CPUMIsGuestDebugStateActive(pVCpu));
15624
15625 HM_RESTORE_PREEMPT();
15626 VMMRZCallRing3Enable(pVCpu);
15627
15628#ifdef VBOX_WITH_STATISTICS
15629 hmR0VmxReadExitQualVmcs(pVmxTransient);
15630 if (VMX_EXIT_QUAL_DRX_DIRECTION(pVmxTransient->uExitQual) == VMX_EXIT_QUAL_DRX_DIRECTION_WRITE)
15631 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitDRxWrite);
15632 else
15633 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitDRxRead);
15634#endif
15635 STAM_COUNTER_INC(&pVCpu->hm.s.StatDRxContextSwitch);
15636 return VINF_SUCCESS;
15637 }
15638 }
15639
15640 /*
15641 * EMInterpretDRx[Write|Read]() calls CPUMIsGuestIn64BitCode() which requires EFER MSR, CS.
15642 * The EFER MSR is always up-to-date.
15643 * Update the segment registers and DR7 from the CPU.
15644 */
15645 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
15646 hmR0VmxReadExitQualVmcs(pVmxTransient);
15647 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, CPUMCTX_EXTRN_SREG_MASK | CPUMCTX_EXTRN_DR7);
15648 AssertRCReturn(rc, rc);
15649 Log4Func(("cs:rip=%#04x:%#RX64\n", pCtx->cs.Sel, pCtx->rip));
15650
15651 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
15652 if (VMX_EXIT_QUAL_DRX_DIRECTION(pVmxTransient->uExitQual) == VMX_EXIT_QUAL_DRX_DIRECTION_WRITE)
15653 {
15654 rc = EMInterpretDRxWrite(pVM, pVCpu, CPUMCTX2CORE(pCtx),
15655 VMX_EXIT_QUAL_DRX_REGISTER(pVmxTransient->uExitQual),
15656 VMX_EXIT_QUAL_DRX_GENREG(pVmxTransient->uExitQual));
15657 if (RT_SUCCESS(rc))
15658 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_DR7);
15659 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitDRxWrite);
15660 }
15661 else
15662 {
15663 rc = EMInterpretDRxRead(pVM, pVCpu, CPUMCTX2CORE(pCtx),
15664 VMX_EXIT_QUAL_DRX_GENREG(pVmxTransient->uExitQual),
15665 VMX_EXIT_QUAL_DRX_REGISTER(pVmxTransient->uExitQual));
15666 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitDRxRead);
15667 }
15668
15669 Assert(rc == VINF_SUCCESS || rc == VERR_EM_INTERPRETER);
15670 if (RT_SUCCESS(rc))
15671 {
15672 int rc2 = hmR0VmxAdvanceGuestRip(pVCpu, pVmxTransient);
15673 AssertRCReturn(rc2, rc2);
15674 return VINF_SUCCESS;
15675 }
15676 return rc;
15677}
15678
15679
15680/**
15681 * VM-exit handler for EPT misconfiguration (VMX_EXIT_EPT_MISCONFIG).
15682 * Conditional VM-exit.
15683 */
15684HMVMX_EXIT_DECL hmR0VmxExitEptMisconfig(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
15685{
15686 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
15687 Assert(pVCpu->CTX_SUFF(pVM)->hm.s.fNestedPaging);
15688
15689 hmR0VmxReadExitIntInfoVmcs(pVmxTransient);
15690 hmR0VmxReadExitIntErrorCodeVmcs(pVmxTransient);
15691 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
15692 hmR0VmxReadIdtVectoringInfoVmcs(pVmxTransient);
15693 hmR0VmxReadIdtVectoringErrorCodeVmcs(pVmxTransient);
15694
15695 /*
15696 * If this VM-exit occurred while delivering an event through the guest IDT, handle it accordingly.
15697 */
15698 VBOXSTRICTRC rcStrict = hmR0VmxCheckExitDueToEventDelivery(pVCpu, pVmxTransient);
15699 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
15700 {
15701 /*
15702 * In the unlikely case where delivering an event causes an EPT misconfig (MMIO), go back to
15703 * instruction emulation to inject the original event. Otherwise, injecting the original event
15704 * using hardware-assisted VMX would trigger the same EPT misconfig VM-exit again.
15705 */
15706 if (!pVCpu->hm.s.Event.fPending)
15707 { /* likely */ }
15708 else
15709 {
15710 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectInterpret);
15711#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
15712 /** @todo NSTVMX: Think about how this should be handled. */
15713 if (pVmxTransient->fIsNestedGuest)
15714 return VERR_VMX_IPE_3;
15715#endif
15716 return VINF_EM_RAW_INJECT_TRPM_EVENT;
15717 }
15718 }
15719 else
15720 {
15721 Assert(rcStrict != VINF_HM_DOUBLE_FAULT);
15722 return rcStrict;
15723 }
15724
15725 /*
15726 * Get sufficient state and update the exit history entry.
15727 */
15728 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
15729 hmR0VmxReadGuestPhysicalAddrVmcs(pVmxTransient);
15730 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, IEM_CPUMCTX_EXTRN_MUST_MASK);
15731 AssertRCReturn(rc, rc);
15732
15733 RTGCPHYS const GCPhys = pVmxTransient->uGuestPhysicalAddr;
15734 PCEMEXITREC pExitRec = EMHistoryUpdateFlagsAndTypeAndPC(pVCpu,
15735 EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM | EMEXIT_F_HM, EMEXITTYPE_MMIO),
15736 pVCpu->cpum.GstCtx.rip + pVCpu->cpum.GstCtx.cs.u64Base);
15737 if (!pExitRec)
15738 {
15739 /*
15740 * If we succeed, resume guest execution.
15741 * If we fail in interpreting the instruction because we couldn't get the guest physical address
15742 * of the page containing the instruction via the guest's page tables (we would invalidate the guest page
15743 * in the host TLB), resume execution which would cause a guest page fault to let the guest handle this
15744 * weird case. See @bugref{6043}.
15745 */
15746 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
15747 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
15748 rcStrict = PGMR0Trap0eHandlerNPMisconfig(pVM, pVCpu, PGMMODE_EPT, CPUMCTX2CORE(pCtx), GCPhys, UINT32_MAX);
15749 Log4Func(("At %#RGp RIP=%#RX64 rc=%Rrc\n", GCPhys, pCtx->rip, VBOXSTRICTRC_VAL(rcStrict)));
15750 if ( rcStrict == VINF_SUCCESS
15751 || rcStrict == VERR_PAGE_TABLE_NOT_PRESENT
15752 || rcStrict == VERR_PAGE_NOT_PRESENT)
15753 {
15754 /* Successfully handled MMIO operation. */
15755 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RSP | HM_CHANGED_GUEST_RFLAGS
15756 | HM_CHANGED_GUEST_APIC_TPR);
15757 rcStrict = VINF_SUCCESS;
15758 }
15759 }
15760 else
15761 {
15762 /*
15763 * Frequent exit or something needing probing. Call EMHistoryExec.
15764 */
15765 Log4(("EptMisscfgExit/%u: %04x:%08RX64: %RGp -> EMHistoryExec\n",
15766 pVCpu->idCpu, pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip, GCPhys));
15767
15768 rcStrict = EMHistoryExec(pVCpu, pExitRec, 0);
15769 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_ALL_GUEST);
15770
15771 Log4(("EptMisscfgExit/%u: %04x:%08RX64: EMHistoryExec -> %Rrc + %04x:%08RX64\n",
15772 pVCpu->idCpu, pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip,
15773 VBOXSTRICTRC_VAL(rcStrict), pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip));
15774 }
15775 return rcStrict;
15776}
15777
15778
15779/**
15780 * VM-exit handler for EPT violation (VMX_EXIT_EPT_VIOLATION). Conditional
15781 * VM-exit.
15782 */
15783HMVMX_EXIT_DECL hmR0VmxExitEptViolation(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
15784{
15785 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
15786 Assert(pVCpu->CTX_SUFF(pVM)->hm.s.fNestedPaging);
15787
15788 hmR0VmxReadExitQualVmcs(pVmxTransient);
15789 hmR0VmxReadExitIntInfoVmcs(pVmxTransient);
15790 hmR0VmxReadExitIntErrorCodeVmcs(pVmxTransient);
15791 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
15792 hmR0VmxReadIdtVectoringInfoVmcs(pVmxTransient);
15793 hmR0VmxReadIdtVectoringErrorCodeVmcs(pVmxTransient);
15794
15795 /*
15796 * If this VM-exit occurred while delivering an event through the guest IDT, handle it accordingly.
15797 */
15798 VBOXSTRICTRC rcStrict = hmR0VmxCheckExitDueToEventDelivery(pVCpu, pVmxTransient);
15799 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
15800 {
15801 /*
15802 * If delivery of an event causes an EPT violation (true nested #PF and not MMIO),
15803 * we shall resolve the nested #PF and re-inject the original event.
15804 */
15805 if (pVCpu->hm.s.Event.fPending)
15806 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectReflectNPF);
15807 }
15808 else
15809 {
15810 Assert(rcStrict != VINF_HM_DOUBLE_FAULT);
15811 return rcStrict;
15812 }
15813
15814 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
15815 hmR0VmxReadGuestPhysicalAddrVmcs(pVmxTransient);
15816 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, IEM_CPUMCTX_EXTRN_MUST_MASK);
15817 AssertRCReturn(rc, rc);
15818
15819 RTGCPHYS const GCPhys = pVmxTransient->uGuestPhysicalAddr;
15820 uint64_t const uExitQual = pVmxTransient->uExitQual;
15821 AssertMsg(((pVmxTransient->uExitQual >> 7) & 3) != 2, ("%#RX64", uExitQual));
15822
15823 RTGCUINT uErrorCode = 0;
15824 if (uExitQual & VMX_EXIT_QUAL_EPT_INSTR_FETCH)
15825 uErrorCode |= X86_TRAP_PF_ID;
15826 if (uExitQual & VMX_EXIT_QUAL_EPT_DATA_WRITE)
15827 uErrorCode |= X86_TRAP_PF_RW;
15828 if (uExitQual & VMX_EXIT_QUAL_EPT_ENTRY_PRESENT)
15829 uErrorCode |= X86_TRAP_PF_P;
15830
15831 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
15832 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
15833 Log4Func(("at %#RX64 (%#RX64 errcode=%#x) cs:rip=%#04x:%#RX64\n", GCPhys, uExitQual, uErrorCode, pCtx->cs.Sel, pCtx->rip));
15834
15835 /*
15836 * Handle the pagefault trap for the nested shadow table.
15837 */
15838 TRPMAssertXcptPF(pVCpu, GCPhys, uErrorCode);
15839 rcStrict = PGMR0Trap0eHandlerNestedPaging(pVM, pVCpu, PGMMODE_EPT, uErrorCode, CPUMCTX2CORE(pCtx), GCPhys);
15840 TRPMResetTrap(pVCpu);
15841
15842 /* Same case as PGMR0Trap0eHandlerNPMisconfig(). See comment above, @bugref{6043}. */
15843 if ( rcStrict == VINF_SUCCESS
15844 || rcStrict == VERR_PAGE_TABLE_NOT_PRESENT
15845 || rcStrict == VERR_PAGE_NOT_PRESENT)
15846 {
15847 /* Successfully synced our nested page tables. */
15848 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitReasonNpf);
15849 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RSP | HM_CHANGED_GUEST_RFLAGS);
15850 return VINF_SUCCESS;
15851 }
15852
15853 Log4Func(("EPT return to ring-3 rcStrict2=%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
15854 return rcStrict;
15855}
15856
15857
15858#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
15859/**
15860 * VM-exit handler for VMCLEAR (VMX_EXIT_VMCLEAR). Unconditional VM-exit.
15861 */
15862HMVMX_EXIT_DECL hmR0VmxExitVmclear(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
15863{
15864 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
15865
15866 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
15867 hmR0VmxReadExitInstrInfoVmcs(pVmxTransient);
15868 hmR0VmxReadExitQualVmcs(pVmxTransient);
15869 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, CPUMCTX_EXTRN_RSP | CPUMCTX_EXTRN_SREG_MASK
15870 | CPUMCTX_EXTRN_HWVIRT
15871 | IEM_CPUMCTX_EXTRN_EXEC_DECODED_MEM_MASK);
15872 AssertRCReturn(rc, rc);
15873
15874 HMVMX_CHECK_EXIT_DUE_TO_VMX_INSTR(pVCpu, pVmxTransient->uExitReason);
15875
15876 VMXVEXITINFO ExitInfo;
15877 RT_ZERO(ExitInfo);
15878 ExitInfo.uReason = pVmxTransient->uExitReason;
15879 ExitInfo.u64Qual = pVmxTransient->uExitQual;
15880 ExitInfo.InstrInfo.u = pVmxTransient->ExitInstrInfo.u;
15881 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
15882 HMVMX_DECODE_MEM_OPERAND(pVCpu, ExitInfo.InstrInfo.u, ExitInfo.u64Qual, VMXMEMACCESS_READ, &ExitInfo.GCPtrEffAddr);
15883
15884 VBOXSTRICTRC rcStrict = IEMExecDecodedVmclear(pVCpu, &ExitInfo);
15885 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
15886 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS | HM_CHANGED_GUEST_HWVIRT);
15887 else if (rcStrict == VINF_IEM_RAISED_XCPT)
15888 {
15889 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
15890 rcStrict = VINF_SUCCESS;
15891 }
15892 return rcStrict;
15893}
15894
15895
15896/**
15897 * VM-exit handler for VMLAUNCH (VMX_EXIT_VMLAUNCH). Unconditional VM-exit.
15898 */
15899HMVMX_EXIT_DECL hmR0VmxExitVmlaunch(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
15900{
15901 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
15902
15903 /* Import the entire VMCS state for now as we would be switching VMCS on successful VMLAUNCH,
15904 otherwise we could import just IEM_CPUMCTX_EXTRN_VMX_VMENTRY_MASK. */
15905 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
15906 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, HMVMX_CPUMCTX_EXTRN_ALL);
15907 AssertRCReturn(rc, rc);
15908
15909 HMVMX_CHECK_EXIT_DUE_TO_VMX_INSTR(pVCpu, pVmxTransient->uExitReason);
15910
15911 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatExitVmentry, z);
15912 VBOXSTRICTRC rcStrict = IEMExecDecodedVmlaunchVmresume(pVCpu, pVmxTransient->cbExitInstr, VMXINSTRID_VMLAUNCH);
15913 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExitVmentry, z);
15914 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
15915 {
15916 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_ALL_GUEST);
15917 if (CPUMIsGuestInVmxNonRootMode(&pVCpu->cpum.GstCtx))
15918 rcStrict = VINF_VMX_VMLAUNCH_VMRESUME;
15919 }
15920 Assert(rcStrict != VINF_IEM_RAISED_XCPT);
15921 return rcStrict;
15922}
15923
15924
15925/**
15926 * VM-exit handler for VMPTRLD (VMX_EXIT_VMPTRLD). Unconditional VM-exit.
15927 */
15928HMVMX_EXIT_DECL hmR0VmxExitVmptrld(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
15929{
15930 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
15931
15932 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
15933 hmR0VmxReadExitInstrInfoVmcs(pVmxTransient);
15934 hmR0VmxReadExitQualVmcs(pVmxTransient);
15935 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, CPUMCTX_EXTRN_RSP | CPUMCTX_EXTRN_SREG_MASK
15936 | CPUMCTX_EXTRN_HWVIRT
15937 | IEM_CPUMCTX_EXTRN_EXEC_DECODED_MEM_MASK);
15938 AssertRCReturn(rc, rc);
15939
15940 HMVMX_CHECK_EXIT_DUE_TO_VMX_INSTR(pVCpu, pVmxTransient->uExitReason);
15941
15942 VMXVEXITINFO ExitInfo;
15943 RT_ZERO(ExitInfo);
15944 ExitInfo.uReason = pVmxTransient->uExitReason;
15945 ExitInfo.u64Qual = pVmxTransient->uExitQual;
15946 ExitInfo.InstrInfo.u = pVmxTransient->ExitInstrInfo.u;
15947 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
15948 HMVMX_DECODE_MEM_OPERAND(pVCpu, ExitInfo.InstrInfo.u, ExitInfo.u64Qual, VMXMEMACCESS_READ, &ExitInfo.GCPtrEffAddr);
15949
15950 VBOXSTRICTRC rcStrict = IEMExecDecodedVmptrld(pVCpu, &ExitInfo);
15951 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
15952 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS | HM_CHANGED_GUEST_HWVIRT);
15953 else if (rcStrict == VINF_IEM_RAISED_XCPT)
15954 {
15955 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
15956 rcStrict = VINF_SUCCESS;
15957 }
15958 return rcStrict;
15959}
15960
15961
15962/**
15963 * VM-exit handler for VMPTRST (VMX_EXIT_VMPTRST). Unconditional VM-exit.
15964 */
15965HMVMX_EXIT_DECL hmR0VmxExitVmptrst(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
15966{
15967 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
15968
15969 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
15970 hmR0VmxReadExitInstrInfoVmcs(pVmxTransient);
15971 hmR0VmxReadExitQualVmcs(pVmxTransient);
15972 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, CPUMCTX_EXTRN_RSP | CPUMCTX_EXTRN_SREG_MASK
15973 | CPUMCTX_EXTRN_HWVIRT
15974 | IEM_CPUMCTX_EXTRN_EXEC_DECODED_MEM_MASK);
15975 AssertRCReturn(rc, rc);
15976
15977 HMVMX_CHECK_EXIT_DUE_TO_VMX_INSTR(pVCpu, pVmxTransient->uExitReason);
15978
15979 VMXVEXITINFO ExitInfo;
15980 RT_ZERO(ExitInfo);
15981 ExitInfo.uReason = pVmxTransient->uExitReason;
15982 ExitInfo.u64Qual = pVmxTransient->uExitQual;
15983 ExitInfo.InstrInfo.u = pVmxTransient->ExitInstrInfo.u;
15984 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
15985 HMVMX_DECODE_MEM_OPERAND(pVCpu, ExitInfo.InstrInfo.u, ExitInfo.u64Qual, VMXMEMACCESS_WRITE, &ExitInfo.GCPtrEffAddr);
15986
15987 VBOXSTRICTRC rcStrict = IEMExecDecodedVmptrst(pVCpu, &ExitInfo);
15988 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
15989 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS);
15990 else if (rcStrict == VINF_IEM_RAISED_XCPT)
15991 {
15992 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
15993 rcStrict = VINF_SUCCESS;
15994 }
15995 return rcStrict;
15996}
15997
15998
15999/**
16000 * VM-exit handler for VMREAD (VMX_EXIT_VMREAD). Conditional VM-exit.
16001 */
16002HMVMX_EXIT_DECL hmR0VmxExitVmread(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16003{
16004 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16005
16006 /*
16007 * Strictly speaking we should not get VMREAD VM-exits for shadow VMCS fields and
16008 * thus might not need to import the shadow VMCS state, it's safer just in case
16009 * code elsewhere dares look at unsynced VMCS fields.
16010 */
16011 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16012 hmR0VmxReadExitInstrInfoVmcs(pVmxTransient);
16013 hmR0VmxReadExitQualVmcs(pVmxTransient);
16014 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, CPUMCTX_EXTRN_RSP | CPUMCTX_EXTRN_SREG_MASK
16015 | CPUMCTX_EXTRN_HWVIRT
16016 | IEM_CPUMCTX_EXTRN_EXEC_DECODED_MEM_MASK);
16017 AssertRCReturn(rc, rc);
16018
16019 HMVMX_CHECK_EXIT_DUE_TO_VMX_INSTR(pVCpu, pVmxTransient->uExitReason);
16020
16021 VMXVEXITINFO ExitInfo;
16022 RT_ZERO(ExitInfo);
16023 ExitInfo.uReason = pVmxTransient->uExitReason;
16024 ExitInfo.u64Qual = pVmxTransient->uExitQual;
16025 ExitInfo.InstrInfo.u = pVmxTransient->ExitInstrInfo.u;
16026 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
16027 if (!ExitInfo.InstrInfo.VmreadVmwrite.fIsRegOperand)
16028 HMVMX_DECODE_MEM_OPERAND(pVCpu, ExitInfo.InstrInfo.u, ExitInfo.u64Qual, VMXMEMACCESS_WRITE, &ExitInfo.GCPtrEffAddr);
16029
16030 VBOXSTRICTRC rcStrict = IEMExecDecodedVmread(pVCpu, &ExitInfo);
16031 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
16032 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS);
16033 else if (rcStrict == VINF_IEM_RAISED_XCPT)
16034 {
16035 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
16036 rcStrict = VINF_SUCCESS;
16037 }
16038 return rcStrict;
16039}
16040
16041
16042/**
16043 * VM-exit handler for VMRESUME (VMX_EXIT_VMRESUME). Unconditional VM-exit.
16044 */
16045HMVMX_EXIT_DECL hmR0VmxExitVmresume(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16046{
16047 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16048
16049 /* Import the entire VMCS state for now as we would be switching VMCS on successful VMRESUME,
16050 otherwise we could import just IEM_CPUMCTX_EXTRN_VMX_VMENTRY_MASK. */
16051 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16052 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, HMVMX_CPUMCTX_EXTRN_ALL);
16053 AssertRCReturn(rc, rc);
16054
16055 HMVMX_CHECK_EXIT_DUE_TO_VMX_INSTR(pVCpu, pVmxTransient->uExitReason);
16056
16057 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatExitVmentry, z);
16058 VBOXSTRICTRC rcStrict = IEMExecDecodedVmlaunchVmresume(pVCpu, pVmxTransient->cbExitInstr, VMXINSTRID_VMRESUME);
16059 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExitVmentry, z);
16060 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
16061 {
16062 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_ALL_GUEST);
16063 if (CPUMIsGuestInVmxNonRootMode(&pVCpu->cpum.GstCtx))
16064 rcStrict = VINF_VMX_VMLAUNCH_VMRESUME;
16065 }
16066 Assert(rcStrict != VINF_IEM_RAISED_XCPT);
16067 return rcStrict;
16068}
16069
16070
16071/**
16072 * VM-exit handler for VMWRITE (VMX_EXIT_VMWRITE). Conditional VM-exit.
16073 */
16074HMVMX_EXIT_DECL hmR0VmxExitVmwrite(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16075{
16076 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16077
16078 /*
16079 * Although we should not get VMWRITE VM-exits for shadow VMCS fields, since our HM hook
16080 * gets invoked when IEM's VMWRITE instruction emulation modifies the current VMCS and it
16081 * flags re-loading the entire shadow VMCS, we should save the entire shadow VMCS here.
16082 */
16083 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16084 hmR0VmxReadExitInstrInfoVmcs(pVmxTransient);
16085 hmR0VmxReadExitQualVmcs(pVmxTransient);
16086 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, CPUMCTX_EXTRN_RSP | CPUMCTX_EXTRN_SREG_MASK
16087 | CPUMCTX_EXTRN_HWVIRT
16088 | IEM_CPUMCTX_EXTRN_EXEC_DECODED_MEM_MASK);
16089 AssertRCReturn(rc, rc);
16090
16091 HMVMX_CHECK_EXIT_DUE_TO_VMX_INSTR(pVCpu, pVmxTransient->uExitReason);
16092
16093 VMXVEXITINFO ExitInfo;
16094 RT_ZERO(ExitInfo);
16095 ExitInfo.uReason = pVmxTransient->uExitReason;
16096 ExitInfo.u64Qual = pVmxTransient->uExitQual;
16097 ExitInfo.InstrInfo.u = pVmxTransient->ExitInstrInfo.u;
16098 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
16099 if (!ExitInfo.InstrInfo.VmreadVmwrite.fIsRegOperand)
16100 HMVMX_DECODE_MEM_OPERAND(pVCpu, ExitInfo.InstrInfo.u, ExitInfo.u64Qual, VMXMEMACCESS_READ, &ExitInfo.GCPtrEffAddr);
16101
16102 VBOXSTRICTRC rcStrict = IEMExecDecodedVmwrite(pVCpu, &ExitInfo);
16103 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
16104 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS | HM_CHANGED_GUEST_HWVIRT);
16105 else if (rcStrict == VINF_IEM_RAISED_XCPT)
16106 {
16107 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
16108 rcStrict = VINF_SUCCESS;
16109 }
16110 return rcStrict;
16111}
16112
16113
16114/**
16115 * VM-exit handler for VMXOFF (VMX_EXIT_VMXOFF). Unconditional VM-exit.
16116 */
16117HMVMX_EXIT_DECL hmR0VmxExitVmxoff(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16118{
16119 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16120
16121 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16122 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, CPUMCTX_EXTRN_CR4
16123 | CPUMCTX_EXTRN_HWVIRT
16124 | IEM_CPUMCTX_EXTRN_EXEC_DECODED_NO_MEM_MASK);
16125 AssertRCReturn(rc, rc);
16126
16127 HMVMX_CHECK_EXIT_DUE_TO_VMX_INSTR(pVCpu, pVmxTransient->uExitReason);
16128
16129 VBOXSTRICTRC rcStrict = IEMExecDecodedVmxoff(pVCpu, pVmxTransient->cbExitInstr);
16130 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
16131 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_HWVIRT);
16132 else if (rcStrict == VINF_IEM_RAISED_XCPT)
16133 {
16134 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
16135 rcStrict = VINF_SUCCESS;
16136 }
16137 return rcStrict;
16138}
16139
16140
16141/**
16142 * VM-exit handler for VMXON (VMX_EXIT_VMXON). Unconditional VM-exit.
16143 */
16144HMVMX_EXIT_DECL hmR0VmxExitVmxon(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16145{
16146 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16147
16148 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16149 hmR0VmxReadExitInstrInfoVmcs(pVmxTransient);
16150 hmR0VmxReadExitQualVmcs(pVmxTransient);
16151 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, CPUMCTX_EXTRN_RSP | CPUMCTX_EXTRN_SREG_MASK
16152 | CPUMCTX_EXTRN_HWVIRT
16153 | IEM_CPUMCTX_EXTRN_EXEC_DECODED_MEM_MASK);
16154 AssertRCReturn(rc, rc);
16155
16156 HMVMX_CHECK_EXIT_DUE_TO_VMX_INSTR(pVCpu, pVmxTransient->uExitReason);
16157
16158 VMXVEXITINFO ExitInfo;
16159 RT_ZERO(ExitInfo);
16160 ExitInfo.uReason = pVmxTransient->uExitReason;
16161 ExitInfo.u64Qual = pVmxTransient->uExitQual;
16162 ExitInfo.InstrInfo.u = pVmxTransient->ExitInstrInfo.u;
16163 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
16164 HMVMX_DECODE_MEM_OPERAND(pVCpu, ExitInfo.InstrInfo.u, ExitInfo.u64Qual, VMXMEMACCESS_READ, &ExitInfo.GCPtrEffAddr);
16165
16166 VBOXSTRICTRC rcStrict = IEMExecDecodedVmxon(pVCpu, &ExitInfo);
16167 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
16168 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS | HM_CHANGED_GUEST_HWVIRT);
16169 else if (rcStrict == VINF_IEM_RAISED_XCPT)
16170 {
16171 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
16172 rcStrict = VINF_SUCCESS;
16173 }
16174 return rcStrict;
16175}
16176
16177
16178/**
16179 * VM-exit handler for INVVPID (VMX_EXIT_INVVPID). Unconditional VM-exit.
16180 */
16181HMVMX_EXIT_DECL hmR0VmxExitInvvpid(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16182{
16183 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16184
16185 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16186 hmR0VmxReadExitInstrInfoVmcs(pVmxTransient);
16187 hmR0VmxReadExitQualVmcs(pVmxTransient);
16188 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, CPUMCTX_EXTRN_RSP | CPUMCTX_EXTRN_SREG_MASK
16189 | IEM_CPUMCTX_EXTRN_EXEC_DECODED_MEM_MASK);
16190 AssertRCReturn(rc, rc);
16191
16192 HMVMX_CHECK_EXIT_DUE_TO_VMX_INSTR(pVCpu, pVmxTransient->uExitReason);
16193
16194 VMXVEXITINFO ExitInfo;
16195 RT_ZERO(ExitInfo);
16196 ExitInfo.uReason = pVmxTransient->uExitReason;
16197 ExitInfo.u64Qual = pVmxTransient->uExitQual;
16198 ExitInfo.InstrInfo.u = pVmxTransient->ExitInstrInfo.u;
16199 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
16200 HMVMX_DECODE_MEM_OPERAND(pVCpu, ExitInfo.InstrInfo.u, ExitInfo.u64Qual, VMXMEMACCESS_READ, &ExitInfo.GCPtrEffAddr);
16201
16202 VBOXSTRICTRC rcStrict = IEMExecDecodedInvvpid(pVCpu, &ExitInfo);
16203 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
16204 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS);
16205 else if (rcStrict == VINF_IEM_RAISED_XCPT)
16206 {
16207 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
16208 rcStrict = VINF_SUCCESS;
16209 }
16210 return rcStrict;
16211}
16212#endif /* VBOX_WITH_NESTED_HWVIRT_VMX */
16213/** @} */
16214
16215
16216#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
16217/** @name Nested-guest VM-exit handlers.
16218 * @{
16219 */
16220/* -=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= */
16221/* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- Nested-guest VM-exit handlers -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= */
16222/* -=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= */
16223
16224/**
16225 * Nested-guest VM-exit handler for exceptions or NMIs (VMX_EXIT_XCPT_OR_NMI).
16226 * Conditional VM-exit.
16227 */
16228HMVMX_EXIT_DECL hmR0VmxExitXcptOrNmiNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16229{
16230 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16231
16232 hmR0VmxReadExitIntInfoVmcs(pVmxTransient);
16233
16234 uint64_t const uExitIntInfo = pVmxTransient->uExitIntInfo;
16235 uint32_t const uExitIntType = VMX_EXIT_INT_INFO_TYPE(uExitIntInfo);
16236 Assert(VMX_EXIT_INT_INFO_IS_VALID(uExitIntInfo));
16237
16238 switch (uExitIntType)
16239 {
16240 /*
16241 * Physical NMIs:
16242 * We shouldn't direct host physical NMIs to the nested-guest. Dispatch it to the host.
16243 */
16244 case VMX_EXIT_INT_INFO_TYPE_NMI:
16245 return hmR0VmxExitHostNmi(pVCpu, pVmxTransient->pVmcsInfo);
16246
16247 /*
16248 * Hardware exceptions,
16249 * Software exceptions,
16250 * Privileged software exceptions:
16251 * Figure out if the exception must be delivered to the guest or the nested-guest.
16252 */
16253 case VMX_EXIT_INT_INFO_TYPE_SW_XCPT:
16254 case VMX_EXIT_INT_INFO_TYPE_PRIV_SW_XCPT:
16255 case VMX_EXIT_INT_INFO_TYPE_HW_XCPT:
16256 {
16257 hmR0VmxReadExitIntErrorCodeVmcs(pVmxTransient);
16258 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16259 hmR0VmxReadIdtVectoringInfoVmcs(pVmxTransient);
16260 hmR0VmxReadIdtVectoringErrorCodeVmcs(pVmxTransient);
16261
16262 PCCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
16263 bool const fIntercept = CPUMIsGuestVmxXcptInterceptSet(pCtx, VMX_EXIT_INT_INFO_VECTOR(uExitIntInfo),
16264 pVmxTransient->uExitIntErrorCode);
16265 if (fIntercept)
16266 {
16267 /* Exit qualification is required for debug and page-fault exceptions. */
16268 hmR0VmxReadExitQualVmcs(pVmxTransient);
16269
16270 /*
16271 * For VM-exits due to software exceptions (those generated by INT3 or INTO) and privileged
16272 * software exceptions (those generated by INT1/ICEBP) we need to supply the VM-exit instruction
16273 * length. However, if delivery of a software interrupt, software exception or privileged
16274 * software exception causes a VM-exit, that too provides the VM-exit instruction length.
16275 */
16276 VMXVEXITINFO ExitInfo;
16277 RT_ZERO(ExitInfo);
16278 ExitInfo.uReason = pVmxTransient->uExitReason;
16279 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
16280 ExitInfo.u64Qual = pVmxTransient->uExitQual;
16281
16282 VMXVEXITEVENTINFO ExitEventInfo;
16283 RT_ZERO(ExitEventInfo);
16284 ExitEventInfo.uExitIntInfo = pVmxTransient->uExitIntInfo;
16285 ExitEventInfo.uExitIntErrCode = pVmxTransient->uExitIntErrorCode;
16286 ExitEventInfo.uIdtVectoringInfo = pVmxTransient->uIdtVectoringInfo;
16287 ExitEventInfo.uIdtVectoringErrCode = pVmxTransient->uIdtVectoringErrorCode;
16288
16289#ifdef DEBUG_ramshankar
16290 hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, HMVMX_CPUMCTX_EXTRN_ALL);
16291 Log4Func(("exit_int_info=%#RX32 err_code=%#RX32 exit_qual=%#RX64\n", pVmxTransient->uExitIntInfo,
16292 pVmxTransient->uExitIntErrorCode, pVmxTransient->uExitQual));
16293 if (VMX_IDT_VECTORING_INFO_IS_VALID(pVmxTransient->uIdtVectoringInfo))
16294 {
16295 Log4Func(("idt_info=%#RX32 idt_errcode=%#RX32 cr2=%#RX64\n", pVmxTransient->uIdtVectoringInfo,
16296 pVmxTransient->uIdtVectoringErrorCode, pCtx->cr2));
16297 }
16298#endif
16299 return IEMExecVmxVmexitXcpt(pVCpu, &ExitInfo, &ExitEventInfo);
16300 }
16301
16302 /* Nested paging is currently a requirement, otherwise we would need to handle shadow #PFs in hmR0VmxExitXcptPF. */
16303 Assert(pVCpu->CTX_SUFF(pVM)->hm.s.fNestedPaging);
16304 return hmR0VmxExitXcpt(pVCpu, pVmxTransient);
16305 }
16306
16307 /*
16308 * Software interrupts:
16309 * VM-exits cannot be caused by software interrupts.
16310 *
16311 * External interrupts:
16312 * This should only happen when "acknowledge external interrupts on VM-exit"
16313 * control is set. However, we never set this when executing a guest or
16314 * nested-guest. For nested-guests it is emulated while injecting interrupts into
16315 * the guest.
16316 */
16317 case VMX_EXIT_INT_INFO_TYPE_SW_INT:
16318 case VMX_EXIT_INT_INFO_TYPE_EXT_INT:
16319 default:
16320 {
16321 pVCpu->hm.s.u32HMError = pVmxTransient->uExitIntInfo;
16322 return VERR_VMX_UNEXPECTED_INTERRUPTION_EXIT_TYPE;
16323 }
16324 }
16325}
16326
16327
16328/**
16329 * Nested-guest VM-exit handler for triple faults (VMX_EXIT_TRIPLE_FAULT).
16330 * Unconditional VM-exit.
16331 */
16332HMVMX_EXIT_DECL hmR0VmxExitTripleFaultNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16333{
16334 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16335 return IEMExecVmxVmexitTripleFault(pVCpu);
16336}
16337
16338
16339/**
16340 * Nested-guest VM-exit handler for interrupt-window exiting (VMX_EXIT_INT_WINDOW).
16341 */
16342HMVMX_EXIT_NSRC_DECL hmR0VmxExitIntWindowNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16343{
16344 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16345
16346 if (CPUMIsGuestVmxProcCtlsSet(&pVCpu->cpum.GstCtx, VMX_PROC_CTLS_INT_WINDOW_EXIT))
16347 return IEMExecVmxVmexit(pVCpu, pVmxTransient->uExitReason, 0 /* uExitQual */);
16348 return hmR0VmxExitIntWindow(pVCpu, pVmxTransient);
16349}
16350
16351
16352/**
16353 * Nested-guest VM-exit handler for NMI-window exiting (VMX_EXIT_NMI_WINDOW).
16354 */
16355HMVMX_EXIT_NSRC_DECL hmR0VmxExitNmiWindowNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16356{
16357 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16358
16359 if (CPUMIsGuestVmxProcCtlsSet(&pVCpu->cpum.GstCtx, VMX_PROC_CTLS_NMI_WINDOW_EXIT))
16360 return IEMExecVmxVmexit(pVCpu, pVmxTransient->uExitReason, 0 /* uExitQual */);
16361 return hmR0VmxExitIntWindow(pVCpu, pVmxTransient);
16362}
16363
16364
16365/**
16366 * Nested-guest VM-exit handler for task switches (VMX_EXIT_TASK_SWITCH).
16367 * Unconditional VM-exit.
16368 */
16369HMVMX_EXIT_DECL hmR0VmxExitTaskSwitchNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16370{
16371 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16372
16373 hmR0VmxReadExitQualVmcs(pVmxTransient);
16374 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16375 hmR0VmxReadIdtVectoringInfoVmcs(pVmxTransient);
16376 hmR0VmxReadIdtVectoringErrorCodeVmcs(pVmxTransient);
16377
16378 VMXVEXITINFO ExitInfo;
16379 RT_ZERO(ExitInfo);
16380 ExitInfo.uReason = pVmxTransient->uExitReason;
16381 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
16382 ExitInfo.u64Qual = pVmxTransient->uExitQual;
16383
16384 VMXVEXITEVENTINFO ExitEventInfo;
16385 RT_ZERO(ExitEventInfo);
16386 ExitEventInfo.uIdtVectoringInfo = pVmxTransient->uIdtVectoringInfo;
16387 ExitEventInfo.uIdtVectoringErrCode = pVmxTransient->uIdtVectoringErrorCode;
16388 return IEMExecVmxVmexitTaskSwitch(pVCpu, &ExitInfo, &ExitEventInfo);
16389}
16390
16391
16392/**
16393 * Nested-guest VM-exit handler for HLT (VMX_EXIT_HLT). Conditional VM-exit.
16394 */
16395HMVMX_EXIT_DECL hmR0VmxExitHltNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16396{
16397 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16398
16399 if (CPUMIsGuestVmxProcCtlsSet(&pVCpu->cpum.GstCtx, VMX_PROC_CTLS_HLT_EXIT))
16400 {
16401 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16402 return IEMExecVmxVmexitInstr(pVCpu, pVmxTransient->uExitReason, pVmxTransient->cbExitInstr);
16403 }
16404 return hmR0VmxExitHlt(pVCpu, pVmxTransient);
16405}
16406
16407
16408/**
16409 * Nested-guest VM-exit handler for INVLPG (VMX_EXIT_INVLPG). Conditional VM-exit.
16410 */
16411HMVMX_EXIT_DECL hmR0VmxExitInvlpgNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16412{
16413 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16414
16415 if (CPUMIsGuestVmxProcCtlsSet(&pVCpu->cpum.GstCtx, VMX_PROC_CTLS_INVLPG_EXIT))
16416 {
16417 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16418 hmR0VmxReadExitQualVmcs(pVmxTransient);
16419
16420 VMXVEXITINFO ExitInfo;
16421 RT_ZERO(ExitInfo);
16422 ExitInfo.uReason = pVmxTransient->uExitReason;
16423 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
16424 ExitInfo.u64Qual = pVmxTransient->uExitQual;
16425 return IEMExecVmxVmexitInstrWithInfo(pVCpu, &ExitInfo);
16426 }
16427 return hmR0VmxExitInvlpg(pVCpu, pVmxTransient);
16428}
16429
16430
16431/**
16432 * Nested-guest VM-exit handler for RDPMC (VMX_EXIT_RDPMC). Conditional VM-exit.
16433 */
16434HMVMX_EXIT_DECL hmR0VmxExitRdpmcNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16435{
16436 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16437
16438 if (CPUMIsGuestVmxProcCtlsSet(&pVCpu->cpum.GstCtx, VMX_PROC_CTLS_RDPMC_EXIT))
16439 {
16440 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16441 return IEMExecVmxVmexitInstr(pVCpu, pVmxTransient->uExitReason, pVmxTransient->cbExitInstr);
16442 }
16443 return hmR0VmxExitRdpmc(pVCpu, pVmxTransient);
16444}
16445
16446
16447/**
16448 * Nested-guest VM-exit handler for VMREAD (VMX_EXIT_VMREAD) and VMWRITE
16449 * (VMX_EXIT_VMWRITE). Conditional VM-exit.
16450 */
16451HMVMX_EXIT_DECL hmR0VmxExitVmreadVmwriteNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16452{
16453 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16454
16455 Assert( pVmxTransient->uExitReason == VMX_EXIT_VMREAD
16456 || pVmxTransient->uExitReason == VMX_EXIT_VMWRITE);
16457
16458 hmR0VmxReadExitInstrInfoVmcs(pVmxTransient);
16459
16460 uint8_t const iGReg = pVmxTransient->ExitInstrInfo.VmreadVmwrite.iReg2;
16461 Assert(iGReg < RT_ELEMENTS(pVCpu->cpum.GstCtx.aGRegs));
16462 uint64_t u64VmcsField = pVCpu->cpum.GstCtx.aGRegs[iGReg].u64;
16463
16464 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_EFER);
16465 if (!CPUMIsGuestInLongModeEx(&pVCpu->cpum.GstCtx))
16466 u64VmcsField &= UINT64_C(0xffffffff);
16467
16468 if (CPUMIsGuestVmxVmreadVmwriteInterceptSet(pVCpu, pVmxTransient->uExitReason, u64VmcsField))
16469 {
16470 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16471 hmR0VmxReadExitQualVmcs(pVmxTransient);
16472
16473 VMXVEXITINFO ExitInfo;
16474 RT_ZERO(ExitInfo);
16475 ExitInfo.uReason = pVmxTransient->uExitReason;
16476 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
16477 ExitInfo.u64Qual = pVmxTransient->uExitQual;
16478 ExitInfo.InstrInfo = pVmxTransient->ExitInstrInfo;
16479 return IEMExecVmxVmexitInstrWithInfo(pVCpu, &ExitInfo);
16480 }
16481
16482 if (pVmxTransient->uExitReason == VMX_EXIT_VMREAD)
16483 return hmR0VmxExitVmread(pVCpu, pVmxTransient);
16484 return hmR0VmxExitVmwrite(pVCpu, pVmxTransient);
16485}
16486
16487
16488/**
16489 * Nested-guest VM-exit handler for RDTSC (VMX_EXIT_RDTSC). Conditional VM-exit.
16490 */
16491HMVMX_EXIT_DECL hmR0VmxExitRdtscNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16492{
16493 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16494
16495 if (CPUMIsGuestVmxProcCtlsSet(&pVCpu->cpum.GstCtx, VMX_PROC_CTLS_RDTSC_EXIT))
16496 {
16497 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16498 return IEMExecVmxVmexitInstr(pVCpu, pVmxTransient->uExitReason, pVmxTransient->cbExitInstr);
16499 }
16500
16501 return hmR0VmxExitRdtsc(pVCpu, pVmxTransient);
16502}
16503
16504
16505/**
16506 * Nested-guest VM-exit handler for control-register accesses (VMX_EXIT_MOV_CRX).
16507 * Conditional VM-exit.
16508 */
16509HMVMX_EXIT_DECL hmR0VmxExitMovCRxNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16510{
16511 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16512
16513 hmR0VmxReadExitQualVmcs(pVmxTransient);
16514 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16515
16516 VBOXSTRICTRC rcStrict;
16517 uint32_t const uAccessType = VMX_EXIT_QUAL_CRX_ACCESS(pVmxTransient->uExitQual);
16518 switch (uAccessType)
16519 {
16520 case VMX_EXIT_QUAL_CRX_ACCESS_WRITE:
16521 {
16522 uint8_t const iCrReg = VMX_EXIT_QUAL_CRX_REGISTER(pVmxTransient->uExitQual);
16523 uint8_t const iGReg = VMX_EXIT_QUAL_CRX_GENREG(pVmxTransient->uExitQual);
16524 Assert(iGReg < RT_ELEMENTS(pVCpu->cpum.GstCtx.aGRegs));
16525 uint64_t const uNewCrX = pVCpu->cpum.GstCtx.aGRegs[iGReg].u64;
16526
16527 bool fIntercept;
16528 switch (iCrReg)
16529 {
16530 case 0:
16531 case 4:
16532 fIntercept = CPUMIsGuestVmxMovToCr0Cr4InterceptSet(&pVCpu->cpum.GstCtx, iCrReg, uNewCrX);
16533 break;
16534
16535 case 3:
16536 fIntercept = CPUMIsGuestVmxMovToCr3InterceptSet(pVCpu, uNewCrX);
16537 break;
16538
16539 case 8:
16540 fIntercept = CPUMIsGuestVmxProcCtlsSet(&pVCpu->cpum.GstCtx, VMX_PROC_CTLS_CR8_LOAD_EXIT);
16541 break;
16542
16543 default:
16544 fIntercept = false;
16545 break;
16546 }
16547 if (fIntercept)
16548 {
16549 VMXVEXITINFO ExitInfo;
16550 RT_ZERO(ExitInfo);
16551 ExitInfo.uReason = pVmxTransient->uExitReason;
16552 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
16553 ExitInfo.u64Qual = pVmxTransient->uExitQual;
16554 rcStrict = IEMExecVmxVmexitInstrWithInfo(pVCpu, &ExitInfo);
16555 }
16556 else
16557 rcStrict = hmR0VmxExitMovToCrX(pVCpu, pVmxTransient->pVmcsInfo, pVmxTransient->cbExitInstr, iGReg, iCrReg);
16558 break;
16559 }
16560
16561 case VMX_EXIT_QUAL_CRX_ACCESS_READ:
16562 {
16563 /*
16564 * CR0/CR4 reads do not cause VM-exits, the read-shadow is used (subject to masking).
16565 * CR2 reads do not cause a VM-exit.
16566 * CR3 reads cause a VM-exit depending on the "CR3 store exiting" control.
16567 * CR8 reads cause a VM-exit depending on the "CR8 store exiting" control.
16568 */
16569 uint8_t const iCrReg = VMX_EXIT_QUAL_CRX_REGISTER(pVmxTransient->uExitQual);
16570 if ( iCrReg == 3
16571 || iCrReg == 8)
16572 {
16573 static const uint32_t s_auCrXReadIntercepts[] = { 0, 0, 0, VMX_PROC_CTLS_CR3_STORE_EXIT, 0,
16574 0, 0, 0, VMX_PROC_CTLS_CR8_STORE_EXIT };
16575 uint32_t const uIntercept = s_auCrXReadIntercepts[iCrReg];
16576 if (CPUMIsGuestVmxProcCtlsSet(&pVCpu->cpum.GstCtx, uIntercept))
16577 {
16578 VMXVEXITINFO ExitInfo;
16579 RT_ZERO(ExitInfo);
16580 ExitInfo.uReason = pVmxTransient->uExitReason;
16581 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
16582 ExitInfo.u64Qual = pVmxTransient->uExitQual;
16583 rcStrict = IEMExecVmxVmexitInstrWithInfo(pVCpu, &ExitInfo);
16584 }
16585 else
16586 {
16587 uint8_t const iGReg = VMX_EXIT_QUAL_CRX_GENREG(pVmxTransient->uExitQual);
16588 rcStrict = hmR0VmxExitMovFromCrX(pVCpu, pVmxTransient->pVmcsInfo, pVmxTransient->cbExitInstr, iGReg, iCrReg);
16589 }
16590 }
16591 else
16592 {
16593 AssertMsgFailed(("MOV from CR%d VM-exit must not happen\n", iCrReg));
16594 HMVMX_UNEXPECTED_EXIT_RET(pVCpu, iCrReg);
16595 }
16596 break;
16597 }
16598
16599 case VMX_EXIT_QUAL_CRX_ACCESS_CLTS:
16600 {
16601 PCVMXVVMCS pVmcsNstGst = pVCpu->cpum.GstCtx.hwvirt.vmx.CTX_SUFF(pVmcs);
16602 Assert(pVmcsNstGst);
16603 uint64_t const uGstHostMask = pVmcsNstGst->u64Cr0Mask.u;
16604 uint64_t const uReadShadow = pVmcsNstGst->u64Cr0ReadShadow.u;
16605 if ( (uGstHostMask & X86_CR0_TS)
16606 && (uReadShadow & X86_CR0_TS))
16607 {
16608 VMXVEXITINFO ExitInfo;
16609 RT_ZERO(ExitInfo);
16610 ExitInfo.uReason = pVmxTransient->uExitReason;
16611 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
16612 ExitInfo.u64Qual = pVmxTransient->uExitQual;
16613 rcStrict = IEMExecVmxVmexitInstrWithInfo(pVCpu, &ExitInfo);
16614 }
16615 else
16616 rcStrict = hmR0VmxExitClts(pVCpu, pVmxTransient->pVmcsInfo, pVmxTransient->cbExitInstr);
16617 break;
16618 }
16619
16620 case VMX_EXIT_QUAL_CRX_ACCESS_LMSW: /* LMSW (Load Machine-Status Word into CR0) */
16621 {
16622 RTGCPTR GCPtrEffDst;
16623 uint16_t const uNewMsw = VMX_EXIT_QUAL_CRX_LMSW_DATA(pVmxTransient->uExitQual);
16624 bool const fMemOperand = VMX_EXIT_QUAL_CRX_LMSW_OP_MEM(pVmxTransient->uExitQual);
16625 if (fMemOperand)
16626 {
16627 hmR0VmxReadGuestLinearAddrVmcs(pVmxTransient);
16628 GCPtrEffDst = pVmxTransient->uGuestLinearAddr;
16629 }
16630 else
16631 GCPtrEffDst = NIL_RTGCPTR;
16632
16633 if (CPUMIsGuestVmxLmswInterceptSet(&pVCpu->cpum.GstCtx, uNewMsw))
16634 {
16635 VMXVEXITINFO ExitInfo;
16636 RT_ZERO(ExitInfo);
16637 ExitInfo.uReason = pVmxTransient->uExitReason;
16638 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
16639 ExitInfo.u64GuestLinearAddr = GCPtrEffDst;
16640 ExitInfo.u64Qual = pVmxTransient->uExitQual;
16641 rcStrict = IEMExecVmxVmexitInstrWithInfo(pVCpu, &ExitInfo);
16642 }
16643 else
16644 rcStrict = hmR0VmxExitLmsw(pVCpu, pVmxTransient->pVmcsInfo, pVmxTransient->cbExitInstr, uNewMsw, GCPtrEffDst);
16645 break;
16646 }
16647
16648 default:
16649 {
16650 AssertMsgFailed(("Unrecognized Mov CRX access type %#x\n", uAccessType));
16651 HMVMX_UNEXPECTED_EXIT_RET(pVCpu, uAccessType);
16652 }
16653 }
16654
16655 if (rcStrict == VINF_IEM_RAISED_XCPT)
16656 {
16657 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
16658 rcStrict = VINF_SUCCESS;
16659 }
16660 return rcStrict;
16661}
16662
16663
16664/**
16665 * Nested-guest VM-exit handler for debug-register accesses (VMX_EXIT_MOV_DRX).
16666 * Conditional VM-exit.
16667 */
16668HMVMX_EXIT_DECL hmR0VmxExitMovDRxNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16669{
16670 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16671
16672 if (CPUMIsGuestVmxProcCtlsSet(&pVCpu->cpum.GstCtx, VMX_PROC_CTLS_MOV_DR_EXIT))
16673 {
16674 hmR0VmxReadExitQualVmcs(pVmxTransient);
16675 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16676
16677 VMXVEXITINFO ExitInfo;
16678 RT_ZERO(ExitInfo);
16679 ExitInfo.uReason = pVmxTransient->uExitReason;
16680 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
16681 ExitInfo.u64Qual = pVmxTransient->uExitQual;
16682 return IEMExecVmxVmexitInstrWithInfo(pVCpu, &ExitInfo);
16683 }
16684 return hmR0VmxExitMovDRx(pVCpu, pVmxTransient);
16685}
16686
16687
16688/**
16689 * Nested-guest VM-exit handler for I/O instructions (VMX_EXIT_IO_INSTR).
16690 * Conditional VM-exit.
16691 */
16692HMVMX_EXIT_DECL hmR0VmxExitIoInstrNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16693{
16694 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16695
16696 hmR0VmxReadExitQualVmcs(pVmxTransient);
16697
16698 uint32_t const uIOPort = VMX_EXIT_QUAL_IO_PORT(pVmxTransient->uExitQual);
16699 uint8_t const uIOSize = VMX_EXIT_QUAL_IO_SIZE(pVmxTransient->uExitQual);
16700 AssertReturn(uIOSize <= 3 && uIOSize != 2, VERR_VMX_IPE_1);
16701
16702 static uint32_t const s_aIOSizes[4] = { 1, 2, 0, 4 }; /* Size of the I/O accesses in bytes. */
16703 uint8_t const cbAccess = s_aIOSizes[uIOSize];
16704 if (CPUMIsGuestVmxIoInterceptSet(pVCpu, uIOPort, cbAccess))
16705 {
16706 /*
16707 * IN/OUT instruction:
16708 * - Provides VM-exit instruction length.
16709 *
16710 * INS/OUTS instruction:
16711 * - Provides VM-exit instruction length.
16712 * - Provides Guest-linear address.
16713 * - Optionally provides VM-exit instruction info (depends on CPU feature).
16714 */
16715 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
16716 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16717
16718 /* Make sure we don't use stale/uninitialized VMX-transient info. below. */
16719 pVmxTransient->ExitInstrInfo.u = 0;
16720 pVmxTransient->uGuestLinearAddr = 0;
16721
16722 bool const fVmxInsOutsInfo = pVM->cpum.ro.GuestFeatures.fVmxInsOutInfo;
16723 bool const fIOString = VMX_EXIT_QUAL_IO_IS_STRING(pVmxTransient->uExitQual);
16724 if (fIOString)
16725 {
16726 hmR0VmxReadGuestLinearAddrVmcs(pVmxTransient);
16727 if (fVmxInsOutsInfo)
16728 {
16729 Assert(RT_BF_GET(pVM->hm.s.vmx.Msrs.u64Basic, VMX_BF_BASIC_VMCS_INS_OUTS)); /* Paranoia. */
16730 hmR0VmxReadExitInstrInfoVmcs(pVmxTransient);
16731 }
16732 }
16733
16734 VMXVEXITINFO ExitInfo;
16735 RT_ZERO(ExitInfo);
16736 ExitInfo.uReason = pVmxTransient->uExitReason;
16737 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
16738 ExitInfo.u64Qual = pVmxTransient->uExitQual;
16739 ExitInfo.InstrInfo = pVmxTransient->ExitInstrInfo;
16740 ExitInfo.u64GuestLinearAddr = pVmxTransient->uGuestLinearAddr;
16741 return IEMExecVmxVmexitInstrWithInfo(pVCpu, &ExitInfo);
16742 }
16743 return hmR0VmxExitIoInstr(pVCpu, pVmxTransient);
16744}
16745
16746
16747/**
16748 * Nested-guest VM-exit handler for RDMSR (VMX_EXIT_RDMSR).
16749 */
16750HMVMX_EXIT_DECL hmR0VmxExitRdmsrNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16751{
16752 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16753
16754 uint32_t fMsrpm;
16755 if (CPUMIsGuestVmxProcCtlsSet(&pVCpu->cpum.GstCtx, VMX_PROC_CTLS_USE_MSR_BITMAPS))
16756 fMsrpm = CPUMGetVmxMsrPermission(pVCpu->cpum.GstCtx.hwvirt.vmx.CTX_SUFF(pvMsrBitmap), pVCpu->cpum.GstCtx.ecx);
16757 else
16758 fMsrpm = VMXMSRPM_EXIT_RD;
16759
16760 if (fMsrpm & VMXMSRPM_EXIT_RD)
16761 {
16762 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16763 return IEMExecVmxVmexitInstr(pVCpu, pVmxTransient->uExitReason, pVmxTransient->cbExitInstr);
16764 }
16765 return hmR0VmxExitRdmsr(pVCpu, pVmxTransient);
16766}
16767
16768
16769/**
16770 * Nested-guest VM-exit handler for WRMSR (VMX_EXIT_WRMSR).
16771 */
16772HMVMX_EXIT_DECL hmR0VmxExitWrmsrNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16773{
16774 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16775
16776 uint32_t fMsrpm;
16777 if (CPUMIsGuestVmxProcCtlsSet(&pVCpu->cpum.GstCtx, VMX_PROC_CTLS_USE_MSR_BITMAPS))
16778 fMsrpm = CPUMGetVmxMsrPermission(pVCpu->cpum.GstCtx.hwvirt.vmx.CTX_SUFF(pvMsrBitmap), pVCpu->cpum.GstCtx.ecx);
16779 else
16780 fMsrpm = VMXMSRPM_EXIT_WR;
16781
16782 if (fMsrpm & VMXMSRPM_EXIT_WR)
16783 {
16784 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16785 return IEMExecVmxVmexitInstr(pVCpu, pVmxTransient->uExitReason, pVmxTransient->cbExitInstr);
16786 }
16787 return hmR0VmxExitWrmsr(pVCpu, pVmxTransient);
16788}
16789
16790
16791/**
16792 * Nested-guest VM-exit handler for MWAIT (VMX_EXIT_MWAIT). Conditional VM-exit.
16793 */
16794HMVMX_EXIT_DECL hmR0VmxExitMwaitNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16795{
16796 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16797
16798 if (CPUMIsGuestVmxProcCtlsSet(&pVCpu->cpum.GstCtx, VMX_PROC_CTLS_MWAIT_EXIT))
16799 {
16800 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16801 return IEMExecVmxVmexitInstr(pVCpu, pVmxTransient->uExitReason, pVmxTransient->cbExitInstr);
16802 }
16803 return hmR0VmxExitMwait(pVCpu, pVmxTransient);
16804}
16805
16806
16807/**
16808 * Nested-guest VM-exit handler for monitor-trap-flag (VMX_EXIT_MTF). Conditional
16809 * VM-exit.
16810 */
16811HMVMX_EXIT_DECL hmR0VmxExitMtfNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16812{
16813 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16814
16815 /** @todo NSTVMX: Should consider debugging nested-guests using VM debugger. */
16816 hmR0VmxReadGuestPendingDbgXctps(pVmxTransient);
16817 VMXVEXITINFO ExitInfo;
16818 RT_ZERO(ExitInfo);
16819 ExitInfo.uReason = pVmxTransient->uExitReason;
16820 ExitInfo.u64GuestPendingDbgXcpts = pVmxTransient->uGuestPendingDbgXcpts;
16821 return IEMExecVmxVmexitTrapLike(pVCpu, &ExitInfo);
16822}
16823
16824
16825/**
16826 * Nested-guest VM-exit handler for MONITOR (VMX_EXIT_MONITOR). Conditional VM-exit.
16827 */
16828HMVMX_EXIT_DECL hmR0VmxExitMonitorNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16829{
16830 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16831
16832 if (CPUMIsGuestVmxProcCtlsSet(&pVCpu->cpum.GstCtx, VMX_PROC_CTLS_MONITOR_EXIT))
16833 {
16834 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16835 return IEMExecVmxVmexitInstr(pVCpu, pVmxTransient->uExitReason, pVmxTransient->cbExitInstr);
16836 }
16837 return hmR0VmxExitMonitor(pVCpu, pVmxTransient);
16838}
16839
16840
16841/**
16842 * Nested-guest VM-exit handler for PAUSE (VMX_EXIT_PAUSE). Conditional VM-exit.
16843 */
16844HMVMX_EXIT_DECL hmR0VmxExitPauseNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16845{
16846 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16847
16848 /** @todo NSTVMX: Think about this more. Does the outer guest need to intercept
16849 * PAUSE when executing a nested-guest? If it does not, we would not need
16850 * to check for the intercepts here. Just call VM-exit... */
16851
16852 /* The CPU would have already performed the necessary CPL checks for PAUSE-loop exiting. */
16853 if ( CPUMIsGuestVmxProcCtlsSet(&pVCpu->cpum.GstCtx, VMX_PROC_CTLS_PAUSE_EXIT)
16854 || CPUMIsGuestVmxProcCtls2Set(&pVCpu->cpum.GstCtx, VMX_PROC_CTLS2_PAUSE_LOOP_EXIT))
16855 {
16856 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16857 return IEMExecVmxVmexitInstr(pVCpu, pVmxTransient->uExitReason, pVmxTransient->cbExitInstr);
16858 }
16859 return hmR0VmxExitPause(pVCpu, pVmxTransient);
16860}
16861
16862
16863/**
16864 * Nested-guest VM-exit handler for when the TPR value is lowered below the
16865 * specified threshold (VMX_EXIT_TPR_BELOW_THRESHOLD). Conditional VM-exit.
16866 */
16867HMVMX_EXIT_NSRC_DECL hmR0VmxExitTprBelowThresholdNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16868{
16869 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16870
16871 if (CPUMIsGuestVmxProcCtlsSet(&pVCpu->cpum.GstCtx, VMX_PROC_CTLS_USE_TPR_SHADOW))
16872 {
16873 hmR0VmxReadGuestPendingDbgXctps(pVmxTransient);
16874 VMXVEXITINFO ExitInfo;
16875 RT_ZERO(ExitInfo);
16876 ExitInfo.uReason = pVmxTransient->uExitReason;
16877 ExitInfo.u64GuestPendingDbgXcpts = pVmxTransient->uGuestPendingDbgXcpts;
16878 return IEMExecVmxVmexitTrapLike(pVCpu, &ExitInfo);
16879 }
16880 return hmR0VmxExitTprBelowThreshold(pVCpu, pVmxTransient);
16881}
16882
16883
16884/**
16885 * Nested-guest VM-exit handler for APIC access (VMX_EXIT_APIC_ACCESS). Conditional
16886 * VM-exit.
16887 */
16888HMVMX_EXIT_DECL hmR0VmxExitApicAccessNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16889{
16890 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16891
16892 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16893 hmR0VmxReadIdtVectoringInfoVmcs(pVmxTransient);
16894 hmR0VmxReadIdtVectoringErrorCodeVmcs(pVmxTransient);
16895 hmR0VmxReadExitQualVmcs(pVmxTransient);
16896
16897 Assert(CPUMIsGuestVmxProcCtls2Set(&pVCpu->cpum.GstCtx, VMX_PROC_CTLS2_VIRT_APIC_ACCESS));
16898
16899 Log4Func(("at offset %#x type=%u\n", VMX_EXIT_QUAL_APIC_ACCESS_OFFSET(pVmxTransient->uExitQual),
16900 VMX_EXIT_QUAL_APIC_ACCESS_TYPE(pVmxTransient->uExitQual)));
16901
16902 VMXVEXITINFO ExitInfo;
16903 RT_ZERO(ExitInfo);
16904 ExitInfo.uReason = pVmxTransient->uExitReason;
16905 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
16906 ExitInfo.u64Qual = pVmxTransient->uExitQual;
16907
16908 VMXVEXITEVENTINFO ExitEventInfo;
16909 RT_ZERO(ExitEventInfo);
16910 ExitEventInfo.uIdtVectoringInfo = pVmxTransient->uIdtVectoringInfo;
16911 ExitEventInfo.uIdtVectoringErrCode = pVmxTransient->uIdtVectoringErrorCode;
16912 return IEMExecVmxVmexitApicAccess(pVCpu, &ExitInfo, &ExitEventInfo);
16913}
16914
16915
16916/**
16917 * Nested-guest VM-exit handler for APIC write emulation (VMX_EXIT_APIC_WRITE).
16918 * Conditional VM-exit.
16919 */
16920HMVMX_EXIT_DECL hmR0VmxExitApicWriteNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16921{
16922 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16923
16924 Assert(CPUMIsGuestVmxProcCtls2Set(&pVCpu->cpum.GstCtx, VMX_PROC_CTLS2_APIC_REG_VIRT));
16925 hmR0VmxReadExitQualVmcs(pVmxTransient);
16926 return IEMExecVmxVmexit(pVCpu, pVmxTransient->uExitReason, pVmxTransient->uExitQual);
16927}
16928
16929
16930/**
16931 * Nested-guest VM-exit handler for virtualized EOI (VMX_EXIT_VIRTUALIZED_EOI).
16932 * Conditional VM-exit.
16933 */
16934HMVMX_EXIT_DECL hmR0VmxExitVirtEoiNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16935{
16936 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16937
16938 Assert(CPUMIsGuestVmxProcCtls2Set(&pVCpu->cpum.GstCtx, VMX_PROC_CTLS2_VIRT_INT_DELIVERY));
16939 hmR0VmxReadExitQualVmcs(pVmxTransient);
16940 return IEMExecVmxVmexit(pVCpu, pVmxTransient->uExitReason, pVmxTransient->uExitQual);
16941}
16942
16943
16944/**
16945 * Nested-guest VM-exit handler for RDTSCP (VMX_EXIT_RDTSCP). Conditional VM-exit.
16946 */
16947HMVMX_EXIT_DECL hmR0VmxExitRdtscpNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16948{
16949 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16950
16951 if (CPUMIsGuestVmxProcCtlsSet(&pVCpu->cpum.GstCtx, VMX_PROC_CTLS_RDTSC_EXIT))
16952 {
16953 Assert(CPUMIsGuestVmxProcCtls2Set(&pVCpu->cpum.GstCtx, VMX_PROC_CTLS2_RDTSCP));
16954 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16955 return IEMExecVmxVmexitInstr(pVCpu, pVmxTransient->uExitReason, pVmxTransient->cbExitInstr);
16956 }
16957 return hmR0VmxExitRdtscp(pVCpu, pVmxTransient);
16958}
16959
16960
16961/**
16962 * Nested-guest VM-exit handler for WBINVD (VMX_EXIT_WBINVD). Conditional VM-exit.
16963 */
16964HMVMX_EXIT_NSRC_DECL hmR0VmxExitWbinvdNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16965{
16966 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16967
16968 if (CPUMIsGuestVmxProcCtls2Set(&pVCpu->cpum.GstCtx, VMX_PROC_CTLS2_WBINVD_EXIT))
16969 {
16970 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16971 return IEMExecVmxVmexitInstr(pVCpu, pVmxTransient->uExitReason, pVmxTransient->cbExitInstr);
16972 }
16973 return hmR0VmxExitWbinvd(pVCpu, pVmxTransient);
16974}
16975
16976
16977/**
16978 * Nested-guest VM-exit handler for INVPCID (VMX_EXIT_INVPCID). Conditional VM-exit.
16979 */
16980HMVMX_EXIT_DECL hmR0VmxExitInvpcidNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16981{
16982 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16983
16984 if (CPUMIsGuestVmxProcCtlsSet(&pVCpu->cpum.GstCtx, VMX_PROC_CTLS_INVLPG_EXIT))
16985 {
16986 Assert(CPUMIsGuestVmxProcCtls2Set(&pVCpu->cpum.GstCtx, VMX_PROC_CTLS2_INVPCID));
16987 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16988 hmR0VmxReadExitQualVmcs(pVmxTransient);
16989 hmR0VmxReadExitInstrInfoVmcs(pVmxTransient);
16990
16991 VMXVEXITINFO ExitInfo;
16992 RT_ZERO(ExitInfo);
16993 ExitInfo.uReason = pVmxTransient->uExitReason;
16994 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
16995 ExitInfo.u64Qual = pVmxTransient->uExitQual;
16996 ExitInfo.InstrInfo = pVmxTransient->ExitInstrInfo;
16997 return IEMExecVmxVmexitInstrWithInfo(pVCpu, &ExitInfo);
16998 }
16999 return hmR0VmxExitInvpcid(pVCpu, pVmxTransient);
17000}
17001
17002
17003/**
17004 * Nested-guest VM-exit handler for invalid-guest state
17005 * (VMX_EXIT_ERR_INVALID_GUEST_STATE). Error VM-exit.
17006 */
17007HMVMX_EXIT_DECL hmR0VmxExitErrInvalidGuestStateNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
17008{
17009 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
17010
17011 /*
17012 * Currently this should never happen because we fully emulate VMLAUNCH/VMRESUME in IEM.
17013 * So if it does happen, it indicates a bug possibly in the hardware-assisted VMX code.
17014 * Handle it like it's in an invalid guest state of the outer guest.
17015 *
17016 * When the fast path is implemented, this should be changed to cause the corresponding
17017 * nested-guest VM-exit.
17018 */
17019 return hmR0VmxExitErrInvalidGuestState(pVCpu, pVmxTransient);
17020}
17021
17022
17023/**
17024 * Nested-guest VM-exit handler for instructions that cause VM-exits uncondtionally
17025 * and only provide the instruction length.
17026 *
17027 * Unconditional VM-exit.
17028 */
17029HMVMX_EXIT_DECL hmR0VmxExitInstrNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
17030{
17031 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
17032
17033#ifdef VBOX_STRICT
17034 PCCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
17035 switch (pVmxTransient->uExitReason)
17036 {
17037 case VMX_EXIT_ENCLS:
17038 Assert(CPUMIsGuestVmxProcCtls2Set(pCtx, VMX_PROC_CTLS2_ENCLS_EXIT));
17039 break;
17040
17041 case VMX_EXIT_VMFUNC:
17042 Assert(CPUMIsGuestVmxProcCtls2Set(pCtx, VMX_PROC_CTLS2_VMFUNC));
17043 break;
17044 }
17045#endif
17046
17047 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
17048 return IEMExecVmxVmexitInstr(pVCpu, pVmxTransient->uExitReason, pVmxTransient->cbExitInstr);
17049}
17050
17051
17052/**
17053 * Nested-guest VM-exit handler for instructions that provide instruction length as
17054 * well as more information.
17055 *
17056 * Unconditional VM-exit.
17057 */
17058HMVMX_EXIT_DECL hmR0VmxExitInstrWithInfoNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
17059{
17060 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
17061
17062#ifdef VBOX_STRICT
17063 PCCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
17064 switch (pVmxTransient->uExitReason)
17065 {
17066 case VMX_EXIT_GDTR_IDTR_ACCESS:
17067 case VMX_EXIT_LDTR_TR_ACCESS:
17068 Assert(CPUMIsGuestVmxProcCtls2Set(pCtx, VMX_PROC_CTLS2_DESC_TABLE_EXIT));
17069 break;
17070
17071 case VMX_EXIT_RDRAND:
17072 Assert(CPUMIsGuestVmxProcCtls2Set(pCtx, VMX_PROC_CTLS2_RDRAND_EXIT));
17073 break;
17074
17075 case VMX_EXIT_RDSEED:
17076 Assert(CPUMIsGuestVmxProcCtls2Set(pCtx, VMX_PROC_CTLS2_RDSEED_EXIT));
17077 break;
17078
17079 case VMX_EXIT_XSAVES:
17080 case VMX_EXIT_XRSTORS:
17081 /** @todo NSTVMX: Verify XSS-bitmap. */
17082 Assert(CPUMIsGuestVmxProcCtls2Set(pCtx, VMX_PROC_CTLS2_XSAVES_XRSTORS));
17083 break;
17084
17085 case VMX_EXIT_UMWAIT:
17086 case VMX_EXIT_TPAUSE:
17087 Assert(CPUMIsGuestVmxProcCtlsSet(pCtx, VMX_PROC_CTLS_RDTSC_EXIT));
17088 Assert(CPUMIsGuestVmxProcCtls2Set(pCtx, VMX_PROC_CTLS2_USER_WAIT_PAUSE));
17089 break;
17090 }
17091#endif
17092
17093 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
17094 hmR0VmxReadExitQualVmcs(pVmxTransient);
17095 hmR0VmxReadExitInstrInfoVmcs(pVmxTransient);
17096
17097 VMXVEXITINFO ExitInfo;
17098 RT_ZERO(ExitInfo);
17099 ExitInfo.uReason = pVmxTransient->uExitReason;
17100 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
17101 ExitInfo.u64Qual = pVmxTransient->uExitQual;
17102 ExitInfo.InstrInfo = pVmxTransient->ExitInstrInfo;
17103 return IEMExecVmxVmexitInstrWithInfo(pVCpu, &ExitInfo);
17104}
17105
17106/** @} */
17107#endif /* VBOX_WITH_NESTED_HWVIRT_VMX */
17108
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