VirtualBox

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

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

VMM/HMVMXR0: Nested VMX: bugref:9180 Build fix.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 702.7 KB
Line 
1/* $Id: HMVMXR0.cpp 80580 2019-09-04 08:49:59Z 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#ifdef VBOX_WITH_REM
39# include <VBox/vmm/rem.h>
40#endif
41#include "HMInternal.h"
42#include <VBox/vmm/vmcc.h>
43#include <VBox/vmm/hmvmxinline.h>
44#include "HMVMXR0.h"
45#include "dtrace/VBoxVMM.h"
46
47#ifdef DEBUG_ramshankar
48# define HMVMX_ALWAYS_SAVE_GUEST_RFLAGS
49# define HMVMX_ALWAYS_SAVE_RO_GUEST_STATE
50# define HMVMX_ALWAYS_SAVE_FULL_GUEST_STATE
51# define HMVMX_ALWAYS_SYNC_FULL_GUEST_STATE
52# define HMVMX_ALWAYS_CLEAN_TRANSIENT
53# define HMVMX_ALWAYS_CHECK_GUEST_STATE
54# define HMVMX_ALWAYS_TRAP_ALL_XCPTS
55# define HMVMX_ALWAYS_TRAP_PF
56# define HMVMX_ALWAYS_FLUSH_TLB
57# define HMVMX_ALWAYS_SWAP_EFER
58#endif
59
60
61/*********************************************************************************************************************************
62* Defined Constants And Macros *
63*********************************************************************************************************************************/
64/** Use the function table. */
65#define HMVMX_USE_FUNCTION_TABLE
66
67/** Determine which tagged-TLB flush handler to use. */
68#define HMVMX_FLUSH_TAGGED_TLB_EPT_VPID 0
69#define HMVMX_FLUSH_TAGGED_TLB_EPT 1
70#define HMVMX_FLUSH_TAGGED_TLB_VPID 2
71#define HMVMX_FLUSH_TAGGED_TLB_NONE 3
72
73/**
74 * Flags to skip redundant reads of some common VMCS fields that are not part of
75 * the guest-CPU or VCPU state but are needed while handling VM-exits.
76 */
77#define HMVMX_READ_IDT_VECTORING_INFO RT_BIT_32(0)
78#define HMVMX_READ_IDT_VECTORING_ERROR_CODE RT_BIT_32(1)
79#define HMVMX_READ_EXIT_QUALIFICATION RT_BIT_32(2)
80#define HMVMX_READ_EXIT_INSTR_LEN RT_BIT_32(3)
81#define HMVMX_READ_EXIT_INTERRUPTION_INFO RT_BIT_32(4)
82#define HMVMX_READ_EXIT_INTERRUPTION_ERROR_CODE RT_BIT_32(5)
83#define HMVMX_READ_EXIT_INSTR_INFO RT_BIT_32(6)
84#define HMVMX_READ_GUEST_LINEAR_ADDR RT_BIT_32(7)
85#define HMVMX_READ_GUEST_PHYSICAL_ADDR RT_BIT_32(8)
86#define HMVMX_READ_GUEST_PENDING_DBG_XCPTS RT_BIT_32(9)
87
88/** All the VMCS fields required for processing of exception/NMI VM-exits. */
89#define HMVMX_READ_XCPT_INFO ( HMVMX_READ_EXIT_INTERRUPTION_INFO \
90 | HMVMX_READ_EXIT_INTERRUPTION_ERROR_CODE \
91 | HMVMX_READ_EXIT_INSTR_LEN \
92 | HMVMX_READ_IDT_VECTORING_INFO \
93 | HMVMX_READ_IDT_VECTORING_ERROR_CODE)
94
95/** Assert that all the given fields have been read from the VMCS. */
96#ifdef VBOX_STRICT
97# define HMVMX_ASSERT_READ(a_pVmxTransient, a_fReadFields) \
98 do { \
99 uint32_t const fVmcsFieldRead = ASMAtomicUoReadU32(&pVmxTransient->fVmcsFieldsRead); \
100 RT_UNTRUSTED_NONVOLATILE_COPY_FENCE(); \
101 Assert((fVmcsFieldRead & (a_fReadFields)) == (a_fReadFields)); \
102 } while (0)
103#else
104# define HMVMX_ASSERT_READ(a_pVmxTransient, a_fReadFields) do { } while (0)
105#endif
106
107/**
108 * Subset of the guest-CPU state that is kept by VMX R0 code while executing the
109 * guest using hardware-assisted VMX.
110 *
111 * This excludes state like GPRs (other than RSP) which are always are
112 * swapped and restored across the world-switch and also registers like EFER,
113 * MSR which cannot be modified by the guest without causing a VM-exit.
114 */
115#define HMVMX_CPUMCTX_EXTRN_ALL ( CPUMCTX_EXTRN_RIP \
116 | CPUMCTX_EXTRN_RFLAGS \
117 | CPUMCTX_EXTRN_RSP \
118 | CPUMCTX_EXTRN_SREG_MASK \
119 | CPUMCTX_EXTRN_TABLE_MASK \
120 | CPUMCTX_EXTRN_KERNEL_GS_BASE \
121 | CPUMCTX_EXTRN_SYSCALL_MSRS \
122 | CPUMCTX_EXTRN_SYSENTER_MSRS \
123 | CPUMCTX_EXTRN_TSC_AUX \
124 | CPUMCTX_EXTRN_OTHER_MSRS \
125 | CPUMCTX_EXTRN_CR0 \
126 | CPUMCTX_EXTRN_CR3 \
127 | CPUMCTX_EXTRN_CR4 \
128 | CPUMCTX_EXTRN_DR7 \
129 | CPUMCTX_EXTRN_HWVIRT \
130 | CPUMCTX_EXTRN_HM_VMX_MASK)
131
132/**
133 * Exception bitmap mask for real-mode guests (real-on-v86).
134 *
135 * We need to intercept all exceptions manually except:
136 * - \#AC and \#DB are always intercepted to prevent the CPU from deadlocking
137 * due to bugs in Intel CPUs.
138 * - \#PF need not be intercepted even in real-mode if we have nested paging
139 * support.
140 */
141#define HMVMX_REAL_MODE_XCPT_MASK ( RT_BIT(X86_XCPT_DE) /* always: | RT_BIT(X86_XCPT_DB) */ | RT_BIT(X86_XCPT_NMI) \
142 | RT_BIT(X86_XCPT_BP) | RT_BIT(X86_XCPT_OF) | RT_BIT(X86_XCPT_BR) \
143 | RT_BIT(X86_XCPT_UD) | RT_BIT(X86_XCPT_NM) | RT_BIT(X86_XCPT_DF) \
144 | RT_BIT(X86_XCPT_CO_SEG_OVERRUN) | RT_BIT(X86_XCPT_TS) | RT_BIT(X86_XCPT_NP) \
145 | RT_BIT(X86_XCPT_SS) | RT_BIT(X86_XCPT_GP) /* RT_BIT(X86_XCPT_PF) */ \
146 | RT_BIT(X86_XCPT_MF) /* always: | RT_BIT(X86_XCPT_AC) */ | RT_BIT(X86_XCPT_MC) \
147 | RT_BIT(X86_XCPT_XF))
148
149/** Maximum VM-instruction error number. */
150#define HMVMX_INSTR_ERROR_MAX 28
151
152/** Profiling macro. */
153#ifdef HM_PROFILE_EXIT_DISPATCH
154# define HMVMX_START_EXIT_DISPATCH_PROF() STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatExitDispatch, ed)
155# define HMVMX_STOP_EXIT_DISPATCH_PROF() STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExitDispatch, ed)
156#else
157# define HMVMX_START_EXIT_DISPATCH_PROF() do { } while (0)
158# define HMVMX_STOP_EXIT_DISPATCH_PROF() do { } while (0)
159#endif
160
161/** Assert that preemption is disabled or covered by thread-context hooks. */
162#define HMVMX_ASSERT_PREEMPT_SAFE(a_pVCpu) Assert( VMMR0ThreadCtxHookIsEnabled((a_pVCpu)) \
163 || !RTThreadPreemptIsEnabled(NIL_RTTHREAD))
164
165/** Assert that we haven't migrated CPUs when thread-context hooks are not
166 * used. */
167#define HMVMX_ASSERT_CPU_SAFE(a_pVCpu) AssertMsg( VMMR0ThreadCtxHookIsEnabled((a_pVCpu)) \
168 || (a_pVCpu)->hm.s.idEnteredCpu == RTMpCpuId(), \
169 ("Illegal migration! Entered on CPU %u Current %u\n", \
170 (a_pVCpu)->hm.s.idEnteredCpu, RTMpCpuId()))
171
172/** Asserts that the given CPUMCTX_EXTRN_XXX bits are present in the guest-CPU
173 * context. */
174#define HMVMX_CPUMCTX_ASSERT(a_pVCpu, a_fExtrnMbz) AssertMsg(!((a_pVCpu)->cpum.GstCtx.fExtrn & (a_fExtrnMbz)), \
175 ("fExtrn=%#RX64 fExtrnMbz=%#RX64\n", \
176 (a_pVCpu)->cpum.GstCtx.fExtrn, (a_fExtrnMbz)))
177
178/** Log the VM-exit reason with an easily visible marker to identify it in a
179 * potential sea of logging data. */
180#define HMVMX_LOG_EXIT(a_pVCpu, a_uExitReason) \
181 do { \
182 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, \
183 HMGetVmxExitName(a_uExitReason))); \
184 } while (0) \
185
186
187/*********************************************************************************************************************************
188* Structures and Typedefs *
189*********************************************************************************************************************************/
190/**
191 * VMX per-VCPU transient state.
192 *
193 * A state structure for holding miscellaneous information across
194 * VMX non-root operation and restored after the transition.
195 */
196typedef struct VMXTRANSIENT
197{
198 /** The host's rflags/eflags. */
199 RTCCUINTREG fEFlags;
200
201 /** The guest's TPR value used for TPR shadowing. */
202 uint8_t u8GuestTpr;
203 /** Alignment. */
204 uint8_t abAlignment0[7];
205
206 /** The basic VM-exit reason. */
207 uint16_t uExitReason;
208 /** Alignment. */
209 uint16_t u16Alignment0;
210 /** The VM-exit interruption error code. */
211 uint32_t uExitIntErrorCode;
212 /** The VM-exit exit code qualification. */
213 uint64_t uExitQual;
214 /** The Guest-linear address. */
215 uint64_t uGuestLinearAddr;
216 /** The Guest-physical address. */
217 uint64_t uGuestPhysicalAddr;
218 /** The Guest pending-debug exceptions. */
219 uint64_t uGuestPendingDbgXcpts;
220
221 /** The VM-exit interruption-information field. */
222 uint32_t uExitIntInfo;
223 /** The VM-exit instruction-length field. */
224 uint32_t cbExitInstr;
225 /** The VM-exit instruction-information field. */
226 VMXEXITINSTRINFO ExitInstrInfo;
227 /** Whether the VM-entry failed or not. */
228 bool fVMEntryFailed;
229 /** Whether we are currently executing a nested-guest. */
230 bool fIsNestedGuest;
231 /** Alignment. */
232 uint8_t abAlignment1[2];
233
234 /** The VM-entry interruption-information field. */
235 uint32_t uEntryIntInfo;
236 /** The VM-entry exception error code field. */
237 uint32_t uEntryXcptErrorCode;
238 /** The VM-entry instruction length field. */
239 uint32_t cbEntryInstr;
240
241 /** IDT-vectoring information field. */
242 uint32_t uIdtVectoringInfo;
243 /** IDT-vectoring error code. */
244 uint32_t uIdtVectoringErrorCode;
245
246 /** Mask of currently read VMCS fields; HMVMX_READ_XXX. */
247 uint32_t fVmcsFieldsRead;
248
249 /** Whether the guest debug state was active at the time of VM-exit. */
250 bool fWasGuestDebugStateActive;
251 /** Whether the hyper debug state was active at the time of VM-exit. */
252 bool fWasHyperDebugStateActive;
253 /** Whether TSC-offsetting and VMX-preemption timer was updated before VM-entry. */
254 bool fUpdatedTscOffsettingAndPreemptTimer;
255 /** Whether the VM-exit was caused by a page-fault during delivery of a
256 * contributory exception or a page-fault. */
257 bool fVectoringDoublePF;
258 /** Whether the VM-exit was caused by a page-fault during delivery of an
259 * external interrupt or NMI. */
260 bool fVectoringPF;
261 /** Whether the TSC_AUX MSR needs to be removed from the auto-load/store MSR
262 * area after VM-exit. */
263 bool fRemoveTscAuxMsr;
264 bool afAlignment0[2];
265
266 /** The VMCS info. object. */
267 PVMXVMCSINFO pVmcsInfo;
268} VMXTRANSIENT;
269AssertCompileMemberAlignment(VMXTRANSIENT, uExitReason, sizeof(uint64_t));
270AssertCompileMemberAlignment(VMXTRANSIENT, uExitIntInfo, sizeof(uint64_t));
271AssertCompileMemberAlignment(VMXTRANSIENT, uEntryIntInfo, sizeof(uint64_t));
272AssertCompileMemberAlignment(VMXTRANSIENT, fWasGuestDebugStateActive, sizeof(uint64_t));
273AssertCompileMemberAlignment(VMXTRANSIENT, pVmcsInfo, sizeof(uint64_t));
274AssertCompileMemberSize(VMXTRANSIENT, ExitInstrInfo, sizeof(uint32_t));
275/** Pointer to VMX transient state. */
276typedef VMXTRANSIENT *PVMXTRANSIENT;
277/** Pointer to a const VMX transient state. */
278typedef const VMXTRANSIENT *PCVMXTRANSIENT;
279
280/**
281 * Memory operand read or write access.
282 */
283typedef enum VMXMEMACCESS
284{
285 VMXMEMACCESS_READ = 0,
286 VMXMEMACCESS_WRITE = 1
287} VMXMEMACCESS;
288
289/**
290 * VMX VM-exit handler.
291 *
292 * @returns Strict VBox status code (i.e. informational status codes too).
293 * @param pVCpu The cross context virtual CPU structure.
294 * @param pVmxTransient The VMX-transient structure.
295 */
296#ifndef HMVMX_USE_FUNCTION_TABLE
297typedef VBOXSTRICTRC FNVMXEXITHANDLER(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient);
298#else
299typedef DECLCALLBACK(VBOXSTRICTRC) FNVMXEXITHANDLER(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient);
300/** Pointer to VM-exit handler. */
301typedef FNVMXEXITHANDLER *PFNVMXEXITHANDLER;
302#endif
303
304/**
305 * VMX VM-exit handler, non-strict status code.
306 *
307 * This is generally the same as FNVMXEXITHANDLER, the NSRC bit is just FYI.
308 *
309 * @returns VBox status code, no informational status code returned.
310 * @param pVCpu The cross context virtual CPU structure.
311 * @param pVmxTransient The VMX-transient structure.
312 *
313 * @remarks This is not used on anything returning VERR_EM_INTERPRETER as the
314 * use of that status code will be replaced with VINF_EM_SOMETHING
315 * later when switching over to IEM.
316 */
317#ifndef HMVMX_USE_FUNCTION_TABLE
318typedef int FNVMXEXITHANDLERNSRC(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient);
319#else
320typedef FNVMXEXITHANDLER FNVMXEXITHANDLERNSRC;
321#endif
322
323
324/*********************************************************************************************************************************
325* Internal Functions *
326*********************************************************************************************************************************/
327#ifndef HMVMX_USE_FUNCTION_TABLE
328DECLINLINE(VBOXSTRICTRC) hmR0VmxHandleExit(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient);
329# define HMVMX_EXIT_DECL DECLINLINE(VBOXSTRICTRC)
330# define HMVMX_EXIT_NSRC_DECL DECLINLINE(int)
331#else
332# define HMVMX_EXIT_DECL static DECLCALLBACK(VBOXSTRICTRC)
333# define HMVMX_EXIT_NSRC_DECL HMVMX_EXIT_DECL
334#endif
335#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
336DECLINLINE(VBOXSTRICTRC) hmR0VmxHandleExitNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient);
337#endif
338
339static int hmR0VmxImportGuestState(PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo, uint64_t fWhat);
340
341/** @name VM-exit handler prototypes.
342 * @{
343 */
344static FNVMXEXITHANDLER hmR0VmxExitXcptOrNmi;
345static FNVMXEXITHANDLER hmR0VmxExitExtInt;
346static FNVMXEXITHANDLER hmR0VmxExitTripleFault;
347static FNVMXEXITHANDLERNSRC hmR0VmxExitIntWindow;
348static FNVMXEXITHANDLERNSRC hmR0VmxExitNmiWindow;
349static FNVMXEXITHANDLER hmR0VmxExitTaskSwitch;
350static FNVMXEXITHANDLER hmR0VmxExitCpuid;
351static FNVMXEXITHANDLER hmR0VmxExitGetsec;
352static FNVMXEXITHANDLER hmR0VmxExitHlt;
353static FNVMXEXITHANDLERNSRC hmR0VmxExitInvd;
354static FNVMXEXITHANDLER hmR0VmxExitInvlpg;
355static FNVMXEXITHANDLER hmR0VmxExitRdpmc;
356static FNVMXEXITHANDLER hmR0VmxExitVmcall;
357#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
358static FNVMXEXITHANDLER hmR0VmxExitVmclear;
359static FNVMXEXITHANDLER hmR0VmxExitVmlaunch;
360static FNVMXEXITHANDLER hmR0VmxExitVmptrld;
361static FNVMXEXITHANDLER hmR0VmxExitVmptrst;
362static FNVMXEXITHANDLER hmR0VmxExitVmread;
363static FNVMXEXITHANDLER hmR0VmxExitVmresume;
364static FNVMXEXITHANDLER hmR0VmxExitVmwrite;
365static FNVMXEXITHANDLER hmR0VmxExitVmxoff;
366static FNVMXEXITHANDLER hmR0VmxExitVmxon;
367static FNVMXEXITHANDLER hmR0VmxExitInvvpid;
368#endif
369static FNVMXEXITHANDLER hmR0VmxExitRdtsc;
370static FNVMXEXITHANDLER hmR0VmxExitMovCRx;
371static FNVMXEXITHANDLER hmR0VmxExitMovDRx;
372static FNVMXEXITHANDLER hmR0VmxExitIoInstr;
373static FNVMXEXITHANDLER hmR0VmxExitRdmsr;
374static FNVMXEXITHANDLER hmR0VmxExitWrmsr;
375static FNVMXEXITHANDLER hmR0VmxExitMwait;
376static FNVMXEXITHANDLER hmR0VmxExitMtf;
377static FNVMXEXITHANDLER hmR0VmxExitMonitor;
378static FNVMXEXITHANDLER hmR0VmxExitPause;
379static FNVMXEXITHANDLERNSRC hmR0VmxExitTprBelowThreshold;
380static FNVMXEXITHANDLER hmR0VmxExitApicAccess;
381static FNVMXEXITHANDLER hmR0VmxExitEptViolation;
382static FNVMXEXITHANDLER hmR0VmxExitEptMisconfig;
383static FNVMXEXITHANDLER hmR0VmxExitRdtscp;
384static FNVMXEXITHANDLER hmR0VmxExitPreemptTimer;
385static FNVMXEXITHANDLERNSRC hmR0VmxExitWbinvd;
386static FNVMXEXITHANDLER hmR0VmxExitXsetbv;
387static FNVMXEXITHANDLER hmR0VmxExitInvpcid;
388static FNVMXEXITHANDLERNSRC hmR0VmxExitSetPendingXcptUD;
389static FNVMXEXITHANDLERNSRC hmR0VmxExitErrInvalidGuestState;
390static FNVMXEXITHANDLERNSRC hmR0VmxExitErrUnexpected;
391/** @} */
392
393#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
394/** @name Nested-guest VM-exit handler prototypes.
395 * @{
396 */
397static FNVMXEXITHANDLER hmR0VmxExitXcptOrNmiNested;
398static FNVMXEXITHANDLER hmR0VmxExitTripleFaultNested;
399static FNVMXEXITHANDLERNSRC hmR0VmxExitIntWindowNested;
400static FNVMXEXITHANDLERNSRC hmR0VmxExitNmiWindowNested;
401static FNVMXEXITHANDLER hmR0VmxExitTaskSwitchNested;
402static FNVMXEXITHANDLER hmR0VmxExitHltNested;
403static FNVMXEXITHANDLER hmR0VmxExitInvlpgNested;
404static FNVMXEXITHANDLER hmR0VmxExitRdpmcNested;
405static FNVMXEXITHANDLER hmR0VmxExitVmreadVmwriteNested;
406static FNVMXEXITHANDLER hmR0VmxExitRdtscNested;
407static FNVMXEXITHANDLER hmR0VmxExitMovCRxNested;
408static FNVMXEXITHANDLER hmR0VmxExitMovDRxNested;
409static FNVMXEXITHANDLER hmR0VmxExitIoInstrNested;
410static FNVMXEXITHANDLER hmR0VmxExitRdmsrNested;
411static FNVMXEXITHANDLER hmR0VmxExitWrmsrNested;
412static FNVMXEXITHANDLER hmR0VmxExitMwaitNested;
413static FNVMXEXITHANDLER hmR0VmxExitMtfNested;
414static FNVMXEXITHANDLER hmR0VmxExitMonitorNested;
415static FNVMXEXITHANDLER hmR0VmxExitPauseNested;
416static FNVMXEXITHANDLERNSRC hmR0VmxExitTprBelowThresholdNested;
417static FNVMXEXITHANDLER hmR0VmxExitApicAccessNested;
418static FNVMXEXITHANDLER hmR0VmxExitApicWriteNested;
419static FNVMXEXITHANDLER hmR0VmxExitVirtEoiNested;
420static FNVMXEXITHANDLER hmR0VmxExitRdtscpNested;
421static FNVMXEXITHANDLERNSRC hmR0VmxExitWbinvdNested;
422static FNVMXEXITHANDLER hmR0VmxExitInvpcidNested;
423static FNVMXEXITHANDLERNSRC hmR0VmxExitErrInvalidGuestStateNested;
424static FNVMXEXITHANDLER hmR0VmxExitInstrNested;
425static FNVMXEXITHANDLER hmR0VmxExitInstrWithInfoNested;
426/** @} */
427#endif /* VBOX_WITH_NESTED_HWVIRT_VMX */
428
429
430/*********************************************************************************************************************************
431* Global Variables *
432*********************************************************************************************************************************/
433#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
434/**
435 * Array of all VMCS fields.
436 * Any fields added to the VT-x spec. should be added here.
437 *
438 * Currently only used to derive shadow VMCS fields for hardware-assisted execution
439 * of nested-guests.
440 */
441static const uint32_t g_aVmcsFields[] =
442{
443 /* 16-bit control fields. */
444 VMX_VMCS16_VPID,
445 VMX_VMCS16_POSTED_INT_NOTIFY_VECTOR,
446 VMX_VMCS16_EPTP_INDEX,
447
448 /* 16-bit guest-state fields. */
449 VMX_VMCS16_GUEST_ES_SEL,
450 VMX_VMCS16_GUEST_CS_SEL,
451 VMX_VMCS16_GUEST_SS_SEL,
452 VMX_VMCS16_GUEST_DS_SEL,
453 VMX_VMCS16_GUEST_FS_SEL,
454 VMX_VMCS16_GUEST_GS_SEL,
455 VMX_VMCS16_GUEST_LDTR_SEL,
456 VMX_VMCS16_GUEST_TR_SEL,
457 VMX_VMCS16_GUEST_INTR_STATUS,
458 VMX_VMCS16_GUEST_PML_INDEX,
459
460 /* 16-bits host-state fields. */
461 VMX_VMCS16_HOST_ES_SEL,
462 VMX_VMCS16_HOST_CS_SEL,
463 VMX_VMCS16_HOST_SS_SEL,
464 VMX_VMCS16_HOST_DS_SEL,
465 VMX_VMCS16_HOST_FS_SEL,
466 VMX_VMCS16_HOST_GS_SEL,
467 VMX_VMCS16_HOST_TR_SEL,
468
469 /* 64-bit control fields. */
470 VMX_VMCS64_CTRL_IO_BITMAP_A_FULL,
471 VMX_VMCS64_CTRL_IO_BITMAP_A_HIGH,
472 VMX_VMCS64_CTRL_IO_BITMAP_B_FULL,
473 VMX_VMCS64_CTRL_IO_BITMAP_B_HIGH,
474 VMX_VMCS64_CTRL_MSR_BITMAP_FULL,
475 VMX_VMCS64_CTRL_MSR_BITMAP_HIGH,
476 VMX_VMCS64_CTRL_EXIT_MSR_STORE_FULL,
477 VMX_VMCS64_CTRL_EXIT_MSR_STORE_HIGH,
478 VMX_VMCS64_CTRL_EXIT_MSR_LOAD_FULL,
479 VMX_VMCS64_CTRL_EXIT_MSR_LOAD_HIGH,
480 VMX_VMCS64_CTRL_ENTRY_MSR_LOAD_FULL,
481 VMX_VMCS64_CTRL_ENTRY_MSR_LOAD_HIGH,
482 VMX_VMCS64_CTRL_EXEC_VMCS_PTR_FULL,
483 VMX_VMCS64_CTRL_EXEC_VMCS_PTR_HIGH,
484 VMX_VMCS64_CTRL_EXEC_PML_ADDR_FULL,
485 VMX_VMCS64_CTRL_EXEC_PML_ADDR_HIGH,
486 VMX_VMCS64_CTRL_TSC_OFFSET_FULL,
487 VMX_VMCS64_CTRL_TSC_OFFSET_HIGH,
488 VMX_VMCS64_CTRL_VIRT_APIC_PAGEADDR_FULL,
489 VMX_VMCS64_CTRL_VIRT_APIC_PAGEADDR_HIGH,
490 VMX_VMCS64_CTRL_APIC_ACCESSADDR_FULL,
491 VMX_VMCS64_CTRL_APIC_ACCESSADDR_HIGH,
492 VMX_VMCS64_CTRL_POSTED_INTR_DESC_FULL,
493 VMX_VMCS64_CTRL_POSTED_INTR_DESC_HIGH,
494 VMX_VMCS64_CTRL_VMFUNC_CTRLS_FULL,
495 VMX_VMCS64_CTRL_VMFUNC_CTRLS_HIGH,
496 VMX_VMCS64_CTRL_EPTP_FULL,
497 VMX_VMCS64_CTRL_EPTP_HIGH,
498 VMX_VMCS64_CTRL_EOI_BITMAP_0_FULL,
499 VMX_VMCS64_CTRL_EOI_BITMAP_0_HIGH,
500 VMX_VMCS64_CTRL_EOI_BITMAP_1_FULL,
501 VMX_VMCS64_CTRL_EOI_BITMAP_1_HIGH,
502 VMX_VMCS64_CTRL_EOI_BITMAP_2_FULL,
503 VMX_VMCS64_CTRL_EOI_BITMAP_2_HIGH,
504 VMX_VMCS64_CTRL_EOI_BITMAP_3_FULL,
505 VMX_VMCS64_CTRL_EOI_BITMAP_3_HIGH,
506 VMX_VMCS64_CTRL_EPTP_LIST_FULL,
507 VMX_VMCS64_CTRL_EPTP_LIST_HIGH,
508 VMX_VMCS64_CTRL_VMREAD_BITMAP_FULL,
509 VMX_VMCS64_CTRL_VMREAD_BITMAP_HIGH,
510 VMX_VMCS64_CTRL_VMWRITE_BITMAP_FULL,
511 VMX_VMCS64_CTRL_VMWRITE_BITMAP_HIGH,
512 VMX_VMCS64_CTRL_VIRTXCPT_INFO_ADDR_FULL,
513 VMX_VMCS64_CTRL_VIRTXCPT_INFO_ADDR_HIGH,
514 VMX_VMCS64_CTRL_XSS_EXITING_BITMAP_FULL,
515 VMX_VMCS64_CTRL_XSS_EXITING_BITMAP_HIGH,
516 VMX_VMCS64_CTRL_ENCLS_EXITING_BITMAP_FULL,
517 VMX_VMCS64_CTRL_ENCLS_EXITING_BITMAP_HIGH,
518 VMX_VMCS64_CTRL_TSC_MULTIPLIER_FULL,
519 VMX_VMCS64_CTRL_TSC_MULTIPLIER_HIGH,
520
521 /* 64-bit read-only data fields. */
522 VMX_VMCS64_RO_GUEST_PHYS_ADDR_FULL,
523 VMX_VMCS64_RO_GUEST_PHYS_ADDR_HIGH,
524
525 /* 64-bit guest-state fields. */
526 VMX_VMCS64_GUEST_VMCS_LINK_PTR_FULL,
527 VMX_VMCS64_GUEST_VMCS_LINK_PTR_HIGH,
528 VMX_VMCS64_GUEST_DEBUGCTL_FULL,
529 VMX_VMCS64_GUEST_DEBUGCTL_HIGH,
530 VMX_VMCS64_GUEST_PAT_FULL,
531 VMX_VMCS64_GUEST_PAT_HIGH,
532 VMX_VMCS64_GUEST_EFER_FULL,
533 VMX_VMCS64_GUEST_EFER_HIGH,
534 VMX_VMCS64_GUEST_PERF_GLOBAL_CTRL_FULL,
535 VMX_VMCS64_GUEST_PERF_GLOBAL_CTRL_HIGH,
536 VMX_VMCS64_GUEST_PDPTE0_FULL,
537 VMX_VMCS64_GUEST_PDPTE0_HIGH,
538 VMX_VMCS64_GUEST_PDPTE1_FULL,
539 VMX_VMCS64_GUEST_PDPTE1_HIGH,
540 VMX_VMCS64_GUEST_PDPTE2_FULL,
541 VMX_VMCS64_GUEST_PDPTE2_HIGH,
542 VMX_VMCS64_GUEST_PDPTE3_FULL,
543 VMX_VMCS64_GUEST_PDPTE3_HIGH,
544 VMX_VMCS64_GUEST_BNDCFGS_FULL,
545 VMX_VMCS64_GUEST_BNDCFGS_HIGH,
546
547 /* 64-bit host-state fields. */
548 VMX_VMCS64_HOST_PAT_FULL,
549 VMX_VMCS64_HOST_PAT_HIGH,
550 VMX_VMCS64_HOST_EFER_FULL,
551 VMX_VMCS64_HOST_EFER_HIGH,
552 VMX_VMCS64_HOST_PERF_GLOBAL_CTRL_FULL,
553 VMX_VMCS64_HOST_PERF_GLOBAL_CTRL_HIGH,
554
555 /* 32-bit control fields. */
556 VMX_VMCS32_CTRL_PIN_EXEC,
557 VMX_VMCS32_CTRL_PROC_EXEC,
558 VMX_VMCS32_CTRL_EXCEPTION_BITMAP,
559 VMX_VMCS32_CTRL_PAGEFAULT_ERROR_MASK,
560 VMX_VMCS32_CTRL_PAGEFAULT_ERROR_MATCH,
561 VMX_VMCS32_CTRL_CR3_TARGET_COUNT,
562 VMX_VMCS32_CTRL_EXIT,
563 VMX_VMCS32_CTRL_EXIT_MSR_STORE_COUNT,
564 VMX_VMCS32_CTRL_EXIT_MSR_LOAD_COUNT,
565 VMX_VMCS32_CTRL_ENTRY,
566 VMX_VMCS32_CTRL_ENTRY_MSR_LOAD_COUNT,
567 VMX_VMCS32_CTRL_ENTRY_INTERRUPTION_INFO,
568 VMX_VMCS32_CTRL_ENTRY_EXCEPTION_ERRCODE,
569 VMX_VMCS32_CTRL_ENTRY_INSTR_LENGTH,
570 VMX_VMCS32_CTRL_TPR_THRESHOLD,
571 VMX_VMCS32_CTRL_PROC_EXEC2,
572 VMX_VMCS32_CTRL_PLE_GAP,
573 VMX_VMCS32_CTRL_PLE_WINDOW,
574
575 /* 32-bits read-only fields. */
576 VMX_VMCS32_RO_VM_INSTR_ERROR,
577 VMX_VMCS32_RO_EXIT_REASON,
578 VMX_VMCS32_RO_EXIT_INTERRUPTION_INFO,
579 VMX_VMCS32_RO_EXIT_INTERRUPTION_ERROR_CODE,
580 VMX_VMCS32_RO_IDT_VECTORING_INFO,
581 VMX_VMCS32_RO_IDT_VECTORING_ERROR_CODE,
582 VMX_VMCS32_RO_EXIT_INSTR_LENGTH,
583 VMX_VMCS32_RO_EXIT_INSTR_INFO,
584
585 /* 32-bit guest-state fields. */
586 VMX_VMCS32_GUEST_ES_LIMIT,
587 VMX_VMCS32_GUEST_CS_LIMIT,
588 VMX_VMCS32_GUEST_SS_LIMIT,
589 VMX_VMCS32_GUEST_DS_LIMIT,
590 VMX_VMCS32_GUEST_FS_LIMIT,
591 VMX_VMCS32_GUEST_GS_LIMIT,
592 VMX_VMCS32_GUEST_LDTR_LIMIT,
593 VMX_VMCS32_GUEST_TR_LIMIT,
594 VMX_VMCS32_GUEST_GDTR_LIMIT,
595 VMX_VMCS32_GUEST_IDTR_LIMIT,
596 VMX_VMCS32_GUEST_ES_ACCESS_RIGHTS,
597 VMX_VMCS32_GUEST_CS_ACCESS_RIGHTS,
598 VMX_VMCS32_GUEST_SS_ACCESS_RIGHTS,
599 VMX_VMCS32_GUEST_DS_ACCESS_RIGHTS,
600 VMX_VMCS32_GUEST_FS_ACCESS_RIGHTS,
601 VMX_VMCS32_GUEST_GS_ACCESS_RIGHTS,
602 VMX_VMCS32_GUEST_LDTR_ACCESS_RIGHTS,
603 VMX_VMCS32_GUEST_TR_ACCESS_RIGHTS,
604 VMX_VMCS32_GUEST_INT_STATE,
605 VMX_VMCS32_GUEST_ACTIVITY_STATE,
606 VMX_VMCS32_GUEST_SMBASE,
607 VMX_VMCS32_GUEST_SYSENTER_CS,
608 VMX_VMCS32_PREEMPT_TIMER_VALUE,
609
610 /* 32-bit host-state fields. */
611 VMX_VMCS32_HOST_SYSENTER_CS,
612
613 /* Natural-width control fields. */
614 VMX_VMCS_CTRL_CR0_MASK,
615 VMX_VMCS_CTRL_CR4_MASK,
616 VMX_VMCS_CTRL_CR0_READ_SHADOW,
617 VMX_VMCS_CTRL_CR4_READ_SHADOW,
618 VMX_VMCS_CTRL_CR3_TARGET_VAL0,
619 VMX_VMCS_CTRL_CR3_TARGET_VAL1,
620 VMX_VMCS_CTRL_CR3_TARGET_VAL2,
621 VMX_VMCS_CTRL_CR3_TARGET_VAL3,
622
623 /* Natural-width read-only data fields. */
624 VMX_VMCS_RO_EXIT_QUALIFICATION,
625 VMX_VMCS_RO_IO_RCX,
626 VMX_VMCS_RO_IO_RSI,
627 VMX_VMCS_RO_IO_RDI,
628 VMX_VMCS_RO_IO_RIP,
629 VMX_VMCS_RO_GUEST_LINEAR_ADDR,
630
631 /* Natural-width guest-state field */
632 VMX_VMCS_GUEST_CR0,
633 VMX_VMCS_GUEST_CR3,
634 VMX_VMCS_GUEST_CR4,
635 VMX_VMCS_GUEST_ES_BASE,
636 VMX_VMCS_GUEST_CS_BASE,
637 VMX_VMCS_GUEST_SS_BASE,
638 VMX_VMCS_GUEST_DS_BASE,
639 VMX_VMCS_GUEST_FS_BASE,
640 VMX_VMCS_GUEST_GS_BASE,
641 VMX_VMCS_GUEST_LDTR_BASE,
642 VMX_VMCS_GUEST_TR_BASE,
643 VMX_VMCS_GUEST_GDTR_BASE,
644 VMX_VMCS_GUEST_IDTR_BASE,
645 VMX_VMCS_GUEST_DR7,
646 VMX_VMCS_GUEST_RSP,
647 VMX_VMCS_GUEST_RIP,
648 VMX_VMCS_GUEST_RFLAGS,
649 VMX_VMCS_GUEST_PENDING_DEBUG_XCPTS,
650 VMX_VMCS_GUEST_SYSENTER_ESP,
651 VMX_VMCS_GUEST_SYSENTER_EIP,
652
653 /* Natural-width host-state fields */
654 VMX_VMCS_HOST_CR0,
655 VMX_VMCS_HOST_CR3,
656 VMX_VMCS_HOST_CR4,
657 VMX_VMCS_HOST_FS_BASE,
658 VMX_VMCS_HOST_GS_BASE,
659 VMX_VMCS_HOST_TR_BASE,
660 VMX_VMCS_HOST_GDTR_BASE,
661 VMX_VMCS_HOST_IDTR_BASE,
662 VMX_VMCS_HOST_SYSENTER_ESP,
663 VMX_VMCS_HOST_SYSENTER_EIP,
664 VMX_VMCS_HOST_RSP,
665 VMX_VMCS_HOST_RIP
666};
667#endif /* VBOX_WITH_NESTED_HWVIRT_VMX */
668
669static const uint32_t g_aVmcsSegBase[] =
670{
671 VMX_VMCS_GUEST_ES_BASE,
672 VMX_VMCS_GUEST_CS_BASE,
673 VMX_VMCS_GUEST_SS_BASE,
674 VMX_VMCS_GUEST_DS_BASE,
675 VMX_VMCS_GUEST_FS_BASE,
676 VMX_VMCS_GUEST_GS_BASE
677};
678static const uint32_t g_aVmcsSegSel[] =
679{
680 VMX_VMCS16_GUEST_ES_SEL,
681 VMX_VMCS16_GUEST_CS_SEL,
682 VMX_VMCS16_GUEST_SS_SEL,
683 VMX_VMCS16_GUEST_DS_SEL,
684 VMX_VMCS16_GUEST_FS_SEL,
685 VMX_VMCS16_GUEST_GS_SEL
686};
687static const uint32_t g_aVmcsSegLimit[] =
688{
689 VMX_VMCS32_GUEST_ES_LIMIT,
690 VMX_VMCS32_GUEST_CS_LIMIT,
691 VMX_VMCS32_GUEST_SS_LIMIT,
692 VMX_VMCS32_GUEST_DS_LIMIT,
693 VMX_VMCS32_GUEST_FS_LIMIT,
694 VMX_VMCS32_GUEST_GS_LIMIT
695};
696static const uint32_t g_aVmcsSegAttr[] =
697{
698 VMX_VMCS32_GUEST_ES_ACCESS_RIGHTS,
699 VMX_VMCS32_GUEST_CS_ACCESS_RIGHTS,
700 VMX_VMCS32_GUEST_SS_ACCESS_RIGHTS,
701 VMX_VMCS32_GUEST_DS_ACCESS_RIGHTS,
702 VMX_VMCS32_GUEST_FS_ACCESS_RIGHTS,
703 VMX_VMCS32_GUEST_GS_ACCESS_RIGHTS
704};
705AssertCompile(RT_ELEMENTS(g_aVmcsSegSel) == X86_SREG_COUNT);
706AssertCompile(RT_ELEMENTS(g_aVmcsSegLimit) == X86_SREG_COUNT);
707AssertCompile(RT_ELEMENTS(g_aVmcsSegBase) == X86_SREG_COUNT);
708AssertCompile(RT_ELEMENTS(g_aVmcsSegAttr) == X86_SREG_COUNT);
709
710#ifdef HMVMX_USE_FUNCTION_TABLE
711/**
712 * VMX_EXIT dispatch table.
713 */
714static const PFNVMXEXITHANDLER g_apfnVMExitHandlers[VMX_EXIT_MAX + 1] =
715{
716 /* 0 VMX_EXIT_XCPT_OR_NMI */ hmR0VmxExitXcptOrNmi,
717 /* 1 VMX_EXIT_EXT_INT */ hmR0VmxExitExtInt,
718 /* 2 VMX_EXIT_TRIPLE_FAULT */ hmR0VmxExitTripleFault,
719 /* 3 VMX_EXIT_INIT_SIGNAL */ hmR0VmxExitErrUnexpected,
720 /* 4 VMX_EXIT_SIPI */ hmR0VmxExitErrUnexpected,
721 /* 5 VMX_EXIT_IO_SMI */ hmR0VmxExitErrUnexpected,
722 /* 6 VMX_EXIT_SMI */ hmR0VmxExitErrUnexpected,
723 /* 7 VMX_EXIT_INT_WINDOW */ hmR0VmxExitIntWindow,
724 /* 8 VMX_EXIT_NMI_WINDOW */ hmR0VmxExitNmiWindow,
725 /* 9 VMX_EXIT_TASK_SWITCH */ hmR0VmxExitTaskSwitch,
726 /* 10 VMX_EXIT_CPUID */ hmR0VmxExitCpuid,
727 /* 11 VMX_EXIT_GETSEC */ hmR0VmxExitGetsec,
728 /* 12 VMX_EXIT_HLT */ hmR0VmxExitHlt,
729 /* 13 VMX_EXIT_INVD */ hmR0VmxExitInvd,
730 /* 14 VMX_EXIT_INVLPG */ hmR0VmxExitInvlpg,
731 /* 15 VMX_EXIT_RDPMC */ hmR0VmxExitRdpmc,
732 /* 16 VMX_EXIT_RDTSC */ hmR0VmxExitRdtsc,
733 /* 17 VMX_EXIT_RSM */ hmR0VmxExitErrUnexpected,
734 /* 18 VMX_EXIT_VMCALL */ hmR0VmxExitVmcall,
735#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
736 /* 19 VMX_EXIT_VMCLEAR */ hmR0VmxExitVmclear,
737 /* 20 VMX_EXIT_VMLAUNCH */ hmR0VmxExitVmlaunch,
738 /* 21 VMX_EXIT_VMPTRLD */ hmR0VmxExitVmptrld,
739 /* 22 VMX_EXIT_VMPTRST */ hmR0VmxExitVmptrst,
740 /* 23 VMX_EXIT_VMREAD */ hmR0VmxExitVmread,
741 /* 24 VMX_EXIT_VMRESUME */ hmR0VmxExitVmresume,
742 /* 25 VMX_EXIT_VMWRITE */ hmR0VmxExitVmwrite,
743 /* 26 VMX_EXIT_VMXOFF */ hmR0VmxExitVmxoff,
744 /* 27 VMX_EXIT_VMXON */ hmR0VmxExitVmxon,
745#else
746 /* 19 VMX_EXIT_VMCLEAR */ hmR0VmxExitSetPendingXcptUD,
747 /* 20 VMX_EXIT_VMLAUNCH */ hmR0VmxExitSetPendingXcptUD,
748 /* 21 VMX_EXIT_VMPTRLD */ hmR0VmxExitSetPendingXcptUD,
749 /* 22 VMX_EXIT_VMPTRST */ hmR0VmxExitSetPendingXcptUD,
750 /* 23 VMX_EXIT_VMREAD */ hmR0VmxExitSetPendingXcptUD,
751 /* 24 VMX_EXIT_VMRESUME */ hmR0VmxExitSetPendingXcptUD,
752 /* 25 VMX_EXIT_VMWRITE */ hmR0VmxExitSetPendingXcptUD,
753 /* 26 VMX_EXIT_VMXOFF */ hmR0VmxExitSetPendingXcptUD,
754 /* 27 VMX_EXIT_VMXON */ hmR0VmxExitSetPendingXcptUD,
755#endif
756 /* 28 VMX_EXIT_MOV_CRX */ hmR0VmxExitMovCRx,
757 /* 29 VMX_EXIT_MOV_DRX */ hmR0VmxExitMovDRx,
758 /* 30 VMX_EXIT_IO_INSTR */ hmR0VmxExitIoInstr,
759 /* 31 VMX_EXIT_RDMSR */ hmR0VmxExitRdmsr,
760 /* 32 VMX_EXIT_WRMSR */ hmR0VmxExitWrmsr,
761 /* 33 VMX_EXIT_ERR_INVALID_GUEST_STATE */ hmR0VmxExitErrInvalidGuestState,
762 /* 34 VMX_EXIT_ERR_MSR_LOAD */ hmR0VmxExitErrUnexpected,
763 /* 35 UNDEFINED */ hmR0VmxExitErrUnexpected,
764 /* 36 VMX_EXIT_MWAIT */ hmR0VmxExitMwait,
765 /* 37 VMX_EXIT_MTF */ hmR0VmxExitMtf,
766 /* 38 UNDEFINED */ hmR0VmxExitErrUnexpected,
767 /* 39 VMX_EXIT_MONITOR */ hmR0VmxExitMonitor,
768 /* 40 VMX_EXIT_PAUSE */ hmR0VmxExitPause,
769 /* 41 VMX_EXIT_ERR_MACHINE_CHECK */ hmR0VmxExitErrUnexpected,
770 /* 42 UNDEFINED */ hmR0VmxExitErrUnexpected,
771 /* 43 VMX_EXIT_TPR_BELOW_THRESHOLD */ hmR0VmxExitTprBelowThreshold,
772 /* 44 VMX_EXIT_APIC_ACCESS */ hmR0VmxExitApicAccess,
773 /* 45 VMX_EXIT_VIRTUALIZED_EOI */ hmR0VmxExitErrUnexpected,
774 /* 46 VMX_EXIT_GDTR_IDTR_ACCESS */ hmR0VmxExitErrUnexpected,
775 /* 47 VMX_EXIT_LDTR_TR_ACCESS */ hmR0VmxExitErrUnexpected,
776 /* 48 VMX_EXIT_EPT_VIOLATION */ hmR0VmxExitEptViolation,
777 /* 49 VMX_EXIT_EPT_MISCONFIG */ hmR0VmxExitEptMisconfig,
778 /* 50 VMX_EXIT_INVEPT */ hmR0VmxExitSetPendingXcptUD,
779 /* 51 VMX_EXIT_RDTSCP */ hmR0VmxExitRdtscp,
780 /* 52 VMX_EXIT_PREEMPT_TIMER */ hmR0VmxExitPreemptTimer,
781#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
782 /* 53 VMX_EXIT_INVVPID */ hmR0VmxExitInvvpid,
783#else
784 /* 53 VMX_EXIT_INVVPID */ hmR0VmxExitSetPendingXcptUD,
785#endif
786 /* 54 VMX_EXIT_WBINVD */ hmR0VmxExitWbinvd,
787 /* 55 VMX_EXIT_XSETBV */ hmR0VmxExitXsetbv,
788 /* 56 VMX_EXIT_APIC_WRITE */ hmR0VmxExitErrUnexpected,
789 /* 57 VMX_EXIT_RDRAND */ hmR0VmxExitErrUnexpected,
790 /* 58 VMX_EXIT_INVPCID */ hmR0VmxExitInvpcid,
791 /* 59 VMX_EXIT_VMFUNC */ hmR0VmxExitErrUnexpected,
792 /* 60 VMX_EXIT_ENCLS */ hmR0VmxExitErrUnexpected,
793 /* 61 VMX_EXIT_RDSEED */ hmR0VmxExitErrUnexpected,
794 /* 62 VMX_EXIT_PML_FULL */ hmR0VmxExitErrUnexpected,
795 /* 63 VMX_EXIT_XSAVES */ hmR0VmxExitErrUnexpected,
796 /* 64 VMX_EXIT_XRSTORS */ hmR0VmxExitErrUnexpected,
797 /* 65 UNDEFINED */ hmR0VmxExitErrUnexpected,
798 /* 66 VMX_EXIT_SPP_EVENT */ hmR0VmxExitErrUnexpected,
799 /* 67 VMX_EXIT_UMWAIT */ hmR0VmxExitErrUnexpected,
800 /* 68 VMX_EXIT_TPAUSE */ hmR0VmxExitErrUnexpected,
801};
802#endif /* HMVMX_USE_FUNCTION_TABLE */
803
804#if defined(VBOX_STRICT) && defined(LOG_ENABLED)
805static const char * const g_apszVmxInstrErrors[HMVMX_INSTR_ERROR_MAX + 1] =
806{
807 /* 0 */ "(Not Used)",
808 /* 1 */ "VMCALL executed in VMX root operation.",
809 /* 2 */ "VMCLEAR with invalid physical address.",
810 /* 3 */ "VMCLEAR with VMXON pointer.",
811 /* 4 */ "VMLAUNCH with non-clear VMCS.",
812 /* 5 */ "VMRESUME with non-launched VMCS.",
813 /* 6 */ "VMRESUME after VMXOFF",
814 /* 7 */ "VM-entry with invalid control fields.",
815 /* 8 */ "VM-entry with invalid host state fields.",
816 /* 9 */ "VMPTRLD with invalid physical address.",
817 /* 10 */ "VMPTRLD with VMXON pointer.",
818 /* 11 */ "VMPTRLD with incorrect revision identifier.",
819 /* 12 */ "VMREAD/VMWRITE from/to unsupported VMCS component.",
820 /* 13 */ "VMWRITE to read-only VMCS component.",
821 /* 14 */ "(Not Used)",
822 /* 15 */ "VMXON executed in VMX root operation.",
823 /* 16 */ "VM-entry with invalid executive-VMCS pointer.",
824 /* 17 */ "VM-entry with non-launched executing VMCS.",
825 /* 18 */ "VM-entry with executive-VMCS pointer not VMXON pointer.",
826 /* 19 */ "VMCALL with non-clear VMCS.",
827 /* 20 */ "VMCALL with invalid VM-exit control fields.",
828 /* 21 */ "(Not Used)",
829 /* 22 */ "VMCALL with incorrect MSEG revision identifier.",
830 /* 23 */ "VMXOFF under dual monitor treatment of SMIs and SMM.",
831 /* 24 */ "VMCALL with invalid SMM-monitor features.",
832 /* 25 */ "VM-entry with invalid VM-execution control fields in executive VMCS.",
833 /* 26 */ "VM-entry with events blocked by MOV SS.",
834 /* 27 */ "(Not Used)",
835 /* 28 */ "Invalid operand to INVEPT/INVVPID."
836};
837#endif /* VBOX_STRICT && LOG_ENABLED */
838
839
840/**
841 * Get the CR0 guest/host mask that does not change through the lifetime of a VM.
842 *
843 * Any bit set in this mask is owned by the host/hypervisor and would cause a
844 * VM-exit when modified by the guest.
845 *
846 * @returns The static CR0 guest/host mask.
847 * @param pVCpu The cross context virtual CPU structure.
848 */
849DECL_FORCE_INLINE(uint64_t) hmR0VmxGetFixedCr0Mask(PCVMCPUCC pVCpu)
850{
851 /*
852 * Modifications to CR0 bits that VT-x ignores saving/restoring (CD, ET, NW) and
853 * to CR0 bits that we require for shadow paging (PG) by the guest must cause VM-exits.
854 */
855 /** @todo Avoid intercepting CR0.PE with unrestricted guest execution. Fix PGM
856 * enmGuestMode to be in-sync with the current mode. See @bugref{6398}
857 * and @bugref{6944}. */
858 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
859 return ( X86_CR0_PE
860 | X86_CR0_NE
861 | (pVM->hm.s.fNestedPaging ? 0 : X86_CR0_WP)
862 | X86_CR0_PG
863 | X86_CR0_ET /* Bit ignored on VM-entry and VM-exit. Don't let the guest modify the host CR0.ET */
864 | X86_CR0_CD /* Bit ignored on VM-entry and VM-exit. Don't let the guest modify the host CR0.CD */
865 | X86_CR0_NW); /* Bit ignored on VM-entry and VM-exit. Don't let the guest modify the host CR0.NW */
866}
867
868
869/**
870 * Gets the CR4 guest/host mask that does not change through the lifetime of a VM.
871 *
872 * Any bit set in this mask is owned by the host/hypervisor and would cause a
873 * VM-exit when modified by the guest.
874 *
875 * @returns The static CR4 guest/host mask.
876 * @param pVCpu The cross context virtual CPU structure.
877 */
878DECL_FORCE_INLINE(uint64_t) hmR0VmxGetFixedCr4Mask(PCVMCPUCC pVCpu)
879{
880 /*
881 * We need to look at the host features here (for e.g. OSXSAVE, PCID) because
882 * these bits are reserved on hardware that does not support them. Since the
883 * CPU cannot refer to our virtual CPUID, we need to intercept CR4 changes to
884 * these bits and handle it depending on whether we expose them to the guest.
885 */
886 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
887 bool const fXSaveRstor = pVM->cpum.ro.HostFeatures.fXSaveRstor;
888 bool const fPcid = pVM->cpum.ro.HostFeatures.fPcid;
889 return ( X86_CR4_VMXE
890 | X86_CR4_VME
891 | X86_CR4_PAE
892 | X86_CR4_PGE
893 | X86_CR4_PSE
894 | (fXSaveRstor ? X86_CR4_OSXSAVE : 0)
895 | (fPcid ? X86_CR4_PCIDE : 0));
896}
897
898
899/**
900 * Returns whether the the VM-exit MSR-store area differs from the VM-exit MSR-load
901 * area.
902 *
903 * @returns @c true if it's different, @c false otherwise.
904 * @param pVmcsInfo The VMCS info. object.
905 */
906DECL_FORCE_INLINE(bool) hmR0VmxIsSeparateExitMsrStoreAreaVmcs(PCVMXVMCSINFO pVmcsInfo)
907{
908 return RT_BOOL( pVmcsInfo->pvGuestMsrStore != pVmcsInfo->pvGuestMsrLoad
909 && pVmcsInfo->pvGuestMsrStore);
910}
911
912
913/**
914 * Sets the given Processor-based VM-execution controls.
915 *
916 * @param pVmxTransient The VMX-transient structure.
917 * @param uProcCtls The Processor-based VM-execution controls to set.
918 */
919static void hmR0VmxSetProcCtlsVmcs(PVMXTRANSIENT pVmxTransient, uint32_t uProcCtls)
920{
921 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
922 if ((pVmcsInfo->u32ProcCtls & uProcCtls) != uProcCtls)
923 {
924 pVmcsInfo->u32ProcCtls |= uProcCtls;
925 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, pVmcsInfo->u32ProcCtls);
926 AssertRC(rc);
927 }
928}
929
930
931/**
932 * Removes the given Processor-based VM-execution controls.
933 *
934 * @param pVCpu The cross context virtual CPU structure.
935 * @param pVmxTransient The VMX-transient structure.
936 * @param uProcCtls The Processor-based VM-execution controls to remove.
937 *
938 * @remarks When executing a nested-guest, this will not remove any of the specified
939 * controls if the guest hypervisor has set any one of them.
940 */
941static void hmR0VmxRemoveProcCtlsVmcs(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient, uint32_t uProcCtls)
942{
943 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
944 if (pVmcsInfo->u32ProcCtls & uProcCtls)
945 {
946#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
947 bool const fRemoveCtls = !pVmxTransient->fIsNestedGuest
948 ? true
949 : !CPUMIsGuestVmxProcCtlsSet(pVCpu, &pVCpu->cpum.GstCtx, uProcCtls);
950#else
951 NOREF(pVCpu);
952 bool const fRemoveCtls = true;
953#endif
954 if (fRemoveCtls)
955 {
956 pVmcsInfo->u32ProcCtls &= ~uProcCtls;
957 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, pVmcsInfo->u32ProcCtls);
958 AssertRC(rc);
959 }
960 }
961}
962
963
964/**
965 * Sets the TSC offset for the current VMCS.
966 *
967 * @param uTscOffset The TSC offset to set.
968 * @param pVmcsInfo The VMCS info. object.
969 */
970static void hmR0VmxSetTscOffsetVmcs(PVMXVMCSINFO pVmcsInfo, uint64_t uTscOffset)
971{
972 if (pVmcsInfo->u64TscOffset != uTscOffset)
973 {
974 int rc = VMXWriteVmcs64(VMX_VMCS64_CTRL_TSC_OFFSET_FULL, uTscOffset);
975 AssertRC(rc);
976 pVmcsInfo->u64TscOffset = uTscOffset;
977 }
978}
979
980
981/**
982 * Adds one or more exceptions to the exception bitmap and commits it to the current
983 * VMCS.
984 *
985 * @param pVmxTransient The VMX-transient structure.
986 * @param uXcptMask The exception(s) to add.
987 */
988static void hmR0VmxAddXcptInterceptMask(PVMXTRANSIENT pVmxTransient, uint32_t uXcptMask)
989{
990 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
991 uint32_t uXcptBitmap = pVmcsInfo->u32XcptBitmap;
992 if ((uXcptBitmap & uXcptMask) != uXcptMask)
993 {
994 uXcptBitmap |= uXcptMask;
995 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_EXCEPTION_BITMAP, uXcptBitmap);
996 AssertRC(rc);
997 pVmcsInfo->u32XcptBitmap = uXcptBitmap;
998 }
999}
1000
1001
1002/**
1003 * Adds an exception to the exception bitmap and commits it to the current VMCS.
1004 *
1005 * @param pVmxTransient The VMX-transient structure.
1006 * @param uXcpt The exception to add.
1007 */
1008static void hmR0VmxAddXcptIntercept(PVMXTRANSIENT pVmxTransient, uint8_t uXcpt)
1009{
1010 Assert(uXcpt <= X86_XCPT_LAST);
1011 hmR0VmxAddXcptInterceptMask(pVmxTransient, RT_BIT_32(uXcpt));
1012}
1013
1014
1015/**
1016 * Remove one or more exceptions from the exception bitmap and commits it to the
1017 * current VMCS.
1018 *
1019 * This takes care of not removing the exception intercept if a nested-guest
1020 * requires the exception to be intercepted.
1021 *
1022 * @returns VBox status code.
1023 * @param pVCpu The cross context virtual CPU structure.
1024 * @param pVmxTransient The VMX-transient structure.
1025 * @param uXcptMask The exception(s) to remove.
1026 */
1027static int hmR0VmxRemoveXcptInterceptMask(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient, uint32_t uXcptMask)
1028{
1029 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
1030 uint32_t u32XcptBitmap = pVmcsInfo->u32XcptBitmap;
1031 if (u32XcptBitmap & uXcptMask)
1032 {
1033#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
1034 if (!pVmxTransient->fIsNestedGuest)
1035 { /* likely */ }
1036 else
1037 {
1038 PCVMXVVMCS pVmcsNstGst = pVCpu->cpum.GstCtx.hwvirt.vmx.CTX_SUFF(pVmcs);
1039 uXcptMask &= ~pVmcsNstGst->u32XcptBitmap;
1040 }
1041#endif
1042#ifdef HMVMX_ALWAYS_TRAP_ALL_XCPTS
1043 uXcptMask &= ~( RT_BIT(X86_XCPT_BP)
1044 | RT_BIT(X86_XCPT_DE)
1045 | RT_BIT(X86_XCPT_NM)
1046 | RT_BIT(X86_XCPT_TS)
1047 | RT_BIT(X86_XCPT_UD)
1048 | RT_BIT(X86_XCPT_NP)
1049 | RT_BIT(X86_XCPT_SS)
1050 | RT_BIT(X86_XCPT_GP)
1051 | RT_BIT(X86_XCPT_PF)
1052 | RT_BIT(X86_XCPT_MF));
1053#elif defined(HMVMX_ALWAYS_TRAP_PF)
1054 uXcptMask &= ~RT_BIT(X86_XCPT_PF);
1055#endif
1056 if (uXcptMask)
1057 {
1058 /* Validate we are not removing any essential exception intercepts. */
1059 Assert(pVCpu->CTX_SUFF(pVM)->hm.s.fNestedPaging || !(uXcptMask & RT_BIT(X86_XCPT_PF)));
1060 NOREF(pVCpu);
1061 Assert(!(uXcptMask & RT_BIT(X86_XCPT_DB)));
1062 Assert(!(uXcptMask & RT_BIT(X86_XCPT_AC)));
1063
1064 /* Remove it from the exception bitmap. */
1065 u32XcptBitmap &= ~uXcptMask;
1066
1067 /* Commit and update the cache if necessary. */
1068 if (pVmcsInfo->u32XcptBitmap != u32XcptBitmap)
1069 {
1070 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_EXCEPTION_BITMAP, u32XcptBitmap);
1071 AssertRC(rc);
1072 pVmcsInfo->u32XcptBitmap = u32XcptBitmap;
1073 }
1074 }
1075 }
1076 return VINF_SUCCESS;
1077}
1078
1079
1080/**
1081 * Remove an exceptions from the exception bitmap and commits it to the current
1082 * VMCS.
1083 *
1084 * @returns VBox status code.
1085 * @param pVCpu The cross context virtual CPU structure.
1086 * @param pVmxTransient The VMX-transient structure.
1087 * @param uXcpt The exception to remove.
1088 */
1089static int hmR0VmxRemoveXcptIntercept(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient, uint8_t uXcpt)
1090{
1091 return hmR0VmxRemoveXcptInterceptMask(pVCpu, pVmxTransient, RT_BIT(uXcpt));
1092}
1093
1094
1095/**
1096 * Loads the VMCS specified by the VMCS info. object.
1097 *
1098 * @returns VBox status code.
1099 * @param pVmcsInfo The VMCS info. object.
1100 *
1101 * @remarks Can be called with interrupts disabled.
1102 */
1103static int hmR0VmxLoadVmcs(PVMXVMCSINFO pVmcsInfo)
1104{
1105 Assert(pVmcsInfo->HCPhysVmcs != 0 && pVmcsInfo->HCPhysVmcs != NIL_RTHCPHYS);
1106 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
1107
1108 int rc = VMXLoadVmcs(pVmcsInfo->HCPhysVmcs);
1109 if (RT_SUCCESS(rc))
1110 pVmcsInfo->fVmcsState |= VMX_V_VMCS_LAUNCH_STATE_CURRENT;
1111 return rc;
1112}
1113
1114
1115/**
1116 * Clears the VMCS specified by the VMCS info. object.
1117 *
1118 * @returns VBox status code.
1119 * @param pVmcsInfo The VMCS info. object.
1120 *
1121 * @remarks Can be called with interrupts disabled.
1122 */
1123static int hmR0VmxClearVmcs(PVMXVMCSINFO pVmcsInfo)
1124{
1125 Assert(pVmcsInfo->HCPhysVmcs != 0 && pVmcsInfo->HCPhysVmcs != NIL_RTHCPHYS);
1126 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
1127
1128 int rc = VMXClearVmcs(pVmcsInfo->HCPhysVmcs);
1129 if (RT_SUCCESS(rc))
1130 pVmcsInfo->fVmcsState = VMX_V_VMCS_LAUNCH_STATE_CLEAR;
1131 return rc;
1132}
1133
1134
1135#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
1136/**
1137 * Loads the shadow VMCS specified by the VMCS info. object.
1138 *
1139 * @returns VBox status code.
1140 * @param pVmcsInfo The VMCS info. object.
1141 *
1142 * @remarks Can be called with interrupts disabled.
1143 */
1144static int hmR0VmxLoadShadowVmcs(PVMXVMCSINFO pVmcsInfo)
1145{
1146 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
1147 Assert(pVmcsInfo->HCPhysShadowVmcs != 0 && pVmcsInfo->HCPhysShadowVmcs != NIL_RTHCPHYS);
1148
1149 int rc = VMXLoadVmcs(pVmcsInfo->HCPhysShadowVmcs);
1150 if (RT_SUCCESS(rc))
1151 pVmcsInfo->fShadowVmcsState |= VMX_V_VMCS_LAUNCH_STATE_CURRENT;
1152 return rc;
1153}
1154
1155
1156/**
1157 * Clears the shadow VMCS specified by the VMCS info. object.
1158 *
1159 * @returns VBox status code.
1160 * @param pVmcsInfo The VMCS info. object.
1161 *
1162 * @remarks Can be called with interrupts disabled.
1163 */
1164static int hmR0VmxClearShadowVmcs(PVMXVMCSINFO pVmcsInfo)
1165{
1166 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
1167 Assert(pVmcsInfo->HCPhysShadowVmcs != 0 && pVmcsInfo->HCPhysShadowVmcs != NIL_RTHCPHYS);
1168
1169 int rc = VMXClearVmcs(pVmcsInfo->HCPhysShadowVmcs);
1170 if (RT_SUCCESS(rc))
1171 pVmcsInfo->fShadowVmcsState = VMX_V_VMCS_LAUNCH_STATE_CLEAR;
1172 return rc;
1173}
1174
1175
1176/**
1177 * Switches from and to the specified VMCSes.
1178 *
1179 * @returns VBox status code.
1180 * @param pVmcsInfoFrom The VMCS info. object we are switching from.
1181 * @param pVmcsInfoTo The VMCS info. object we are switching to.
1182 *
1183 * @remarks Called with interrupts disabled.
1184 */
1185static int hmR0VmxSwitchVmcs(PVMXVMCSINFO pVmcsInfoFrom, PVMXVMCSINFO pVmcsInfoTo)
1186{
1187 /*
1188 * Clear the VMCS we are switching out if it has not already been cleared.
1189 * This will sync any CPU internal data back to the VMCS.
1190 */
1191 if (pVmcsInfoFrom->fVmcsState != VMX_V_VMCS_LAUNCH_STATE_CLEAR)
1192 {
1193 int rc = hmR0VmxClearVmcs(pVmcsInfoFrom);
1194 if (RT_SUCCESS(rc))
1195 {
1196 /*
1197 * The shadow VMCS, if any, would not be active at this point since we
1198 * would have cleared it while importing the virtual hardware-virtualization
1199 * state as part the VMLAUNCH/VMRESUME VM-exit. Hence, there's no need to
1200 * clear the shadow VMCS here, just assert for safety.
1201 */
1202 Assert(!pVmcsInfoFrom->pvShadowVmcs || pVmcsInfoFrom->fShadowVmcsState == VMX_V_VMCS_LAUNCH_STATE_CLEAR);
1203 }
1204 else
1205 return rc;
1206 }
1207
1208 /*
1209 * Clear the VMCS we are switching to if it has not already been cleared.
1210 * This will initialize the VMCS launch state to "clear" required for loading it.
1211 *
1212 * See Intel spec. 31.6 "Preparation And Launching A Virtual Machine".
1213 */
1214 if (pVmcsInfoTo->fVmcsState != VMX_V_VMCS_LAUNCH_STATE_CLEAR)
1215 {
1216 int rc = hmR0VmxClearVmcs(pVmcsInfoTo);
1217 if (RT_SUCCESS(rc))
1218 { /* likely */ }
1219 else
1220 return rc;
1221 }
1222
1223 /*
1224 * Finally, load the VMCS we are switching to.
1225 */
1226 return hmR0VmxLoadVmcs(pVmcsInfoTo);
1227}
1228
1229
1230/**
1231 * Switches between the guest VMCS and the nested-guest VMCS as specified by the
1232 * caller.
1233 *
1234 * @returns VBox status code.
1235 * @param pVCpu The cross context virtual CPU structure.
1236 * @param fSwitchToNstGstVmcs Whether to switch to the nested-guest VMCS (pass
1237 * true) or guest VMCS (pass false).
1238 */
1239static int hmR0VmxSwitchToGstOrNstGstVmcs(PVMCPUCC pVCpu, bool fSwitchToNstGstVmcs)
1240{
1241 /* Ensure we have synced everything from the guest-CPU context to the VMCS before switching. */
1242 HMVMX_CPUMCTX_ASSERT(pVCpu, HMVMX_CPUMCTX_EXTRN_ALL);
1243
1244 PVMXVMCSINFO pVmcsInfoFrom;
1245 PVMXVMCSINFO pVmcsInfoTo;
1246 if (fSwitchToNstGstVmcs)
1247 {
1248 pVmcsInfoFrom = &pVCpu->hm.s.vmx.VmcsInfo;
1249 pVmcsInfoTo = &pVCpu->hm.s.vmx.VmcsInfoNstGst;
1250 }
1251 else
1252 {
1253 pVmcsInfoFrom = &pVCpu->hm.s.vmx.VmcsInfoNstGst;
1254 pVmcsInfoTo = &pVCpu->hm.s.vmx.VmcsInfo;
1255 }
1256
1257 /*
1258 * Disable interrupts to prevent being preempted while we switch the current VMCS as the
1259 * preemption hook code path acquires the current VMCS.
1260 */
1261 RTCCUINTREG const fEFlags = ASMIntDisableFlags();
1262
1263 int rc = hmR0VmxSwitchVmcs(pVmcsInfoFrom, pVmcsInfoTo);
1264 if (RT_SUCCESS(rc))
1265 {
1266 pVCpu->hm.s.vmx.fSwitchedToNstGstVmcs = fSwitchToNstGstVmcs;
1267
1268 /*
1269 * If we are switching to a VMCS that was executed on a different host CPU or was
1270 * never executed before, flag that we need to export the host state before executing
1271 * guest/nested-guest code using hardware-assisted VMX.
1272 *
1273 * This could probably be done in a preemptible context since the preemption hook
1274 * will flag the necessary change in host context. However, since preemption is
1275 * already disabled and to avoid making assumptions about host specific code in
1276 * RTMpCpuId when called with preemption enabled, we'll do this while preemption is
1277 * disabled.
1278 */
1279 if (pVmcsInfoTo->idHostCpuState == RTMpCpuId())
1280 { /* likely */ }
1281 else
1282 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_HOST_CONTEXT | HM_CHANGED_VMX_HOST_GUEST_SHARED_STATE);
1283
1284 ASMSetFlags(fEFlags);
1285
1286 /*
1287 * We use a different VM-exit MSR-store areas for the guest and nested-guest. Hence,
1288 * flag that we need to update the host MSR values there. Even if we decide in the
1289 * future to share the VM-exit MSR-store area page between the guest and nested-guest,
1290 * if its content differs, we would have to update the host MSRs anyway.
1291 */
1292 pVCpu->hm.s.vmx.fUpdatedHostAutoMsrs = false;
1293 }
1294 else
1295 ASMSetFlags(fEFlags);
1296 return rc;
1297}
1298#endif /* VBOX_WITH_NESTED_HWVIRT_VMX */
1299
1300
1301/**
1302 * Updates the VM's last error record.
1303 *
1304 * If there was a VMX instruction error, reads the error data from the VMCS and
1305 * updates VCPU's last error record as well.
1306 *
1307 * @param pVCpu The cross context virtual CPU structure of the calling EMT.
1308 * Can be NULL if @a rc is not VERR_VMX_UNABLE_TO_START_VM or
1309 * VERR_VMX_INVALID_VMCS_FIELD.
1310 * @param rc The error code.
1311 */
1312static void hmR0VmxUpdateErrorRecord(PVMCPUCC pVCpu, int rc)
1313{
1314 if ( rc == VERR_VMX_INVALID_VMCS_FIELD
1315 || rc == VERR_VMX_UNABLE_TO_START_VM)
1316 {
1317 AssertPtrReturnVoid(pVCpu);
1318 VMXReadVmcs32(VMX_VMCS32_RO_VM_INSTR_ERROR, &pVCpu->hm.s.vmx.LastError.u32InstrError);
1319 }
1320 pVCpu->CTX_SUFF(pVM)->hm.s.rcInit = rc;
1321}
1322
1323
1324#ifdef VBOX_STRICT
1325/**
1326 * Reads the VM-entry interruption-information field from the VMCS into the VMX
1327 * transient structure.
1328 *
1329 * @param pVmxTransient The VMX-transient structure.
1330 */
1331DECLINLINE(void) hmR0VmxReadEntryIntInfoVmcs(PVMXTRANSIENT pVmxTransient)
1332{
1333 int rc = VMXReadVmcs32(VMX_VMCS32_CTRL_ENTRY_INTERRUPTION_INFO, &pVmxTransient->uEntryIntInfo);
1334 AssertRC(rc);
1335}
1336
1337
1338/**
1339 * Reads the VM-entry exception error code field from the VMCS into
1340 * the VMX transient structure.
1341 *
1342 * @param pVmxTransient The VMX-transient structure.
1343 */
1344DECLINLINE(void) hmR0VmxReadEntryXcptErrorCodeVmcs(PVMXTRANSIENT pVmxTransient)
1345{
1346 int rc = VMXReadVmcs32(VMX_VMCS32_CTRL_ENTRY_EXCEPTION_ERRCODE, &pVmxTransient->uEntryXcptErrorCode);
1347 AssertRC(rc);
1348}
1349
1350
1351/**
1352 * Reads the VM-entry exception error code field from the VMCS into
1353 * the VMX transient structure.
1354 *
1355 * @param pVmxTransient The VMX-transient structure.
1356 */
1357DECLINLINE(void) hmR0VmxReadEntryInstrLenVmcs(PVMXTRANSIENT pVmxTransient)
1358{
1359 int rc = VMXReadVmcs32(VMX_VMCS32_CTRL_ENTRY_INSTR_LENGTH, &pVmxTransient->cbEntryInstr);
1360 AssertRC(rc);
1361}
1362#endif /* VBOX_STRICT */
1363
1364
1365/**
1366 * Reads the VM-exit interruption-information field from the VMCS into the VMX
1367 * transient structure.
1368 *
1369 * @param pVmxTransient The VMX-transient structure.
1370 */
1371DECLINLINE(void) hmR0VmxReadExitIntInfoVmcs(PVMXTRANSIENT pVmxTransient)
1372{
1373 if (!(pVmxTransient->fVmcsFieldsRead & HMVMX_READ_EXIT_INTERRUPTION_INFO))
1374 {
1375 int rc = VMXReadVmcs32(VMX_VMCS32_RO_EXIT_INTERRUPTION_INFO, &pVmxTransient->uExitIntInfo);
1376 AssertRC(rc);
1377 pVmxTransient->fVmcsFieldsRead |= HMVMX_READ_EXIT_INTERRUPTION_INFO;
1378 }
1379}
1380
1381
1382/**
1383 * Reads the VM-exit interruption error code from the VMCS into the VMX
1384 * transient structure.
1385 *
1386 * @param pVmxTransient The VMX-transient structure.
1387 */
1388DECLINLINE(void) hmR0VmxReadExitIntErrorCodeVmcs(PVMXTRANSIENT pVmxTransient)
1389{
1390 if (!(pVmxTransient->fVmcsFieldsRead & HMVMX_READ_EXIT_INTERRUPTION_ERROR_CODE))
1391 {
1392 int rc = VMXReadVmcs32(VMX_VMCS32_RO_EXIT_INTERRUPTION_ERROR_CODE, &pVmxTransient->uExitIntErrorCode);
1393 AssertRC(rc);
1394 pVmxTransient->fVmcsFieldsRead |= HMVMX_READ_EXIT_INTERRUPTION_ERROR_CODE;
1395 }
1396}
1397
1398
1399/**
1400 * Reads the VM-exit instruction length field from the VMCS into the VMX
1401 * transient structure.
1402 *
1403 * @param pVmxTransient The VMX-transient structure.
1404 */
1405DECLINLINE(void) hmR0VmxReadExitInstrLenVmcs(PVMXTRANSIENT pVmxTransient)
1406{
1407 if (!(pVmxTransient->fVmcsFieldsRead & HMVMX_READ_EXIT_INSTR_LEN))
1408 {
1409 int rc = VMXReadVmcs32(VMX_VMCS32_RO_EXIT_INSTR_LENGTH, &pVmxTransient->cbExitInstr);
1410 AssertRC(rc);
1411 pVmxTransient->fVmcsFieldsRead |= HMVMX_READ_EXIT_INSTR_LEN;
1412 }
1413}
1414
1415
1416/**
1417 * Reads the VM-exit instruction-information field from the VMCS into
1418 * the VMX transient structure.
1419 *
1420 * @param pVmxTransient The VMX-transient structure.
1421 */
1422DECLINLINE(void) hmR0VmxReadExitInstrInfoVmcs(PVMXTRANSIENT pVmxTransient)
1423{
1424 if (!(pVmxTransient->fVmcsFieldsRead & HMVMX_READ_EXIT_INSTR_INFO))
1425 {
1426 int rc = VMXReadVmcs32(VMX_VMCS32_RO_EXIT_INSTR_INFO, &pVmxTransient->ExitInstrInfo.u);
1427 AssertRC(rc);
1428 pVmxTransient->fVmcsFieldsRead |= HMVMX_READ_EXIT_INSTR_INFO;
1429 }
1430}
1431
1432
1433/**
1434 * Reads the Exit Qualification from the VMCS into the VMX transient structure.
1435 *
1436 * @param pVmxTransient The VMX-transient structure.
1437 */
1438DECLINLINE(void) hmR0VmxReadExitQualVmcs(PVMXTRANSIENT pVmxTransient)
1439{
1440 if (!(pVmxTransient->fVmcsFieldsRead & HMVMX_READ_EXIT_QUALIFICATION))
1441 {
1442 int rc = VMXReadVmcsNw(VMX_VMCS_RO_EXIT_QUALIFICATION, &pVmxTransient->uExitQual);
1443 AssertRC(rc);
1444 pVmxTransient->fVmcsFieldsRead |= HMVMX_READ_EXIT_QUALIFICATION;
1445 }
1446}
1447
1448
1449/**
1450 * Reads the Guest-linear address from the VMCS into the VMX transient structure.
1451 *
1452 * @param pVmxTransient The VMX-transient structure.
1453 */
1454DECLINLINE(void) hmR0VmxReadGuestLinearAddrVmcs(PVMXTRANSIENT pVmxTransient)
1455{
1456 if (!(pVmxTransient->fVmcsFieldsRead & HMVMX_READ_GUEST_LINEAR_ADDR))
1457 {
1458 int rc = VMXReadVmcsNw(VMX_VMCS_RO_GUEST_LINEAR_ADDR, &pVmxTransient->uGuestLinearAddr);
1459 AssertRC(rc);
1460 pVmxTransient->fVmcsFieldsRead |= HMVMX_READ_GUEST_LINEAR_ADDR;
1461 }
1462}
1463
1464
1465/**
1466 * Reads the Guest-physical address from the VMCS into the VMX transient structure.
1467 *
1468 * @param pVmxTransient The VMX-transient structure.
1469 */
1470DECLINLINE(void) hmR0VmxReadGuestPhysicalAddrVmcs(PVMXTRANSIENT pVmxTransient)
1471{
1472 if (!(pVmxTransient->fVmcsFieldsRead & HMVMX_READ_GUEST_PHYSICAL_ADDR))
1473 {
1474 int rc = VMXReadVmcs64(VMX_VMCS64_RO_GUEST_PHYS_ADDR_FULL, &pVmxTransient->uGuestPhysicalAddr);
1475 AssertRC(rc);
1476 pVmxTransient->fVmcsFieldsRead |= HMVMX_READ_GUEST_PHYSICAL_ADDR;
1477 }
1478}
1479
1480#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
1481/**
1482 * Reads the Guest pending-debug exceptions from the VMCS into the VMX transient
1483 * structure.
1484 *
1485 * @param pVmxTransient The VMX-transient structure.
1486 */
1487DECLINLINE(void) hmR0VmxReadGuestPendingDbgXctps(PVMXTRANSIENT pVmxTransient)
1488{
1489 if (!(pVmxTransient->fVmcsFieldsRead & HMVMX_READ_GUEST_PENDING_DBG_XCPTS))
1490 {
1491 int rc = VMXReadVmcsNw(VMX_VMCS_GUEST_PENDING_DEBUG_XCPTS, &pVmxTransient->uGuestPendingDbgXcpts);
1492 AssertRC(rc);
1493 pVmxTransient->fVmcsFieldsRead |= HMVMX_READ_GUEST_PENDING_DBG_XCPTS;
1494 }
1495}
1496#endif
1497
1498/**
1499 * Reads the IDT-vectoring information field from the VMCS into the VMX
1500 * transient structure.
1501 *
1502 * @param pVmxTransient The VMX-transient structure.
1503 *
1504 * @remarks No-long-jump zone!!!
1505 */
1506DECLINLINE(void) hmR0VmxReadIdtVectoringInfoVmcs(PVMXTRANSIENT pVmxTransient)
1507{
1508 if (!(pVmxTransient->fVmcsFieldsRead & HMVMX_READ_IDT_VECTORING_INFO))
1509 {
1510 int rc = VMXReadVmcs32(VMX_VMCS32_RO_IDT_VECTORING_INFO, &pVmxTransient->uIdtVectoringInfo);
1511 AssertRC(rc);
1512 pVmxTransient->fVmcsFieldsRead |= HMVMX_READ_IDT_VECTORING_INFO;
1513 }
1514}
1515
1516
1517/**
1518 * Reads the IDT-vectoring error code from the VMCS into the VMX
1519 * transient structure.
1520 *
1521 * @param pVmxTransient The VMX-transient structure.
1522 */
1523DECLINLINE(void) hmR0VmxReadIdtVectoringErrorCodeVmcs(PVMXTRANSIENT pVmxTransient)
1524{
1525 if (!(pVmxTransient->fVmcsFieldsRead & HMVMX_READ_IDT_VECTORING_ERROR_CODE))
1526 {
1527 int rc = VMXReadVmcs32(VMX_VMCS32_RO_IDT_VECTORING_ERROR_CODE, &pVmxTransient->uIdtVectoringErrorCode);
1528 AssertRC(rc);
1529 pVmxTransient->fVmcsFieldsRead |= HMVMX_READ_IDT_VECTORING_ERROR_CODE;
1530 }
1531}
1532
1533#ifdef HMVMX_ALWAYS_SAVE_RO_GUEST_STATE
1534/**
1535 * Reads all relevant read-only VMCS fields into the VMX transient structure.
1536 *
1537 * @param pVmxTransient The VMX-transient structure.
1538 */
1539static void hmR0VmxReadAllRoFieldsVmcs(PVMXTRANSIENT pVmxTransient)
1540{
1541 int rc = VMXReadVmcsNw(VMX_VMCS_RO_EXIT_QUALIFICATION, &pVmxTransient->uExitQual);
1542 rc |= VMXReadVmcs32(VMX_VMCS32_RO_EXIT_INSTR_LENGTH, &pVmxTransient->cbExitInstr);
1543 rc |= VMXReadVmcs32(VMX_VMCS32_RO_EXIT_INSTR_INFO, &pVmxTransient->ExitInstrInfo.u);
1544 rc |= VMXReadVmcs32(VMX_VMCS32_RO_IDT_VECTORING_INFO, &pVmxTransient->uIdtVectoringInfo);
1545 rc |= VMXReadVmcs32(VMX_VMCS32_RO_IDT_VECTORING_ERROR_CODE, &pVmxTransient->uIdtVectoringErrorCode);
1546 rc |= VMXReadVmcs32(VMX_VMCS32_RO_EXIT_INTERRUPTION_INFO, &pVmxTransient->uExitIntInfo);
1547 rc |= VMXReadVmcs32(VMX_VMCS32_RO_EXIT_INTERRUPTION_ERROR_CODE, &pVmxTransient->uExitIntErrorCode);
1548 rc |= VMXReadVmcsNw(VMX_VMCS_RO_GUEST_LINEAR_ADDR, &pVmxTransient->uGuestLinearAddr);
1549 rc |= VMXReadVmcs64(VMX_VMCS64_RO_GUEST_PHYS_ADDR_FULL, &pVmxTransient->uGuestPhysicalAddr);
1550 AssertRC(rc);
1551 pVmxTransient->fVmcsFieldsRead |= HMVMX_READ_EXIT_QUALIFICATION
1552 | HMVMX_READ_EXIT_INSTR_LEN
1553 | HMVMX_READ_EXIT_INSTR_INFO
1554 | HMVMX_READ_IDT_VECTORING_INFO
1555 | HMVMX_READ_IDT_VECTORING_ERROR_CODE
1556 | HMVMX_READ_EXIT_INTERRUPTION_INFO
1557 | HMVMX_READ_EXIT_INTERRUPTION_ERROR_CODE
1558 | HMVMX_READ_GUEST_LINEAR_ADDR
1559 | HMVMX_READ_GUEST_PHYSICAL_ADDR;
1560}
1561#endif
1562
1563/**
1564 * Enters VMX root mode operation on the current CPU.
1565 *
1566 * @returns VBox status code.
1567 * @param pVM The cross context VM structure. Can be
1568 * NULL, after a resume.
1569 * @param HCPhysCpuPage Physical address of the VMXON region.
1570 * @param pvCpuPage Pointer to the VMXON region.
1571 */
1572static int hmR0VmxEnterRootMode(PVMCC pVM, RTHCPHYS HCPhysCpuPage, void *pvCpuPage)
1573{
1574 Assert(HCPhysCpuPage && HCPhysCpuPage != NIL_RTHCPHYS);
1575 Assert(RT_ALIGN_T(HCPhysCpuPage, _4K, RTHCPHYS) == HCPhysCpuPage);
1576 Assert(pvCpuPage);
1577 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
1578
1579 if (pVM)
1580 {
1581 /* Write the VMCS revision identifier to the VMXON region. */
1582 *(uint32_t *)pvCpuPage = RT_BF_GET(pVM->hm.s.vmx.Msrs.u64Basic, VMX_BF_BASIC_VMCS_ID);
1583 }
1584
1585 /* Paranoid: Disable interrupts as, in theory, interrupt handlers might mess with CR4. */
1586 RTCCUINTREG const fEFlags = ASMIntDisableFlags();
1587
1588 /* Enable the VMX bit in CR4 if necessary. */
1589 RTCCUINTREG const uOldCr4 = SUPR0ChangeCR4(X86_CR4_VMXE, RTCCUINTREG_MAX);
1590
1591 /* Enter VMX root mode. */
1592 int rc = VMXEnable(HCPhysCpuPage);
1593 if (RT_FAILURE(rc))
1594 {
1595 if (!(uOldCr4 & X86_CR4_VMXE))
1596 SUPR0ChangeCR4(0 /* fOrMask */, ~X86_CR4_VMXE);
1597
1598 if (pVM)
1599 pVM->hm.s.vmx.HCPhysVmxEnableError = HCPhysCpuPage;
1600 }
1601
1602 /* Restore interrupts. */
1603 ASMSetFlags(fEFlags);
1604 return rc;
1605}
1606
1607
1608/**
1609 * Exits VMX root mode operation on the current CPU.
1610 *
1611 * @returns VBox status code.
1612 */
1613static int hmR0VmxLeaveRootMode(void)
1614{
1615 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
1616
1617 /* Paranoid: Disable interrupts as, in theory, interrupts handlers might mess with CR4. */
1618 RTCCUINTREG const fEFlags = ASMIntDisableFlags();
1619
1620 /* If we're for some reason not in VMX root mode, then don't leave it. */
1621 RTCCUINTREG const uHostCr4 = ASMGetCR4();
1622
1623 int rc;
1624 if (uHostCr4 & X86_CR4_VMXE)
1625 {
1626 /* Exit VMX root mode and clear the VMX bit in CR4. */
1627 VMXDisable();
1628 SUPR0ChangeCR4(0 /* fOrMask */, ~X86_CR4_VMXE);
1629 rc = VINF_SUCCESS;
1630 }
1631 else
1632 rc = VERR_VMX_NOT_IN_VMX_ROOT_MODE;
1633
1634 /* Restore interrupts. */
1635 ASMSetFlags(fEFlags);
1636 return rc;
1637}
1638
1639
1640/**
1641 * Allocates and maps a physically contiguous page. The allocated page is
1642 * zero'd out (used by various VT-x structures).
1643 *
1644 * @returns IPRT status code.
1645 * @param pMemObj Pointer to the ring-0 memory object.
1646 * @param ppVirt Where to store the virtual address of the allocation.
1647 * @param pHCPhys Where to store the physical address of the allocation.
1648 */
1649static int hmR0VmxPageAllocZ(PRTR0MEMOBJ pMemObj, PRTR0PTR ppVirt, PRTHCPHYS pHCPhys)
1650{
1651 AssertPtr(pMemObj);
1652 AssertPtr(ppVirt);
1653 AssertPtr(pHCPhys);
1654 int rc = RTR0MemObjAllocCont(pMemObj, X86_PAGE_4K_SIZE, false /* fExecutable */);
1655 if (RT_FAILURE(rc))
1656 return rc;
1657 *ppVirt = RTR0MemObjAddress(*pMemObj);
1658 *pHCPhys = RTR0MemObjGetPagePhysAddr(*pMemObj, 0 /* iPage */);
1659 ASMMemZero32(*ppVirt, X86_PAGE_4K_SIZE);
1660 return VINF_SUCCESS;
1661}
1662
1663
1664/**
1665 * Frees and unmaps an allocated, physical page.
1666 *
1667 * @param pMemObj Pointer to the ring-0 memory object.
1668 * @param ppVirt Where to re-initialize the virtual address of allocation as
1669 * 0.
1670 * @param pHCPhys Where to re-initialize the physical address of the
1671 * allocation as 0.
1672 */
1673static void hmR0VmxPageFree(PRTR0MEMOBJ pMemObj, PRTR0PTR ppVirt, PRTHCPHYS pHCPhys)
1674{
1675 AssertPtr(pMemObj);
1676 AssertPtr(ppVirt);
1677 AssertPtr(pHCPhys);
1678 /* NULL is valid, accepted and ignored by the free function below. */
1679 RTR0MemObjFree(*pMemObj, true /* fFreeMappings */);
1680 *pMemObj = NIL_RTR0MEMOBJ;
1681 *ppVirt = NULL;
1682 *pHCPhys = NIL_RTHCPHYS;
1683}
1684
1685
1686/**
1687 * Initializes a VMCS info. object.
1688 *
1689 * @param pVmcsInfo The VMCS info. object.
1690 */
1691static void hmR0VmxInitVmcsInfo(PVMXVMCSINFO pVmcsInfo)
1692{
1693 memset(pVmcsInfo, 0, sizeof(*pVmcsInfo));
1694
1695 Assert(pVmcsInfo->hMemObjVmcs == NIL_RTR0MEMOBJ);
1696 Assert(pVmcsInfo->hMemObjShadowVmcs == NIL_RTR0MEMOBJ);
1697 Assert(pVmcsInfo->hMemObjMsrBitmap == NIL_RTR0MEMOBJ);
1698 Assert(pVmcsInfo->hMemObjGuestMsrLoad == NIL_RTR0MEMOBJ);
1699 Assert(pVmcsInfo->hMemObjGuestMsrStore == NIL_RTR0MEMOBJ);
1700 Assert(pVmcsInfo->hMemObjHostMsrLoad == NIL_RTR0MEMOBJ);
1701 pVmcsInfo->HCPhysVmcs = NIL_RTHCPHYS;
1702 pVmcsInfo->HCPhysShadowVmcs = NIL_RTHCPHYS;
1703 pVmcsInfo->HCPhysMsrBitmap = NIL_RTHCPHYS;
1704 pVmcsInfo->HCPhysGuestMsrLoad = NIL_RTHCPHYS;
1705 pVmcsInfo->HCPhysGuestMsrStore = NIL_RTHCPHYS;
1706 pVmcsInfo->HCPhysHostMsrLoad = NIL_RTHCPHYS;
1707 pVmcsInfo->HCPhysVirtApic = NIL_RTHCPHYS;
1708 pVmcsInfo->HCPhysEPTP = NIL_RTHCPHYS;
1709 pVmcsInfo->u64VmcsLinkPtr = NIL_RTHCPHYS;
1710 pVmcsInfo->idHostCpuState = NIL_RTCPUID;
1711 pVmcsInfo->idHostCpuExec = NIL_RTCPUID;
1712}
1713
1714
1715/**
1716 * Frees the VT-x structures for a VMCS info. object.
1717 *
1718 * @param pVM The cross context VM structure.
1719 * @param pVmcsInfo The VMCS info. object.
1720 */
1721static void hmR0VmxFreeVmcsInfo(PVMCC pVM, PVMXVMCSINFO pVmcsInfo)
1722{
1723 hmR0VmxPageFree(&pVmcsInfo->hMemObjVmcs, &pVmcsInfo->pvVmcs, &pVmcsInfo->HCPhysVmcs);
1724
1725#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
1726 if (pVM->hm.s.vmx.fUseVmcsShadowing)
1727 hmR0VmxPageFree(&pVmcsInfo->hMemObjShadowVmcs, &pVmcsInfo->pvShadowVmcs, &pVmcsInfo->HCPhysShadowVmcs);
1728#endif
1729
1730 if (pVM->hm.s.vmx.Msrs.ProcCtls.n.allowed1 & VMX_PROC_CTLS_USE_MSR_BITMAPS)
1731 hmR0VmxPageFree(&pVmcsInfo->hMemObjMsrBitmap, &pVmcsInfo->pvMsrBitmap, &pVmcsInfo->HCPhysMsrBitmap);
1732
1733 hmR0VmxPageFree(&pVmcsInfo->hMemObjHostMsrLoad, &pVmcsInfo->pvHostMsrLoad, &pVmcsInfo->HCPhysHostMsrLoad);
1734 hmR0VmxPageFree(&pVmcsInfo->hMemObjGuestMsrLoad, &pVmcsInfo->pvGuestMsrLoad, &pVmcsInfo->HCPhysGuestMsrLoad);
1735 hmR0VmxPageFree(&pVmcsInfo->hMemObjGuestMsrStore, &pVmcsInfo->pvGuestMsrStore, &pVmcsInfo->HCPhysGuestMsrStore);
1736
1737 hmR0VmxInitVmcsInfo(pVmcsInfo);
1738}
1739
1740
1741/**
1742 * Allocates the VT-x structures for a VMCS info. object.
1743 *
1744 * @returns VBox status code.
1745 * @param pVCpu The cross context virtual CPU structure.
1746 * @param pVmcsInfo The VMCS info. object.
1747 * @param fIsNstGstVmcs Whether this is a nested-guest VMCS.
1748 */
1749static int hmR0VmxAllocVmcsInfo(PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo, bool fIsNstGstVmcs)
1750{
1751 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
1752
1753 /* Allocate the guest VM control structure (VMCS). */
1754 int rc = hmR0VmxPageAllocZ(&pVmcsInfo->hMemObjVmcs, &pVmcsInfo->pvVmcs, &pVmcsInfo->HCPhysVmcs);
1755 if (RT_SUCCESS(rc))
1756 {
1757 if (!fIsNstGstVmcs)
1758 {
1759#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
1760 if (pVM->hm.s.vmx.fUseVmcsShadowing)
1761 rc = hmR0VmxPageAllocZ(&pVmcsInfo->hMemObjShadowVmcs, &pVmcsInfo->pvShadowVmcs, &pVmcsInfo->HCPhysShadowVmcs);
1762#endif
1763 if (RT_SUCCESS(rc))
1764 {
1765 /* Get the allocated virtual-APIC page from the virtual APIC device. */
1766 if ( PDMHasApic(pVCpu->CTX_SUFF(pVM))
1767 && (pVM->hm.s.vmx.Msrs.ProcCtls.n.allowed1 & VMX_PROC_CTLS_USE_TPR_SHADOW))
1768 rc = APICGetApicPageForCpu(pVCpu, &pVmcsInfo->HCPhysVirtApic, (PRTR0PTR)&pVmcsInfo->pbVirtApic, NULL /*pR3Ptr*/);
1769 }
1770 }
1771 else
1772 {
1773 /* We don't yet support exposing VMCS shadowing to the guest. */
1774 Assert(pVmcsInfo->HCPhysShadowVmcs == NIL_RTHCPHYS);
1775 Assert(!pVmcsInfo->pvShadowVmcs);
1776
1777 /* Get the allocated virtual-APIC page from CPUM. */
1778 if (pVM->hm.s.vmx.Msrs.ProcCtls.n.allowed1 & VMX_PROC_CTLS_USE_TPR_SHADOW)
1779 {
1780 /** @todo NSTVMX: Get rid of this. There is no need to allocate a separate HC
1781 * page for this. Use the one provided by the nested-guest directly. */
1782 pVmcsInfo->pbVirtApic = (uint8_t *)CPUMGetGuestVmxVirtApicPage(pVCpu, &pVCpu->cpum.GstCtx,
1783 &pVmcsInfo->HCPhysVirtApic);
1784 Assert(pVmcsInfo->pbVirtApic);
1785 Assert(pVmcsInfo->HCPhysVirtApic && pVmcsInfo->HCPhysVirtApic != NIL_RTHCPHYS);
1786 }
1787 }
1788
1789 if (RT_SUCCESS(rc))
1790 {
1791 /*
1792 * Allocate the MSR-bitmap if supported by the CPU. The MSR-bitmap is for
1793 * transparent accesses of specific MSRs.
1794 *
1795 * If the condition for enabling MSR bitmaps changes here, don't forget to
1796 * update HMIsMsrBitmapActive().
1797 *
1798 * We don't share MSR bitmaps between the guest and nested-guest as we then
1799 * don't need to care about carefully restoring the guest MSR bitmap.
1800 * The guest visible nested-guest MSR bitmap needs to remain unchanged.
1801 * Hence, allocate a separate MSR bitmap for the guest and nested-guest.
1802 * We also don't need to re-initialize the nested-guest MSR bitmap here as
1803 * we do that later while merging VMCS.
1804 */
1805 if (pVM->hm.s.vmx.Msrs.ProcCtls.n.allowed1 & VMX_PROC_CTLS_USE_MSR_BITMAPS)
1806 {
1807 rc = hmR0VmxPageAllocZ(&pVmcsInfo->hMemObjMsrBitmap, &pVmcsInfo->pvMsrBitmap, &pVmcsInfo->HCPhysMsrBitmap);
1808 if ( RT_SUCCESS(rc)
1809 && !fIsNstGstVmcs)
1810 ASMMemFill32(pVmcsInfo->pvMsrBitmap, X86_PAGE_4K_SIZE, UINT32_C(0xffffffff));
1811 }
1812
1813 if (RT_SUCCESS(rc))
1814 {
1815 /*
1816 * Allocate the VM-entry MSR-load area for the guest MSRs.
1817 *
1818 * Similar to MSR-bitmaps, we do not share the auto MSR-load/store are between
1819 * the guest and nested-guest.
1820 */
1821 rc = hmR0VmxPageAllocZ(&pVmcsInfo->hMemObjGuestMsrLoad, &pVmcsInfo->pvGuestMsrLoad,
1822 &pVmcsInfo->HCPhysGuestMsrLoad);
1823 if (RT_SUCCESS(rc))
1824 {
1825 /*
1826 * We use the same page for VM-entry MSR-load and VM-exit MSR store areas.
1827 * These contain the guest MSRs to load on VM-entry and store on VM-exit.
1828 */
1829 Assert(pVmcsInfo->hMemObjGuestMsrStore == NIL_RTR0MEMOBJ);
1830 pVmcsInfo->pvGuestMsrStore = pVmcsInfo->pvGuestMsrLoad;
1831 pVmcsInfo->HCPhysGuestMsrStore = pVmcsInfo->HCPhysGuestMsrLoad;
1832
1833 /* Allocate the VM-exit MSR-load page for the host MSRs. */
1834 rc = hmR0VmxPageAllocZ(&pVmcsInfo->hMemObjHostMsrLoad, &pVmcsInfo->pvHostMsrLoad,
1835 &pVmcsInfo->HCPhysHostMsrLoad);
1836 }
1837 }
1838 }
1839 }
1840
1841 return rc;
1842}
1843
1844
1845/**
1846 * Free all VT-x structures for the VM.
1847 *
1848 * @returns IPRT status code.
1849 * @param pVM The cross context VM structure.
1850 */
1851static void hmR0VmxStructsFree(PVMCC pVM)
1852{
1853#ifdef VBOX_WITH_CRASHDUMP_MAGIC
1854 hmR0VmxPageFree(&pVM->hm.s.vmx.hMemObjScratch, &pVM->hm.s.vmx.pbScratch, &pVM->hm.s.vmx.HCPhysScratch);
1855#endif
1856 hmR0VmxPageFree(&pVM->hm.s.vmx.hMemObjApicAccess, (PRTR0PTR)&pVM->hm.s.vmx.pbApicAccess, &pVM->hm.s.vmx.HCPhysApicAccess);
1857
1858#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
1859 if (pVM->hm.s.vmx.fUseVmcsShadowing)
1860 {
1861 RTMemFree(pVM->hm.s.vmx.paShadowVmcsFields);
1862 RTMemFree(pVM->hm.s.vmx.paShadowVmcsRoFields);
1863 hmR0VmxPageFree(&pVM->hm.s.vmx.hMemObjVmreadBitmap, &pVM->hm.s.vmx.pvVmreadBitmap, &pVM->hm.s.vmx.HCPhysVmreadBitmap);
1864 hmR0VmxPageFree(&pVM->hm.s.vmx.hMemObjVmwriteBitmap, &pVM->hm.s.vmx.pvVmwriteBitmap, &pVM->hm.s.vmx.HCPhysVmwriteBitmap);
1865 }
1866#endif
1867
1868 for (VMCPUID idCpu = 0; idCpu < pVM->cCpus; idCpu++)
1869 {
1870 PVMCPUCC pVCpu = VMCC_GET_CPU(pVM, idCpu);
1871 PVMXVMCSINFO pVmcsInfo = &pVCpu->hm.s.vmx.VmcsInfo;
1872 hmR0VmxFreeVmcsInfo(pVM, pVmcsInfo);
1873#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
1874 if (pVM->cpum.ro.GuestFeatures.fVmx)
1875 {
1876 pVmcsInfo = &pVCpu->hm.s.vmx.VmcsInfoNstGst;
1877 hmR0VmxFreeVmcsInfo(pVM, pVmcsInfo);
1878 }
1879#endif
1880 }
1881}
1882
1883
1884/**
1885 * Allocate all VT-x structures for the VM.
1886 *
1887 * @returns IPRT status code.
1888 * @param pVM The cross context VM structure.
1889 */
1890static int hmR0VmxStructsAlloc(PVMCC pVM)
1891{
1892 /*
1893 * Sanity check the VMCS size reported by the CPU as we assume 4KB allocations.
1894 * The VMCS size cannot be more than 4096 bytes.
1895 *
1896 * See Intel spec. Appendix A.1 "Basic VMX Information".
1897 */
1898 uint32_t const cbVmcs = RT_BF_GET(pVM->hm.s.vmx.Msrs.u64Basic, VMX_BF_BASIC_VMCS_SIZE);
1899 if (cbVmcs <= X86_PAGE_4K_SIZE)
1900 { /* likely */ }
1901 else
1902 {
1903 VMCC_GET_CPU_0(pVM)->hm.s.u32HMError = VMX_UFC_INVALID_VMCS_SIZE;
1904 return VERR_HM_UNSUPPORTED_CPU_FEATURE_COMBO;
1905 }
1906
1907 /*
1908 * Initialize/check members up-front so we can cleanup en masse on allocation failures.
1909 */
1910#ifdef VBOX_WITH_CRASHDUMP_MAGIC
1911 Assert(pVM->hm.s.vmx.hMemObjScratch == NIL_RTR0MEMOBJ);
1912 Assert(pVM->hm.s.vmx.pbScratch == NULL);
1913 pVM->hm.s.vmx.HCPhysScratch = NIL_RTHCPHYS;
1914#endif
1915
1916 Assert(pVM->hm.s.vmx.hMemObjApicAccess == NIL_RTR0MEMOBJ);
1917 Assert(pVM->hm.s.vmx.pbApicAccess == NULL);
1918 pVM->hm.s.vmx.HCPhysApicAccess = NIL_RTHCPHYS;
1919
1920 for (VMCPUID idCpu = 0; idCpu < pVM->cCpus; idCpu++)
1921 {
1922 PVMCPUCC pVCpu = VMCC_GET_CPU(pVM, idCpu);
1923 hmR0VmxInitVmcsInfo(&pVCpu->hm.s.vmx.VmcsInfo);
1924 hmR0VmxInitVmcsInfo(&pVCpu->hm.s.vmx.VmcsInfoNstGst);
1925 }
1926
1927 /*
1928 * Allocate per-VM VT-x structures.
1929 */
1930 int rc = VINF_SUCCESS;
1931#ifdef VBOX_WITH_CRASHDUMP_MAGIC
1932 /* Allocate crash-dump magic scratch page. */
1933 rc = hmR0VmxPageAllocZ(&pVM->hm.s.vmx.hMemObjScratch, &pVM->hm.s.vmx.pbScratch, &pVM->hm.s.vmx.HCPhysScratch);
1934 if (RT_FAILURE(rc))
1935 {
1936 hmR0VmxStructsFree(pVM);
1937 return rc;
1938 }
1939 strcpy((char *)pVM->hm.s.vmx.pbScratch, "SCRATCH Magic");
1940 *(uint64_t *)(pVM->hm.s.vmx.pbScratch + 16) = UINT64_C(0xdeadbeefdeadbeef);
1941#endif
1942
1943 /* Allocate the APIC-access page for trapping APIC accesses from the guest. */
1944 if (pVM->hm.s.vmx.Msrs.ProcCtls2.n.allowed1 & VMX_PROC_CTLS2_VIRT_APIC_ACCESS)
1945 {
1946 rc = hmR0VmxPageAllocZ(&pVM->hm.s.vmx.hMemObjApicAccess, (PRTR0PTR)&pVM->hm.s.vmx.pbApicAccess,
1947 &pVM->hm.s.vmx.HCPhysApicAccess);
1948 if (RT_FAILURE(rc))
1949 {
1950 hmR0VmxStructsFree(pVM);
1951 return rc;
1952 }
1953 }
1954
1955#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
1956 /* Allocate the shadow VMCS fields array, VMREAD, VMWRITE bitmaps.. */
1957 if (pVM->hm.s.vmx.fUseVmcsShadowing)
1958 {
1959 Assert(!pVM->hm.s.vmx.cShadowVmcsFields);
1960 Assert(!pVM->hm.s.vmx.cShadowVmcsRoFields);
1961 pVM->hm.s.vmx.paShadowVmcsFields = (uint32_t *)RTMemAllocZ(sizeof(g_aVmcsFields));
1962 pVM->hm.s.vmx.paShadowVmcsRoFields = (uint32_t *)RTMemAllocZ(sizeof(g_aVmcsFields));
1963 if (RT_LIKELY( pVM->hm.s.vmx.paShadowVmcsFields
1964 && pVM->hm.s.vmx.paShadowVmcsRoFields))
1965 {
1966 rc = hmR0VmxPageAllocZ(&pVM->hm.s.vmx.hMemObjVmreadBitmap, &pVM->hm.s.vmx.pvVmreadBitmap,
1967 &pVM->hm.s.vmx.HCPhysVmreadBitmap);
1968 if (RT_SUCCESS(rc))
1969 {
1970 rc = hmR0VmxPageAllocZ(&pVM->hm.s.vmx.hMemObjVmwriteBitmap, &pVM->hm.s.vmx.pvVmwriteBitmap,
1971 &pVM->hm.s.vmx.HCPhysVmwriteBitmap);
1972 }
1973 }
1974 else
1975 rc = VERR_NO_MEMORY;
1976
1977 if (RT_FAILURE(rc))
1978 {
1979 hmR0VmxStructsFree(pVM);
1980 return rc;
1981 }
1982 }
1983#endif
1984
1985 /*
1986 * Initialize per-VCPU VT-x structures.
1987 */
1988 for (VMCPUID idCpu = 0; idCpu < pVM->cCpus; idCpu++)
1989 {
1990 /* Allocate the guest VMCS structures. */
1991 PVMCPUCC pVCpu = VMCC_GET_CPU(pVM, idCpu);
1992 rc = hmR0VmxAllocVmcsInfo(pVCpu, &pVCpu->hm.s.vmx.VmcsInfo, false /* fIsNstGstVmcs */);
1993 if (RT_SUCCESS(rc))
1994 {
1995#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
1996 /* Allocate the nested-guest VMCS structures, when the VMX feature is exposed to the guest. */
1997 if (pVM->cpum.ro.GuestFeatures.fVmx)
1998 {
1999 rc = hmR0VmxAllocVmcsInfo(pVCpu, &pVCpu->hm.s.vmx.VmcsInfoNstGst, true /* fIsNstGstVmcs */);
2000 if (RT_SUCCESS(rc))
2001 { /* likely */ }
2002 else
2003 break;
2004 }
2005#endif
2006 }
2007 else
2008 break;
2009 }
2010
2011 if (RT_FAILURE(rc))
2012 {
2013 hmR0VmxStructsFree(pVM);
2014 return rc;
2015 }
2016
2017 return VINF_SUCCESS;
2018}
2019
2020#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
2021/**
2022 * Returns whether an MSR at the given MSR-bitmap offset is intercepted or not.
2023 *
2024 * @returns @c true if the MSR is intercepted, @c false otherwise.
2025 * @param pvMsrBitmap The MSR bitmap.
2026 * @param offMsr The MSR byte offset.
2027 * @param iBit The bit offset from the byte offset.
2028 */
2029DECLINLINE(bool) hmR0VmxIsMsrBitSet(const void *pvMsrBitmap, uint16_t offMsr, int32_t iBit)
2030{
2031 uint8_t const * const pbMsrBitmap = (uint8_t const * const)pvMsrBitmap;
2032 Assert(pbMsrBitmap);
2033 Assert(offMsr + (iBit >> 3) <= X86_PAGE_4K_SIZE);
2034 return ASMBitTest(pbMsrBitmap + offMsr, iBit);
2035}
2036#endif
2037
2038/**
2039 * Sets the permission bits for the specified MSR in the given MSR bitmap.
2040 *
2041 * If the passed VMCS is a nested-guest VMCS, this function ensures that the
2042 * read/write intercept is cleared from the MSR bitmap used for hardware-assisted
2043 * VMX execution of the nested-guest, only if nested-guest is also not intercepting
2044 * the read/write access of this MSR.
2045 *
2046 * @param pVCpu The cross context virtual CPU structure.
2047 * @param pVmcsInfo The VMCS info. object.
2048 * @param fIsNstGstVmcs Whether this is a nested-guest VMCS.
2049 * @param idMsr The MSR value.
2050 * @param fMsrpm The MSR permissions (see VMXMSRPM_XXX). This must
2051 * include both a read -and- a write permission!
2052 *
2053 * @sa CPUMGetVmxMsrPermission.
2054 * @remarks Can be called with interrupts disabled.
2055 */
2056static void hmR0VmxSetMsrPermission(PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo, bool fIsNstGstVmcs, uint32_t idMsr, uint32_t fMsrpm)
2057{
2058 uint8_t *pbMsrBitmap = (uint8_t *)pVmcsInfo->pvMsrBitmap;
2059 Assert(pbMsrBitmap);
2060 Assert(VMXMSRPM_IS_FLAG_VALID(fMsrpm));
2061
2062 /*
2063 * MSR-bitmap Layout:
2064 * Byte index MSR range Interpreted as
2065 * 0x000 - 0x3ff 0x00000000 - 0x00001fff Low MSR read bits.
2066 * 0x400 - 0x7ff 0xc0000000 - 0xc0001fff High MSR read bits.
2067 * 0x800 - 0xbff 0x00000000 - 0x00001fff Low MSR write bits.
2068 * 0xc00 - 0xfff 0xc0000000 - 0xc0001fff High MSR write bits.
2069 *
2070 * A bit corresponding to an MSR within the above range causes a VM-exit
2071 * if the bit is 1 on executions of RDMSR/WRMSR. If an MSR falls out of
2072 * the MSR range, it always cause a VM-exit.
2073 *
2074 * See Intel spec. 24.6.9 "MSR-Bitmap Address".
2075 */
2076 uint16_t const offBitmapRead = 0;
2077 uint16_t const offBitmapWrite = 0x800;
2078 uint16_t offMsr;
2079 int32_t iBit;
2080 if (idMsr <= UINT32_C(0x00001fff))
2081 {
2082 offMsr = 0;
2083 iBit = idMsr;
2084 }
2085 else if (idMsr - UINT32_C(0xc0000000) <= UINT32_C(0x00001fff))
2086 {
2087 offMsr = 0x400;
2088 iBit = idMsr - UINT32_C(0xc0000000);
2089 }
2090 else
2091 AssertMsgFailedReturnVoid(("Invalid MSR %#RX32\n", idMsr));
2092
2093 /*
2094 * Set the MSR read permission.
2095 */
2096 uint16_t const offMsrRead = offBitmapRead + offMsr;
2097 Assert(offMsrRead + (iBit >> 3) < offBitmapWrite);
2098 if (fMsrpm & VMXMSRPM_ALLOW_RD)
2099 {
2100#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
2101 bool const fClear = !fIsNstGstVmcs ? true
2102 : !hmR0VmxIsMsrBitSet(pVCpu->cpum.GstCtx.hwvirt.vmx.CTX_SUFF(pvMsrBitmap), offMsrRead, iBit);
2103#else
2104 RT_NOREF2(pVCpu, fIsNstGstVmcs);
2105 bool const fClear = true;
2106#endif
2107 if (fClear)
2108 ASMBitClear(pbMsrBitmap + offMsrRead, iBit);
2109 }
2110 else
2111 ASMBitSet(pbMsrBitmap + offMsrRead, iBit);
2112
2113 /*
2114 * Set the MSR write permission.
2115 */
2116 uint16_t const offMsrWrite = offBitmapWrite + offMsr;
2117 Assert(offMsrWrite + (iBit >> 3) < X86_PAGE_4K_SIZE);
2118 if (fMsrpm & VMXMSRPM_ALLOW_WR)
2119 {
2120#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
2121 bool const fClear = !fIsNstGstVmcs ? true
2122 : !hmR0VmxIsMsrBitSet(pVCpu->cpum.GstCtx.hwvirt.vmx.CTX_SUFF(pvMsrBitmap), offMsrWrite, iBit);
2123#else
2124 RT_NOREF2(pVCpu, fIsNstGstVmcs);
2125 bool const fClear = true;
2126#endif
2127 if (fClear)
2128 ASMBitClear(pbMsrBitmap + offMsrWrite, iBit);
2129 }
2130 else
2131 ASMBitSet(pbMsrBitmap + offMsrWrite, iBit);
2132}
2133
2134
2135/**
2136 * Updates the VMCS with the number of effective MSRs in the auto-load/store MSR
2137 * area.
2138 *
2139 * @returns VBox status code.
2140 * @param pVCpu The cross context virtual CPU structure.
2141 * @param pVmcsInfo The VMCS info. object.
2142 * @param cMsrs The number of MSRs.
2143 */
2144static int hmR0VmxSetAutoLoadStoreMsrCount(PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo, uint32_t cMsrs)
2145{
2146 /* Shouldn't ever happen but there -is- a number. We're well within the recommended 512. */
2147 uint32_t const cMaxSupportedMsrs = VMX_MISC_MAX_MSRS(pVCpu->CTX_SUFF(pVM)->hm.s.vmx.Msrs.u64Misc);
2148 if (RT_LIKELY(cMsrs < cMaxSupportedMsrs))
2149 {
2150 /* Commit the MSR counts to the VMCS and update the cache. */
2151 if (pVmcsInfo->cEntryMsrLoad != cMsrs)
2152 {
2153 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_ENTRY_MSR_LOAD_COUNT, cMsrs); AssertRC(rc);
2154 rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_EXIT_MSR_STORE_COUNT, cMsrs); AssertRC(rc);
2155 rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_EXIT_MSR_LOAD_COUNT, cMsrs); AssertRC(rc);
2156 pVmcsInfo->cEntryMsrLoad = cMsrs;
2157 pVmcsInfo->cExitMsrStore = cMsrs;
2158 pVmcsInfo->cExitMsrLoad = cMsrs;
2159 }
2160 return VINF_SUCCESS;
2161 }
2162
2163 LogRel(("Auto-load/store MSR count exceeded! cMsrs=%u MaxSupported=%u\n", cMsrs, cMaxSupportedMsrs));
2164 pVCpu->hm.s.u32HMError = VMX_UFC_INSUFFICIENT_GUEST_MSR_STORAGE;
2165 return VERR_HM_UNSUPPORTED_CPU_FEATURE_COMBO;
2166}
2167
2168
2169/**
2170 * Adds a new (or updates the value of an existing) guest/host MSR
2171 * pair to be swapped during the world-switch as part of the
2172 * auto-load/store MSR area in the VMCS.
2173 *
2174 * @returns VBox status code.
2175 * @param pVCpu The cross context virtual CPU structure.
2176 * @param pVmxTransient The VMX-transient structure.
2177 * @param idMsr The MSR.
2178 * @param uGuestMsrValue Value of the guest MSR.
2179 * @param fSetReadWrite Whether to set the guest read/write access of this
2180 * MSR (thus not causing a VM-exit).
2181 * @param fUpdateHostMsr Whether to update the value of the host MSR if
2182 * necessary.
2183 */
2184static int hmR0VmxAddAutoLoadStoreMsr(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient, uint32_t idMsr, uint64_t uGuestMsrValue,
2185 bool fSetReadWrite, bool fUpdateHostMsr)
2186{
2187 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
2188 bool const fIsNstGstVmcs = pVmxTransient->fIsNestedGuest;
2189 PVMXAUTOMSR pGuestMsrLoad = (PVMXAUTOMSR)pVmcsInfo->pvGuestMsrLoad;
2190 uint32_t cMsrs = pVmcsInfo->cEntryMsrLoad;
2191 uint32_t i;
2192
2193 /* Paranoia. */
2194 Assert(pGuestMsrLoad);
2195
2196 LogFlowFunc(("pVCpu=%p idMsr=%#RX32 uGestMsrValue=%#RX64\n", pVCpu, idMsr, uGuestMsrValue));
2197
2198 /* Check if the MSR already exists in the VM-entry MSR-load area. */
2199 for (i = 0; i < cMsrs; i++)
2200 {
2201 if (pGuestMsrLoad[i].u32Msr == idMsr)
2202 break;
2203 }
2204
2205 bool fAdded = false;
2206 if (i == cMsrs)
2207 {
2208 /* The MSR does not exist, bump the MSR count to make room for the new MSR. */
2209 ++cMsrs;
2210 int rc = hmR0VmxSetAutoLoadStoreMsrCount(pVCpu, pVmcsInfo, cMsrs);
2211 AssertMsgRCReturn(rc, ("Insufficient space to add MSR to VM-entry MSR-load/store area %u\n", idMsr), rc);
2212
2213 /* Set the guest to read/write this MSR without causing VM-exits. */
2214 if ( fSetReadWrite
2215 && (pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_USE_MSR_BITMAPS))
2216 hmR0VmxSetMsrPermission(pVCpu, pVmcsInfo, fIsNstGstVmcs, idMsr, VMXMSRPM_ALLOW_RD_WR);
2217
2218 Log4Func(("Added MSR %#RX32, cMsrs=%u\n", idMsr, cMsrs));
2219 fAdded = true;
2220 }
2221
2222 /* Update the MSR value for the newly added or already existing MSR. */
2223 pGuestMsrLoad[i].u32Msr = idMsr;
2224 pGuestMsrLoad[i].u64Value = uGuestMsrValue;
2225
2226 /* Create the corresponding slot in the VM-exit MSR-store area if we use a different page. */
2227 if (hmR0VmxIsSeparateExitMsrStoreAreaVmcs(pVmcsInfo))
2228 {
2229 PVMXAUTOMSR pGuestMsrStore = (PVMXAUTOMSR)pVmcsInfo->pvGuestMsrStore;
2230 pGuestMsrStore[i].u32Msr = idMsr;
2231 pGuestMsrStore[i].u64Value = uGuestMsrValue;
2232 }
2233
2234 /* Update the corresponding slot in the host MSR area. */
2235 PVMXAUTOMSR pHostMsr = (PVMXAUTOMSR)pVmcsInfo->pvHostMsrLoad;
2236 Assert(pHostMsr != pVmcsInfo->pvGuestMsrLoad);
2237 Assert(pHostMsr != pVmcsInfo->pvGuestMsrStore);
2238 pHostMsr[i].u32Msr = idMsr;
2239
2240 /*
2241 * Only if the caller requests to update the host MSR value AND we've newly added the
2242 * MSR to the host MSR area do we actually update the value. Otherwise, it will be
2243 * updated by hmR0VmxUpdateAutoLoadHostMsrs().
2244 *
2245 * We do this for performance reasons since reading MSRs may be quite expensive.
2246 */
2247 if (fAdded)
2248 {
2249 if (fUpdateHostMsr)
2250 {
2251 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
2252 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
2253 pHostMsr[i].u64Value = ASMRdMsr(idMsr);
2254 }
2255 else
2256 {
2257 /* Someone else can do the work. */
2258 pVCpu->hm.s.vmx.fUpdatedHostAutoMsrs = false;
2259 }
2260 }
2261 return VINF_SUCCESS;
2262}
2263
2264
2265/**
2266 * Removes a guest/host MSR pair to be swapped during the world-switch from the
2267 * auto-load/store MSR area in the VMCS.
2268 *
2269 * @returns VBox status code.
2270 * @param pVCpu The cross context virtual CPU structure.
2271 * @param pVmxTransient The VMX-transient structure.
2272 * @param idMsr The MSR.
2273 */
2274static int hmR0VmxRemoveAutoLoadStoreMsr(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient, uint32_t idMsr)
2275{
2276 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
2277 bool const fIsNstGstVmcs = pVmxTransient->fIsNestedGuest;
2278 PVMXAUTOMSR pGuestMsrLoad = (PVMXAUTOMSR)pVmcsInfo->pvGuestMsrLoad;
2279 uint32_t cMsrs = pVmcsInfo->cEntryMsrLoad;
2280
2281 LogFlowFunc(("pVCpu=%p idMsr=%#RX32\n", pVCpu, idMsr));
2282
2283 for (uint32_t i = 0; i < cMsrs; i++)
2284 {
2285 /* Find the MSR. */
2286 if (pGuestMsrLoad[i].u32Msr == idMsr)
2287 {
2288 /*
2289 * If it's the last MSR, we only need to reduce the MSR count.
2290 * If it's -not- the last MSR, copy the last MSR in place of it and reduce the MSR count.
2291 */
2292 if (i < cMsrs - 1)
2293 {
2294 /* Remove it from the VM-entry MSR-load area. */
2295 pGuestMsrLoad[i].u32Msr = pGuestMsrLoad[cMsrs - 1].u32Msr;
2296 pGuestMsrLoad[i].u64Value = pGuestMsrLoad[cMsrs - 1].u64Value;
2297
2298 /* Remove it from the VM-exit MSR-store area if it's in a different page. */
2299 if (hmR0VmxIsSeparateExitMsrStoreAreaVmcs(pVmcsInfo))
2300 {
2301 PVMXAUTOMSR pGuestMsrStore = (PVMXAUTOMSR)pVmcsInfo->pvGuestMsrStore;
2302 Assert(pGuestMsrStore[i].u32Msr == idMsr);
2303 pGuestMsrStore[i].u32Msr = pGuestMsrStore[cMsrs - 1].u32Msr;
2304 pGuestMsrStore[i].u64Value = pGuestMsrStore[cMsrs - 1].u64Value;
2305 }
2306
2307 /* Remove it from the VM-exit MSR-load area. */
2308 PVMXAUTOMSR pHostMsr = (PVMXAUTOMSR)pVmcsInfo->pvHostMsrLoad;
2309 Assert(pHostMsr[i].u32Msr == idMsr);
2310 pHostMsr[i].u32Msr = pHostMsr[cMsrs - 1].u32Msr;
2311 pHostMsr[i].u64Value = pHostMsr[cMsrs - 1].u64Value;
2312 }
2313
2314 /* Reduce the count to reflect the removed MSR and bail. */
2315 --cMsrs;
2316 break;
2317 }
2318 }
2319
2320 /* Update the VMCS if the count changed (meaning the MSR was found and removed). */
2321 if (cMsrs != pVmcsInfo->cEntryMsrLoad)
2322 {
2323 int rc = hmR0VmxSetAutoLoadStoreMsrCount(pVCpu, pVmcsInfo, cMsrs);
2324 AssertRCReturn(rc, rc);
2325
2326 /* We're no longer swapping MSRs during the world-switch, intercept guest read/writes to them. */
2327 if (pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_USE_MSR_BITMAPS)
2328 hmR0VmxSetMsrPermission(pVCpu, pVmcsInfo, fIsNstGstVmcs, idMsr, VMXMSRPM_EXIT_RD | VMXMSRPM_EXIT_WR);
2329
2330 Log4Func(("Removed MSR %#RX32, cMsrs=%u\n", idMsr, cMsrs));
2331 return VINF_SUCCESS;
2332 }
2333
2334 return VERR_NOT_FOUND;
2335}
2336
2337
2338/**
2339 * Checks if the specified guest MSR is part of the VM-entry MSR-load area.
2340 *
2341 * @returns @c true if found, @c false otherwise.
2342 * @param pVmcsInfo The VMCS info. object.
2343 * @param idMsr The MSR to find.
2344 */
2345static bool hmR0VmxIsAutoLoadGuestMsr(PCVMXVMCSINFO pVmcsInfo, uint32_t idMsr)
2346{
2347 PCVMXAUTOMSR pMsrs = (PCVMXAUTOMSR)pVmcsInfo->pvGuestMsrLoad;
2348 uint32_t const cMsrs = pVmcsInfo->cEntryMsrLoad;
2349 Assert(pMsrs);
2350 Assert(sizeof(*pMsrs) * cMsrs <= X86_PAGE_4K_SIZE);
2351 for (uint32_t i = 0; i < cMsrs; i++)
2352 {
2353 if (pMsrs[i].u32Msr == idMsr)
2354 return true;
2355 }
2356 return false;
2357}
2358
2359
2360/**
2361 * Updates the value of all host MSRs in the VM-exit MSR-load area.
2362 *
2363 * @param pVCpu The cross context virtual CPU structure.
2364 * @param pVmcsInfo The VMCS info. object.
2365 *
2366 * @remarks No-long-jump zone!!!
2367 */
2368static void hmR0VmxUpdateAutoLoadHostMsrs(PCVMCPUCC pVCpu, PCVMXVMCSINFO pVmcsInfo)
2369{
2370 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
2371
2372 PVMXAUTOMSR pHostMsrLoad = (PVMXAUTOMSR)pVmcsInfo->pvHostMsrLoad;
2373 uint32_t const cMsrs = pVmcsInfo->cExitMsrLoad;
2374 Assert(pHostMsrLoad);
2375 Assert(sizeof(*pHostMsrLoad) * cMsrs <= X86_PAGE_4K_SIZE);
2376 LogFlowFunc(("pVCpu=%p cMsrs=%u\n", pVCpu, cMsrs));
2377 for (uint32_t i = 0; i < cMsrs; i++)
2378 {
2379 /*
2380 * Performance hack for the host EFER MSR. We use the cached value rather than re-read it.
2381 * Strict builds will catch mismatches in hmR0VmxCheckAutoLoadStoreMsrs(). See @bugref{7368}.
2382 */
2383 if (pHostMsrLoad[i].u32Msr == MSR_K6_EFER)
2384 pHostMsrLoad[i].u64Value = pVCpu->CTX_SUFF(pVM)->hm.s.vmx.u64HostMsrEfer;
2385 else
2386 pHostMsrLoad[i].u64Value = ASMRdMsr(pHostMsrLoad[i].u32Msr);
2387 }
2388}
2389
2390
2391/**
2392 * Saves a set of host MSRs to allow read/write passthru access to the guest and
2393 * perform lazy restoration of the host MSRs while leaving VT-x.
2394 *
2395 * @param pVCpu The cross context virtual CPU structure.
2396 *
2397 * @remarks No-long-jump zone!!!
2398 */
2399static void hmR0VmxLazySaveHostMsrs(PVMCPUCC pVCpu)
2400{
2401 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
2402
2403 /*
2404 * Note: If you're adding MSRs here, make sure to update the MSR-bitmap accesses in hmR0VmxSetupVmcsProcCtls().
2405 */
2406 if (!(pVCpu->hm.s.vmx.fLazyMsrs & VMX_LAZY_MSRS_SAVED_HOST))
2407 {
2408 Assert(!(pVCpu->hm.s.vmx.fLazyMsrs & VMX_LAZY_MSRS_LOADED_GUEST)); /* Guest MSRs better not be loaded now. */
2409 if (pVCpu->CTX_SUFF(pVM)->hm.s.fAllow64BitGuests)
2410 {
2411 pVCpu->hm.s.vmx.u64HostMsrLStar = ASMRdMsr(MSR_K8_LSTAR);
2412 pVCpu->hm.s.vmx.u64HostMsrStar = ASMRdMsr(MSR_K6_STAR);
2413 pVCpu->hm.s.vmx.u64HostMsrSfMask = ASMRdMsr(MSR_K8_SF_MASK);
2414 pVCpu->hm.s.vmx.u64HostMsrKernelGsBase = ASMRdMsr(MSR_K8_KERNEL_GS_BASE);
2415 }
2416 pVCpu->hm.s.vmx.fLazyMsrs |= VMX_LAZY_MSRS_SAVED_HOST;
2417 }
2418}
2419
2420
2421/**
2422 * Checks whether the MSR belongs to the set of guest MSRs that we restore
2423 * lazily while leaving VT-x.
2424 *
2425 * @returns true if it does, false otherwise.
2426 * @param pVCpu The cross context virtual CPU structure.
2427 * @param idMsr The MSR to check.
2428 */
2429static bool hmR0VmxIsLazyGuestMsr(PCVMCPUCC pVCpu, uint32_t idMsr)
2430{
2431 if (pVCpu->CTX_SUFF(pVM)->hm.s.fAllow64BitGuests)
2432 {
2433 switch (idMsr)
2434 {
2435 case MSR_K8_LSTAR:
2436 case MSR_K6_STAR:
2437 case MSR_K8_SF_MASK:
2438 case MSR_K8_KERNEL_GS_BASE:
2439 return true;
2440 }
2441 }
2442 return false;
2443}
2444
2445
2446/**
2447 * Loads a set of guests MSRs to allow read/passthru to the guest.
2448 *
2449 * The name of this function is slightly confusing. This function does NOT
2450 * postpone loading, but loads the MSR right now. "hmR0VmxLazy" is simply a
2451 * common prefix for functions dealing with "lazy restoration" of the shared
2452 * MSRs.
2453 *
2454 * @param pVCpu The cross context virtual CPU structure.
2455 *
2456 * @remarks No-long-jump zone!!!
2457 */
2458static void hmR0VmxLazyLoadGuestMsrs(PVMCPUCC pVCpu)
2459{
2460 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
2461 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
2462
2463 Assert(pVCpu->hm.s.vmx.fLazyMsrs & VMX_LAZY_MSRS_SAVED_HOST);
2464 if (pVCpu->CTX_SUFF(pVM)->hm.s.fAllow64BitGuests)
2465 {
2466 /*
2467 * If the guest MSRs are not loaded -and- if all the guest MSRs are identical
2468 * to the MSRs on the CPU (which are the saved host MSRs, see assertion above) then
2469 * we can skip a few MSR writes.
2470 *
2471 * Otherwise, it implies either 1. they're not loaded, or 2. they're loaded but the
2472 * guest MSR values in the guest-CPU context might be different to what's currently
2473 * loaded in the CPU. In either case, we need to write the new guest MSR values to the
2474 * CPU, see @bugref{8728}.
2475 */
2476 PCCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
2477 if ( !(pVCpu->hm.s.vmx.fLazyMsrs & VMX_LAZY_MSRS_LOADED_GUEST)
2478 && pCtx->msrKERNELGSBASE == pVCpu->hm.s.vmx.u64HostMsrKernelGsBase
2479 && pCtx->msrLSTAR == pVCpu->hm.s.vmx.u64HostMsrLStar
2480 && pCtx->msrSTAR == pVCpu->hm.s.vmx.u64HostMsrStar
2481 && pCtx->msrSFMASK == pVCpu->hm.s.vmx.u64HostMsrSfMask)
2482 {
2483#ifdef VBOX_STRICT
2484 Assert(ASMRdMsr(MSR_K8_KERNEL_GS_BASE) == pCtx->msrKERNELGSBASE);
2485 Assert(ASMRdMsr(MSR_K8_LSTAR) == pCtx->msrLSTAR);
2486 Assert(ASMRdMsr(MSR_K6_STAR) == pCtx->msrSTAR);
2487 Assert(ASMRdMsr(MSR_K8_SF_MASK) == pCtx->msrSFMASK);
2488#endif
2489 }
2490 else
2491 {
2492 ASMWrMsr(MSR_K8_KERNEL_GS_BASE, pCtx->msrKERNELGSBASE);
2493 ASMWrMsr(MSR_K8_LSTAR, pCtx->msrLSTAR);
2494 ASMWrMsr(MSR_K6_STAR, pCtx->msrSTAR);
2495 ASMWrMsr(MSR_K8_SF_MASK, pCtx->msrSFMASK);
2496 }
2497 }
2498 pVCpu->hm.s.vmx.fLazyMsrs |= VMX_LAZY_MSRS_LOADED_GUEST;
2499}
2500
2501
2502/**
2503 * Performs lazy restoration of the set of host MSRs if they were previously
2504 * loaded with guest MSR values.
2505 *
2506 * @param pVCpu The cross context virtual CPU structure.
2507 *
2508 * @remarks No-long-jump zone!!!
2509 * @remarks The guest MSRs should have been saved back into the guest-CPU
2510 * context by hmR0VmxImportGuestState()!!!
2511 */
2512static void hmR0VmxLazyRestoreHostMsrs(PVMCPUCC pVCpu)
2513{
2514 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
2515 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
2516
2517 if (pVCpu->hm.s.vmx.fLazyMsrs & VMX_LAZY_MSRS_LOADED_GUEST)
2518 {
2519 Assert(pVCpu->hm.s.vmx.fLazyMsrs & VMX_LAZY_MSRS_SAVED_HOST);
2520 if (pVCpu->CTX_SUFF(pVM)->hm.s.fAllow64BitGuests)
2521 {
2522 ASMWrMsr(MSR_K8_LSTAR, pVCpu->hm.s.vmx.u64HostMsrLStar);
2523 ASMWrMsr(MSR_K6_STAR, pVCpu->hm.s.vmx.u64HostMsrStar);
2524 ASMWrMsr(MSR_K8_SF_MASK, pVCpu->hm.s.vmx.u64HostMsrSfMask);
2525 ASMWrMsr(MSR_K8_KERNEL_GS_BASE, pVCpu->hm.s.vmx.u64HostMsrKernelGsBase);
2526 }
2527 }
2528 pVCpu->hm.s.vmx.fLazyMsrs &= ~(VMX_LAZY_MSRS_LOADED_GUEST | VMX_LAZY_MSRS_SAVED_HOST);
2529}
2530
2531
2532/**
2533 * Verifies that our cached values of the VMCS fields are all consistent with
2534 * what's actually present in the VMCS.
2535 *
2536 * @returns VBox status code.
2537 * @retval VINF_SUCCESS if all our caches match their respective VMCS fields.
2538 * @retval VERR_VMX_VMCS_FIELD_CACHE_INVALID if a cache field doesn't match the
2539 * VMCS content. HMCPU error-field is
2540 * updated, see VMX_VCI_XXX.
2541 * @param pVCpu The cross context virtual CPU structure.
2542 * @param pVmcsInfo The VMCS info. object.
2543 * @param fIsNstGstVmcs Whether this is a nested-guest VMCS.
2544 */
2545static int hmR0VmxCheckVmcsCtls(PVMCPUCC pVCpu, PCVMXVMCSINFO pVmcsInfo, bool fIsNstGstVmcs)
2546{
2547 const char * const pcszVmcs = fIsNstGstVmcs ? "Nested-guest VMCS" : "VMCS";
2548
2549 uint32_t u32Val;
2550 int rc = VMXReadVmcs32(VMX_VMCS32_CTRL_ENTRY, &u32Val);
2551 AssertRC(rc);
2552 AssertMsgReturnStmt(pVmcsInfo->u32EntryCtls == u32Val,
2553 ("%s controls mismatch: Cache=%#RX32 VMCS=%#RX32\n", pcszVmcs, pVmcsInfo->u32EntryCtls, u32Val),
2554 pVCpu->hm.s.u32HMError = VMX_VCI_CTRL_ENTRY,
2555 VERR_VMX_VMCS_FIELD_CACHE_INVALID);
2556
2557 rc = VMXReadVmcs32(VMX_VMCS32_CTRL_EXIT, &u32Val);
2558 AssertRC(rc);
2559 AssertMsgReturnStmt(pVmcsInfo->u32ExitCtls == u32Val,
2560 ("%s controls mismatch: Cache=%#RX32 VMCS=%#RX32\n", pcszVmcs, pVmcsInfo->u32ExitCtls, u32Val),
2561 pVCpu->hm.s.u32HMError = VMX_VCI_CTRL_EXIT,
2562 VERR_VMX_VMCS_FIELD_CACHE_INVALID);
2563
2564 rc = VMXReadVmcs32(VMX_VMCS32_CTRL_PIN_EXEC, &u32Val);
2565 AssertRC(rc);
2566 AssertMsgReturnStmt(pVmcsInfo->u32PinCtls == u32Val,
2567 ("%s controls mismatch: Cache=%#RX32 VMCS=%#RX32\n", pcszVmcs, pVmcsInfo->u32PinCtls, u32Val),
2568 pVCpu->hm.s.u32HMError = VMX_VCI_CTRL_PIN_EXEC,
2569 VERR_VMX_VMCS_FIELD_CACHE_INVALID);
2570
2571 rc = VMXReadVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, &u32Val);
2572 AssertRC(rc);
2573 AssertMsgReturnStmt(pVmcsInfo->u32ProcCtls == u32Val,
2574 ("%s controls mismatch: Cache=%#RX32 VMCS=%#RX32\n", pcszVmcs, pVmcsInfo->u32ProcCtls, u32Val),
2575 pVCpu->hm.s.u32HMError = VMX_VCI_CTRL_PROC_EXEC,
2576 VERR_VMX_VMCS_FIELD_CACHE_INVALID);
2577
2578 if (pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_USE_SECONDARY_CTLS)
2579 {
2580 rc = VMXReadVmcs32(VMX_VMCS32_CTRL_PROC_EXEC2, &u32Val);
2581 AssertRC(rc);
2582 AssertMsgReturnStmt(pVmcsInfo->u32ProcCtls2 == u32Val,
2583 ("%s controls mismatch: Cache=%#RX32 VMCS=%#RX32\n", pcszVmcs, pVmcsInfo->u32ProcCtls2, u32Val),
2584 pVCpu->hm.s.u32HMError = VMX_VCI_CTRL_PROC_EXEC2,
2585 VERR_VMX_VMCS_FIELD_CACHE_INVALID);
2586 }
2587
2588 rc = VMXReadVmcs32(VMX_VMCS32_CTRL_EXCEPTION_BITMAP, &u32Val);
2589 AssertRC(rc);
2590 AssertMsgReturnStmt(pVmcsInfo->u32XcptBitmap == u32Val,
2591 ("%s exception bitmap mismatch: Cache=%#RX32 VMCS=%#RX32\n", pcszVmcs, pVmcsInfo->u32XcptBitmap, u32Val),
2592 pVCpu->hm.s.u32HMError = VMX_VCI_CTRL_XCPT_BITMAP,
2593 VERR_VMX_VMCS_FIELD_CACHE_INVALID);
2594
2595 uint64_t u64Val;
2596 rc = VMXReadVmcs64(VMX_VMCS64_CTRL_TSC_OFFSET_FULL, &u64Val);
2597 AssertRC(rc);
2598 AssertMsgReturnStmt(pVmcsInfo->u64TscOffset == u64Val,
2599 ("%s TSC offset mismatch: Cache=%#RX64 VMCS=%#RX64\n", pcszVmcs, pVmcsInfo->u64TscOffset, u64Val),
2600 pVCpu->hm.s.u32HMError = VMX_VCI_CTRL_TSC_OFFSET,
2601 VERR_VMX_VMCS_FIELD_CACHE_INVALID);
2602
2603 NOREF(pcszVmcs);
2604 return VINF_SUCCESS;
2605}
2606
2607
2608#ifdef VBOX_STRICT
2609/**
2610 * Verifies that our cached host EFER MSR value has not changed since we cached it.
2611 *
2612 * @param pVCpu The cross context virtual CPU structure.
2613 * @param pVmcsInfo The VMCS info. object.
2614 */
2615static void hmR0VmxCheckHostEferMsr(PCVMCPUCC pVCpu, PCVMXVMCSINFO pVmcsInfo)
2616{
2617 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
2618
2619 if (pVmcsInfo->u32ExitCtls & VMX_EXIT_CTLS_LOAD_EFER_MSR)
2620 {
2621 uint64_t const uHostEferMsr = ASMRdMsr(MSR_K6_EFER);
2622 uint64_t const uHostEferMsrCache = pVCpu->CTX_SUFF(pVM)->hm.s.vmx.u64HostMsrEfer;
2623 uint64_t uVmcsEferMsrVmcs;
2624 int rc = VMXReadVmcs64(VMX_VMCS64_HOST_EFER_FULL, &uVmcsEferMsrVmcs);
2625 AssertRC(rc);
2626
2627 AssertMsgReturnVoid(uHostEferMsr == uVmcsEferMsrVmcs,
2628 ("EFER Host/VMCS mismatch! host=%#RX64 vmcs=%#RX64\n", uHostEferMsr, uVmcsEferMsrVmcs));
2629 AssertMsgReturnVoid(uHostEferMsr == uHostEferMsrCache,
2630 ("EFER Host/Cache mismatch! host=%#RX64 cache=%#RX64\n", uHostEferMsr, uHostEferMsrCache));
2631 }
2632}
2633
2634
2635/**
2636 * Verifies whether the guest/host MSR pairs in the auto-load/store area in the
2637 * VMCS are correct.
2638 *
2639 * @param pVCpu The cross context virtual CPU structure.
2640 * @param pVmcsInfo The VMCS info. object.
2641 * @param fIsNstGstVmcs Whether this is a nested-guest VMCS.
2642 */
2643static void hmR0VmxCheckAutoLoadStoreMsrs(PVMCPUCC pVCpu, PCVMXVMCSINFO pVmcsInfo, bool fIsNstGstVmcs)
2644{
2645 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
2646
2647 /* Read the various MSR-area counts from the VMCS. */
2648 uint32_t cEntryLoadMsrs;
2649 uint32_t cExitStoreMsrs;
2650 uint32_t cExitLoadMsrs;
2651 int rc = VMXReadVmcs32(VMX_VMCS32_CTRL_ENTRY_MSR_LOAD_COUNT, &cEntryLoadMsrs); AssertRC(rc);
2652 rc = VMXReadVmcs32(VMX_VMCS32_CTRL_EXIT_MSR_STORE_COUNT, &cExitStoreMsrs); AssertRC(rc);
2653 rc = VMXReadVmcs32(VMX_VMCS32_CTRL_EXIT_MSR_LOAD_COUNT, &cExitLoadMsrs); AssertRC(rc);
2654
2655 /* Verify all the MSR counts are the same. */
2656 Assert(cEntryLoadMsrs == cExitStoreMsrs);
2657 Assert(cExitStoreMsrs == cExitLoadMsrs);
2658 uint32_t const cMsrs = cExitLoadMsrs;
2659
2660 /* Verify the MSR counts do not exceed the maximum count supported by the hardware. */
2661 Assert(cMsrs < VMX_MISC_MAX_MSRS(pVCpu->CTX_SUFF(pVM)->hm.s.vmx.Msrs.u64Misc));
2662
2663 /* Verify the MSR counts are within the allocated page size. */
2664 Assert(sizeof(VMXAUTOMSR) * cMsrs <= X86_PAGE_4K_SIZE);
2665
2666 /* Verify the relevant contents of the MSR areas match. */
2667 PCVMXAUTOMSR pGuestMsrLoad = (PCVMXAUTOMSR)pVmcsInfo->pvGuestMsrLoad;
2668 PCVMXAUTOMSR pGuestMsrStore = (PCVMXAUTOMSR)pVmcsInfo->pvGuestMsrStore;
2669 PCVMXAUTOMSR pHostMsrLoad = (PCVMXAUTOMSR)pVmcsInfo->pvHostMsrLoad;
2670 bool const fSeparateExitMsrStorePage = hmR0VmxIsSeparateExitMsrStoreAreaVmcs(pVmcsInfo);
2671 for (uint32_t i = 0; i < cMsrs; i++)
2672 {
2673 /* Verify that the MSRs are paired properly and that the host MSR has the correct value. */
2674 if (fSeparateExitMsrStorePage)
2675 {
2676 AssertMsgReturnVoid(pGuestMsrLoad->u32Msr == pGuestMsrStore->u32Msr,
2677 ("GuestMsrLoad=%#RX32 GuestMsrStore=%#RX32 cMsrs=%u\n",
2678 pGuestMsrLoad->u32Msr, pGuestMsrStore->u32Msr, cMsrs));
2679 }
2680
2681 AssertMsgReturnVoid(pHostMsrLoad->u32Msr == pGuestMsrLoad->u32Msr,
2682 ("HostMsrLoad=%#RX32 GuestMsrLoad=%#RX32 cMsrs=%u\n",
2683 pHostMsrLoad->u32Msr, pGuestMsrLoad->u32Msr, cMsrs));
2684
2685 uint64_t const u64Msr = ASMRdMsr(pHostMsrLoad->u32Msr);
2686 AssertMsgReturnVoid(pHostMsrLoad->u64Value == u64Msr,
2687 ("u32Msr=%#RX32 VMCS Value=%#RX64 ASMRdMsr=%#RX64 cMsrs=%u\n",
2688 pHostMsrLoad->u32Msr, pHostMsrLoad->u64Value, u64Msr, cMsrs));
2689
2690 /* Verify that cached host EFER MSR matches what's loaded the CPU. */
2691 bool const fIsEferMsr = RT_BOOL(pHostMsrLoad->u32Msr == MSR_K6_EFER);
2692 if (fIsEferMsr)
2693 {
2694 AssertMsgReturnVoid(u64Msr == pVCpu->CTX_SUFF(pVM)->hm.s.vmx.u64HostMsrEfer,
2695 ("Cached=%#RX64 ASMRdMsr=%#RX64 cMsrs=%u\n",
2696 pVCpu->CTX_SUFF(pVM)->hm.s.vmx.u64HostMsrEfer, u64Msr, cMsrs));
2697 }
2698
2699 /* Verify that the accesses are as expected in the MSR bitmap for auto-load/store MSRs. */
2700 if (pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_USE_MSR_BITMAPS)
2701 {
2702 uint32_t const fMsrpm = CPUMGetVmxMsrPermission(pVmcsInfo->pvMsrBitmap, pGuestMsrLoad->u32Msr);
2703 if (fIsEferMsr)
2704 {
2705 AssertMsgReturnVoid((fMsrpm & VMXMSRPM_EXIT_RD), ("Passthru read for EFER MSR!?\n"));
2706 AssertMsgReturnVoid((fMsrpm & VMXMSRPM_EXIT_WR), ("Passthru write for EFER MSR!?\n"));
2707 }
2708 else
2709 {
2710 if (!fIsNstGstVmcs)
2711 {
2712 AssertMsgReturnVoid((fMsrpm & VMXMSRPM_ALLOW_RD_WR) == VMXMSRPM_ALLOW_RD_WR,
2713 ("u32Msr=%#RX32 cMsrs=%u No passthru read/write!\n", pGuestMsrLoad->u32Msr, cMsrs));
2714 }
2715 else
2716 {
2717 /*
2718 * A nested-guest VMCS must -also- allow read/write passthrough for the MSR for us to
2719 * execute a nested-guest with MSR passthrough.
2720 *
2721 * Check if the nested-guest MSR bitmap allows passthrough, and if so, assert that we
2722 * allow passthrough too.
2723 */
2724 void const *pvMsrBitmapNstGst = pVCpu->cpum.GstCtx.hwvirt.vmx.CTX_SUFF(pvMsrBitmap);
2725 Assert(pvMsrBitmapNstGst);
2726 uint32_t const fMsrpmNstGst = CPUMGetVmxMsrPermission(pvMsrBitmapNstGst, pGuestMsrLoad->u32Msr);
2727 AssertMsgReturnVoid(fMsrpm == fMsrpmNstGst,
2728 ("u32Msr=%#RX32 cMsrs=%u Permission mismatch fMsrpm=%#x fMsrpmNstGst=%#x!\n",
2729 pGuestMsrLoad->u32Msr, cMsrs, fMsrpm, fMsrpmNstGst));
2730 }
2731 }
2732 }
2733
2734 /* Move to the next MSR. */
2735 pHostMsrLoad++;
2736 pGuestMsrLoad++;
2737 pGuestMsrStore++;
2738 }
2739}
2740#endif /* VBOX_STRICT */
2741
2742
2743/**
2744 * Flushes the TLB using EPT.
2745 *
2746 * @returns VBox status code.
2747 * @param pVCpu The cross context virtual CPU structure of the calling
2748 * EMT. Can be NULL depending on @a enmTlbFlush.
2749 * @param pVmcsInfo The VMCS info. object. Can be NULL depending on @a
2750 * enmTlbFlush.
2751 * @param enmTlbFlush Type of flush.
2752 *
2753 * @remarks Caller is responsible for making sure this function is called only
2754 * when NestedPaging is supported and providing @a enmTlbFlush that is
2755 * supported by the CPU.
2756 * @remarks Can be called with interrupts disabled.
2757 */
2758static void hmR0VmxFlushEpt(PVMCPUCC pVCpu, PCVMXVMCSINFO pVmcsInfo, VMXTLBFLUSHEPT enmTlbFlush)
2759{
2760 uint64_t au64Descriptor[2];
2761 if (enmTlbFlush == VMXTLBFLUSHEPT_ALL_CONTEXTS)
2762 au64Descriptor[0] = 0;
2763 else
2764 {
2765 Assert(pVCpu);
2766 Assert(pVmcsInfo);
2767 au64Descriptor[0] = pVmcsInfo->HCPhysEPTP;
2768 }
2769 au64Descriptor[1] = 0; /* MBZ. Intel spec. 33.3 "VMX Instructions" */
2770
2771 int rc = VMXR0InvEPT(enmTlbFlush, &au64Descriptor[0]);
2772 AssertMsg(rc == VINF_SUCCESS, ("VMXR0InvEPT %#x %#RHp failed. rc=%Rrc\n", enmTlbFlush, au64Descriptor[0], rc));
2773
2774 if ( RT_SUCCESS(rc)
2775 && pVCpu)
2776 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushNestedPaging);
2777}
2778
2779
2780/**
2781 * Flushes the TLB using VPID.
2782 *
2783 * @returns VBox status code.
2784 * @param pVCpu The cross context virtual CPU structure of the calling
2785 * EMT. Can be NULL depending on @a enmTlbFlush.
2786 * @param enmTlbFlush Type of flush.
2787 * @param GCPtr Virtual address of the page to flush (can be 0 depending
2788 * on @a enmTlbFlush).
2789 *
2790 * @remarks Can be called with interrupts disabled.
2791 */
2792static void hmR0VmxFlushVpid(PVMCPUCC pVCpu, VMXTLBFLUSHVPID enmTlbFlush, RTGCPTR GCPtr)
2793{
2794 Assert(pVCpu->CTX_SUFF(pVM)->hm.s.vmx.fVpid);
2795
2796 uint64_t au64Descriptor[2];
2797 if (enmTlbFlush == VMXTLBFLUSHVPID_ALL_CONTEXTS)
2798 {
2799 au64Descriptor[0] = 0;
2800 au64Descriptor[1] = 0;
2801 }
2802 else
2803 {
2804 AssertPtr(pVCpu);
2805 AssertMsg(pVCpu->hm.s.uCurrentAsid != 0, ("VMXR0InvVPID: invalid ASID %lu\n", pVCpu->hm.s.uCurrentAsid));
2806 AssertMsg(pVCpu->hm.s.uCurrentAsid <= UINT16_MAX, ("VMXR0InvVPID: invalid ASID %lu\n", pVCpu->hm.s.uCurrentAsid));
2807 au64Descriptor[0] = pVCpu->hm.s.uCurrentAsid;
2808 au64Descriptor[1] = GCPtr;
2809 }
2810
2811 int rc = VMXR0InvVPID(enmTlbFlush, &au64Descriptor[0]);
2812 AssertMsg(rc == VINF_SUCCESS,
2813 ("VMXR0InvVPID %#x %u %RGv failed with %Rrc\n", enmTlbFlush, pVCpu ? pVCpu->hm.s.uCurrentAsid : 0, GCPtr, rc));
2814
2815 if ( RT_SUCCESS(rc)
2816 && pVCpu)
2817 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushAsid);
2818 NOREF(rc);
2819}
2820
2821
2822/**
2823 * Invalidates a guest page by guest virtual address. Only relevant for EPT/VPID,
2824 * otherwise there is nothing really to invalidate.
2825 *
2826 * @returns VBox status code.
2827 * @param pVCpu The cross context virtual CPU structure.
2828 * @param GCVirt Guest virtual address of the page to invalidate.
2829 */
2830VMMR0DECL(int) VMXR0InvalidatePage(PVMCPUCC pVCpu, RTGCPTR GCVirt)
2831{
2832 AssertPtr(pVCpu);
2833 LogFlowFunc(("pVCpu=%p GCVirt=%RGv\n", pVCpu, GCVirt));
2834
2835 if (!VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_TLB_FLUSH))
2836 {
2837 /*
2838 * We must invalidate the guest TLB entry in either case, we cannot ignore it even for
2839 * the EPT case. See @bugref{6043} and @bugref{6177}.
2840 *
2841 * Set the VMCPU_FF_TLB_FLUSH force flag and flush before VM-entry in hmR0VmxFlushTLB*()
2842 * as this function maybe called in a loop with individual addresses.
2843 */
2844 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
2845 if (pVM->hm.s.vmx.fVpid)
2846 {
2847 bool fVpidFlush = RT_BOOL(pVM->hm.s.vmx.Msrs.u64EptVpidCaps & MSR_IA32_VMX_EPT_VPID_CAP_INVVPID_INDIV_ADDR);
2848 if (fVpidFlush)
2849 {
2850 hmR0VmxFlushVpid(pVCpu, VMXTLBFLUSHVPID_INDIV_ADDR, GCVirt);
2851 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushTlbInvlpgVirt);
2852 }
2853 else
2854 VMCPU_FF_SET(pVCpu, VMCPU_FF_TLB_FLUSH);
2855 }
2856 else if (pVM->hm.s.fNestedPaging)
2857 VMCPU_FF_SET(pVCpu, VMCPU_FF_TLB_FLUSH);
2858 }
2859
2860 return VINF_SUCCESS;
2861}
2862
2863
2864/**
2865 * Dummy placeholder for tagged-TLB flush handling before VM-entry. Used in the
2866 * case where neither EPT nor VPID is supported by the CPU.
2867 *
2868 * @param pHostCpu The HM physical-CPU structure.
2869 * @param pVCpu The cross context virtual CPU structure.
2870 *
2871 * @remarks Called with interrupts disabled.
2872 */
2873static void hmR0VmxFlushTaggedTlbNone(PHMPHYSCPU pHostCpu, PVMCPUCC pVCpu)
2874{
2875 AssertPtr(pVCpu);
2876 AssertPtr(pHostCpu);
2877
2878 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_TLB_FLUSH);
2879
2880 Assert(pHostCpu->idCpu != NIL_RTCPUID);
2881 pVCpu->hm.s.idLastCpu = pHostCpu->idCpu;
2882 pVCpu->hm.s.cTlbFlushes = pHostCpu->cTlbFlushes;
2883 pVCpu->hm.s.fForceTLBFlush = false;
2884 return;
2885}
2886
2887
2888/**
2889 * Flushes the tagged-TLB entries for EPT+VPID CPUs as necessary.
2890 *
2891 * @param pHostCpu The HM physical-CPU structure.
2892 * @param pVCpu The cross context virtual CPU structure.
2893 * @param pVmcsInfo The VMCS info. object.
2894 *
2895 * @remarks All references to "ASID" in this function pertains to "VPID" in Intel's
2896 * nomenclature. The reason is, to avoid confusion in compare statements
2897 * since the host-CPU copies are named "ASID".
2898 *
2899 * @remarks Called with interrupts disabled.
2900 */
2901static void hmR0VmxFlushTaggedTlbBoth(PHMPHYSCPU pHostCpu, PVMCPUCC pVCpu, PCVMXVMCSINFO pVmcsInfo)
2902{
2903#ifdef VBOX_WITH_STATISTICS
2904 bool fTlbFlushed = false;
2905# define HMVMX_SET_TAGGED_TLB_FLUSHED() do { fTlbFlushed = true; } while (0)
2906# define HMVMX_UPDATE_FLUSH_SKIPPED_STAT() do { \
2907 if (!fTlbFlushed) \
2908 STAM_COUNTER_INC(&pVCpu->hm.s.StatNoFlushTlbWorldSwitch); \
2909 } while (0)
2910#else
2911# define HMVMX_SET_TAGGED_TLB_FLUSHED() do { } while (0)
2912# define HMVMX_UPDATE_FLUSH_SKIPPED_STAT() do { } while (0)
2913#endif
2914
2915 AssertPtr(pVCpu);
2916 AssertPtr(pHostCpu);
2917 Assert(pHostCpu->idCpu != NIL_RTCPUID);
2918
2919 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
2920 AssertMsg(pVM->hm.s.fNestedPaging && pVM->hm.s.vmx.fVpid,
2921 ("hmR0VmxFlushTaggedTlbBoth cannot be invoked unless NestedPaging & VPID are enabled."
2922 "fNestedPaging=%RTbool fVpid=%RTbool", pVM->hm.s.fNestedPaging, pVM->hm.s.vmx.fVpid));
2923
2924 /*
2925 * Force a TLB flush for the first world-switch if the current CPU differs from the one we
2926 * ran on last. If the TLB flush count changed, another VM (VCPU rather) has hit the ASID
2927 * limit while flushing the TLB or the host CPU is online after a suspend/resume, so we
2928 * cannot reuse the current ASID anymore.
2929 */
2930 if ( pVCpu->hm.s.idLastCpu != pHostCpu->idCpu
2931 || pVCpu->hm.s.cTlbFlushes != pHostCpu->cTlbFlushes)
2932 {
2933 ++pHostCpu->uCurrentAsid;
2934 if (pHostCpu->uCurrentAsid >= pVM->hm.s.uMaxAsid)
2935 {
2936 pHostCpu->uCurrentAsid = 1; /* Wraparound to 1; host uses 0. */
2937 pHostCpu->cTlbFlushes++; /* All VCPUs that run on this host CPU must use a new VPID. */
2938 pHostCpu->fFlushAsidBeforeUse = true; /* All VCPUs that run on this host CPU must flush their new VPID before use. */
2939 }
2940
2941 pVCpu->hm.s.uCurrentAsid = pHostCpu->uCurrentAsid;
2942 pVCpu->hm.s.idLastCpu = pHostCpu->idCpu;
2943 pVCpu->hm.s.cTlbFlushes = pHostCpu->cTlbFlushes;
2944
2945 /*
2946 * Flush by EPT when we get rescheduled to a new host CPU to ensure EPT-only tagged mappings are also
2947 * invalidated. We don't need to flush-by-VPID here as flushing by EPT covers it. See @bugref{6568}.
2948 */
2949 hmR0VmxFlushEpt(pVCpu, pVmcsInfo, pVM->hm.s.vmx.enmTlbFlushEpt);
2950 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushTlbWorldSwitch);
2951 HMVMX_SET_TAGGED_TLB_FLUSHED();
2952 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_TLB_FLUSH);
2953 }
2954 else if (VMCPU_FF_TEST_AND_CLEAR(pVCpu, VMCPU_FF_TLB_FLUSH)) /* Check for explicit TLB flushes. */
2955 {
2956 /*
2957 * Changes to the EPT paging structure by VMM requires flushing-by-EPT as the CPU
2958 * creates guest-physical (ie. only EPT-tagged) mappings while traversing the EPT
2959 * tables when EPT is in use. Flushing-by-VPID will only flush linear (only
2960 * VPID-tagged) and combined (EPT+VPID tagged) mappings but not guest-physical
2961 * mappings, see @bugref{6568}.
2962 *
2963 * See Intel spec. 28.3.2 "Creating and Using Cached Translation Information".
2964 */
2965 hmR0VmxFlushEpt(pVCpu, pVmcsInfo, pVM->hm.s.vmx.enmTlbFlushEpt);
2966 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushTlb);
2967 HMVMX_SET_TAGGED_TLB_FLUSHED();
2968 }
2969 else if (pVCpu->hm.s.vmx.fSwitchedNstGstFlushTlb)
2970 {
2971 /*
2972 * The nested-guest specifies its own guest-physical address to use as the APIC-access
2973 * address which requires flushing the TLB of EPT cached structures.
2974 *
2975 * See Intel spec. 28.3.3.4 "Guidelines for Use of the INVEPT Instruction".
2976 */
2977 hmR0VmxFlushEpt(pVCpu, pVmcsInfo, pVM->hm.s.vmx.enmTlbFlushEpt);
2978 pVCpu->hm.s.vmx.fSwitchedNstGstFlushTlb = false;
2979 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushTlbNstGst);
2980 HMVMX_SET_TAGGED_TLB_FLUSHED();
2981 }
2982
2983
2984 pVCpu->hm.s.fForceTLBFlush = false;
2985 HMVMX_UPDATE_FLUSH_SKIPPED_STAT();
2986
2987 Assert(pVCpu->hm.s.idLastCpu == pHostCpu->idCpu);
2988 Assert(pVCpu->hm.s.cTlbFlushes == pHostCpu->cTlbFlushes);
2989 AssertMsg(pVCpu->hm.s.cTlbFlushes == pHostCpu->cTlbFlushes,
2990 ("Flush count mismatch for cpu %d (%u vs %u)\n", pHostCpu->idCpu, pVCpu->hm.s.cTlbFlushes, pHostCpu->cTlbFlushes));
2991 AssertMsg(pHostCpu->uCurrentAsid >= 1 && pHostCpu->uCurrentAsid < pVM->hm.s.uMaxAsid,
2992 ("Cpu[%u] uCurrentAsid=%u cTlbFlushes=%u pVCpu->idLastCpu=%u pVCpu->cTlbFlushes=%u\n", pHostCpu->idCpu,
2993 pHostCpu->uCurrentAsid, pHostCpu->cTlbFlushes, pVCpu->hm.s.idLastCpu, pVCpu->hm.s.cTlbFlushes));
2994 AssertMsg(pVCpu->hm.s.uCurrentAsid >= 1 && pVCpu->hm.s.uCurrentAsid < pVM->hm.s.uMaxAsid,
2995 ("Cpu[%u] pVCpu->uCurrentAsid=%u\n", pHostCpu->idCpu, pVCpu->hm.s.uCurrentAsid));
2996
2997 /* Update VMCS with the VPID. */
2998 int rc = VMXWriteVmcs16(VMX_VMCS16_VPID, pVCpu->hm.s.uCurrentAsid);
2999 AssertRC(rc);
3000
3001#undef HMVMX_SET_TAGGED_TLB_FLUSHED
3002}
3003
3004
3005/**
3006 * Flushes the tagged-TLB entries for EPT CPUs as necessary.
3007 *
3008 * @param pHostCpu The HM physical-CPU structure.
3009 * @param pVCpu The cross context virtual CPU structure.
3010 * @param pVmcsInfo The VMCS info. object.
3011 *
3012 * @remarks Called with interrupts disabled.
3013 */
3014static void hmR0VmxFlushTaggedTlbEpt(PHMPHYSCPU pHostCpu, PVMCPUCC pVCpu, PCVMXVMCSINFO pVmcsInfo)
3015{
3016 AssertPtr(pVCpu);
3017 AssertPtr(pHostCpu);
3018 Assert(pHostCpu->idCpu != NIL_RTCPUID);
3019 AssertMsg(pVCpu->CTX_SUFF(pVM)->hm.s.fNestedPaging, ("hmR0VmxFlushTaggedTlbEpt cannot be invoked without NestedPaging."));
3020 AssertMsg(!pVCpu->CTX_SUFF(pVM)->hm.s.vmx.fVpid, ("hmR0VmxFlushTaggedTlbEpt cannot be invoked with VPID."));
3021
3022 /*
3023 * Force a TLB flush for the first world-switch if the current CPU differs from the one we ran on last.
3024 * A change in the TLB flush count implies the host CPU is online after a suspend/resume.
3025 */
3026 if ( pVCpu->hm.s.idLastCpu != pHostCpu->idCpu
3027 || pVCpu->hm.s.cTlbFlushes != pHostCpu->cTlbFlushes)
3028 {
3029 pVCpu->hm.s.fForceTLBFlush = true;
3030 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushTlbWorldSwitch);
3031 }
3032
3033 /* Check for explicit TLB flushes. */
3034 if (VMCPU_FF_TEST_AND_CLEAR(pVCpu, VMCPU_FF_TLB_FLUSH))
3035 {
3036 pVCpu->hm.s.fForceTLBFlush = true;
3037 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushTlb);
3038 }
3039
3040 /* Check for TLB flushes while switching to/from a nested-guest. */
3041 if (pVCpu->hm.s.vmx.fSwitchedNstGstFlushTlb)
3042 {
3043 pVCpu->hm.s.fForceTLBFlush = true;
3044 pVCpu->hm.s.vmx.fSwitchedNstGstFlushTlb = false;
3045 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushTlbNstGst);
3046 }
3047
3048 pVCpu->hm.s.idLastCpu = pHostCpu->idCpu;
3049 pVCpu->hm.s.cTlbFlushes = pHostCpu->cTlbFlushes;
3050
3051 if (pVCpu->hm.s.fForceTLBFlush)
3052 {
3053 hmR0VmxFlushEpt(pVCpu, pVmcsInfo, pVCpu->CTX_SUFF(pVM)->hm.s.vmx.enmTlbFlushEpt);
3054 pVCpu->hm.s.fForceTLBFlush = false;
3055 }
3056}
3057
3058
3059/**
3060 * Flushes the tagged-TLB entries for VPID CPUs as necessary.
3061 *
3062 * @param pHostCpu The HM physical-CPU structure.
3063 * @param pVCpu The cross context virtual CPU structure.
3064 *
3065 * @remarks Called with interrupts disabled.
3066 */
3067static void hmR0VmxFlushTaggedTlbVpid(PHMPHYSCPU pHostCpu, PVMCPUCC pVCpu)
3068{
3069 AssertPtr(pVCpu);
3070 AssertPtr(pHostCpu);
3071 Assert(pHostCpu->idCpu != NIL_RTCPUID);
3072 AssertMsg(pVCpu->CTX_SUFF(pVM)->hm.s.vmx.fVpid, ("hmR0VmxFlushTlbVpid cannot be invoked without VPID."));
3073 AssertMsg(!pVCpu->CTX_SUFF(pVM)->hm.s.fNestedPaging, ("hmR0VmxFlushTlbVpid cannot be invoked with NestedPaging"));
3074
3075 /*
3076 * Force a TLB flush for the first world switch if the current CPU differs from the one we
3077 * ran on last. If the TLB flush count changed, another VM (VCPU rather) has hit the ASID
3078 * limit while flushing the TLB or the host CPU is online after a suspend/resume, so we
3079 * cannot reuse the current ASID anymore.
3080 */
3081 if ( pVCpu->hm.s.idLastCpu != pHostCpu->idCpu
3082 || pVCpu->hm.s.cTlbFlushes != pHostCpu->cTlbFlushes)
3083 {
3084 pVCpu->hm.s.fForceTLBFlush = true;
3085 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushTlbWorldSwitch);
3086 }
3087
3088 /* Check for explicit TLB flushes. */
3089 if (VMCPU_FF_TEST_AND_CLEAR(pVCpu, VMCPU_FF_TLB_FLUSH))
3090 {
3091 /*
3092 * If we ever support VPID flush combinations other than ALL or SINGLE-context (see
3093 * hmR0VmxSetupTaggedTlb()) we would need to explicitly flush in this case (add an
3094 * fExplicitFlush = true here and change the pHostCpu->fFlushAsidBeforeUse check below to
3095 * include fExplicitFlush's too) - an obscure corner case.
3096 */
3097 pVCpu->hm.s.fForceTLBFlush = true;
3098 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushTlb);
3099 }
3100
3101 /* Check for TLB flushes while switching to/from a nested-guest. */
3102 if (pVCpu->hm.s.vmx.fSwitchedNstGstFlushTlb)
3103 {
3104 pVCpu->hm.s.fForceTLBFlush = true;
3105 pVCpu->hm.s.vmx.fSwitchedNstGstFlushTlb = false;
3106 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushTlbNstGst);
3107 }
3108
3109 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
3110 pVCpu->hm.s.idLastCpu = pHostCpu->idCpu;
3111 if (pVCpu->hm.s.fForceTLBFlush)
3112 {
3113 ++pHostCpu->uCurrentAsid;
3114 if (pHostCpu->uCurrentAsid >= pVM->hm.s.uMaxAsid)
3115 {
3116 pHostCpu->uCurrentAsid = 1; /* Wraparound to 1; host uses 0 */
3117 pHostCpu->cTlbFlushes++; /* All VCPUs that run on this host CPU must use a new VPID. */
3118 pHostCpu->fFlushAsidBeforeUse = true; /* All VCPUs that run on this host CPU must flush their new VPID before use. */
3119 }
3120
3121 pVCpu->hm.s.fForceTLBFlush = false;
3122 pVCpu->hm.s.cTlbFlushes = pHostCpu->cTlbFlushes;
3123 pVCpu->hm.s.uCurrentAsid = pHostCpu->uCurrentAsid;
3124 if (pHostCpu->fFlushAsidBeforeUse)
3125 {
3126 if (pVM->hm.s.vmx.enmTlbFlushVpid == VMXTLBFLUSHVPID_SINGLE_CONTEXT)
3127 hmR0VmxFlushVpid(pVCpu, VMXTLBFLUSHVPID_SINGLE_CONTEXT, 0 /* GCPtr */);
3128 else if (pVM->hm.s.vmx.enmTlbFlushVpid == VMXTLBFLUSHVPID_ALL_CONTEXTS)
3129 {
3130 hmR0VmxFlushVpid(pVCpu, VMXTLBFLUSHVPID_ALL_CONTEXTS, 0 /* GCPtr */);
3131 pHostCpu->fFlushAsidBeforeUse = false;
3132 }
3133 else
3134 {
3135 /* hmR0VmxSetupTaggedTlb() ensures we never get here. Paranoia. */
3136 AssertMsgFailed(("Unsupported VPID-flush context type.\n"));
3137 }
3138 }
3139 }
3140
3141 AssertMsg(pVCpu->hm.s.cTlbFlushes == pHostCpu->cTlbFlushes,
3142 ("Flush count mismatch for cpu %d (%u vs %u)\n", pHostCpu->idCpu, pVCpu->hm.s.cTlbFlushes, pHostCpu->cTlbFlushes));
3143 AssertMsg(pHostCpu->uCurrentAsid >= 1 && pHostCpu->uCurrentAsid < pVM->hm.s.uMaxAsid,
3144 ("Cpu[%u] uCurrentAsid=%u cTlbFlushes=%u pVCpu->idLastCpu=%u pVCpu->cTlbFlushes=%u\n", pHostCpu->idCpu,
3145 pHostCpu->uCurrentAsid, pHostCpu->cTlbFlushes, pVCpu->hm.s.idLastCpu, pVCpu->hm.s.cTlbFlushes));
3146 AssertMsg(pVCpu->hm.s.uCurrentAsid >= 1 && pVCpu->hm.s.uCurrentAsid < pVM->hm.s.uMaxAsid,
3147 ("Cpu[%u] pVCpu->uCurrentAsid=%u\n", pHostCpu->idCpu, pVCpu->hm.s.uCurrentAsid));
3148
3149 int rc = VMXWriteVmcs16(VMX_VMCS16_VPID, pVCpu->hm.s.uCurrentAsid);
3150 AssertRC(rc);
3151}
3152
3153
3154/**
3155 * Flushes the guest TLB entry based on CPU capabilities.
3156 *
3157 * @param pHostCpu The HM physical-CPU structure.
3158 * @param pVCpu The cross context virtual CPU structure.
3159 * @param pVmcsInfo The VMCS info. object.
3160 *
3161 * @remarks Called with interrupts disabled.
3162 */
3163static void hmR0VmxFlushTaggedTlb(PHMPHYSCPU pHostCpu, PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo)
3164{
3165#ifdef HMVMX_ALWAYS_FLUSH_TLB
3166 VMCPU_FF_SET(pVCpu, VMCPU_FF_TLB_FLUSH);
3167#endif
3168 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
3169 switch (pVM->hm.s.vmx.enmTlbFlushType)
3170 {
3171 case VMXTLBFLUSHTYPE_EPT_VPID: hmR0VmxFlushTaggedTlbBoth(pHostCpu, pVCpu, pVmcsInfo); break;
3172 case VMXTLBFLUSHTYPE_EPT: hmR0VmxFlushTaggedTlbEpt(pHostCpu, pVCpu, pVmcsInfo); break;
3173 case VMXTLBFLUSHTYPE_VPID: hmR0VmxFlushTaggedTlbVpid(pHostCpu, pVCpu); break;
3174 case VMXTLBFLUSHTYPE_NONE: hmR0VmxFlushTaggedTlbNone(pHostCpu, pVCpu); break;
3175 default:
3176 AssertMsgFailed(("Invalid flush-tag function identifier\n"));
3177 break;
3178 }
3179 /* Don't assert that VMCPU_FF_TLB_FLUSH should no longer be pending. It can be set by other EMTs. */
3180}
3181
3182
3183/**
3184 * Sets up the appropriate tagged TLB-flush level and handler for flushing guest
3185 * TLB entries from the host TLB before VM-entry.
3186 *
3187 * @returns VBox status code.
3188 * @param pVM The cross context VM structure.
3189 */
3190static int hmR0VmxSetupTaggedTlb(PVMCC pVM)
3191{
3192 /*
3193 * Determine optimal flush type for nested paging.
3194 * We cannot ignore EPT if no suitable flush-types is supported by the CPU as we've already setup
3195 * unrestricted guest execution (see hmR3InitFinalizeR0()).
3196 */
3197 if (pVM->hm.s.fNestedPaging)
3198 {
3199 if (pVM->hm.s.vmx.Msrs.u64EptVpidCaps & MSR_IA32_VMX_EPT_VPID_CAP_INVEPT)
3200 {
3201 if (pVM->hm.s.vmx.Msrs.u64EptVpidCaps & MSR_IA32_VMX_EPT_VPID_CAP_INVEPT_SINGLE_CONTEXT)
3202 pVM->hm.s.vmx.enmTlbFlushEpt = VMXTLBFLUSHEPT_SINGLE_CONTEXT;
3203 else if (pVM->hm.s.vmx.Msrs.u64EptVpidCaps & MSR_IA32_VMX_EPT_VPID_CAP_INVEPT_ALL_CONTEXTS)
3204 pVM->hm.s.vmx.enmTlbFlushEpt = VMXTLBFLUSHEPT_ALL_CONTEXTS;
3205 else
3206 {
3207 /* Shouldn't happen. EPT is supported but no suitable flush-types supported. */
3208 pVM->hm.s.vmx.enmTlbFlushEpt = VMXTLBFLUSHEPT_NOT_SUPPORTED;
3209 VMCC_GET_CPU_0(pVM)->hm.s.u32HMError = VMX_UFC_EPT_FLUSH_TYPE_UNSUPPORTED;
3210 return VERR_HM_UNSUPPORTED_CPU_FEATURE_COMBO;
3211 }
3212
3213 /* Make sure the write-back cacheable memory type for EPT is supported. */
3214 if (RT_UNLIKELY(!(pVM->hm.s.vmx.Msrs.u64EptVpidCaps & MSR_IA32_VMX_EPT_VPID_CAP_EMT_WB)))
3215 {
3216 pVM->hm.s.vmx.enmTlbFlushEpt = VMXTLBFLUSHEPT_NOT_SUPPORTED;
3217 VMCC_GET_CPU_0(pVM)->hm.s.u32HMError = VMX_UFC_EPT_MEM_TYPE_NOT_WB;
3218 return VERR_HM_UNSUPPORTED_CPU_FEATURE_COMBO;
3219 }
3220
3221 /* EPT requires a page-walk length of 4. */
3222 if (RT_UNLIKELY(!(pVM->hm.s.vmx.Msrs.u64EptVpidCaps & MSR_IA32_VMX_EPT_VPID_CAP_PAGE_WALK_LENGTH_4)))
3223 {
3224 pVM->hm.s.vmx.enmTlbFlushEpt = VMXTLBFLUSHEPT_NOT_SUPPORTED;
3225 VMCC_GET_CPU_0(pVM)->hm.s.u32HMError = VMX_UFC_EPT_PAGE_WALK_LENGTH_UNSUPPORTED;
3226 return VERR_HM_UNSUPPORTED_CPU_FEATURE_COMBO;
3227 }
3228 }
3229 else
3230 {
3231 /* Shouldn't happen. EPT is supported but INVEPT instruction is not supported. */
3232 pVM->hm.s.vmx.enmTlbFlushEpt = VMXTLBFLUSHEPT_NOT_SUPPORTED;
3233 VMCC_GET_CPU_0(pVM)->hm.s.u32HMError = VMX_UFC_EPT_INVEPT_UNAVAILABLE;
3234 return VERR_HM_UNSUPPORTED_CPU_FEATURE_COMBO;
3235 }
3236 }
3237
3238 /*
3239 * Determine optimal flush type for VPID.
3240 */
3241 if (pVM->hm.s.vmx.fVpid)
3242 {
3243 if (pVM->hm.s.vmx.Msrs.u64EptVpidCaps & MSR_IA32_VMX_EPT_VPID_CAP_INVVPID)
3244 {
3245 if (pVM->hm.s.vmx.Msrs.u64EptVpidCaps & MSR_IA32_VMX_EPT_VPID_CAP_INVVPID_SINGLE_CONTEXT)
3246 pVM->hm.s.vmx.enmTlbFlushVpid = VMXTLBFLUSHVPID_SINGLE_CONTEXT;
3247 else if (pVM->hm.s.vmx.Msrs.u64EptVpidCaps & MSR_IA32_VMX_EPT_VPID_CAP_INVVPID_ALL_CONTEXTS)
3248 pVM->hm.s.vmx.enmTlbFlushVpid = VMXTLBFLUSHVPID_ALL_CONTEXTS;
3249 else
3250 {
3251 /* Neither SINGLE nor ALL-context flush types for VPID is supported by the CPU. Ignore VPID capability. */
3252 if (pVM->hm.s.vmx.Msrs.u64EptVpidCaps & MSR_IA32_VMX_EPT_VPID_CAP_INVVPID_INDIV_ADDR)
3253 LogRelFunc(("Only INDIV_ADDR supported. Ignoring VPID.\n"));
3254 if (pVM->hm.s.vmx.Msrs.u64EptVpidCaps & MSR_IA32_VMX_EPT_VPID_CAP_INVVPID_SINGLE_CONTEXT_RETAIN_GLOBALS)
3255 LogRelFunc(("Only SINGLE_CONTEXT_RETAIN_GLOBALS supported. Ignoring VPID.\n"));
3256 pVM->hm.s.vmx.enmTlbFlushVpid = VMXTLBFLUSHVPID_NOT_SUPPORTED;
3257 pVM->hm.s.vmx.fVpid = false;
3258 }
3259 }
3260 else
3261 {
3262 /* Shouldn't happen. VPID is supported but INVVPID is not supported by the CPU. Ignore VPID capability. */
3263 Log4Func(("VPID supported without INVEPT support. Ignoring VPID.\n"));
3264 pVM->hm.s.vmx.enmTlbFlushVpid = VMXTLBFLUSHVPID_NOT_SUPPORTED;
3265 pVM->hm.s.vmx.fVpid = false;
3266 }
3267 }
3268
3269 /*
3270 * Setup the handler for flushing tagged-TLBs.
3271 */
3272 if (pVM->hm.s.fNestedPaging && pVM->hm.s.vmx.fVpid)
3273 pVM->hm.s.vmx.enmTlbFlushType = VMXTLBFLUSHTYPE_EPT_VPID;
3274 else if (pVM->hm.s.fNestedPaging)
3275 pVM->hm.s.vmx.enmTlbFlushType = VMXTLBFLUSHTYPE_EPT;
3276 else if (pVM->hm.s.vmx.fVpid)
3277 pVM->hm.s.vmx.enmTlbFlushType = VMXTLBFLUSHTYPE_VPID;
3278 else
3279 pVM->hm.s.vmx.enmTlbFlushType = VMXTLBFLUSHTYPE_NONE;
3280 return VINF_SUCCESS;
3281}
3282
3283
3284#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
3285/**
3286 * Sets up the shadow VMCS fields arrays.
3287 *
3288 * This function builds arrays of VMCS fields to sync the shadow VMCS later while
3289 * executing the guest.
3290 *
3291 * @returns VBox status code.
3292 * @param pVM The cross context VM structure.
3293 */
3294static int hmR0VmxSetupShadowVmcsFieldsArrays(PVMCC pVM)
3295{
3296 /*
3297 * Paranoia. Ensure we haven't exposed the VMWRITE-All VMX feature to the guest
3298 * when the host does not support it.
3299 */
3300 bool const fGstVmwriteAll = pVM->cpum.ro.GuestFeatures.fVmxVmwriteAll;
3301 if ( !fGstVmwriteAll
3302 || (pVM->hm.s.vmx.Msrs.u64Misc & VMX_MISC_VMWRITE_ALL))
3303 { /* likely. */ }
3304 else
3305 {
3306 LogRelFunc(("VMX VMWRITE-All feature exposed to the guest but host CPU does not support it!\n"));
3307 VMCC_GET_CPU_0(pVM)->hm.s.u32HMError = VMX_UFC_GST_HOST_VMWRITE_ALL;
3308 return VERR_HM_UNSUPPORTED_CPU_FEATURE_COMBO;
3309 }
3310
3311 uint32_t const cVmcsFields = RT_ELEMENTS(g_aVmcsFields);
3312 uint32_t cRwFields = 0;
3313 uint32_t cRoFields = 0;
3314 for (uint32_t i = 0; i < cVmcsFields; i++)
3315 {
3316 VMXVMCSFIELD VmcsField;
3317 VmcsField.u = g_aVmcsFields[i];
3318
3319 /*
3320 * We will be writing "FULL" (64-bit) fields while syncing the shadow VMCS.
3321 * Therefore, "HIGH" (32-bit portion of 64-bit) fields must not be included
3322 * in the shadow VMCS fields array as they would be redundant.
3323 *
3324 * If the VMCS field depends on a CPU feature that is not exposed to the guest,
3325 * we must not include it in the shadow VMCS fields array. Guests attempting to
3326 * VMREAD/VMWRITE such VMCS fields would cause a VM-exit and we shall emulate
3327 * the required behavior.
3328 */
3329 if ( VmcsField.n.fAccessType == VMX_VMCSFIELD_ACCESS_FULL
3330 && CPUMIsGuestVmxVmcsFieldValid(pVM, VmcsField.u))
3331 {
3332 /*
3333 * Read-only fields are placed in a separate array so that while syncing shadow
3334 * VMCS fields later (which is more performance critical) we can avoid branches.
3335 *
3336 * However, if the guest can write to all fields (including read-only fields),
3337 * we treat it a as read/write field. Otherwise, writing to these fields would
3338 * cause a VMWRITE instruction error while syncing the shadow VMCS .
3339 */
3340 if ( fGstVmwriteAll
3341 || !VMXIsVmcsFieldReadOnly(VmcsField.u))
3342 pVM->hm.s.vmx.paShadowVmcsFields[cRwFields++] = VmcsField.u;
3343 else
3344 pVM->hm.s.vmx.paShadowVmcsRoFields[cRoFields++] = VmcsField.u;
3345 }
3346 }
3347
3348 /* Update the counts. */
3349 pVM->hm.s.vmx.cShadowVmcsFields = cRwFields;
3350 pVM->hm.s.vmx.cShadowVmcsRoFields = cRoFields;
3351 return VINF_SUCCESS;
3352}
3353
3354
3355/**
3356 * Sets up the VMREAD and VMWRITE bitmaps.
3357 *
3358 * @param pVM The cross context VM structure.
3359 */
3360static void hmR0VmxSetupVmreadVmwriteBitmaps(PVMCC pVM)
3361{
3362 /*
3363 * By default, ensure guest attempts to acceses to any VMCS fields cause VM-exits.
3364 */
3365 uint32_t const cbBitmap = X86_PAGE_4K_SIZE;
3366 uint8_t *pbVmreadBitmap = (uint8_t *)pVM->hm.s.vmx.pvVmreadBitmap;
3367 uint8_t *pbVmwriteBitmap = (uint8_t *)pVM->hm.s.vmx.pvVmwriteBitmap;
3368 ASMMemFill32(pbVmreadBitmap, cbBitmap, UINT32_C(0xffffffff));
3369 ASMMemFill32(pbVmwriteBitmap, cbBitmap, UINT32_C(0xffffffff));
3370
3371 /*
3372 * Skip intercepting VMREAD/VMWRITE to guest read/write fields in the
3373 * VMREAD and VMWRITE bitmaps.
3374 */
3375 {
3376 uint32_t const *paShadowVmcsFields = pVM->hm.s.vmx.paShadowVmcsFields;
3377 uint32_t const cShadowVmcsFields = pVM->hm.s.vmx.cShadowVmcsFields;
3378 for (uint32_t i = 0; i < cShadowVmcsFields; i++)
3379 {
3380 uint32_t const uVmcsField = paShadowVmcsFields[i];
3381 Assert(!(uVmcsField & VMX_VMCSFIELD_RSVD_MASK));
3382 Assert(uVmcsField >> 3 < cbBitmap);
3383 ASMBitClear(pbVmreadBitmap + (uVmcsField >> 3), uVmcsField & 7);
3384 ASMBitClear(pbVmwriteBitmap + (uVmcsField >> 3), uVmcsField & 7);
3385 }
3386 }
3387
3388 /*
3389 * Skip intercepting VMREAD for guest read-only fields in the VMREAD bitmap
3390 * if the host supports VMWRITE to all supported VMCS fields.
3391 */
3392 if (pVM->hm.s.vmx.Msrs.u64Misc & VMX_MISC_VMWRITE_ALL)
3393 {
3394 uint32_t const *paShadowVmcsRoFields = pVM->hm.s.vmx.paShadowVmcsRoFields;
3395 uint32_t const cShadowVmcsRoFields = pVM->hm.s.vmx.cShadowVmcsRoFields;
3396 for (uint32_t i = 0; i < cShadowVmcsRoFields; i++)
3397 {
3398 uint32_t const uVmcsField = paShadowVmcsRoFields[i];
3399 Assert(!(uVmcsField & VMX_VMCSFIELD_RSVD_MASK));
3400 Assert(uVmcsField >> 3 < cbBitmap);
3401 ASMBitClear(pbVmreadBitmap + (uVmcsField >> 3), uVmcsField & 7);
3402 }
3403 }
3404}
3405#endif /* VBOX_WITH_NESTED_HWVIRT_VMX */
3406
3407
3408/**
3409 * Sets up the virtual-APIC page address for the VMCS.
3410 *
3411 * @param pVmcsInfo The VMCS info. object.
3412 */
3413DECLINLINE(void) hmR0VmxSetupVmcsVirtApicAddr(PCVMXVMCSINFO pVmcsInfo)
3414{
3415 RTHCPHYS const HCPhysVirtApic = pVmcsInfo->HCPhysVirtApic;
3416 Assert(HCPhysVirtApic != NIL_RTHCPHYS);
3417 Assert(!(HCPhysVirtApic & 0xfff)); /* Bits 11:0 MBZ. */
3418 int rc = VMXWriteVmcs64(VMX_VMCS64_CTRL_VIRT_APIC_PAGEADDR_FULL, HCPhysVirtApic);
3419 AssertRC(rc);
3420}
3421
3422
3423/**
3424 * Sets up the MSR-bitmap address for the VMCS.
3425 *
3426 * @param pVmcsInfo The VMCS info. object.
3427 */
3428DECLINLINE(void) hmR0VmxSetupVmcsMsrBitmapAddr(PCVMXVMCSINFO pVmcsInfo)
3429{
3430 RTHCPHYS const HCPhysMsrBitmap = pVmcsInfo->HCPhysMsrBitmap;
3431 Assert(HCPhysMsrBitmap != NIL_RTHCPHYS);
3432 Assert(!(HCPhysMsrBitmap & 0xfff)); /* Bits 11:0 MBZ. */
3433 int rc = VMXWriteVmcs64(VMX_VMCS64_CTRL_MSR_BITMAP_FULL, HCPhysMsrBitmap);
3434 AssertRC(rc);
3435}
3436
3437
3438/**
3439 * Sets up the APIC-access page address for the VMCS.
3440 *
3441 * @param pVCpu The cross context virtual CPU structure.
3442 */
3443DECLINLINE(void) hmR0VmxSetupVmcsApicAccessAddr(PVMCPUCC pVCpu)
3444{
3445 RTHCPHYS const HCPhysApicAccess = pVCpu->CTX_SUFF(pVM)->hm.s.vmx.HCPhysApicAccess;
3446 Assert(HCPhysApicAccess != NIL_RTHCPHYS);
3447 Assert(!(HCPhysApicAccess & 0xfff)); /* Bits 11:0 MBZ. */
3448 int rc = VMXWriteVmcs64(VMX_VMCS64_CTRL_APIC_ACCESSADDR_FULL, HCPhysApicAccess);
3449 AssertRC(rc);
3450}
3451
3452
3453#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
3454/**
3455 * Sets up the VMREAD bitmap address for the VMCS.
3456 *
3457 * @param pVCpu The cross context virtual CPU structure.
3458 */
3459DECLINLINE(void) hmR0VmxSetupVmcsVmreadBitmapAddr(PVMCPUCC pVCpu)
3460{
3461 RTHCPHYS const HCPhysVmreadBitmap = pVCpu->CTX_SUFF(pVM)->hm.s.vmx.HCPhysVmreadBitmap;
3462 Assert(HCPhysVmreadBitmap != NIL_RTHCPHYS);
3463 Assert(!(HCPhysVmreadBitmap & 0xfff)); /* Bits 11:0 MBZ. */
3464 int rc = VMXWriteVmcs64(VMX_VMCS64_CTRL_VMREAD_BITMAP_FULL, HCPhysVmreadBitmap);
3465 AssertRC(rc);
3466}
3467
3468
3469/**
3470 * Sets up the VMWRITE bitmap address for the VMCS.
3471 *
3472 * @param pVCpu The cross context virtual CPU structure.
3473 */
3474DECLINLINE(void) hmR0VmxSetupVmcsVmwriteBitmapAddr(PVMCPUCC pVCpu)
3475{
3476 RTHCPHYS const HCPhysVmwriteBitmap = pVCpu->CTX_SUFF(pVM)->hm.s.vmx.HCPhysVmwriteBitmap;
3477 Assert(HCPhysVmwriteBitmap != NIL_RTHCPHYS);
3478 Assert(!(HCPhysVmwriteBitmap & 0xfff)); /* Bits 11:0 MBZ. */
3479 int rc = VMXWriteVmcs64(VMX_VMCS64_CTRL_VMWRITE_BITMAP_FULL, HCPhysVmwriteBitmap);
3480 AssertRC(rc);
3481}
3482#endif
3483
3484
3485/**
3486 * Sets up the VM-entry MSR load, VM-exit MSR-store and VM-exit MSR-load addresses
3487 * in the VMCS.
3488 *
3489 * @returns VBox status code.
3490 * @param pVmcsInfo The VMCS info. object.
3491 */
3492DECLINLINE(int) hmR0VmxSetupVmcsAutoLoadStoreMsrAddrs(PVMXVMCSINFO pVmcsInfo)
3493{
3494 RTHCPHYS const HCPhysGuestMsrLoad = pVmcsInfo->HCPhysGuestMsrLoad;
3495 Assert(HCPhysGuestMsrLoad != NIL_RTHCPHYS);
3496 Assert(!(HCPhysGuestMsrLoad & 0xf)); /* Bits 3:0 MBZ. */
3497
3498 RTHCPHYS const HCPhysGuestMsrStore = pVmcsInfo->HCPhysGuestMsrStore;
3499 Assert(HCPhysGuestMsrStore != NIL_RTHCPHYS);
3500 Assert(!(HCPhysGuestMsrStore & 0xf)); /* Bits 3:0 MBZ. */
3501
3502 RTHCPHYS const HCPhysHostMsrLoad = pVmcsInfo->HCPhysHostMsrLoad;
3503 Assert(HCPhysHostMsrLoad != NIL_RTHCPHYS);
3504 Assert(!(HCPhysHostMsrLoad & 0xf)); /* Bits 3:0 MBZ. */
3505
3506 int rc = VMXWriteVmcs64(VMX_VMCS64_CTRL_ENTRY_MSR_LOAD_FULL, HCPhysGuestMsrLoad); AssertRC(rc);
3507 rc = VMXWriteVmcs64(VMX_VMCS64_CTRL_EXIT_MSR_STORE_FULL, HCPhysGuestMsrStore); AssertRC(rc);
3508 rc = VMXWriteVmcs64(VMX_VMCS64_CTRL_EXIT_MSR_LOAD_FULL, HCPhysHostMsrLoad); AssertRC(rc);
3509 return VINF_SUCCESS;
3510}
3511
3512
3513/**
3514 * Sets up MSR permissions in the MSR bitmap of a VMCS info. object.
3515 *
3516 * @param pVCpu The cross context virtual CPU structure.
3517 * @param pVmcsInfo The VMCS info. object.
3518 */
3519static void hmR0VmxSetupVmcsMsrPermissions(PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo)
3520{
3521 Assert(pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_USE_MSR_BITMAPS);
3522
3523 /*
3524 * The guest can access the following MSRs (read, write) without causing
3525 * VM-exits; they are loaded/stored automatically using fields in the VMCS.
3526 */
3527 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
3528 hmR0VmxSetMsrPermission(pVCpu, pVmcsInfo, false, MSR_IA32_SYSENTER_CS, VMXMSRPM_ALLOW_RD_WR);
3529 hmR0VmxSetMsrPermission(pVCpu, pVmcsInfo, false, MSR_IA32_SYSENTER_ESP, VMXMSRPM_ALLOW_RD_WR);
3530 hmR0VmxSetMsrPermission(pVCpu, pVmcsInfo, false, MSR_IA32_SYSENTER_EIP, VMXMSRPM_ALLOW_RD_WR);
3531 hmR0VmxSetMsrPermission(pVCpu, pVmcsInfo, false, MSR_K8_GS_BASE, VMXMSRPM_ALLOW_RD_WR);
3532 hmR0VmxSetMsrPermission(pVCpu, pVmcsInfo, false, MSR_K8_FS_BASE, VMXMSRPM_ALLOW_RD_WR);
3533
3534 /*
3535 * The IA32_PRED_CMD and IA32_FLUSH_CMD MSRs are write-only and has no state
3536 * associated with then. We never need to intercept access (writes need to be
3537 * executed without causing a VM-exit, reads will #GP fault anyway).
3538 *
3539 * The IA32_SPEC_CTRL MSR is read/write and has state. We allow the guest to
3540 * read/write them. We swap the the guest/host MSR value using the
3541 * auto-load/store MSR area.
3542 */
3543 if (pVM->cpum.ro.GuestFeatures.fIbpb)
3544 hmR0VmxSetMsrPermission(pVCpu, pVmcsInfo, false, MSR_IA32_PRED_CMD, VMXMSRPM_ALLOW_RD_WR);
3545 if (pVM->cpum.ro.GuestFeatures.fFlushCmd)
3546 hmR0VmxSetMsrPermission(pVCpu, pVmcsInfo, false, MSR_IA32_FLUSH_CMD, VMXMSRPM_ALLOW_RD_WR);
3547 if (pVM->cpum.ro.GuestFeatures.fIbrs)
3548 hmR0VmxSetMsrPermission(pVCpu, pVmcsInfo, false, MSR_IA32_SPEC_CTRL, VMXMSRPM_ALLOW_RD_WR);
3549
3550 /*
3551 * Allow full read/write access for the following MSRs (mandatory for VT-x)
3552 * required for 64-bit guests.
3553 */
3554 if (pVM->hm.s.fAllow64BitGuests)
3555 {
3556 hmR0VmxSetMsrPermission(pVCpu, pVmcsInfo, false, MSR_K8_LSTAR, VMXMSRPM_ALLOW_RD_WR);
3557 hmR0VmxSetMsrPermission(pVCpu, pVmcsInfo, false, MSR_K6_STAR, VMXMSRPM_ALLOW_RD_WR);
3558 hmR0VmxSetMsrPermission(pVCpu, pVmcsInfo, false, MSR_K8_SF_MASK, VMXMSRPM_ALLOW_RD_WR);
3559 hmR0VmxSetMsrPermission(pVCpu, pVmcsInfo, false, MSR_K8_KERNEL_GS_BASE, VMXMSRPM_ALLOW_RD_WR);
3560 }
3561
3562 /*
3563 * IA32_EFER MSR is always intercepted, see @bugref{9180#c37}.
3564 */
3565#ifdef VBOX_STRICT
3566 Assert(pVmcsInfo->pvMsrBitmap);
3567 uint32_t const fMsrpmEfer = CPUMGetVmxMsrPermission(pVmcsInfo->pvMsrBitmap, MSR_K6_EFER);
3568 Assert(fMsrpmEfer == VMXMSRPM_EXIT_RD_WR);
3569#endif
3570}
3571
3572
3573/**
3574 * Sets up pin-based VM-execution controls in the VMCS.
3575 *
3576 * @returns VBox status code.
3577 * @param pVCpu The cross context virtual CPU structure.
3578 * @param pVmcsInfo The VMCS info. object.
3579 */
3580static int hmR0VmxSetupVmcsPinCtls(PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo)
3581{
3582 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
3583 uint32_t fVal = pVM->hm.s.vmx.Msrs.PinCtls.n.allowed0; /* Bits set here must always be set. */
3584 uint32_t const fZap = pVM->hm.s.vmx.Msrs.PinCtls.n.allowed1; /* Bits cleared here must always be cleared. */
3585
3586 fVal |= VMX_PIN_CTLS_EXT_INT_EXIT /* External interrupts cause a VM-exit. */
3587 | VMX_PIN_CTLS_NMI_EXIT; /* Non-maskable interrupts (NMIs) cause a VM-exit. */
3588
3589 if (pVM->hm.s.vmx.Msrs.PinCtls.n.allowed1 & VMX_PIN_CTLS_VIRT_NMI)
3590 fVal |= VMX_PIN_CTLS_VIRT_NMI; /* Use virtual NMIs and virtual-NMI blocking features. */
3591
3592 /* Enable the VMX-preemption timer. */
3593 if (pVM->hm.s.vmx.fUsePreemptTimer)
3594 {
3595 Assert(pVM->hm.s.vmx.Msrs.PinCtls.n.allowed1 & VMX_PIN_CTLS_PREEMPT_TIMER);
3596 fVal |= VMX_PIN_CTLS_PREEMPT_TIMER;
3597 }
3598
3599#if 0
3600 /* Enable posted-interrupt processing. */
3601 if (pVM->hm.s.fPostedIntrs)
3602 {
3603 Assert(pVM->hm.s.vmx.Msrs.PinCtls.n.allowed1 & VMX_PIN_CTLS_POSTED_INT);
3604 Assert(pVM->hm.s.vmx.Msrs.ExitCtls.n.allowed1 & VMX_EXIT_CTLS_ACK_EXT_INT);
3605 fVal |= VMX_PIN_CTLS_POSTED_INT;
3606 }
3607#endif
3608
3609 if ((fVal & fZap) != fVal)
3610 {
3611 LogRelFunc(("Invalid pin-based VM-execution controls combo! Cpu=%#RX32 fVal=%#RX32 fZap=%#RX32\n",
3612 pVM->hm.s.vmx.Msrs.PinCtls.n.allowed0, fVal, fZap));
3613 pVCpu->hm.s.u32HMError = VMX_UFC_CTRL_PIN_EXEC;
3614 return VERR_HM_UNSUPPORTED_CPU_FEATURE_COMBO;
3615 }
3616
3617 /* Commit it to the VMCS and update our cache. */
3618 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PIN_EXEC, fVal);
3619 AssertRC(rc);
3620 pVmcsInfo->u32PinCtls = fVal;
3621
3622 return VINF_SUCCESS;
3623}
3624
3625
3626/**
3627 * Sets up secondary processor-based VM-execution controls in the VMCS.
3628 *
3629 * @returns VBox status code.
3630 * @param pVCpu The cross context virtual CPU structure.
3631 * @param pVmcsInfo The VMCS info. object.
3632 */
3633static int hmR0VmxSetupVmcsProcCtls2(PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo)
3634{
3635 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
3636 uint32_t fVal = pVM->hm.s.vmx.Msrs.ProcCtls2.n.allowed0; /* Bits set here must be set in the VMCS. */
3637 uint32_t const fZap = pVM->hm.s.vmx.Msrs.ProcCtls2.n.allowed1; /* Bits cleared here must be cleared in the VMCS. */
3638
3639 /* WBINVD causes a VM-exit. */
3640 if (pVM->hm.s.vmx.Msrs.ProcCtls2.n.allowed1 & VMX_PROC_CTLS2_WBINVD_EXIT)
3641 fVal |= VMX_PROC_CTLS2_WBINVD_EXIT;
3642
3643 /* Enable EPT (aka nested-paging). */
3644 if (pVM->hm.s.fNestedPaging)
3645 fVal |= VMX_PROC_CTLS2_EPT;
3646
3647 /* Enable the INVPCID instruction if we expose it to the guest and is supported
3648 by the hardware. Without this, guest executing INVPCID would cause a #UD. */
3649 if ( pVM->cpum.ro.GuestFeatures.fInvpcid
3650 && (pVM->hm.s.vmx.Msrs.ProcCtls2.n.allowed1 & VMX_PROC_CTLS2_INVPCID))
3651 fVal |= VMX_PROC_CTLS2_INVPCID;
3652
3653 /* Enable VPID. */
3654 if (pVM->hm.s.vmx.fVpid)
3655 fVal |= VMX_PROC_CTLS2_VPID;
3656
3657 /* Enable unrestricted guest execution. */
3658 if (pVM->hm.s.vmx.fUnrestrictedGuest)
3659 fVal |= VMX_PROC_CTLS2_UNRESTRICTED_GUEST;
3660
3661#if 0
3662 if (pVM->hm.s.fVirtApicRegs)
3663 {
3664 /* Enable APIC-register virtualization. */
3665 Assert(pVM->hm.s.vmx.Msrs.ProcCtls2.n.allowed1 & VMX_PROC_CTLS2_APIC_REG_VIRT);
3666 fVal |= VMX_PROC_CTLS2_APIC_REG_VIRT;
3667
3668 /* Enable virtual-interrupt delivery. */
3669 Assert(pVM->hm.s.vmx.Msrs.ProcCtls2.n.allowed1 & VMX_PROC_CTLS2_VIRT_INTR_DELIVERY);
3670 fVal |= VMX_PROC_CTLS2_VIRT_INTR_DELIVERY;
3671 }
3672#endif
3673
3674 /* Virtualize-APIC accesses if supported by the CPU. The virtual-APIC page is
3675 where the TPR shadow resides. */
3676 /** @todo VIRT_X2APIC support, it's mutually exclusive with this. So must be
3677 * done dynamically. */
3678 if (pVM->hm.s.vmx.Msrs.ProcCtls2.n.allowed1 & VMX_PROC_CTLS2_VIRT_APIC_ACCESS)
3679 {
3680 fVal |= VMX_PROC_CTLS2_VIRT_APIC_ACCESS;
3681 hmR0VmxSetupVmcsApicAccessAddr(pVCpu);
3682 }
3683
3684 /* Enable the RDTSCP instruction if we expose it to the guest and is supported
3685 by the hardware. Without this, guest executing RDTSCP would cause a #UD. */
3686 if ( pVM->cpum.ro.GuestFeatures.fRdTscP
3687 && (pVM->hm.s.vmx.Msrs.ProcCtls2.n.allowed1 & VMX_PROC_CTLS2_RDTSCP))
3688 fVal |= VMX_PROC_CTLS2_RDTSCP;
3689
3690 /* Enable Pause-Loop exiting. */
3691 if ( (pVM->hm.s.vmx.Msrs.ProcCtls2.n.allowed1 & VMX_PROC_CTLS2_PAUSE_LOOP_EXIT)
3692 && pVM->hm.s.vmx.cPleGapTicks
3693 && pVM->hm.s.vmx.cPleWindowTicks)
3694 {
3695 fVal |= VMX_PROC_CTLS2_PAUSE_LOOP_EXIT;
3696
3697 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PLE_GAP, pVM->hm.s.vmx.cPleGapTicks); AssertRC(rc);
3698 rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PLE_WINDOW, pVM->hm.s.vmx.cPleWindowTicks); AssertRC(rc);
3699 }
3700
3701 if ((fVal & fZap) != fVal)
3702 {
3703 LogRelFunc(("Invalid secondary processor-based VM-execution controls combo! cpu=%#RX32 fVal=%#RX32 fZap=%#RX32\n",
3704 pVM->hm.s.vmx.Msrs.ProcCtls2.n.allowed0, fVal, fZap));
3705 pVCpu->hm.s.u32HMError = VMX_UFC_CTRL_PROC_EXEC2;
3706 return VERR_HM_UNSUPPORTED_CPU_FEATURE_COMBO;
3707 }
3708
3709 /* Commit it to the VMCS and update our cache. */
3710 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC2, fVal);
3711 AssertRC(rc);
3712 pVmcsInfo->u32ProcCtls2 = fVal;
3713
3714 return VINF_SUCCESS;
3715}
3716
3717
3718/**
3719 * Sets up processor-based VM-execution controls in the VMCS.
3720 *
3721 * @returns VBox status code.
3722 * @param pVCpu The cross context virtual CPU structure.
3723 * @param pVmcsInfo The VMCS info. object.
3724 */
3725static int hmR0VmxSetupVmcsProcCtls(PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo)
3726{
3727 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
3728
3729 uint32_t fVal = pVM->hm.s.vmx.Msrs.ProcCtls.n.allowed0; /* Bits set here must be set in the VMCS. */
3730 uint32_t const fZap = pVM->hm.s.vmx.Msrs.ProcCtls.n.allowed1; /* Bits cleared here must be cleared in the VMCS. */
3731
3732 fVal |= VMX_PROC_CTLS_HLT_EXIT /* HLT causes a VM-exit. */
3733 | VMX_PROC_CTLS_USE_TSC_OFFSETTING /* Use TSC-offsetting. */
3734 | VMX_PROC_CTLS_MOV_DR_EXIT /* MOV DRx causes a VM-exit. */
3735 | VMX_PROC_CTLS_UNCOND_IO_EXIT /* All IO instructions cause a VM-exit. */
3736 | VMX_PROC_CTLS_RDPMC_EXIT /* RDPMC causes a VM-exit. */
3737 | VMX_PROC_CTLS_MONITOR_EXIT /* MONITOR causes a VM-exit. */
3738 | VMX_PROC_CTLS_MWAIT_EXIT; /* MWAIT causes a VM-exit. */
3739
3740 /* We toggle VMX_PROC_CTLS_MOV_DR_EXIT later, check if it's not -always- needed to be set or clear. */
3741 if ( !(pVM->hm.s.vmx.Msrs.ProcCtls.n.allowed1 & VMX_PROC_CTLS_MOV_DR_EXIT)
3742 || (pVM->hm.s.vmx.Msrs.ProcCtls.n.allowed0 & VMX_PROC_CTLS_MOV_DR_EXIT))
3743 {
3744 pVCpu->hm.s.u32HMError = VMX_UFC_CTRL_PROC_MOV_DRX_EXIT;
3745 return VERR_HM_UNSUPPORTED_CPU_FEATURE_COMBO;
3746 }
3747
3748 /* Without nested paging, INVLPG (also affects INVPCID) and MOV CR3 instructions should cause VM-exits. */
3749 if (!pVM->hm.s.fNestedPaging)
3750 {
3751 Assert(!pVM->hm.s.vmx.fUnrestrictedGuest);
3752 fVal |= VMX_PROC_CTLS_INVLPG_EXIT
3753 | VMX_PROC_CTLS_CR3_LOAD_EXIT
3754 | VMX_PROC_CTLS_CR3_STORE_EXIT;
3755 }
3756
3757 /* Use TPR shadowing if supported by the CPU. */
3758 if ( PDMHasApic(pVM)
3759 && pVM->hm.s.vmx.Msrs.ProcCtls.n.allowed1 & VMX_PROC_CTLS_USE_TPR_SHADOW)
3760 {
3761 fVal |= VMX_PROC_CTLS_USE_TPR_SHADOW; /* CR8 reads from the Virtual-APIC page. */
3762 /* CR8 writes cause a VM-exit based on TPR threshold. */
3763 Assert(!(fVal & VMX_PROC_CTLS_CR8_STORE_EXIT));
3764 Assert(!(fVal & VMX_PROC_CTLS_CR8_LOAD_EXIT));
3765 hmR0VmxSetupVmcsVirtApicAddr(pVmcsInfo);
3766 }
3767 else
3768 {
3769 /* Some 32-bit CPUs do not support CR8 load/store exiting as MOV CR8 is
3770 invalid on 32-bit Intel CPUs. Set this control only for 64-bit guests. */
3771 if (pVM->hm.s.fAllow64BitGuests)
3772 {
3773 fVal |= VMX_PROC_CTLS_CR8_STORE_EXIT /* CR8 reads cause a VM-exit. */
3774 | VMX_PROC_CTLS_CR8_LOAD_EXIT; /* CR8 writes cause a VM-exit. */
3775 }
3776 }
3777
3778 /* Use MSR-bitmaps if supported by the CPU. */
3779 if (pVM->hm.s.vmx.Msrs.ProcCtls.n.allowed1 & VMX_PROC_CTLS_USE_MSR_BITMAPS)
3780 {
3781 fVal |= VMX_PROC_CTLS_USE_MSR_BITMAPS;
3782 hmR0VmxSetupVmcsMsrBitmapAddr(pVmcsInfo);
3783 }
3784
3785 /* Use the secondary processor-based VM-execution controls if supported by the CPU. */
3786 if (pVM->hm.s.vmx.Msrs.ProcCtls.n.allowed1 & VMX_PROC_CTLS_USE_SECONDARY_CTLS)
3787 fVal |= VMX_PROC_CTLS_USE_SECONDARY_CTLS;
3788
3789 if ((fVal & fZap) != fVal)
3790 {
3791 LogRelFunc(("Invalid processor-based VM-execution controls combo! cpu=%#RX32 fVal=%#RX32 fZap=%#RX32\n",
3792 pVM->hm.s.vmx.Msrs.ProcCtls.n.allowed0, fVal, fZap));
3793 pVCpu->hm.s.u32HMError = VMX_UFC_CTRL_PROC_EXEC;
3794 return VERR_HM_UNSUPPORTED_CPU_FEATURE_COMBO;
3795 }
3796
3797 /* Commit it to the VMCS and update our cache. */
3798 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, fVal);
3799 AssertRC(rc);
3800 pVmcsInfo->u32ProcCtls = fVal;
3801
3802 /* Set up MSR permissions that don't change through the lifetime of the VM. */
3803 if (pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_USE_MSR_BITMAPS)
3804 hmR0VmxSetupVmcsMsrPermissions(pVCpu, pVmcsInfo);
3805
3806 /* Set up secondary processor-based VM-execution controls if the CPU supports it. */
3807 if (pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_USE_SECONDARY_CTLS)
3808 return hmR0VmxSetupVmcsProcCtls2(pVCpu, pVmcsInfo);
3809
3810 /* Sanity check, should not really happen. */
3811 if (RT_LIKELY(!pVM->hm.s.vmx.fUnrestrictedGuest))
3812 { /* likely */ }
3813 else
3814 {
3815 pVCpu->hm.s.u32HMError = VMX_UFC_INVALID_UX_COMBO;
3816 return VERR_HM_UNSUPPORTED_CPU_FEATURE_COMBO;
3817 }
3818
3819 /* Old CPUs without secondary processor-based VM-execution controls would end up here. */
3820 return VINF_SUCCESS;
3821}
3822
3823
3824/**
3825 * Sets up miscellaneous (everything other than Pin, Processor and secondary
3826 * Processor-based VM-execution) control fields in the VMCS.
3827 *
3828 * @returns VBox status code.
3829 * @param pVCpu The cross context virtual CPU structure.
3830 * @param pVmcsInfo The VMCS info. object.
3831 */
3832static int hmR0VmxSetupVmcsMiscCtls(PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo)
3833{
3834#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
3835 if (pVCpu->CTX_SUFF(pVM)->hm.s.vmx.fUseVmcsShadowing)
3836 {
3837 hmR0VmxSetupVmcsVmreadBitmapAddr(pVCpu);
3838 hmR0VmxSetupVmcsVmwriteBitmapAddr(pVCpu);
3839 }
3840#endif
3841
3842 Assert(pVmcsInfo->u64VmcsLinkPtr == NIL_RTHCPHYS);
3843 int rc = VMXWriteVmcs64(VMX_VMCS64_GUEST_VMCS_LINK_PTR_FULL, NIL_RTHCPHYS);
3844 AssertRC(rc);
3845
3846 rc = hmR0VmxSetupVmcsAutoLoadStoreMsrAddrs(pVmcsInfo);
3847 if (RT_SUCCESS(rc))
3848 {
3849 uint64_t const u64Cr0Mask = hmR0VmxGetFixedCr0Mask(pVCpu);
3850 uint64_t const u64Cr4Mask = hmR0VmxGetFixedCr4Mask(pVCpu);
3851
3852 rc = VMXWriteVmcsNw(VMX_VMCS_CTRL_CR0_MASK, u64Cr0Mask); AssertRC(rc);
3853 rc = VMXWriteVmcsNw(VMX_VMCS_CTRL_CR4_MASK, u64Cr4Mask); AssertRC(rc);
3854
3855 pVmcsInfo->u64Cr0Mask = u64Cr0Mask;
3856 pVmcsInfo->u64Cr4Mask = u64Cr4Mask;
3857 return VINF_SUCCESS;
3858 }
3859 else
3860 LogRelFunc(("Failed to initialize VMCS auto-load/store MSR addresses. rc=%Rrc\n", rc));
3861 return rc;
3862}
3863
3864
3865/**
3866 * Sets up the initial exception bitmap in the VMCS based on static conditions.
3867 *
3868 * We shall setup those exception intercepts that don't change during the
3869 * lifetime of the VM here. The rest are done dynamically while loading the
3870 * guest state.
3871 *
3872 * @param pVCpu The cross context virtual CPU structure.
3873 * @param pVmcsInfo The VMCS info. object.
3874 */
3875static void hmR0VmxSetupVmcsXcptBitmap(PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo)
3876{
3877 /*
3878 * The following exceptions are always intercepted:
3879 *
3880 * #AC - To prevent the guest from hanging the CPU.
3881 * #DB - To maintain the DR6 state even when intercepting DRx reads/writes and
3882 * recursive #DBs can cause a CPU hang.
3883 * #PF - To sync our shadow page tables when nested-paging is not used.
3884 */
3885 bool const fNestedPaging = pVCpu->CTX_SUFF(pVM)->hm.s.fNestedPaging;
3886 uint32_t const uXcptBitmap = RT_BIT(X86_XCPT_AC)
3887 | RT_BIT(X86_XCPT_DB)
3888 | (fNestedPaging ? 0 : RT_BIT(X86_XCPT_PF));
3889
3890 /* Commit it to the VMCS. */
3891 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_EXCEPTION_BITMAP, uXcptBitmap);
3892 AssertRC(rc);
3893
3894 /* Update our cache of the exception bitmap. */
3895 pVmcsInfo->u32XcptBitmap = uXcptBitmap;
3896}
3897
3898
3899#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
3900/**
3901 * Sets up the VMCS for executing a nested-guest using hardware-assisted VMX.
3902 *
3903 * @returns VBox status code.
3904 * @param pVCpu The cross context virtual CPU structure.
3905 * @param pVmcsInfo The VMCS info. object.
3906 */
3907static int hmR0VmxSetupVmcsCtlsNested(PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo)
3908{
3909 Assert(pVmcsInfo->u64VmcsLinkPtr == NIL_RTHCPHYS);
3910 int rc = VMXWriteVmcs64(VMX_VMCS64_GUEST_VMCS_LINK_PTR_FULL, NIL_RTHCPHYS);
3911 AssertRC(rc);
3912
3913 rc = hmR0VmxSetupVmcsAutoLoadStoreMsrAddrs(pVmcsInfo);
3914 if (RT_SUCCESS(rc))
3915 {
3916 if (pVCpu->CTX_SUFF(pVM)->hm.s.vmx.Msrs.ProcCtls.n.allowed1 & VMX_PROC_CTLS_USE_MSR_BITMAPS)
3917 hmR0VmxSetupVmcsMsrBitmapAddr(pVmcsInfo);
3918 return VINF_SUCCESS;
3919 }
3920 else
3921 LogRelFunc(("Failed to set up the VMCS link pointer in the nested-guest VMCS. rc=%Rrc\n", rc));
3922 return rc;
3923}
3924#endif
3925
3926
3927/**
3928 * Sets up the VMCS for executing a guest (or nested-guest) using hardware-assisted
3929 * VMX.
3930 *
3931 * @returns VBox status code.
3932 * @param pVCpu The cross context virtual CPU structure.
3933 * @param pVmcsInfo The VMCS info. object.
3934 * @param fIsNstGstVmcs Whether this is a nested-guest VMCS.
3935 */
3936static int hmR0VmxSetupVmcs(PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo, bool fIsNstGstVmcs)
3937{
3938 Assert(pVmcsInfo->pvVmcs);
3939 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
3940
3941 /* Set the CPU specified revision identifier at the beginning of the VMCS structure. */
3942 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
3943 *(uint32_t *)pVmcsInfo->pvVmcs = RT_BF_GET(pVM->hm.s.vmx.Msrs.u64Basic, VMX_BF_BASIC_VMCS_ID);
3944 const char * const pszVmcs = fIsNstGstVmcs ? "nested-guest VMCS" : "guest VMCS";
3945
3946 LogFlowFunc(("\n"));
3947
3948 /*
3949 * Initialize the VMCS using VMCLEAR before loading the VMCS.
3950 * See Intel spec. 31.6 "Preparation And Launching A Virtual Machine".
3951 */
3952 int rc = hmR0VmxClearVmcs(pVmcsInfo);
3953 if (RT_SUCCESS(rc))
3954 {
3955 rc = hmR0VmxLoadVmcs(pVmcsInfo);
3956 if (RT_SUCCESS(rc))
3957 {
3958 if (!fIsNstGstVmcs)
3959 {
3960 rc = hmR0VmxSetupVmcsPinCtls(pVCpu, pVmcsInfo);
3961 if (RT_SUCCESS(rc))
3962 {
3963 rc = hmR0VmxSetupVmcsProcCtls(pVCpu, pVmcsInfo);
3964 if (RT_SUCCESS(rc))
3965 {
3966 rc = hmR0VmxSetupVmcsMiscCtls(pVCpu, pVmcsInfo);
3967 if (RT_SUCCESS(rc))
3968 {
3969 hmR0VmxSetupVmcsXcptBitmap(pVCpu, pVmcsInfo);
3970#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
3971 /*
3972 * If a shadow VMCS is allocated for the VMCS info. object, initialize the
3973 * VMCS revision ID and shadow VMCS indicator bit. Also, clear the VMCS
3974 * making it fit for use when VMCS shadowing is later enabled.
3975 */
3976 if (pVmcsInfo->pvShadowVmcs)
3977 {
3978 VMXVMCSREVID VmcsRevId;
3979 VmcsRevId.u = RT_BF_GET(pVM->hm.s.vmx.Msrs.u64Basic, VMX_BF_BASIC_VMCS_ID);
3980 VmcsRevId.n.fIsShadowVmcs = 1;
3981 *(uint32_t *)pVmcsInfo->pvShadowVmcs = VmcsRevId.u;
3982 rc = hmR0VmxClearShadowVmcs(pVmcsInfo);
3983 if (RT_SUCCESS(rc))
3984 { /* likely */ }
3985 else
3986 LogRelFunc(("Failed to initialize shadow VMCS. rc=%Rrc\n", rc));
3987 }
3988#endif
3989 }
3990 else
3991 LogRelFunc(("Failed to setup miscellaneous controls. rc=%Rrc\n", rc));
3992 }
3993 else
3994 LogRelFunc(("Failed to setup processor-based VM-execution controls. rc=%Rrc\n", rc));
3995 }
3996 else
3997 LogRelFunc(("Failed to setup pin-based controls. rc=%Rrc\n", rc));
3998 }
3999 else
4000 {
4001#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
4002 rc = hmR0VmxSetupVmcsCtlsNested(pVCpu, pVmcsInfo);
4003 if (RT_SUCCESS(rc))
4004 { /* likely */ }
4005 else
4006 LogRelFunc(("Failed to initialize nested-guest VMCS. rc=%Rrc\n", rc));
4007#else
4008 AssertFailed();
4009#endif
4010 }
4011 }
4012 else
4013 LogRelFunc(("Failed to load the %s. rc=%Rrc\n", rc, pszVmcs));
4014 }
4015 else
4016 LogRelFunc(("Failed to clear the %s. rc=%Rrc\n", rc, pszVmcs));
4017
4018 /* Sync any CPU internal VMCS data back into our VMCS in memory. */
4019 if (RT_SUCCESS(rc))
4020 {
4021 rc = hmR0VmxClearVmcs(pVmcsInfo);
4022 if (RT_SUCCESS(rc))
4023 { /* likely */ }
4024 else
4025 LogRelFunc(("Failed to clear the %s post setup. rc=%Rrc\n", rc, pszVmcs));
4026 }
4027
4028 /*
4029 * Update the last-error record both for failures and success, so we
4030 * can propagate the status code back to ring-3 for diagnostics.
4031 */
4032 hmR0VmxUpdateErrorRecord(pVCpu, rc);
4033 NOREF(pszVmcs);
4034 return rc;
4035}
4036
4037
4038/**
4039 * Does global VT-x initialization (called during module initialization).
4040 *
4041 * @returns VBox status code.
4042 */
4043VMMR0DECL(int) VMXR0GlobalInit(void)
4044{
4045#ifdef HMVMX_USE_FUNCTION_TABLE
4046 AssertCompile(VMX_EXIT_MAX + 1 == RT_ELEMENTS(g_apfnVMExitHandlers));
4047# ifdef VBOX_STRICT
4048 for (unsigned i = 0; i < RT_ELEMENTS(g_apfnVMExitHandlers); i++)
4049 Assert(g_apfnVMExitHandlers[i]);
4050# endif
4051#endif
4052 return VINF_SUCCESS;
4053}
4054
4055
4056/**
4057 * Does global VT-x termination (called during module termination).
4058 */
4059VMMR0DECL(void) VMXR0GlobalTerm()
4060{
4061 /* Nothing to do currently. */
4062}
4063
4064
4065/**
4066 * Sets up and activates VT-x on the current CPU.
4067 *
4068 * @returns VBox status code.
4069 * @param pHostCpu The HM physical-CPU structure.
4070 * @param pVM The cross context VM structure. Can be
4071 * NULL after a host resume operation.
4072 * @param pvCpuPage Pointer to the VMXON region (can be NULL if @a
4073 * fEnabledByHost is @c true).
4074 * @param HCPhysCpuPage Physical address of the VMXON region (can be 0 if
4075 * @a fEnabledByHost is @c true).
4076 * @param fEnabledByHost Set if SUPR0EnableVTx() or similar was used to
4077 * enable VT-x on the host.
4078 * @param pHwvirtMsrs Pointer to the hardware-virtualization MSRs.
4079 */
4080VMMR0DECL(int) VMXR0EnableCpu(PHMPHYSCPU pHostCpu, PVMCC pVM, void *pvCpuPage, RTHCPHYS HCPhysCpuPage, bool fEnabledByHost,
4081 PCSUPHWVIRTMSRS pHwvirtMsrs)
4082{
4083 AssertPtr(pHostCpu);
4084 AssertPtr(pHwvirtMsrs);
4085 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
4086
4087 /* Enable VT-x if it's not already enabled by the host. */
4088 if (!fEnabledByHost)
4089 {
4090 int rc = hmR0VmxEnterRootMode(pVM, HCPhysCpuPage, pvCpuPage);
4091 if (RT_FAILURE(rc))
4092 return rc;
4093 }
4094
4095 /*
4096 * Flush all EPT tagged-TLB entries (in case VirtualBox or any other hypervisor have been
4097 * using EPTPs) so we don't retain any stale guest-physical mappings which won't get
4098 * invalidated when flushing by VPID.
4099 */
4100 if (pHwvirtMsrs->u.vmx.u64EptVpidCaps & MSR_IA32_VMX_EPT_VPID_CAP_INVEPT_ALL_CONTEXTS)
4101 {
4102 hmR0VmxFlushEpt(NULL /* pVCpu */, NULL /* pVmcsInfo */, VMXTLBFLUSHEPT_ALL_CONTEXTS);
4103 pHostCpu->fFlushAsidBeforeUse = false;
4104 }
4105 else
4106 pHostCpu->fFlushAsidBeforeUse = true;
4107
4108 /* Ensure each VCPU scheduled on this CPU gets a new VPID on resume. See @bugref{6255}. */
4109 ++pHostCpu->cTlbFlushes;
4110
4111 return VINF_SUCCESS;
4112}
4113
4114
4115/**
4116 * Deactivates VT-x on the current CPU.
4117 *
4118 * @returns VBox status code.
4119 * @param pvCpuPage Pointer to the VMXON region.
4120 * @param HCPhysCpuPage Physical address of the VMXON region.
4121 *
4122 * @remarks This function should never be called when SUPR0EnableVTx() or
4123 * similar was used to enable VT-x on the host.
4124 */
4125VMMR0DECL(int) VMXR0DisableCpu(void *pvCpuPage, RTHCPHYS HCPhysCpuPage)
4126{
4127 RT_NOREF2(pvCpuPage, HCPhysCpuPage);
4128
4129 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
4130 return hmR0VmxLeaveRootMode();
4131}
4132
4133
4134/**
4135 * Does per-VM VT-x initialization.
4136 *
4137 * @returns VBox status code.
4138 * @param pVM The cross context VM structure.
4139 */
4140VMMR0DECL(int) VMXR0InitVM(PVMCC pVM)
4141{
4142 AssertPtr(pVM);
4143 LogFlowFunc(("pVM=%p\n", pVM));
4144
4145 int rc = hmR0VmxStructsAlloc(pVM);
4146 if (RT_FAILURE(rc))
4147 {
4148 LogRelFunc(("Failed to allocated VMX structures. rc=%Rrc\n", rc));
4149 return rc;
4150 }
4151
4152 return VINF_SUCCESS;
4153}
4154
4155
4156/**
4157 * Does per-VM VT-x termination.
4158 *
4159 * @returns VBox status code.
4160 * @param pVM The cross context VM structure.
4161 */
4162VMMR0DECL(int) VMXR0TermVM(PVMCC pVM)
4163{
4164 AssertPtr(pVM);
4165 LogFlowFunc(("pVM=%p\n", pVM));
4166
4167#ifdef VBOX_WITH_CRASHDUMP_MAGIC
4168 if (pVM->hm.s.vmx.hMemObjScratch != NIL_RTR0MEMOBJ)
4169 {
4170 Assert(pVM->hm.s.vmx.pvScratch);
4171 ASMMemZero32(pVM->hm.s.vmx.pvScratch, X86_PAGE_4K_SIZE);
4172 }
4173#endif
4174 hmR0VmxStructsFree(pVM);
4175 return VINF_SUCCESS;
4176}
4177
4178
4179/**
4180 * Sets up the VM for execution using hardware-assisted VMX.
4181 * This function is only called once per-VM during initialization.
4182 *
4183 * @returns VBox status code.
4184 * @param pVM The cross context VM structure.
4185 */
4186VMMR0DECL(int) VMXR0SetupVM(PVMCC pVM)
4187{
4188 AssertPtr(pVM);
4189 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
4190
4191 LogFlowFunc(("pVM=%p\n", pVM));
4192
4193 /*
4194 * At least verify if VMX is enabled, since we can't check if we're in
4195 * VMX root mode or not without causing a #GP.
4196 */
4197 RTCCUINTREG const uHostCr4 = ASMGetCR4();
4198 if (RT_LIKELY(uHostCr4 & X86_CR4_VMXE))
4199 { /* likely */ }
4200 else
4201 return VERR_VMX_NOT_IN_VMX_ROOT_MODE;
4202
4203 /*
4204 * Without unrestricted guest execution, pRealModeTSS and pNonPagingModeEPTPageTable *must*
4205 * always be allocated. We no longer support the highly unlikely case of unrestricted guest
4206 * without pRealModeTSS, see hmR3InitFinalizeR0Intel().
4207 */
4208 if ( !pVM->hm.s.vmx.fUnrestrictedGuest
4209 && ( !pVM->hm.s.vmx.pNonPagingModeEPTPageTable
4210 || !pVM->hm.s.vmx.pRealModeTSS))
4211 {
4212 LogRelFunc(("Invalid real-on-v86 state.\n"));
4213 return VERR_INTERNAL_ERROR;
4214 }
4215
4216 /* Initialize these always, see hmR3InitFinalizeR0().*/
4217 pVM->hm.s.vmx.enmTlbFlushEpt = VMXTLBFLUSHEPT_NONE;
4218 pVM->hm.s.vmx.enmTlbFlushVpid = VMXTLBFLUSHVPID_NONE;
4219
4220 /* Setup the tagged-TLB flush handlers. */
4221 int rc = hmR0VmxSetupTaggedTlb(pVM);
4222 if (RT_FAILURE(rc))
4223 {
4224 LogRelFunc(("Failed to setup tagged TLB. rc=%Rrc\n", rc));
4225 return rc;
4226 }
4227
4228#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
4229 /* Setup the shadow VMCS fields array and VMREAD/VMWRITE bitmaps. */
4230 if (pVM->hm.s.vmx.fUseVmcsShadowing)
4231 {
4232 rc = hmR0VmxSetupShadowVmcsFieldsArrays(pVM);
4233 if (RT_SUCCESS(rc))
4234 hmR0VmxSetupVmreadVmwriteBitmaps(pVM);
4235 else
4236 {
4237 LogRelFunc(("Failed to setup shadow VMCS fields arrays. rc=%Rrc\n", rc));
4238 return rc;
4239 }
4240 }
4241#endif
4242
4243 for (VMCPUID idCpu = 0; idCpu < pVM->cCpus; idCpu++)
4244 {
4245 PVMCPUCC pVCpu = VMCC_GET_CPU(pVM, idCpu);
4246 Log4Func(("pVCpu=%p idCpu=%RU32\n", pVCpu, pVCpu->idCpu));
4247
4248 rc = hmR0VmxSetupVmcs(pVCpu, &pVCpu->hm.s.vmx.VmcsInfo, false /* fIsNstGstVmcs */);
4249 if (RT_SUCCESS(rc))
4250 {
4251#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
4252 if (pVM->cpum.ro.GuestFeatures.fVmx)
4253 {
4254 rc = hmR0VmxSetupVmcs(pVCpu, &pVCpu->hm.s.vmx.VmcsInfoNstGst, true /* fIsNstGstVmcs */);
4255 if (RT_SUCCESS(rc))
4256 { /* likely */ }
4257 else
4258 {
4259 LogRelFunc(("Nested-guest VMCS setup failed. rc=%Rrc\n", rc));
4260 return rc;
4261 }
4262 }
4263#endif
4264 }
4265 else
4266 {
4267 LogRelFunc(("VMCS setup failed. rc=%Rrc\n", rc));
4268 return rc;
4269 }
4270 }
4271
4272 return VINF_SUCCESS;
4273}
4274
4275
4276/**
4277 * Saves the host control registers (CR0, CR3, CR4) into the host-state area in
4278 * the VMCS.
4279 */
4280static void hmR0VmxExportHostControlRegs(void)
4281{
4282 int rc = VMXWriteVmcsNw(VMX_VMCS_HOST_CR0, ASMGetCR0()); AssertRC(rc);
4283 rc = VMXWriteVmcsNw(VMX_VMCS_HOST_CR3, ASMGetCR3()); AssertRC(rc);
4284 rc = VMXWriteVmcsNw(VMX_VMCS_HOST_CR4, ASMGetCR4()); AssertRC(rc);
4285}
4286
4287
4288/**
4289 * Saves the host segment registers and GDTR, IDTR, (TR, GS and FS bases) into
4290 * the host-state area in the VMCS.
4291 *
4292 * @returns VBox status code.
4293 * @param pVCpu The cross context virtual CPU structure.
4294 */
4295static int hmR0VmxExportHostSegmentRegs(PVMCPUCC pVCpu)
4296{
4297/**
4298 * Macro for adjusting host segment selectors to satisfy VT-x's VM-entry
4299 * requirements. See hmR0VmxExportHostSegmentRegs().
4300 */
4301#define VMXLOCAL_ADJUST_HOST_SEG(a_Seg, a_selValue) \
4302 if ((a_selValue) & (X86_SEL_RPL | X86_SEL_LDT)) \
4303 { \
4304 bool fValidSelector = true; \
4305 if ((a_selValue) & X86_SEL_LDT) \
4306 { \
4307 uint32_t const uAttr = ASMGetSegAttr(a_selValue); \
4308 fValidSelector = RT_BOOL(uAttr != UINT32_MAX && (uAttr & X86_DESC_P)); \
4309 } \
4310 if (fValidSelector) \
4311 { \
4312 pVCpu->hm.s.vmx.fRestoreHostFlags |= VMX_RESTORE_HOST_SEL_##a_Seg; \
4313 pVCpu->hm.s.vmx.RestoreHost.uHostSel##a_Seg = (a_selValue); \
4314 } \
4315 (a_selValue) = 0; \
4316 }
4317
4318 /*
4319 * If we've executed guest code using hardware-assisted VMX, the host-state bits
4320 * will be messed up. We should -not- save the messed up state without restoring
4321 * the original host-state, see @bugref{7240}.
4322 *
4323 * This apparently can happen (most likely the FPU changes), deal with it rather than
4324 * asserting. Was observed booting Solaris 10u10 32-bit guest.
4325 */
4326 if ( (pVCpu->hm.s.vmx.fRestoreHostFlags & VMX_RESTORE_HOST_REQUIRED)
4327 && (pVCpu->hm.s.vmx.fRestoreHostFlags & ~VMX_RESTORE_HOST_REQUIRED))
4328 {
4329 Log4Func(("Restoring Host State: fRestoreHostFlags=%#RX32 HostCpuId=%u\n", pVCpu->hm.s.vmx.fRestoreHostFlags,
4330 pVCpu->idCpu));
4331 VMXRestoreHostState(pVCpu->hm.s.vmx.fRestoreHostFlags, &pVCpu->hm.s.vmx.RestoreHost);
4332 }
4333 pVCpu->hm.s.vmx.fRestoreHostFlags = 0;
4334
4335 /*
4336 * Host segment registers.
4337 */
4338 RTSEL uSelES = ASMGetES();
4339 RTSEL uSelCS = ASMGetCS();
4340 RTSEL uSelSS = ASMGetSS();
4341 RTSEL uSelDS = ASMGetDS();
4342 RTSEL uSelFS = ASMGetFS();
4343 RTSEL uSelGS = ASMGetGS();
4344 RTSEL uSelTR = ASMGetTR();
4345
4346 /*
4347 * Determine if the host segment registers are suitable for VT-x. Otherwise use zero to
4348 * gain VM-entry and restore them before we get preempted.
4349 *
4350 * See Intel spec. 26.2.3 "Checks on Host Segment and Descriptor-Table Registers".
4351 */
4352 VMXLOCAL_ADJUST_HOST_SEG(DS, uSelDS);
4353 VMXLOCAL_ADJUST_HOST_SEG(ES, uSelES);
4354 VMXLOCAL_ADJUST_HOST_SEG(FS, uSelFS);
4355 VMXLOCAL_ADJUST_HOST_SEG(GS, uSelGS);
4356
4357 /* Verification based on Intel spec. 26.2.3 "Checks on Host Segment and Descriptor-Table Registers" */
4358 Assert(!(uSelCS & X86_SEL_RPL)); Assert(!(uSelCS & X86_SEL_LDT));
4359 Assert(!(uSelSS & X86_SEL_RPL)); Assert(!(uSelSS & X86_SEL_LDT));
4360 Assert(!(uSelDS & X86_SEL_RPL)); Assert(!(uSelDS & X86_SEL_LDT));
4361 Assert(!(uSelES & X86_SEL_RPL)); Assert(!(uSelES & X86_SEL_LDT));
4362 Assert(!(uSelFS & X86_SEL_RPL)); Assert(!(uSelFS & X86_SEL_LDT));
4363 Assert(!(uSelGS & X86_SEL_RPL)); Assert(!(uSelGS & X86_SEL_LDT));
4364 Assert(!(uSelTR & X86_SEL_RPL)); Assert(!(uSelTR & X86_SEL_LDT));
4365 Assert(uSelCS);
4366 Assert(uSelTR);
4367
4368 /* Write these host selector fields into the host-state area in the VMCS. */
4369 int rc = VMXWriteVmcs16(VMX_VMCS16_HOST_CS_SEL, uSelCS); AssertRC(rc);
4370 rc = VMXWriteVmcs16(VMX_VMCS16_HOST_SS_SEL, uSelSS); AssertRC(rc);
4371 rc = VMXWriteVmcs16(VMX_VMCS16_HOST_DS_SEL, uSelDS); AssertRC(rc);
4372 rc = VMXWriteVmcs16(VMX_VMCS16_HOST_ES_SEL, uSelES); AssertRC(rc);
4373 rc = VMXWriteVmcs16(VMX_VMCS16_HOST_FS_SEL, uSelFS); AssertRC(rc);
4374 rc = VMXWriteVmcs16(VMX_VMCS16_HOST_GS_SEL, uSelGS); AssertRC(rc);
4375 rc = VMXWriteVmcs16(VMX_VMCS16_HOST_TR_SEL, uSelTR); AssertRC(rc);
4376
4377 /*
4378 * Host GDTR and IDTR.
4379 */
4380 RTGDTR Gdtr;
4381 RTIDTR Idtr;
4382 RT_ZERO(Gdtr);
4383 RT_ZERO(Idtr);
4384 ASMGetGDTR(&Gdtr);
4385 ASMGetIDTR(&Idtr);
4386 rc = VMXWriteVmcsNw(VMX_VMCS_HOST_GDTR_BASE, Gdtr.pGdt); AssertRC(rc);
4387 rc = VMXWriteVmcsNw(VMX_VMCS_HOST_IDTR_BASE, Idtr.pIdt); AssertRC(rc);
4388
4389 /*
4390 * Determine if we need to manually need to restore the GDTR and IDTR limits as VT-x zaps
4391 * them to the maximum limit (0xffff) on every VM-exit.
4392 */
4393 if (Gdtr.cbGdt != 0xffff)
4394 pVCpu->hm.s.vmx.fRestoreHostFlags |= VMX_RESTORE_HOST_GDTR;
4395
4396 /*
4397 * IDT limit is effectively capped at 0xfff. (See Intel spec. 6.14.1 "64-Bit Mode IDT" and
4398 * Intel spec. 6.2 "Exception and Interrupt Vectors".) Therefore if the host has the limit
4399 * as 0xfff, VT-x bloating the limit to 0xffff shouldn't cause any different CPU behavior.
4400 * However, several hosts either insists on 0xfff being the limit (Windows Patch Guard) or
4401 * uses the limit for other purposes (darwin puts the CPU ID in there but botches sidt
4402 * alignment in at least one consumer). So, we're only allowing the IDTR.LIMIT to be left
4403 * at 0xffff on hosts where we are sure it won't cause trouble.
4404 */
4405#if defined(RT_OS_LINUX) || defined(RT_OS_SOLARIS)
4406 if (Idtr.cbIdt < 0x0fff)
4407#else
4408 if (Idtr.cbIdt != 0xffff)
4409#endif
4410 {
4411 pVCpu->hm.s.vmx.fRestoreHostFlags |= VMX_RESTORE_HOST_IDTR;
4412 AssertCompile(sizeof(Idtr) == sizeof(X86XDTR64));
4413 memcpy(&pVCpu->hm.s.vmx.RestoreHost.HostIdtr, &Idtr, sizeof(X86XDTR64));
4414 }
4415
4416 /*
4417 * Host TR base. Verify that TR selector doesn't point past the GDT. Masking off the TI
4418 * and RPL bits is effectively what the CPU does for "scaling by 8". TI is always 0 and
4419 * RPL should be too in most cases.
4420 */
4421 AssertMsgReturn((uSelTR | X86_SEL_RPL_LDT) <= Gdtr.cbGdt,
4422 ("TR selector exceeds limit. TR=%RTsel cbGdt=%#x\n", uSelTR, Gdtr.cbGdt), VERR_VMX_INVALID_HOST_STATE);
4423
4424 PCX86DESCHC pDesc = (PCX86DESCHC)(Gdtr.pGdt + (uSelTR & X86_SEL_MASK));
4425 uintptr_t const uTRBase = X86DESC64_BASE(pDesc);
4426
4427 /*
4428 * VT-x unconditionally restores the TR limit to 0x67 and type to 11 (32-bit busy TSS) on
4429 * all VM-exits. The type is the same for 64-bit busy TSS[1]. The limit needs manual
4430 * restoration if the host has something else. Task switching is not supported in 64-bit
4431 * mode[2], but the limit still matters as IOPM is supported in 64-bit mode. Restoring the
4432 * limit lazily while returning to ring-3 is safe because IOPM is not applicable in ring-0.
4433 *
4434 * [1] See Intel spec. 3.5 "System Descriptor Types".
4435 * [2] See Intel spec. 7.2.3 "TSS Descriptor in 64-bit mode".
4436 */
4437 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
4438 Assert(pDesc->System.u4Type == 11);
4439 if ( pDesc->System.u16LimitLow != 0x67
4440 || pDesc->System.u4LimitHigh)
4441 {
4442 pVCpu->hm.s.vmx.fRestoreHostFlags |= VMX_RESTORE_HOST_SEL_TR;
4443 /* If the host has made GDT read-only, we would need to temporarily toggle CR0.WP before writing the GDT. */
4444 if (pVM->hm.s.fHostKernelFeatures & SUPKERNELFEATURES_GDT_READ_ONLY)
4445 pVCpu->hm.s.vmx.fRestoreHostFlags |= VMX_RESTORE_HOST_GDT_READ_ONLY;
4446 pVCpu->hm.s.vmx.RestoreHost.uHostSelTR = uSelTR;
4447 }
4448
4449 /*
4450 * Store the GDTR as we need it when restoring the GDT and while restoring the TR.
4451 */
4452 if (pVCpu->hm.s.vmx.fRestoreHostFlags & (VMX_RESTORE_HOST_GDTR | VMX_RESTORE_HOST_SEL_TR))
4453 {
4454 AssertCompile(sizeof(Gdtr) == sizeof(X86XDTR64));
4455 memcpy(&pVCpu->hm.s.vmx.RestoreHost.HostGdtr, &Gdtr, sizeof(X86XDTR64));
4456 if (pVM->hm.s.fHostKernelFeatures & SUPKERNELFEATURES_GDT_NEED_WRITABLE)
4457 {
4458 /* The GDT is read-only but the writable GDT is available. */
4459 pVCpu->hm.s.vmx.fRestoreHostFlags |= VMX_RESTORE_HOST_GDT_NEED_WRITABLE;
4460 pVCpu->hm.s.vmx.RestoreHost.HostGdtrRw.cb = Gdtr.cbGdt;
4461 rc = SUPR0GetCurrentGdtRw(&pVCpu->hm.s.vmx.RestoreHost.HostGdtrRw.uAddr);
4462 AssertRCReturn(rc, rc);
4463 }
4464 }
4465
4466 rc = VMXWriteVmcsNw(VMX_VMCS_HOST_TR_BASE, uTRBase);
4467 AssertRC(rc);
4468
4469 /*
4470 * Host FS base and GS base.
4471 */
4472 uint64_t const u64FSBase = ASMRdMsr(MSR_K8_FS_BASE);
4473 uint64_t const u64GSBase = ASMRdMsr(MSR_K8_GS_BASE);
4474 rc = VMXWriteVmcsNw(VMX_VMCS_HOST_FS_BASE, u64FSBase); AssertRC(rc);
4475 rc = VMXWriteVmcsNw(VMX_VMCS_HOST_GS_BASE, u64GSBase); AssertRC(rc);
4476
4477 /* Store the base if we have to restore FS or GS manually as we need to restore the base as well. */
4478 if (pVCpu->hm.s.vmx.fRestoreHostFlags & VMX_RESTORE_HOST_SEL_FS)
4479 pVCpu->hm.s.vmx.RestoreHost.uHostFSBase = u64FSBase;
4480 if (pVCpu->hm.s.vmx.fRestoreHostFlags & VMX_RESTORE_HOST_SEL_GS)
4481 pVCpu->hm.s.vmx.RestoreHost.uHostGSBase = u64GSBase;
4482
4483 return VINF_SUCCESS;
4484#undef VMXLOCAL_ADJUST_HOST_SEG
4485}
4486
4487
4488/**
4489 * Exports certain host MSRs in the VM-exit MSR-load area and some in the
4490 * host-state area of the VMCS.
4491 *
4492 * These MSRs will be automatically restored on the host after every successful
4493 * VM-exit.
4494 *
4495 * @param pVCpu The cross context virtual CPU structure.
4496 *
4497 * @remarks No-long-jump zone!!!
4498 */
4499static void hmR0VmxExportHostMsrs(PVMCPUCC pVCpu)
4500{
4501 AssertPtr(pVCpu);
4502
4503 /*
4504 * Save MSRs that we restore lazily (due to preemption or transition to ring-3)
4505 * rather than swapping them on every VM-entry.
4506 */
4507 hmR0VmxLazySaveHostMsrs(pVCpu);
4508
4509 /*
4510 * Host Sysenter MSRs.
4511 */
4512 int rc = VMXWriteVmcs32(VMX_VMCS32_HOST_SYSENTER_CS, ASMRdMsr_Low(MSR_IA32_SYSENTER_CS)); AssertRC(rc);
4513 rc = VMXWriteVmcsNw(VMX_VMCS_HOST_SYSENTER_ESP, ASMRdMsr(MSR_IA32_SYSENTER_ESP)); AssertRC(rc);
4514 rc = VMXWriteVmcsNw(VMX_VMCS_HOST_SYSENTER_EIP, ASMRdMsr(MSR_IA32_SYSENTER_EIP)); AssertRC(rc);
4515
4516 /*
4517 * Host EFER MSR.
4518 *
4519 * If the CPU supports the newer VMCS controls for managing EFER, use it. Otherwise it's
4520 * done as part of auto-load/store MSR area in the VMCS, see hmR0VmxExportGuestMsrs().
4521 */
4522 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
4523 if (pVM->hm.s.vmx.fSupportsVmcsEfer)
4524 {
4525 rc = VMXWriteVmcs64(VMX_VMCS64_HOST_EFER_FULL, pVM->hm.s.vmx.u64HostMsrEfer);
4526 AssertRC(rc);
4527 }
4528
4529 /** @todo IA32_PERF_GLOBALCTRL, IA32_PAT also see
4530 * hmR0VmxExportGuestEntryExitCtls(). */
4531}
4532
4533
4534/**
4535 * Figures out if we need to swap the EFER MSR which is particularly expensive.
4536 *
4537 * We check all relevant bits. For now, that's everything besides LMA/LME, as
4538 * these two bits are handled by VM-entry, see hmR0VMxExportGuestEntryExitCtls().
4539 *
4540 * @returns true if we need to load guest EFER, false otherwise.
4541 * @param pVCpu The cross context virtual CPU structure.
4542 *
4543 * @remarks Requires EFER, CR4.
4544 * @remarks No-long-jump zone!!!
4545 */
4546static bool hmR0VmxShouldSwapEferMsr(PCVMCPUCC pVCpu)
4547{
4548#ifdef HMVMX_ALWAYS_SWAP_EFER
4549 RT_NOREF(pVCpu);
4550 return true;
4551#else
4552 PCCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
4553 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
4554 uint64_t const u64HostEfer = pVM->hm.s.vmx.u64HostMsrEfer;
4555 uint64_t const u64GuestEfer = pCtx->msrEFER;
4556
4557 /*
4558 * For 64-bit guests, if EFER.SCE bit differs, we need to swap the EFER MSR
4559 * to ensure that the guest's SYSCALL behaviour isn't broken, see @bugref{7386}.
4560 */
4561 if ( CPUMIsGuestInLongModeEx(pCtx)
4562 && (u64GuestEfer & MSR_K6_EFER_SCE) != (u64HostEfer & MSR_K6_EFER_SCE))
4563 return true;
4564
4565 /*
4566 * If the guest uses PAE and EFER.NXE bit differs, we need to swap the EFER MSR
4567 * as it affects guest paging. 64-bit paging implies CR4.PAE as well.
4568 *
4569 * See Intel spec. 4.5 "IA-32e Paging".
4570 * See Intel spec. 4.1.1 "Three Paging Modes".
4571 *
4572 * Verify that we always intercept CR4.PAE and CR0.PG bits, so we don't need to
4573 * import CR4 and CR0 from the VMCS here as those bits are always up to date.
4574 */
4575 Assert(hmR0VmxGetFixedCr4Mask(pVCpu) & X86_CR4_PAE);
4576 Assert(hmR0VmxGetFixedCr0Mask(pVCpu) & X86_CR0_PG);
4577 if ( (pCtx->cr4 & X86_CR4_PAE)
4578 && (pCtx->cr0 & X86_CR0_PG)
4579 && (u64GuestEfer & MSR_K6_EFER_NXE) != (u64HostEfer & MSR_K6_EFER_NXE))
4580 {
4581 /* Assert that host is NX capable. */
4582 Assert(pVCpu->CTX_SUFF(pVM)->cpum.ro.HostFeatures.fNoExecute);
4583 return true;
4584 }
4585
4586 return false;
4587#endif
4588}
4589
4590/**
4591 * Exports the guest state with appropriate VM-entry and VM-exit controls in the
4592 * VMCS.
4593 *
4594 * This is typically required when the guest changes paging mode.
4595 *
4596 * @returns VBox status code.
4597 * @param pVCpu The cross context virtual CPU structure.
4598 * @param pVmxTransient The VMX-transient structure.
4599 *
4600 * @remarks Requires EFER.
4601 * @remarks No-long-jump zone!!!
4602 */
4603static int hmR0VmxExportGuestEntryExitCtls(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
4604{
4605 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_VMX_ENTRY_EXIT_CTLS)
4606 {
4607 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
4608 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
4609
4610 /*
4611 * VM-entry controls.
4612 */
4613 {
4614 uint32_t fVal = pVM->hm.s.vmx.Msrs.EntryCtls.n.allowed0; /* Bits set here must be set in the VMCS. */
4615 uint32_t const fZap = pVM->hm.s.vmx.Msrs.EntryCtls.n.allowed1; /* Bits cleared here must be cleared in the VMCS. */
4616
4617 /*
4618 * Load the guest debug controls (DR7 and IA32_DEBUGCTL MSR) on VM-entry.
4619 * The first VT-x capable CPUs only supported the 1-setting of this bit.
4620 *
4621 * For nested-guests, this is a mandatory VM-entry control. It's also
4622 * required because we do not want to leak host bits to the nested-guest.
4623 */
4624 fVal |= VMX_ENTRY_CTLS_LOAD_DEBUG;
4625
4626 /*
4627 * Set if the guest is in long mode. This will set/clear the EFER.LMA bit on VM-entry.
4628 *
4629 * For nested-guests, the "IA-32e mode guest" control we initialize with what is
4630 * required to get the nested-guest working with hardware-assisted VMX execution.
4631 * It depends on the nested-guest's IA32_EFER.LMA bit. Remember, a guest hypervisor
4632 * can skip intercepting changes to the EFER MSR. This is why it it needs to be done
4633 * here rather than while merging the guest VMCS controls.
4634 */
4635 if (CPUMIsGuestInLongModeEx(&pVCpu->cpum.GstCtx))
4636 fVal |= VMX_ENTRY_CTLS_IA32E_MODE_GUEST;
4637 else
4638 Assert(!(fVal & VMX_ENTRY_CTLS_IA32E_MODE_GUEST));
4639
4640 /*
4641 * If the CPU supports the newer VMCS controls for managing guest/host EFER, use it.
4642 *
4643 * For nested-guests, we use the "load IA32_EFER" if the hardware supports it,
4644 * regardless of whether the nested-guest VMCS specifies it because we are free to
4645 * load whatever MSRs we require and we do not need to modify the guest visible copy
4646 * of the VM-entry MSR load area.
4647 */
4648 if ( pVM->hm.s.vmx.fSupportsVmcsEfer
4649 && hmR0VmxShouldSwapEferMsr(pVCpu))
4650 fVal |= VMX_ENTRY_CTLS_LOAD_EFER_MSR;
4651 else
4652 Assert(!(fVal & VMX_ENTRY_CTLS_LOAD_EFER_MSR));
4653
4654 /*
4655 * The following should -not- be set (since we're not in SMM mode):
4656 * - VMX_ENTRY_CTLS_ENTRY_TO_SMM
4657 * - VMX_ENTRY_CTLS_DEACTIVATE_DUAL_MON
4658 */
4659
4660 /** @todo VMX_ENTRY_CTLS_LOAD_PERF_MSR,
4661 * VMX_ENTRY_CTLS_LOAD_PAT_MSR. */
4662
4663 if ((fVal & fZap) == fVal)
4664 { /* likely */ }
4665 else
4666 {
4667 Log4Func(("Invalid VM-entry controls combo! Cpu=%#RX32 fVal=%#RX32 fZap=%#RX32\n",
4668 pVM->hm.s.vmx.Msrs.EntryCtls.n.allowed0, fVal, fZap));
4669 pVCpu->hm.s.u32HMError = VMX_UFC_CTRL_ENTRY;
4670 return VERR_HM_UNSUPPORTED_CPU_FEATURE_COMBO;
4671 }
4672
4673 /* Commit it to the VMCS. */
4674 if (pVmcsInfo->u32EntryCtls != fVal)
4675 {
4676 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_ENTRY, fVal);
4677 AssertRC(rc);
4678 pVmcsInfo->u32EntryCtls = fVal;
4679 }
4680 }
4681
4682 /*
4683 * VM-exit controls.
4684 */
4685 {
4686 uint32_t fVal = pVM->hm.s.vmx.Msrs.ExitCtls.n.allowed0; /* Bits set here must be set in the VMCS. */
4687 uint32_t const fZap = pVM->hm.s.vmx.Msrs.ExitCtls.n.allowed1; /* Bits cleared here must be cleared in the VMCS. */
4688
4689 /*
4690 * Save debug controls (DR7 & IA32_DEBUGCTL_MSR). The first VT-x CPUs only
4691 * supported the 1-setting of this bit.
4692 *
4693 * For nested-guests, we set the "save debug controls" as the converse
4694 * "load debug controls" is mandatory for nested-guests anyway.
4695 */
4696 fVal |= VMX_EXIT_CTLS_SAVE_DEBUG;
4697
4698 /*
4699 * Set the host long mode active (EFER.LMA) bit (which Intel calls
4700 * "Host address-space size") if necessary. On VM-exit, VT-x sets both the
4701 * host EFER.LMA and EFER.LME bit to this value. See assertion in
4702 * hmR0VmxExportHostMsrs().
4703 *
4704 * For nested-guests, we always set this bit as we do not support 32-bit
4705 * hosts.
4706 */
4707 fVal |= VMX_EXIT_CTLS_HOST_ADDR_SPACE_SIZE;
4708
4709 /*
4710 * If the VMCS EFER MSR fields are supported by the hardware, we use it.
4711 *
4712 * For nested-guests, we should use the "save IA32_EFER" control if we also
4713 * used the "load IA32_EFER" control while exporting VM-entry controls.
4714 */
4715 if ( pVM->hm.s.vmx.fSupportsVmcsEfer
4716 && hmR0VmxShouldSwapEferMsr(pVCpu))
4717 {
4718 fVal |= VMX_EXIT_CTLS_SAVE_EFER_MSR
4719 | VMX_EXIT_CTLS_LOAD_EFER_MSR;
4720 }
4721
4722 /*
4723 * Enable saving of the VMX-preemption timer value on VM-exit.
4724 * For nested-guests, currently not exposed/used.
4725 */
4726 if ( pVM->hm.s.vmx.fUsePreemptTimer
4727 && (pVM->hm.s.vmx.Msrs.ExitCtls.n.allowed1 & VMX_EXIT_CTLS_SAVE_PREEMPT_TIMER))
4728 fVal |= VMX_EXIT_CTLS_SAVE_PREEMPT_TIMER;
4729
4730 /* Don't acknowledge external interrupts on VM-exit. We want to let the host do that. */
4731 Assert(!(fVal & VMX_EXIT_CTLS_ACK_EXT_INT));
4732
4733 /** @todo VMX_EXIT_CTLS_LOAD_PERF_MSR,
4734 * VMX_EXIT_CTLS_SAVE_PAT_MSR,
4735 * VMX_EXIT_CTLS_LOAD_PAT_MSR. */
4736
4737 if ((fVal & fZap) == fVal)
4738 { /* likely */ }
4739 else
4740 {
4741 Log4Func(("Invalid VM-exit controls combo! cpu=%#RX32 fVal=%#RX32 fZap=%R#X32\n",
4742 pVM->hm.s.vmx.Msrs.ExitCtls.n.allowed0, fVal, fZap));
4743 pVCpu->hm.s.u32HMError = VMX_UFC_CTRL_EXIT;
4744 return VERR_HM_UNSUPPORTED_CPU_FEATURE_COMBO;
4745 }
4746
4747 /* Commit it to the VMCS. */
4748 if (pVmcsInfo->u32ExitCtls != fVal)
4749 {
4750 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_EXIT, fVal);
4751 AssertRC(rc);
4752 pVmcsInfo->u32ExitCtls = fVal;
4753 }
4754 }
4755
4756 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_VMX_ENTRY_EXIT_CTLS);
4757 }
4758 return VINF_SUCCESS;
4759}
4760
4761
4762/**
4763 * Sets the TPR threshold in the VMCS.
4764 *
4765 * @param pVmcsInfo The VMCS info. object.
4766 * @param u32TprThreshold The TPR threshold (task-priority class only).
4767 */
4768DECLINLINE(void) hmR0VmxApicSetTprThreshold(PVMXVMCSINFO pVmcsInfo, uint32_t u32TprThreshold)
4769{
4770 Assert(!(u32TprThreshold & ~VMX_TPR_THRESHOLD_MASK)); /* Bits 31:4 MBZ. */
4771 Assert(pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_USE_TPR_SHADOW);
4772 RT_NOREF(pVmcsInfo);
4773 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_TPR_THRESHOLD, u32TprThreshold);
4774 AssertRC(rc);
4775}
4776
4777
4778/**
4779 * Exports the guest APIC TPR state into the VMCS.
4780 *
4781 * @returns VBox status code.
4782 * @param pVCpu The cross context virtual CPU structure.
4783 * @param pVmxTransient The VMX-transient structure.
4784 *
4785 * @remarks No-long-jump zone!!!
4786 */
4787static int hmR0VmxExportGuestApicTpr(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
4788{
4789 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_APIC_TPR)
4790 {
4791 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_APIC_TPR);
4792
4793 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
4794 if (!pVmxTransient->fIsNestedGuest)
4795 {
4796 if ( PDMHasApic(pVCpu->CTX_SUFF(pVM))
4797 && APICIsEnabled(pVCpu))
4798 {
4799 /*
4800 * Setup TPR shadowing.
4801 */
4802 if (pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_USE_TPR_SHADOW)
4803 {
4804 bool fPendingIntr = false;
4805 uint8_t u8Tpr = 0;
4806 uint8_t u8PendingIntr = 0;
4807 int rc = APICGetTpr(pVCpu, &u8Tpr, &fPendingIntr, &u8PendingIntr);
4808 AssertRCReturn(rc, rc);
4809
4810 /*
4811 * If there are interrupts pending but masked by the TPR, instruct VT-x to
4812 * cause a TPR-below-threshold VM-exit when the guest lowers its TPR below the
4813 * priority of the pending interrupt so we can deliver the interrupt. If there
4814 * are no interrupts pending, set threshold to 0 to not cause any
4815 * TPR-below-threshold VM-exits.
4816 */
4817 uint32_t u32TprThreshold = 0;
4818 if (fPendingIntr)
4819 {
4820 /* Bits 3:0 of the TPR threshold field correspond to bits 7:4 of the TPR
4821 (which is the Task-Priority Class). */
4822 const uint8_t u8PendingPriority = u8PendingIntr >> 4;
4823 const uint8_t u8TprPriority = u8Tpr >> 4;
4824 if (u8PendingPriority <= u8TprPriority)
4825 u32TprThreshold = u8PendingPriority;
4826 }
4827
4828 hmR0VmxApicSetTprThreshold(pVmcsInfo, u32TprThreshold);
4829 }
4830 }
4831 }
4832 /* else: the TPR threshold has already been updated while merging the nested-guest VMCS. */
4833 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_APIC_TPR);
4834 }
4835 return VINF_SUCCESS;
4836}
4837
4838
4839/**
4840 * Gets the guest interruptibility-state.
4841 *
4842 * @returns Guest's interruptibility-state.
4843 * @param pVCpu The cross context virtual CPU structure.
4844 * @param pVmxTransient The VMX-transient structure.
4845 *
4846 * @remarks No-long-jump zone!!!
4847 */
4848static uint32_t hmR0VmxGetGuestIntrState(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
4849{
4850 /*
4851 * Check if we should inhibit interrupt delivery due to instructions like STI and MOV SS.
4852 */
4853 uint32_t fIntrState = 0;
4854 if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS))
4855 {
4856 /* If inhibition is active, RIP and RFLAGS should've been imported from the VMCS already. */
4857 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_RIP | CPUMCTX_EXTRN_RFLAGS);
4858
4859 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
4860 if (pCtx->rip == EMGetInhibitInterruptsPC(pVCpu))
4861 {
4862 if (pCtx->eflags.Bits.u1IF)
4863 fIntrState = VMX_VMCS_GUEST_INT_STATE_BLOCK_STI;
4864 else
4865 fIntrState = VMX_VMCS_GUEST_INT_STATE_BLOCK_MOVSS;
4866 }
4867 else if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS))
4868 {
4869 /*
4870 * We can clear the inhibit force flag as even if we go back to the recompiler
4871 * without executing guest code in VT-x, the flag's condition to be cleared is
4872 * met and thus the cleared state is correct.
4873 */
4874 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS);
4875 }
4876 }
4877
4878 /*
4879 * NMIs to the guest are blocked after an NMI is injected until the guest executes an IRET. We only
4880 * bother with virtual-NMI blocking when we have support for virtual NMIs in the CPU, otherwise
4881 * setting this would block host-NMIs and IRET will not clear the blocking.
4882 *
4883 * We always set NMI-exiting so when the host receives an NMI we get a VM-exit.
4884 *
4885 * See Intel spec. 26.6.1 "Interruptibility state". See @bugref{7445}.
4886 */
4887 PCVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
4888 if ( (pVmcsInfo->u32PinCtls & VMX_PIN_CTLS_VIRT_NMI)
4889 && CPUMIsGuestNmiBlocking(pVCpu))
4890 fIntrState |= VMX_VMCS_GUEST_INT_STATE_BLOCK_NMI;
4891
4892 return fIntrState;
4893}
4894
4895
4896/**
4897 * Exports the exception intercepts required for guest execution in the VMCS.
4898 *
4899 * @returns VBox status code.
4900 * @param pVCpu The cross context virtual CPU structure.
4901 * @param pVmxTransient The VMX-transient structure.
4902 *
4903 * @remarks No-long-jump zone!!!
4904 */
4905static int hmR0VmxExportGuestXcptIntercepts(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
4906{
4907 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_VMX_XCPT_INTERCEPTS)
4908 {
4909 /* When executing a nested-guest, we do not need to trap GIM hypercalls by intercepting #UD. */
4910 if ( !pVmxTransient->fIsNestedGuest
4911 && pVCpu->hm.s.fGIMTrapXcptUD)
4912 hmR0VmxAddXcptIntercept(pVmxTransient, X86_XCPT_UD);
4913 else
4914 hmR0VmxRemoveXcptIntercept(pVCpu, pVmxTransient, X86_XCPT_UD);
4915
4916 /* Other exception intercepts are handled elsewhere, e.g. while exporting guest CR0. */
4917 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_VMX_XCPT_INTERCEPTS);
4918 }
4919 return VINF_SUCCESS;
4920}
4921
4922
4923/**
4924 * Exports the guest's RIP into the guest-state area in the VMCS.
4925 *
4926 * @returns VBox status code.
4927 * @param pVCpu The cross context virtual CPU structure.
4928 *
4929 * @remarks No-long-jump zone!!!
4930 */
4931static int hmR0VmxExportGuestRip(PVMCPUCC pVCpu)
4932{
4933 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_RIP)
4934 {
4935 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_RIP);
4936
4937 int rc = VMXWriteVmcsNw(VMX_VMCS_GUEST_RIP, pVCpu->cpum.GstCtx.rip);
4938 AssertRC(rc);
4939
4940 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_RIP);
4941 Log4Func(("rip=%#RX64\n", pVCpu->cpum.GstCtx.rip));
4942 }
4943 return VINF_SUCCESS;
4944}
4945
4946
4947/**
4948 * Exports the guest's RSP into the guest-state area in the VMCS.
4949 *
4950 * @returns VBox status code.
4951 * @param pVCpu The cross context virtual CPU structure.
4952 *
4953 * @remarks No-long-jump zone!!!
4954 */
4955static int hmR0VmxExportGuestRsp(PVMCPUCC pVCpu)
4956{
4957 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_RSP)
4958 {
4959 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_RSP);
4960
4961 int rc = VMXWriteVmcsNw(VMX_VMCS_GUEST_RSP, pVCpu->cpum.GstCtx.rsp);
4962 AssertRC(rc);
4963
4964 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_RSP);
4965 Log4Func(("rsp=%#RX64\n", pVCpu->cpum.GstCtx.rsp));
4966 }
4967 return VINF_SUCCESS;
4968}
4969
4970
4971/**
4972 * Exports the guest's RFLAGS into the guest-state area in the VMCS.
4973 *
4974 * @returns VBox status code.
4975 * @param pVCpu The cross context virtual CPU structure.
4976 * @param pVmxTransient The VMX-transient structure.
4977 *
4978 * @remarks No-long-jump zone!!!
4979 */
4980static int hmR0VmxExportGuestRflags(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
4981{
4982 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_RFLAGS)
4983 {
4984 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_RFLAGS);
4985
4986 /* Intel spec. 2.3.1 "System Flags and Fields in IA-32e Mode" claims the upper 32-bits of RFLAGS are reserved (MBZ).
4987 Let us assert it as such and use 32-bit VMWRITE. */
4988 Assert(!RT_HI_U32(pVCpu->cpum.GstCtx.rflags.u64));
4989 X86EFLAGS fEFlags = pVCpu->cpum.GstCtx.eflags;
4990 Assert(fEFlags.u32 & X86_EFL_RA1_MASK);
4991 Assert(!(fEFlags.u32 & ~(X86_EFL_1 | X86_EFL_LIVE_MASK)));
4992
4993 /*
4994 * If we're emulating real-mode using Virtual 8086 mode, save the real-mode eflags so
4995 * we can restore them on VM-exit. Modify the real-mode guest's eflags so that VT-x
4996 * can run the real-mode guest code under Virtual 8086 mode.
4997 */
4998 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
4999 if (pVmcsInfo->RealMode.fRealOnV86Active)
5000 {
5001 Assert(pVCpu->CTX_SUFF(pVM)->hm.s.vmx.pRealModeTSS);
5002 Assert(PDMVmmDevHeapIsEnabled(pVCpu->CTX_SUFF(pVM)));
5003 Assert(!pVmxTransient->fIsNestedGuest);
5004 pVmcsInfo->RealMode.Eflags.u32 = fEFlags.u32; /* Save the original eflags of the real-mode guest. */
5005 fEFlags.Bits.u1VM = 1; /* Set the Virtual 8086 mode bit. */
5006 fEFlags.Bits.u2IOPL = 0; /* Change IOPL to 0, otherwise certain instructions won't fault. */
5007 }
5008
5009 int rc = VMXWriteVmcsNw(VMX_VMCS_GUEST_RFLAGS, fEFlags.u32);
5010 AssertRC(rc);
5011
5012 /*
5013 * Setup pending debug exceptions if the guest is single-stepping using EFLAGS.TF.
5014 *
5015 * We must avoid setting any automatic debug exceptions delivery when single-stepping
5016 * through the hypervisor debugger using EFLAGS.TF.
5017 */
5018 if ( !pVmxTransient->fIsNestedGuest
5019 && !pVCpu->hm.s.fSingleInstruction
5020 && fEFlags.Bits.u1TF)
5021 {
5022 /** @todo r=ramshankar: Warning!! We ASSUME EFLAGS.TF will not cleared on
5023 * premature trips to ring-3 esp since IEM does not yet handle it. */
5024 rc = VMXWriteVmcsNw(VMX_VMCS_GUEST_PENDING_DEBUG_XCPTS, VMX_VMCS_GUEST_PENDING_DEBUG_XCPT_BS);
5025 AssertRC(rc);
5026 }
5027 /* else: for nested-guest currently handling while merging controls. */
5028
5029 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_RFLAGS);
5030 Log4Func(("eflags=%#RX32\n", fEFlags.u32));
5031 }
5032 return VINF_SUCCESS;
5033}
5034
5035
5036#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
5037/**
5038 * Copies the nested-guest VMCS to the shadow VMCS.
5039 *
5040 * @returns VBox status code.
5041 * @param pVCpu The cross context virtual CPU structure.
5042 * @param pVmcsInfo The VMCS info. object.
5043 *
5044 * @remarks No-long-jump zone!!!
5045 */
5046static int hmR0VmxCopyNstGstToShadowVmcs(PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo)
5047{
5048 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
5049 PCVMXVVMCS pVmcsNstGst = pVCpu->cpum.GstCtx.hwvirt.vmx.CTX_SUFF(pVmcs);
5050
5051 /*
5052 * Disable interrupts so we don't get preempted while the shadow VMCS is the
5053 * current VMCS, as we may try saving guest lazy MSRs.
5054 *
5055 * Strictly speaking the lazy MSRs are not in the VMCS, but I'd rather not risk
5056 * calling the import VMCS code which is currently performing the guest MSR reads
5057 * (on 64-bit hosts) and accessing the auto-load/store MSR area on 32-bit hosts
5058 * and the rest of the VMX leave session machinery.
5059 */
5060 RTCCUINTREG const fEFlags = ASMIntDisableFlags();
5061
5062 int rc = hmR0VmxLoadShadowVmcs(pVmcsInfo);
5063 if (RT_SUCCESS(rc))
5064 {
5065 /*
5066 * Copy all guest read/write VMCS fields.
5067 *
5068 * We don't check for VMWRITE failures here for performance reasons and
5069 * because they are not expected to fail, barring irrecoverable conditions
5070 * like hardware errors.
5071 */
5072 uint32_t const cShadowVmcsFields = pVM->hm.s.vmx.cShadowVmcsFields;
5073 for (uint32_t i = 0; i < cShadowVmcsFields; i++)
5074 {
5075 uint64_t u64Val;
5076 uint32_t const uVmcsField = pVM->hm.s.vmx.paShadowVmcsFields[i];
5077 IEMReadVmxVmcsField(pVmcsNstGst, uVmcsField, &u64Val);
5078 VMXWriteVmcs64(uVmcsField, u64Val);
5079 }
5080
5081 /*
5082 * If the host CPU supports writing all VMCS fields, copy the guest read-only
5083 * VMCS fields, so the guest can VMREAD them without causing a VM-exit.
5084 */
5085 if (pVM->hm.s.vmx.Msrs.u64Misc & VMX_MISC_VMWRITE_ALL)
5086 {
5087 uint32_t const cShadowVmcsRoFields = pVM->hm.s.vmx.cShadowVmcsRoFields;
5088 for (uint32_t i = 0; i < cShadowVmcsRoFields; i++)
5089 {
5090 uint64_t u64Val;
5091 uint32_t const uVmcsField = pVM->hm.s.vmx.paShadowVmcsRoFields[i];
5092 IEMReadVmxVmcsField(pVmcsNstGst, uVmcsField, &u64Val);
5093 VMXWriteVmcs64(uVmcsField, u64Val);
5094 }
5095 }
5096
5097 rc = hmR0VmxClearShadowVmcs(pVmcsInfo);
5098 rc |= hmR0VmxLoadVmcs(pVmcsInfo);
5099 }
5100
5101 ASMSetFlags(fEFlags);
5102 return rc;
5103}
5104
5105
5106/**
5107 * Copies the shadow VMCS to the nested-guest VMCS.
5108 *
5109 * @returns VBox status code.
5110 * @param pVCpu The cross context virtual CPU structure.
5111 * @param pVmcsInfo The VMCS info. object.
5112 *
5113 * @remarks Called with interrupts disabled.
5114 */
5115static int hmR0VmxCopyShadowToNstGstVmcs(PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo)
5116{
5117 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
5118 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
5119 PVMXVVMCS pVmcsNstGst = pVCpu->cpum.GstCtx.hwvirt.vmx.CTX_SUFF(pVmcs);
5120
5121 int rc = hmR0VmxLoadShadowVmcs(pVmcsInfo);
5122 if (RT_SUCCESS(rc))
5123 {
5124 /*
5125 * Copy guest read/write fields from the shadow VMCS.
5126 * Guest read-only fields cannot be modified, so no need to copy them.
5127 *
5128 * We don't check for VMREAD failures here for performance reasons and
5129 * because they are not expected to fail, barring irrecoverable conditions
5130 * like hardware errors.
5131 */
5132 uint32_t const cShadowVmcsFields = pVM->hm.s.vmx.cShadowVmcsFields;
5133 for (uint32_t i = 0; i < cShadowVmcsFields; i++)
5134 {
5135 uint64_t u64Val;
5136 uint32_t const uVmcsField = pVM->hm.s.vmx.paShadowVmcsFields[i];
5137 VMXReadVmcs64(uVmcsField, &u64Val);
5138 IEMWriteVmxVmcsField(pVmcsNstGst, uVmcsField, u64Val);
5139 }
5140
5141 rc = hmR0VmxClearShadowVmcs(pVmcsInfo);
5142 rc |= hmR0VmxLoadVmcs(pVmcsInfo);
5143 }
5144 return rc;
5145}
5146
5147
5148/**
5149 * Enables VMCS shadowing for the given VMCS info. object.
5150 *
5151 * @param pVmcsInfo The VMCS info. object.
5152 *
5153 * @remarks No-long-jump zone!!!
5154 */
5155static void hmR0VmxEnableVmcsShadowing(PVMXVMCSINFO pVmcsInfo)
5156{
5157 uint32_t uProcCtls2 = pVmcsInfo->u32ProcCtls2;
5158 if (!(uProcCtls2 & VMX_PROC_CTLS2_VMCS_SHADOWING))
5159 {
5160 Assert(pVmcsInfo->HCPhysShadowVmcs != 0 && pVmcsInfo->HCPhysShadowVmcs != NIL_RTHCPHYS);
5161 uProcCtls2 |= VMX_PROC_CTLS2_VMCS_SHADOWING;
5162 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC2, uProcCtls2); AssertRC(rc);
5163 rc = VMXWriteVmcs64(VMX_VMCS64_GUEST_VMCS_LINK_PTR_FULL, pVmcsInfo->HCPhysShadowVmcs); AssertRC(rc);
5164 pVmcsInfo->u32ProcCtls2 = uProcCtls2;
5165 pVmcsInfo->u64VmcsLinkPtr = pVmcsInfo->HCPhysShadowVmcs;
5166 Log4Func(("Enabled\n"));
5167 }
5168}
5169
5170
5171/**
5172 * Disables VMCS shadowing for the given VMCS info. object.
5173 *
5174 * @param pVmcsInfo The VMCS info. object.
5175 *
5176 * @remarks No-long-jump zone!!!
5177 */
5178static void hmR0VmxDisableVmcsShadowing(PVMXVMCSINFO pVmcsInfo)
5179{
5180 /*
5181 * We want all VMREAD and VMWRITE instructions to cause VM-exits, so we clear the
5182 * VMCS shadowing control. However, VM-entry requires the shadow VMCS indicator bit
5183 * to match the VMCS shadowing control if the VMCS link pointer is not NIL_RTHCPHYS.
5184 * Hence, we must also reset the VMCS link pointer to ensure VM-entry does not fail.
5185 *
5186 * See Intel spec. 26.2.1.1 "VM-Execution Control Fields".
5187 * See Intel spec. 26.3.1.5 "Checks on Guest Non-Register State".
5188 */
5189 uint32_t uProcCtls2 = pVmcsInfo->u32ProcCtls2;
5190 if (uProcCtls2 & VMX_PROC_CTLS2_VMCS_SHADOWING)
5191 {
5192 uProcCtls2 &= ~VMX_PROC_CTLS2_VMCS_SHADOWING;
5193 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC2, uProcCtls2); AssertRC(rc);
5194 rc = VMXWriteVmcs64(VMX_VMCS64_GUEST_VMCS_LINK_PTR_FULL, NIL_RTHCPHYS); AssertRC(rc);
5195 pVmcsInfo->u32ProcCtls2 = uProcCtls2;
5196 pVmcsInfo->u64VmcsLinkPtr = NIL_RTHCPHYS;
5197 Log4Func(("Disabled\n"));
5198 }
5199}
5200#endif
5201
5202
5203/**
5204 * Exports the guest hardware-virtualization state.
5205 *
5206 * @returns VBox status code.
5207 * @param pVCpu The cross context virtual CPU structure.
5208 * @param pVmxTransient The VMX-transient structure.
5209 *
5210 * @remarks No-long-jump zone!!!
5211 */
5212static int hmR0VmxExportGuestHwvirtState(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
5213{
5214 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_HWVIRT)
5215 {
5216#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
5217 /*
5218 * Check if the VMX feature is exposed to the guest and if the host CPU supports
5219 * VMCS shadowing.
5220 */
5221 if (pVCpu->CTX_SUFF(pVM)->hm.s.vmx.fUseVmcsShadowing)
5222 {
5223 /*
5224 * If the guest hypervisor has loaded a current VMCS and is in VMX root mode,
5225 * copy the guest hypervisor's current VMCS into the shadow VMCS and enable
5226 * VMCS shadowing to skip intercepting some or all VMREAD/VMWRITE VM-exits.
5227 *
5228 * We check for VMX root mode here in case the guest executes VMXOFF without
5229 * clearing the current VMCS pointer and our VMXOFF instruction emulation does
5230 * not clear the current VMCS pointer.
5231 */
5232 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
5233 if ( CPUMIsGuestInVmxRootMode(&pVCpu->cpum.GstCtx)
5234 && !CPUMIsGuestInVmxNonRootMode(&pVCpu->cpum.GstCtx)
5235 && CPUMIsGuestVmxCurrentVmcsValid(pVCpu, &pVCpu->cpum.GstCtx))
5236 {
5237 /* Paranoia. */
5238 Assert(!pVmxTransient->fIsNestedGuest);
5239
5240 /*
5241 * For performance reasons, also check if the guest hypervisor's current VMCS
5242 * was newly loaded or modified before copying it to the shadow VMCS.
5243 */
5244 if (!pVCpu->hm.s.vmx.fCopiedNstGstToShadowVmcs)
5245 {
5246 int rc = hmR0VmxCopyNstGstToShadowVmcs(pVCpu, pVmcsInfo);
5247 AssertRCReturn(rc, rc);
5248 pVCpu->hm.s.vmx.fCopiedNstGstToShadowVmcs = true;
5249 }
5250 hmR0VmxEnableVmcsShadowing(pVmcsInfo);
5251 }
5252 else
5253 hmR0VmxDisableVmcsShadowing(pVmcsInfo);
5254 }
5255#else
5256 NOREF(pVmxTransient);
5257#endif
5258 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_HWVIRT);
5259 }
5260 return VINF_SUCCESS;
5261}
5262
5263
5264/**
5265 * Exports the guest CR0 control register into the guest-state area in the VMCS.
5266 *
5267 * The guest FPU state is always pre-loaded hence we don't need to bother about
5268 * sharing FPU related CR0 bits between the guest and host.
5269 *
5270 * @returns VBox status code.
5271 * @param pVCpu The cross context virtual CPU structure.
5272 * @param pVmxTransient The VMX-transient structure.
5273 *
5274 * @remarks No-long-jump zone!!!
5275 */
5276static int hmR0VmxExportGuestCR0(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
5277{
5278 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_CR0)
5279 {
5280 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
5281 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
5282
5283 /*
5284 * Figure out fixed CR0 bits in VMX operation.
5285 */
5286 uint64_t fSetCr0 = pVM->hm.s.vmx.Msrs.u64Cr0Fixed0;
5287 uint64_t const fZapCr0 = pVM->hm.s.vmx.Msrs.u64Cr0Fixed1;
5288 if (pVM->hm.s.vmx.fUnrestrictedGuest)
5289 fSetCr0 &= ~(uint64_t)(X86_CR0_PE | X86_CR0_PG);
5290 else
5291 Assert((fSetCr0 & (X86_CR0_PE | X86_CR0_PG)) == (X86_CR0_PE | X86_CR0_PG));
5292
5293 if (!pVmxTransient->fIsNestedGuest)
5294 {
5295 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_CR0);
5296 uint64_t u64GuestCr0 = pVCpu->cpum.GstCtx.cr0;
5297 uint64_t const u64ShadowCr0 = u64GuestCr0;
5298 Assert(!RT_HI_U32(u64GuestCr0));
5299
5300 /*
5301 * Setup VT-x's view of the guest CR0.
5302 */
5303 uint32_t uProcCtls = pVmcsInfo->u32ProcCtls;
5304 if (pVM->hm.s.fNestedPaging)
5305 {
5306 if (CPUMIsGuestPagingEnabled(pVCpu))
5307 {
5308 /* The guest has paging enabled, let it access CR3 without causing a VM-exit if supported. */
5309 uProcCtls &= ~( VMX_PROC_CTLS_CR3_LOAD_EXIT
5310 | VMX_PROC_CTLS_CR3_STORE_EXIT);
5311 }
5312 else
5313 {
5314 /* The guest doesn't have paging enabled, make CR3 access cause a VM-exit to update our shadow. */
5315 uProcCtls |= VMX_PROC_CTLS_CR3_LOAD_EXIT
5316 | VMX_PROC_CTLS_CR3_STORE_EXIT;
5317 }
5318
5319 /* If we have unrestricted guest execution, we never have to intercept CR3 reads. */
5320 if (pVM->hm.s.vmx.fUnrestrictedGuest)
5321 uProcCtls &= ~VMX_PROC_CTLS_CR3_STORE_EXIT;
5322 }
5323 else
5324 {
5325 /* Guest CPL 0 writes to its read-only pages should cause a #PF VM-exit. */
5326 u64GuestCr0 |= X86_CR0_WP;
5327 }
5328
5329 /*
5330 * Guest FPU bits.
5331 *
5332 * Since we pre-load the guest FPU always before VM-entry there is no need to track lazy state
5333 * using CR0.TS.
5334 *
5335 * Intel spec. 23.8 "Restrictions on VMX operation" mentions that CR0.NE bit must always be
5336 * set on the first CPUs to support VT-x and no mention of with regards to UX in VM-entry checks.
5337 */
5338 u64GuestCr0 |= X86_CR0_NE;
5339
5340 /* If CR0.NE isn't set, we need to intercept #MF exceptions and report them to the guest differently. */
5341 bool const fInterceptMF = !(u64ShadowCr0 & X86_CR0_NE);
5342
5343 /*
5344 * Update exception intercepts.
5345 */
5346 uint32_t uXcptBitmap = pVmcsInfo->u32XcptBitmap;
5347 if (pVmcsInfo->RealMode.fRealOnV86Active)
5348 {
5349 Assert(PDMVmmDevHeapIsEnabled(pVM));
5350 Assert(pVM->hm.s.vmx.pRealModeTSS);
5351 uXcptBitmap |= HMVMX_REAL_MODE_XCPT_MASK;
5352 }
5353 else
5354 {
5355 /* For now, cleared here as mode-switches can happen outside HM/VT-x. See @bugref{7626#c11}. */
5356 uXcptBitmap &= ~HMVMX_REAL_MODE_XCPT_MASK;
5357 if (fInterceptMF)
5358 uXcptBitmap |= RT_BIT(X86_XCPT_MF);
5359 }
5360
5361 /* Additional intercepts for debugging, define these yourself explicitly. */
5362#ifdef HMVMX_ALWAYS_TRAP_ALL_XCPTS
5363 uXcptBitmap |= 0
5364 | RT_BIT(X86_XCPT_BP)
5365 | RT_BIT(X86_XCPT_DE)
5366 | RT_BIT(X86_XCPT_NM)
5367 | RT_BIT(X86_XCPT_TS)
5368 | RT_BIT(X86_XCPT_UD)
5369 | RT_BIT(X86_XCPT_NP)
5370 | RT_BIT(X86_XCPT_SS)
5371 | RT_BIT(X86_XCPT_GP)
5372 | RT_BIT(X86_XCPT_PF)
5373 | RT_BIT(X86_XCPT_MF)
5374 ;
5375#elif defined(HMVMX_ALWAYS_TRAP_PF)
5376 uXcptBitmap |= RT_BIT(X86_XCPT_PF);
5377#endif
5378 if (pVCpu->hm.s.fTrapXcptGpForLovelyMesaDrv)
5379 uXcptBitmap |= RT_BIT(X86_XCPT_GP);
5380 Assert(pVM->hm.s.fNestedPaging || (uXcptBitmap & RT_BIT(X86_XCPT_PF)));
5381
5382 /* Apply the hardware specified fixed CR0 bits and enable caching. */
5383 u64GuestCr0 |= fSetCr0;
5384 u64GuestCr0 &= fZapCr0;
5385 u64GuestCr0 &= ~(uint64_t)(X86_CR0_CD | X86_CR0_NW);
5386
5387 /* Commit the CR0 and related fields to the guest VMCS. */
5388 int rc = VMXWriteVmcsNw(VMX_VMCS_GUEST_CR0, u64GuestCr0); AssertRC(rc);
5389 rc = VMXWriteVmcsNw(VMX_VMCS_CTRL_CR0_READ_SHADOW, u64ShadowCr0); AssertRC(rc);
5390 if (uProcCtls != pVmcsInfo->u32ProcCtls)
5391 {
5392 rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, uProcCtls);
5393 AssertRC(rc);
5394 }
5395 if (uXcptBitmap != pVmcsInfo->u32XcptBitmap)
5396 {
5397 rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_EXCEPTION_BITMAP, uXcptBitmap);
5398 AssertRC(rc);
5399 }
5400
5401 /* Update our caches. */
5402 pVmcsInfo->u32ProcCtls = uProcCtls;
5403 pVmcsInfo->u32XcptBitmap = uXcptBitmap;
5404
5405 Log4Func(("cr0=%#RX64 shadow=%#RX64 set=%#RX64 zap=%#RX64\n", u64GuestCr0, u64ShadowCr0, fSetCr0, fZapCr0));
5406 }
5407 else
5408 {
5409 /*
5410 * With nested-guests, we may have extended the guest/host mask here since we
5411 * merged in the outer guest's mask. Thus, the merged mask can include more bits
5412 * (to read from the nested-guest CR0 read-shadow) than the guest hypervisor
5413 * originally supplied. We must copy those bits from the nested-guest CR0 into
5414 * the nested-guest CR0 read-shadow.
5415 */
5416 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_CR0);
5417 uint64_t u64GuestCr0 = pVCpu->cpum.GstCtx.cr0;
5418 uint64_t const u64ShadowCr0 = CPUMGetGuestVmxMaskedCr0(pVCpu, &pVCpu->cpum.GstCtx, pVmcsInfo->u64Cr0Mask);
5419 Assert(!RT_HI_U32(u64GuestCr0));
5420 Assert(u64GuestCr0 & X86_CR0_NE);
5421
5422 /*
5423 * Apply the hardware specified fixed CR0 bits and enable caching.
5424 * Note! We could be altering our VMX emulation's fixed bits. We thus
5425 * need to re-apply them while importing CR0.
5426 */
5427 u64GuestCr0 |= fSetCr0;
5428 u64GuestCr0 &= fZapCr0;
5429 u64GuestCr0 &= ~(uint64_t)(X86_CR0_CD | X86_CR0_NW);
5430
5431 /* Commit the CR0 and CR0 read-shadow to the nested-guest VMCS. */
5432 int rc = VMXWriteVmcsNw(VMX_VMCS_GUEST_CR0, u64GuestCr0); AssertRC(rc);
5433 rc = VMXWriteVmcsNw(VMX_VMCS_CTRL_CR0_READ_SHADOW, u64ShadowCr0); AssertRC(rc);
5434
5435 Log4Func(("cr0=%#RX64 shadow=%#RX64 (set=%#RX64 zap=%#RX64)\n", u64GuestCr0, u64ShadowCr0, fSetCr0, fZapCr0));
5436 }
5437
5438 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_CR0);
5439 }
5440
5441 return VINF_SUCCESS;
5442}
5443
5444
5445/**
5446 * Exports the guest control registers (CR3, CR4) into the guest-state area
5447 * in the VMCS.
5448 *
5449 * @returns VBox strict status code.
5450 * @retval VINF_EM_RESCHEDULE_REM if we try to emulate non-paged guest code
5451 * without unrestricted guest access and the VMMDev is not presently
5452 * mapped (e.g. EFI32).
5453 *
5454 * @param pVCpu The cross context virtual CPU structure.
5455 * @param pVmxTransient The VMX-transient structure.
5456 *
5457 * @remarks No-long-jump zone!!!
5458 */
5459static VBOXSTRICTRC hmR0VmxExportGuestCR3AndCR4(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
5460{
5461 int rc = VINF_SUCCESS;
5462 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
5463
5464 /*
5465 * Guest CR2.
5466 * It's always loaded in the assembler code. Nothing to do here.
5467 */
5468
5469 /*
5470 * Guest CR3.
5471 */
5472 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_CR3)
5473 {
5474 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_CR3);
5475
5476 if (pVM->hm.s.fNestedPaging)
5477 {
5478 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
5479 pVmcsInfo->HCPhysEPTP = PGMGetHyperCR3(pVCpu);
5480
5481 /* Validate. See Intel spec. 28.2.2 "EPT Translation Mechanism" and 24.6.11 "Extended-Page-Table Pointer (EPTP)" */
5482 Assert(pVmcsInfo->HCPhysEPTP != NIL_RTHCPHYS);
5483 Assert(!(pVmcsInfo->HCPhysEPTP & UINT64_C(0xfff0000000000000)));
5484 Assert(!(pVmcsInfo->HCPhysEPTP & 0xfff));
5485
5486 /* VMX_EPT_MEMTYPE_WB support is already checked in hmR0VmxSetupTaggedTlb(). */
5487 pVmcsInfo->HCPhysEPTP |= VMX_EPT_MEMTYPE_WB
5488 | (VMX_EPT_PAGE_WALK_LENGTH_DEFAULT << VMX_EPT_PAGE_WALK_LENGTH_SHIFT);
5489
5490 /* Validate. See Intel spec. 26.2.1 "Checks on VMX Controls" */
5491 AssertMsg( ((pVmcsInfo->HCPhysEPTP >> 3) & 0x07) == 3 /* Bits 3:5 (EPT page walk length - 1) must be 3. */
5492 && ((pVmcsInfo->HCPhysEPTP >> 7) & 0x1f) == 0, /* Bits 7:11 MBZ. */
5493 ("EPTP %#RX64\n", pVmcsInfo->HCPhysEPTP));
5494 AssertMsg( !((pVmcsInfo->HCPhysEPTP >> 6) & 0x01) /* Bit 6 (EPT accessed & dirty bit). */
5495 || (pVM->hm.s.vmx.Msrs.u64EptVpidCaps & MSR_IA32_VMX_EPT_VPID_CAP_EPT_ACCESS_DIRTY),
5496 ("EPTP accessed/dirty bit not supported by CPU but set %#RX64\n", pVmcsInfo->HCPhysEPTP));
5497
5498 rc = VMXWriteVmcs64(VMX_VMCS64_CTRL_EPTP_FULL, pVmcsInfo->HCPhysEPTP);
5499 AssertRC(rc);
5500
5501 uint64_t u64GuestCr3;
5502 PCCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
5503 if ( pVM->hm.s.vmx.fUnrestrictedGuest
5504 || CPUMIsGuestPagingEnabledEx(pCtx))
5505 {
5506 /* If the guest is in PAE mode, pass the PDPEs to VT-x using the VMCS fields. */
5507 if (CPUMIsGuestInPAEModeEx(pCtx))
5508 {
5509 rc = PGMGstGetPaePdpes(pVCpu, &pVCpu->hm.s.aPdpes[0]);
5510 AssertRC(rc);
5511 rc = VMXWriteVmcs64(VMX_VMCS64_GUEST_PDPTE0_FULL, pVCpu->hm.s.aPdpes[0].u); AssertRC(rc);
5512 rc = VMXWriteVmcs64(VMX_VMCS64_GUEST_PDPTE1_FULL, pVCpu->hm.s.aPdpes[1].u); AssertRC(rc);
5513 rc = VMXWriteVmcs64(VMX_VMCS64_GUEST_PDPTE2_FULL, pVCpu->hm.s.aPdpes[2].u); AssertRC(rc);
5514 rc = VMXWriteVmcs64(VMX_VMCS64_GUEST_PDPTE3_FULL, pVCpu->hm.s.aPdpes[3].u); AssertRC(rc);
5515 }
5516
5517 /*
5518 * The guest's view of its CR3 is unblemished with nested paging when the
5519 * guest is using paging or we have unrestricted guest execution to handle
5520 * the guest when it's not using paging.
5521 */
5522 u64GuestCr3 = pCtx->cr3;
5523 }
5524 else
5525 {
5526 /*
5527 * The guest is not using paging, but the CPU (VT-x) has to. While the guest
5528 * thinks it accesses physical memory directly, we use our identity-mapped
5529 * page table to map guest-linear to guest-physical addresses. EPT takes care
5530 * of translating it to host-physical addresses.
5531 */
5532 RTGCPHYS GCPhys;
5533 Assert(pVM->hm.s.vmx.pNonPagingModeEPTPageTable);
5534
5535 /* We obtain it here every time as the guest could have relocated this PCI region. */
5536 rc = PDMVmmDevHeapR3ToGCPhys(pVM, pVM->hm.s.vmx.pNonPagingModeEPTPageTable, &GCPhys);
5537 if (RT_SUCCESS(rc))
5538 { /* likely */ }
5539 else if (rc == VERR_PDM_DEV_HEAP_R3_TO_GCPHYS)
5540 {
5541 Log4Func(("VERR_PDM_DEV_HEAP_R3_TO_GCPHYS -> VINF_EM_RESCHEDULE_REM\n"));
5542 return VINF_EM_RESCHEDULE_REM; /* We cannot execute now, switch to REM/IEM till the guest maps in VMMDev. */
5543 }
5544 else
5545 AssertMsgFailedReturn(("%Rrc\n", rc), rc);
5546
5547 u64GuestCr3 = GCPhys;
5548 }
5549
5550 Log4Func(("guest_cr3=%#RX64 (GstN)\n", u64GuestCr3));
5551 rc = VMXWriteVmcsNw(VMX_VMCS_GUEST_CR3, u64GuestCr3);
5552 AssertRC(rc);
5553 }
5554 else
5555 {
5556 Assert(!pVmxTransient->fIsNestedGuest);
5557 /* Non-nested paging case, just use the hypervisor's CR3. */
5558 RTHCPHYS const HCPhysGuestCr3 = PGMGetHyperCR3(pVCpu);
5559
5560 Log4Func(("guest_cr3=%#RX64 (HstN)\n", HCPhysGuestCr3));
5561 rc = VMXWriteVmcsNw(VMX_VMCS_GUEST_CR3, HCPhysGuestCr3);
5562 AssertRC(rc);
5563 }
5564
5565 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_CR3);
5566 }
5567
5568 /*
5569 * Guest CR4.
5570 * ASSUMES this is done everytime we get in from ring-3! (XCR0)
5571 */
5572 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_CR4)
5573 {
5574 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
5575 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
5576
5577 /*
5578 * Figure out fixed CR4 bits in VMX operation.
5579 */
5580 uint64_t const fSetCr4 = pVM->hm.s.vmx.Msrs.u64Cr4Fixed0;
5581 uint64_t const fZapCr4 = pVM->hm.s.vmx.Msrs.u64Cr4Fixed1;
5582
5583 /*
5584 * With nested-guests, we may have extended the guest/host mask here (since we
5585 * merged in the outer guest's mask, see hmR0VmxMergeVmcsNested). This means, the
5586 * mask can include more bits (to read from the nested-guest CR4 read-shadow) than
5587 * the guest hypervisor originally supplied. Thus, we should, in essence, copy
5588 * those bits from the nested-guest CR4 into the nested-guest CR4 read-shadow.
5589 */
5590 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_CR4);
5591 uint64_t u64GuestCr4 = pCtx->cr4;
5592 uint64_t const u64ShadowCr4 = !pVmxTransient->fIsNestedGuest
5593 ? pCtx->cr4
5594 : CPUMGetGuestVmxMaskedCr4(pVCpu, pCtx, pVmcsInfo->u64Cr4Mask);
5595 Assert(!RT_HI_U32(u64GuestCr4));
5596
5597 /*
5598 * Setup VT-x's view of the guest CR4.
5599 *
5600 * If we're emulating real-mode using virtual-8086 mode, we want to redirect software
5601 * interrupts to the 8086 program interrupt handler. Clear the VME bit (the interrupt
5602 * redirection bitmap is already all 0, see hmR3InitFinalizeR0())
5603 *
5604 * See Intel spec. 20.2 "Software Interrupt Handling Methods While in Virtual-8086 Mode".
5605 */
5606 if (pVmcsInfo->RealMode.fRealOnV86Active)
5607 {
5608 Assert(pVM->hm.s.vmx.pRealModeTSS);
5609 Assert(PDMVmmDevHeapIsEnabled(pVM));
5610 u64GuestCr4 &= ~(uint64_t)X86_CR4_VME;
5611 }
5612
5613 if (pVM->hm.s.fNestedPaging)
5614 {
5615 if ( !CPUMIsGuestPagingEnabledEx(pCtx)
5616 && !pVM->hm.s.vmx.fUnrestrictedGuest)
5617 {
5618 /* We use 4 MB pages in our identity mapping page table when the guest doesn't have paging. */
5619 u64GuestCr4 |= X86_CR4_PSE;
5620 /* Our identity mapping is a 32-bit page directory. */
5621 u64GuestCr4 &= ~(uint64_t)X86_CR4_PAE;
5622 }
5623 /* else use guest CR4.*/
5624 }
5625 else
5626 {
5627 Assert(!pVmxTransient->fIsNestedGuest);
5628
5629 /*
5630 * The shadow paging modes and guest paging modes are different, the shadow is in accordance with the host
5631 * paging mode and thus we need to adjust VT-x's view of CR4 depending on our shadow page tables.
5632 */
5633 switch (pVCpu->hm.s.enmShadowMode)
5634 {
5635 case PGMMODE_REAL: /* Real-mode. */
5636 case PGMMODE_PROTECTED: /* Protected mode without paging. */
5637 case PGMMODE_32_BIT: /* 32-bit paging. */
5638 {
5639 u64GuestCr4 &= ~(uint64_t)X86_CR4_PAE;
5640 break;
5641 }
5642
5643 case PGMMODE_PAE: /* PAE paging. */
5644 case PGMMODE_PAE_NX: /* PAE paging with NX. */
5645 {
5646 u64GuestCr4 |= X86_CR4_PAE;
5647 break;
5648 }
5649
5650 case PGMMODE_AMD64: /* 64-bit AMD paging (long mode). */
5651 case PGMMODE_AMD64_NX: /* 64-bit AMD paging (long mode) with NX enabled. */
5652#ifdef VBOX_WITH_64_BITS_GUESTS
5653 break;
5654#endif
5655 default:
5656 AssertFailed();
5657 return VERR_PGM_UNSUPPORTED_SHADOW_PAGING_MODE;
5658 }
5659 }
5660
5661 /*
5662 * Apply the hardware specified fixed CR4 bits (mainly CR4.VMXE).
5663 * Note! For nested-guests, we could be altering our VMX emulation's
5664 * fixed bits. We thus need to re-apply them while importing CR4.
5665 */
5666 u64GuestCr4 |= fSetCr4;
5667 u64GuestCr4 &= fZapCr4;
5668
5669 /* Commit the CR4 and CR4 read-shadow to the guest VMCS. */
5670 rc = VMXWriteVmcsNw(VMX_VMCS_GUEST_CR4, u64GuestCr4); AssertRC(rc);
5671 rc = VMXWriteVmcsNw(VMX_VMCS_CTRL_CR4_READ_SHADOW, u64ShadowCr4); AssertRC(rc);
5672
5673 /* Whether to save/load/restore XCR0 during world switch depends on CR4.OSXSAVE and host+guest XCR0. */
5674 pVCpu->hm.s.fLoadSaveGuestXcr0 = (pCtx->cr4 & X86_CR4_OSXSAVE) && pCtx->aXcr[0] != ASMGetXcr0();
5675
5676 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_CR4);
5677
5678 Log4Func(("cr4=%#RX64 shadow=%#RX64 (set=%#RX64 zap=%#RX64)\n", u64GuestCr4, u64ShadowCr4, fSetCr4, fZapCr4));
5679 }
5680 return rc;
5681}
5682
5683
5684/**
5685 * Exports the guest debug registers into the guest-state area in the VMCS.
5686 * The guest debug bits are partially shared with the host (e.g. DR6, DR0-3).
5687 *
5688 * This also sets up whether \#DB and MOV DRx accesses cause VM-exits.
5689 *
5690 * @returns VBox status code.
5691 * @param pVCpu The cross context virtual CPU structure.
5692 * @param pVmxTransient The VMX-transient structure.
5693 *
5694 * @remarks No-long-jump zone!!!
5695 */
5696static int hmR0VmxExportSharedDebugState(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
5697{
5698 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
5699
5700 /** @todo NSTVMX: Figure out what we want to do with nested-guest instruction
5701 * stepping. */
5702 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
5703 if (pVmxTransient->fIsNestedGuest)
5704 {
5705 int rc = VMXWriteVmcsNw(VMX_VMCS_GUEST_DR7, CPUMGetGuestDR7(pVCpu));
5706 AssertRC(rc);
5707
5708 /* Always intercept Mov DRx accesses for the nested-guest for now. */
5709 pVmcsInfo->u32ProcCtls |= VMX_PROC_CTLS_MOV_DR_EXIT;
5710 rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, pVmcsInfo->u32ProcCtls);
5711 AssertRC(rc);
5712 return VINF_SUCCESS;
5713 }
5714
5715#ifdef VBOX_STRICT
5716 /* Validate. Intel spec. 26.3.1.1 "Checks on Guest Controls Registers, Debug Registers, MSRs" */
5717 if (pVmcsInfo->u32EntryCtls & VMX_ENTRY_CTLS_LOAD_DEBUG)
5718 {
5719 /* Validate. Intel spec. 17.2 "Debug Registers", recompiler paranoia checks. */
5720 Assert((pVCpu->cpum.GstCtx.dr[7] & (X86_DR7_MBZ_MASK | X86_DR7_RAZ_MASK)) == 0);
5721 Assert((pVCpu->cpum.GstCtx.dr[7] & X86_DR7_RA1_MASK) == X86_DR7_RA1_MASK);
5722 }
5723#endif
5724
5725 bool fSteppingDB = false;
5726 bool fInterceptMovDRx = false;
5727 uint32_t uProcCtls = pVmcsInfo->u32ProcCtls;
5728 if (pVCpu->hm.s.fSingleInstruction)
5729 {
5730 /* If the CPU supports the monitor trap flag, use it for single stepping in DBGF and avoid intercepting #DB. */
5731 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
5732 if (pVM->hm.s.vmx.Msrs.ProcCtls.n.allowed1 & VMX_PROC_CTLS_MONITOR_TRAP_FLAG)
5733 {
5734 uProcCtls |= VMX_PROC_CTLS_MONITOR_TRAP_FLAG;
5735 Assert(fSteppingDB == false);
5736 }
5737 else
5738 {
5739 pVCpu->cpum.GstCtx.eflags.u32 |= X86_EFL_TF;
5740 pVCpu->hm.s.fCtxChanged |= HM_CHANGED_GUEST_RFLAGS;
5741 pVCpu->hm.s.fClearTrapFlag = true;
5742 fSteppingDB = true;
5743 }
5744 }
5745
5746 uint64_t u64GuestDr7;
5747 if ( fSteppingDB
5748 || (CPUMGetHyperDR7(pVCpu) & X86_DR7_ENABLED_MASK))
5749 {
5750 /*
5751 * Use the combined guest and host DRx values found in the hypervisor register set
5752 * because the hypervisor debugger has breakpoints active or someone is single stepping
5753 * on the host side without a monitor trap flag.
5754 *
5755 * Note! DBGF expects a clean DR6 state before executing guest code.
5756 */
5757 if (!CPUMIsHyperDebugStateActive(pVCpu))
5758 {
5759 CPUMR0LoadHyperDebugState(pVCpu, true /* include DR6 */);
5760 Assert(CPUMIsHyperDebugStateActive(pVCpu));
5761 Assert(!CPUMIsGuestDebugStateActive(pVCpu));
5762 }
5763
5764 /* Update DR7 with the hypervisor value (other DRx registers are handled by CPUM one way or another). */
5765 u64GuestDr7 = CPUMGetHyperDR7(pVCpu);
5766 pVCpu->hm.s.fUsingHyperDR7 = true;
5767 fInterceptMovDRx = true;
5768 }
5769 else
5770 {
5771 /*
5772 * If the guest has enabled debug registers, we need to load them prior to
5773 * executing guest code so they'll trigger at the right time.
5774 */
5775 if (pVCpu->cpum.GstCtx.dr[7] & (X86_DR7_ENABLED_MASK | X86_DR7_GD))
5776 {
5777 if (!CPUMIsGuestDebugStateActive(pVCpu))
5778 {
5779 CPUMR0LoadGuestDebugState(pVCpu, true /* include DR6 */);
5780 Assert(CPUMIsGuestDebugStateActive(pVCpu));
5781 Assert(!CPUMIsHyperDebugStateActive(pVCpu));
5782 STAM_COUNTER_INC(&pVCpu->hm.s.StatDRxArmed);
5783 }
5784 Assert(!fInterceptMovDRx);
5785 }
5786 else if (!CPUMIsGuestDebugStateActive(pVCpu))
5787 {
5788 /*
5789 * If no debugging enabled, we'll lazy load DR0-3. Unlike on AMD-V, we
5790 * must intercept #DB in order to maintain a correct DR6 guest value, and
5791 * because we need to intercept it to prevent nested #DBs from hanging the
5792 * CPU, we end up always having to intercept it. See hmR0VmxSetupVmcsXcptBitmap().
5793 */
5794 fInterceptMovDRx = true;
5795 }
5796
5797 /* Update DR7 with the actual guest value. */
5798 u64GuestDr7 = pVCpu->cpum.GstCtx.dr[7];
5799 pVCpu->hm.s.fUsingHyperDR7 = false;
5800 }
5801
5802 if (fInterceptMovDRx)
5803 uProcCtls |= VMX_PROC_CTLS_MOV_DR_EXIT;
5804 else
5805 uProcCtls &= ~VMX_PROC_CTLS_MOV_DR_EXIT;
5806
5807 /*
5808 * Update the processor-based VM-execution controls with the MOV-DRx intercepts and the
5809 * monitor-trap flag and update our cache.
5810 */
5811 if (uProcCtls != pVmcsInfo->u32ProcCtls)
5812 {
5813 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, uProcCtls);
5814 AssertRC(rc);
5815 pVmcsInfo->u32ProcCtls = uProcCtls;
5816 }
5817
5818 /*
5819 * Update guest DR7.
5820 */
5821 int rc = VMXWriteVmcsNw(VMX_VMCS_GUEST_DR7, u64GuestDr7);
5822 AssertRC(rc);
5823
5824 /*
5825 * If we have forced EFLAGS.TF to be set because we're single-stepping in the hypervisor debugger,
5826 * we need to clear interrupt inhibition if any as otherwise it causes a VM-entry failure.
5827 *
5828 * See Intel spec. 26.3.1.5 "Checks on Guest Non-Register State".
5829 */
5830 if (fSteppingDB)
5831 {
5832 Assert(pVCpu->hm.s.fSingleInstruction);
5833 Assert(pVCpu->cpum.GstCtx.eflags.Bits.u1TF);
5834
5835 uint32_t fIntrState = 0;
5836 rc = VMXReadVmcs32(VMX_VMCS32_GUEST_INT_STATE, &fIntrState);
5837 AssertRC(rc);
5838
5839 if (fIntrState & (VMX_VMCS_GUEST_INT_STATE_BLOCK_STI | VMX_VMCS_GUEST_INT_STATE_BLOCK_MOVSS))
5840 {
5841 fIntrState &= ~(VMX_VMCS_GUEST_INT_STATE_BLOCK_STI | VMX_VMCS_GUEST_INT_STATE_BLOCK_MOVSS);
5842 rc = VMXWriteVmcs32(VMX_VMCS32_GUEST_INT_STATE, fIntrState);
5843 AssertRC(rc);
5844 }
5845 }
5846
5847 return VINF_SUCCESS;
5848}
5849
5850
5851#ifdef VBOX_STRICT
5852/**
5853 * Strict function to validate segment registers.
5854 *
5855 * @param pVCpu The cross context virtual CPU structure.
5856 * @param pVmcsInfo The VMCS info. object.
5857 *
5858 * @remarks Will import guest CR0 on strict builds during validation of
5859 * segments.
5860 */
5861static void hmR0VmxValidateSegmentRegs(PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo)
5862{
5863 /*
5864 * Validate segment registers. See Intel spec. 26.3.1.2 "Checks on Guest Segment Registers".
5865 *
5866 * The reason we check for attribute value 0 in this function and not just the unusable bit is
5867 * because hmR0VmxExportGuestSegReg() only updates the VMCS' copy of the value with the
5868 * unusable bit and doesn't change the guest-context value.
5869 */
5870 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
5871 PCCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
5872 hmR0VmxImportGuestState(pVCpu, pVmcsInfo, CPUMCTX_EXTRN_CR0);
5873 if ( !pVM->hm.s.vmx.fUnrestrictedGuest
5874 && ( !CPUMIsGuestInRealModeEx(pCtx)
5875 && !CPUMIsGuestInV86ModeEx(pCtx)))
5876 {
5877 /* Protected mode checks */
5878 /* CS */
5879 Assert(pCtx->cs.Attr.n.u1Present);
5880 Assert(!(pCtx->cs.Attr.u & 0xf00));
5881 Assert(!(pCtx->cs.Attr.u & 0xfffe0000));
5882 Assert( (pCtx->cs.u32Limit & 0xfff) == 0xfff
5883 || !(pCtx->cs.Attr.n.u1Granularity));
5884 Assert( !(pCtx->cs.u32Limit & 0xfff00000)
5885 || (pCtx->cs.Attr.n.u1Granularity));
5886 /* CS cannot be loaded with NULL in protected mode. */
5887 Assert(pCtx->cs.Attr.u && !(pCtx->cs.Attr.u & X86DESCATTR_UNUSABLE)); /** @todo is this really true even for 64-bit CS? */
5888 if (pCtx->cs.Attr.n.u4Type == 9 || pCtx->cs.Attr.n.u4Type == 11)
5889 Assert(pCtx->cs.Attr.n.u2Dpl == pCtx->ss.Attr.n.u2Dpl);
5890 else if (pCtx->cs.Attr.n.u4Type == 13 || pCtx->cs.Attr.n.u4Type == 15)
5891 Assert(pCtx->cs.Attr.n.u2Dpl <= pCtx->ss.Attr.n.u2Dpl);
5892 else
5893 AssertMsgFailed(("Invalid CS Type %#x\n", pCtx->cs.Attr.n.u2Dpl));
5894 /* SS */
5895 Assert((pCtx->ss.Sel & X86_SEL_RPL) == (pCtx->cs.Sel & X86_SEL_RPL));
5896 Assert(pCtx->ss.Attr.n.u2Dpl == (pCtx->ss.Sel & X86_SEL_RPL));
5897 if ( !(pCtx->cr0 & X86_CR0_PE)
5898 || pCtx->cs.Attr.n.u4Type == 3)
5899 {
5900 Assert(!pCtx->ss.Attr.n.u2Dpl);
5901 }
5902 if (pCtx->ss.Attr.u && !(pCtx->ss.Attr.u & X86DESCATTR_UNUSABLE))
5903 {
5904 Assert((pCtx->ss.Sel & X86_SEL_RPL) == (pCtx->cs.Sel & X86_SEL_RPL));
5905 Assert(pCtx->ss.Attr.n.u4Type == 3 || pCtx->ss.Attr.n.u4Type == 7);
5906 Assert(pCtx->ss.Attr.n.u1Present);
5907 Assert(!(pCtx->ss.Attr.u & 0xf00));
5908 Assert(!(pCtx->ss.Attr.u & 0xfffe0000));
5909 Assert( (pCtx->ss.u32Limit & 0xfff) == 0xfff
5910 || !(pCtx->ss.Attr.n.u1Granularity));
5911 Assert( !(pCtx->ss.u32Limit & 0xfff00000)
5912 || (pCtx->ss.Attr.n.u1Granularity));
5913 }
5914 /* DS, ES, FS, GS - only check for usable selectors, see hmR0VmxExportGuestSegReg(). */
5915 if (pCtx->ds.Attr.u && !(pCtx->ds.Attr.u & X86DESCATTR_UNUSABLE))
5916 {
5917 Assert(pCtx->ds.Attr.n.u4Type & X86_SEL_TYPE_ACCESSED);
5918 Assert(pCtx->ds.Attr.n.u1Present);
5919 Assert(pCtx->ds.Attr.n.u4Type > 11 || pCtx->ds.Attr.n.u2Dpl >= (pCtx->ds.Sel & X86_SEL_RPL));
5920 Assert(!(pCtx->ds.Attr.u & 0xf00));
5921 Assert(!(pCtx->ds.Attr.u & 0xfffe0000));
5922 Assert( (pCtx->ds.u32Limit & 0xfff) == 0xfff
5923 || !(pCtx->ds.Attr.n.u1Granularity));
5924 Assert( !(pCtx->ds.u32Limit & 0xfff00000)
5925 || (pCtx->ds.Attr.n.u1Granularity));
5926 Assert( !(pCtx->ds.Attr.n.u4Type & X86_SEL_TYPE_CODE)
5927 || (pCtx->ds.Attr.n.u4Type & X86_SEL_TYPE_READ));
5928 }
5929 if (pCtx->es.Attr.u && !(pCtx->es.Attr.u & X86DESCATTR_UNUSABLE))
5930 {
5931 Assert(pCtx->es.Attr.n.u4Type & X86_SEL_TYPE_ACCESSED);
5932 Assert(pCtx->es.Attr.n.u1Present);
5933 Assert(pCtx->es.Attr.n.u4Type > 11 || pCtx->es.Attr.n.u2Dpl >= (pCtx->es.Sel & X86_SEL_RPL));
5934 Assert(!(pCtx->es.Attr.u & 0xf00));
5935 Assert(!(pCtx->es.Attr.u & 0xfffe0000));
5936 Assert( (pCtx->es.u32Limit & 0xfff) == 0xfff
5937 || !(pCtx->es.Attr.n.u1Granularity));
5938 Assert( !(pCtx->es.u32Limit & 0xfff00000)
5939 || (pCtx->es.Attr.n.u1Granularity));
5940 Assert( !(pCtx->es.Attr.n.u4Type & X86_SEL_TYPE_CODE)
5941 || (pCtx->es.Attr.n.u4Type & X86_SEL_TYPE_READ));
5942 }
5943 if (pCtx->fs.Attr.u && !(pCtx->fs.Attr.u & X86DESCATTR_UNUSABLE))
5944 {
5945 Assert(pCtx->fs.Attr.n.u4Type & X86_SEL_TYPE_ACCESSED);
5946 Assert(pCtx->fs.Attr.n.u1Present);
5947 Assert(pCtx->fs.Attr.n.u4Type > 11 || pCtx->fs.Attr.n.u2Dpl >= (pCtx->fs.Sel & X86_SEL_RPL));
5948 Assert(!(pCtx->fs.Attr.u & 0xf00));
5949 Assert(!(pCtx->fs.Attr.u & 0xfffe0000));
5950 Assert( (pCtx->fs.u32Limit & 0xfff) == 0xfff
5951 || !(pCtx->fs.Attr.n.u1Granularity));
5952 Assert( !(pCtx->fs.u32Limit & 0xfff00000)
5953 || (pCtx->fs.Attr.n.u1Granularity));
5954 Assert( !(pCtx->fs.Attr.n.u4Type & X86_SEL_TYPE_CODE)
5955 || (pCtx->fs.Attr.n.u4Type & X86_SEL_TYPE_READ));
5956 }
5957 if (pCtx->gs.Attr.u && !(pCtx->gs.Attr.u & X86DESCATTR_UNUSABLE))
5958 {
5959 Assert(pCtx->gs.Attr.n.u4Type & X86_SEL_TYPE_ACCESSED);
5960 Assert(pCtx->gs.Attr.n.u1Present);
5961 Assert(pCtx->gs.Attr.n.u4Type > 11 || pCtx->gs.Attr.n.u2Dpl >= (pCtx->gs.Sel & X86_SEL_RPL));
5962 Assert(!(pCtx->gs.Attr.u & 0xf00));
5963 Assert(!(pCtx->gs.Attr.u & 0xfffe0000));
5964 Assert( (pCtx->gs.u32Limit & 0xfff) == 0xfff
5965 || !(pCtx->gs.Attr.n.u1Granularity));
5966 Assert( !(pCtx->gs.u32Limit & 0xfff00000)
5967 || (pCtx->gs.Attr.n.u1Granularity));
5968 Assert( !(pCtx->gs.Attr.n.u4Type & X86_SEL_TYPE_CODE)
5969 || (pCtx->gs.Attr.n.u4Type & X86_SEL_TYPE_READ));
5970 }
5971 /* 64-bit capable CPUs. */
5972 Assert(!RT_HI_U32(pCtx->cs.u64Base));
5973 Assert(!pCtx->ss.Attr.u || !RT_HI_U32(pCtx->ss.u64Base));
5974 Assert(!pCtx->ds.Attr.u || !RT_HI_U32(pCtx->ds.u64Base));
5975 Assert(!pCtx->es.Attr.u || !RT_HI_U32(pCtx->es.u64Base));
5976 }
5977 else if ( CPUMIsGuestInV86ModeEx(pCtx)
5978 || ( CPUMIsGuestInRealModeEx(pCtx)
5979 && !pVM->hm.s.vmx.fUnrestrictedGuest))
5980 {
5981 /* Real and v86 mode checks. */
5982 /* hmR0VmxExportGuestSegReg() writes the modified in VMCS. We want what we're feeding to VT-x. */
5983 uint32_t u32CSAttr, u32SSAttr, u32DSAttr, u32ESAttr, u32FSAttr, u32GSAttr;
5984 if (pVmcsInfo->RealMode.fRealOnV86Active)
5985 {
5986 u32CSAttr = 0xf3; u32SSAttr = 0xf3; u32DSAttr = 0xf3;
5987 u32ESAttr = 0xf3; u32FSAttr = 0xf3; u32GSAttr = 0xf3;
5988 }
5989 else
5990 {
5991 u32CSAttr = pCtx->cs.Attr.u; u32SSAttr = pCtx->ss.Attr.u; u32DSAttr = pCtx->ds.Attr.u;
5992 u32ESAttr = pCtx->es.Attr.u; u32FSAttr = pCtx->fs.Attr.u; u32GSAttr = pCtx->gs.Attr.u;
5993 }
5994
5995 /* CS */
5996 AssertMsg((pCtx->cs.u64Base == (uint64_t)pCtx->cs.Sel << 4), ("CS base %#x %#x\n", pCtx->cs.u64Base, pCtx->cs.Sel));
5997 Assert(pCtx->cs.u32Limit == 0xffff);
5998 Assert(u32CSAttr == 0xf3);
5999 /* SS */
6000 Assert(pCtx->ss.u64Base == (uint64_t)pCtx->ss.Sel << 4);
6001 Assert(pCtx->ss.u32Limit == 0xffff);
6002 Assert(u32SSAttr == 0xf3);
6003 /* DS */
6004 Assert(pCtx->ds.u64Base == (uint64_t)pCtx->ds.Sel << 4);
6005 Assert(pCtx->ds.u32Limit == 0xffff);
6006 Assert(u32DSAttr == 0xf3);
6007 /* ES */
6008 Assert(pCtx->es.u64Base == (uint64_t)pCtx->es.Sel << 4);
6009 Assert(pCtx->es.u32Limit == 0xffff);
6010 Assert(u32ESAttr == 0xf3);
6011 /* FS */
6012 Assert(pCtx->fs.u64Base == (uint64_t)pCtx->fs.Sel << 4);
6013 Assert(pCtx->fs.u32Limit == 0xffff);
6014 Assert(u32FSAttr == 0xf3);
6015 /* GS */
6016 Assert(pCtx->gs.u64Base == (uint64_t)pCtx->gs.Sel << 4);
6017 Assert(pCtx->gs.u32Limit == 0xffff);
6018 Assert(u32GSAttr == 0xf3);
6019 /* 64-bit capable CPUs. */
6020 Assert(!RT_HI_U32(pCtx->cs.u64Base));
6021 Assert(!u32SSAttr || !RT_HI_U32(pCtx->ss.u64Base));
6022 Assert(!u32DSAttr || !RT_HI_U32(pCtx->ds.u64Base));
6023 Assert(!u32ESAttr || !RT_HI_U32(pCtx->es.u64Base));
6024 }
6025}
6026#endif /* VBOX_STRICT */
6027
6028
6029/**
6030 * Exports a guest segment register into the guest-state area in the VMCS.
6031 *
6032 * @returns VBox status code.
6033 * @param pVCpu The cross context virtual CPU structure.
6034 * @param pVmcsInfo The VMCS info. object.
6035 * @param iSegReg The segment register number (X86_SREG_XXX).
6036 * @param pSelReg Pointer to the segment selector.
6037 *
6038 * @remarks No-long-jump zone!!!
6039 */
6040static int hmR0VmxExportGuestSegReg(PVMCPUCC pVCpu, PCVMXVMCSINFO pVmcsInfo, uint8_t iSegReg, PCCPUMSELREG pSelReg)
6041{
6042 Assert(iSegReg < X86_SREG_COUNT);
6043 uint32_t const idxSel = g_aVmcsSegSel[iSegReg];
6044 uint32_t const idxLimit = g_aVmcsSegLimit[iSegReg];
6045 uint32_t const idxBase = g_aVmcsSegBase[iSegReg];
6046 uint32_t const idxAttr = g_aVmcsSegAttr[iSegReg];
6047
6048 uint32_t u32Access = pSelReg->Attr.u;
6049 if (pVmcsInfo->RealMode.fRealOnV86Active)
6050 {
6051 /* VT-x requires our real-using-v86 mode hack to override the segment access-right bits. */
6052 u32Access = 0xf3;
6053 Assert(pVCpu->CTX_SUFF(pVM)->hm.s.vmx.pRealModeTSS);
6054 Assert(PDMVmmDevHeapIsEnabled(pVCpu->CTX_SUFF(pVM)));
6055 RT_NOREF_PV(pVCpu);
6056 }
6057 else
6058 {
6059 /*
6060 * The way to differentiate between whether this is really a null selector or was just
6061 * a selector loaded with 0 in real-mode is using the segment attributes. A selector
6062 * loaded in real-mode with the value 0 is valid and usable in protected-mode and we
6063 * should -not- mark it as an unusable segment. Both the recompiler & VT-x ensures
6064 * NULL selectors loaded in protected-mode have their attribute as 0.
6065 */
6066 if (!u32Access)
6067 u32Access = X86DESCATTR_UNUSABLE;
6068 }
6069
6070 /* Validate segment access rights. Refer to Intel spec. "26.3.1.2 Checks on Guest Segment Registers". */
6071 AssertMsg((u32Access & X86DESCATTR_UNUSABLE) || (u32Access & X86_SEL_TYPE_ACCESSED),
6072 ("Access bit not set for usable segment. idx=%#x sel=%#x attr %#x\n", idxBase, pSelReg, pSelReg->Attr.u));
6073
6074 /*
6075 * Commit it to the VMCS.
6076 */
6077 int rc = VMXWriteVmcs32(idxSel, pSelReg->Sel); AssertRC(rc);
6078 rc = VMXWriteVmcs32(idxLimit, pSelReg->u32Limit); AssertRC(rc);
6079 rc = VMXWriteVmcsNw(idxBase, pSelReg->u64Base); AssertRC(rc);
6080 rc = VMXWriteVmcs32(idxAttr, u32Access); AssertRC(rc);
6081 return VINF_SUCCESS;
6082}
6083
6084
6085/**
6086 * Exports the guest segment registers, GDTR, IDTR, LDTR, TR into the guest-state
6087 * area in the VMCS.
6088 *
6089 * @returns VBox status code.
6090 * @param pVCpu The cross context virtual CPU structure.
6091 * @param pVmxTransient The VMX-transient structure.
6092 *
6093 * @remarks Will import guest CR0 on strict builds during validation of
6094 * segments.
6095 * @remarks No-long-jump zone!!!
6096 */
6097static int hmR0VmxExportGuestSegRegsXdtr(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
6098{
6099 int rc = VERR_INTERNAL_ERROR_5;
6100 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
6101 PCCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
6102 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
6103
6104 /*
6105 * Guest Segment registers: CS, SS, DS, ES, FS, GS.
6106 */
6107 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_SREG_MASK)
6108 {
6109#ifdef VBOX_WITH_REM
6110 if (!pVM->hm.s.vmx.fUnrestrictedGuest)
6111 {
6112 Assert(!pVmxTransient->fIsNestedGuest);
6113 Assert(pVM->hm.s.vmx.pRealModeTSS);
6114 AssertCompile(PGMMODE_REAL < PGMMODE_PROTECTED);
6115 if ( pVmcsInfo->fWasInRealMode
6116 && PGMGetGuestMode(pVCpu) >= PGMMODE_PROTECTED)
6117 {
6118 /*
6119 * Notify the recompiler must flush its code-cache as the guest -may-
6120 * rewrite code it in real-mode (e.g. OpenBSD 4.0).
6121 */
6122 REMFlushTBs(pVM);
6123 Log4Func(("Switch to protected mode detected!\n"));
6124 pVmcsInfo->fWasInRealMode = false;
6125 }
6126 }
6127#endif
6128 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_CS)
6129 {
6130 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_CS);
6131 if (pVmcsInfo->RealMode.fRealOnV86Active)
6132 pVmcsInfo->RealMode.AttrCS.u = pCtx->cs.Attr.u;
6133 rc = hmR0VmxExportGuestSegReg(pVCpu, pVmcsInfo, X86_SREG_CS, &pCtx->cs);
6134 AssertRC(rc);
6135 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_CS);
6136 }
6137
6138 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_SS)
6139 {
6140 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_SS);
6141 if (pVmcsInfo->RealMode.fRealOnV86Active)
6142 pVmcsInfo->RealMode.AttrSS.u = pCtx->ss.Attr.u;
6143 rc = hmR0VmxExportGuestSegReg(pVCpu, pVmcsInfo, X86_SREG_SS, &pCtx->ss);
6144 AssertRC(rc);
6145 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_SS);
6146 }
6147
6148 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_DS)
6149 {
6150 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_DS);
6151 if (pVmcsInfo->RealMode.fRealOnV86Active)
6152 pVmcsInfo->RealMode.AttrDS.u = pCtx->ds.Attr.u;
6153 rc = hmR0VmxExportGuestSegReg(pVCpu, pVmcsInfo, X86_SREG_DS, &pCtx->ds);
6154 AssertRC(rc);
6155 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_DS);
6156 }
6157
6158 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_ES)
6159 {
6160 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_ES);
6161 if (pVmcsInfo->RealMode.fRealOnV86Active)
6162 pVmcsInfo->RealMode.AttrES.u = pCtx->es.Attr.u;
6163 rc = hmR0VmxExportGuestSegReg(pVCpu, pVmcsInfo, X86_SREG_ES, &pCtx->es);
6164 AssertRC(rc);
6165 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_ES);
6166 }
6167
6168 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_FS)
6169 {
6170 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_FS);
6171 if (pVmcsInfo->RealMode.fRealOnV86Active)
6172 pVmcsInfo->RealMode.AttrFS.u = pCtx->fs.Attr.u;
6173 rc = hmR0VmxExportGuestSegReg(pVCpu, pVmcsInfo, X86_SREG_FS, &pCtx->fs);
6174 AssertRC(rc);
6175 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_FS);
6176 }
6177
6178 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_GS)
6179 {
6180 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_GS);
6181 if (pVmcsInfo->RealMode.fRealOnV86Active)
6182 pVmcsInfo->RealMode.AttrGS.u = pCtx->gs.Attr.u;
6183 rc = hmR0VmxExportGuestSegReg(pVCpu, pVmcsInfo, X86_SREG_GS, &pCtx->gs);
6184 AssertRC(rc);
6185 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_GS);
6186 }
6187
6188#ifdef VBOX_STRICT
6189 hmR0VmxValidateSegmentRegs(pVCpu, pVmcsInfo);
6190#endif
6191 Log4Func(("cs={%#04x base=%#RX64 limit=%#RX32 attr=%#RX32}\n", pCtx->cs.Sel, pCtx->cs.u64Base, pCtx->cs.u32Limit,
6192 pCtx->cs.Attr.u));
6193 }
6194
6195 /*
6196 * Guest TR.
6197 */
6198 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_TR)
6199 {
6200 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_TR);
6201
6202 /*
6203 * Real-mode emulation using virtual-8086 mode with CR4.VME. Interrupt redirection is
6204 * achieved using the interrupt redirection bitmap (all bits cleared to let the guest
6205 * handle INT-n's) in the TSS. See hmR3InitFinalizeR0() to see how pRealModeTSS is setup.
6206 */
6207 uint16_t u16Sel;
6208 uint32_t u32Limit;
6209 uint64_t u64Base;
6210 uint32_t u32AccessRights;
6211 if (!pVmcsInfo->RealMode.fRealOnV86Active)
6212 {
6213 u16Sel = pCtx->tr.Sel;
6214 u32Limit = pCtx->tr.u32Limit;
6215 u64Base = pCtx->tr.u64Base;
6216 u32AccessRights = pCtx->tr.Attr.u;
6217 }
6218 else
6219 {
6220 Assert(!pVmxTransient->fIsNestedGuest);
6221 Assert(pVM->hm.s.vmx.pRealModeTSS);
6222 Assert(PDMVmmDevHeapIsEnabled(pVM)); /* Guaranteed by HMCanExecuteGuest() -XXX- what about inner loop changes? */
6223
6224 /* We obtain it here every time as PCI regions could be reconfigured in the guest, changing the VMMDev base. */
6225 RTGCPHYS GCPhys;
6226 rc = PDMVmmDevHeapR3ToGCPhys(pVM, pVM->hm.s.vmx.pRealModeTSS, &GCPhys);
6227 AssertRCReturn(rc, rc);
6228
6229 X86DESCATTR DescAttr;
6230 DescAttr.u = 0;
6231 DescAttr.n.u1Present = 1;
6232 DescAttr.n.u4Type = X86_SEL_TYPE_SYS_386_TSS_BUSY;
6233
6234 u16Sel = 0;
6235 u32Limit = HM_VTX_TSS_SIZE;
6236 u64Base = GCPhys;
6237 u32AccessRights = DescAttr.u;
6238 }
6239
6240 /* Validate. */
6241 Assert(!(u16Sel & RT_BIT(2)));
6242 AssertMsg( (u32AccessRights & 0xf) == X86_SEL_TYPE_SYS_386_TSS_BUSY
6243 || (u32AccessRights & 0xf) == X86_SEL_TYPE_SYS_286_TSS_BUSY, ("TSS is not busy!? %#x\n", u32AccessRights));
6244 AssertMsg(!(u32AccessRights & X86DESCATTR_UNUSABLE), ("TR unusable bit is not clear!? %#x\n", u32AccessRights));
6245 Assert(!(u32AccessRights & RT_BIT(4))); /* System MBZ.*/
6246 Assert(u32AccessRights & RT_BIT(7)); /* Present MB1.*/
6247 Assert(!(u32AccessRights & 0xf00)); /* 11:8 MBZ. */
6248 Assert(!(u32AccessRights & 0xfffe0000)); /* 31:17 MBZ. */
6249 Assert( (u32Limit & 0xfff) == 0xfff
6250 || !(u32AccessRights & RT_BIT(15))); /* Granularity MBZ. */
6251 Assert( !(pCtx->tr.u32Limit & 0xfff00000)
6252 || (u32AccessRights & RT_BIT(15))); /* Granularity MB1. */
6253
6254 rc = VMXWriteVmcs16(VMX_VMCS16_GUEST_TR_SEL, u16Sel); AssertRC(rc);
6255 rc = VMXWriteVmcs32(VMX_VMCS32_GUEST_TR_LIMIT, u32Limit); AssertRC(rc);
6256 rc = VMXWriteVmcs32(VMX_VMCS32_GUEST_TR_ACCESS_RIGHTS, u32AccessRights); AssertRC(rc);
6257 rc = VMXWriteVmcsNw(VMX_VMCS_GUEST_TR_BASE, u64Base); AssertRC(rc);
6258
6259 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_TR);
6260 Log4Func(("tr base=%#RX64 limit=%#RX32\n", pCtx->tr.u64Base, pCtx->tr.u32Limit));
6261 }
6262
6263 /*
6264 * Guest GDTR.
6265 */
6266 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_GDTR)
6267 {
6268 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_GDTR);
6269
6270 rc = VMXWriteVmcs32(VMX_VMCS32_GUEST_GDTR_LIMIT, pCtx->gdtr.cbGdt); AssertRC(rc);
6271 rc = VMXWriteVmcsNw(VMX_VMCS_GUEST_GDTR_BASE, pCtx->gdtr.pGdt); AssertRC(rc);
6272
6273 /* Validate. */
6274 Assert(!(pCtx->gdtr.cbGdt & 0xffff0000)); /* Bits 31:16 MBZ. */
6275
6276 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_GDTR);
6277 Log4Func(("gdtr base=%#RX64 limit=%#RX32\n", pCtx->gdtr.pGdt, pCtx->gdtr.cbGdt));
6278 }
6279
6280 /*
6281 * Guest LDTR.
6282 */
6283 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_LDTR)
6284 {
6285 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_LDTR);
6286
6287 /* The unusable bit is specific to VT-x, if it's a null selector mark it as an unusable segment. */
6288 uint32_t u32Access;
6289 if ( !pVmxTransient->fIsNestedGuest
6290 && !pCtx->ldtr.Attr.u)
6291 u32Access = X86DESCATTR_UNUSABLE;
6292 else
6293 u32Access = pCtx->ldtr.Attr.u;
6294
6295 rc = VMXWriteVmcs16(VMX_VMCS16_GUEST_LDTR_SEL, pCtx->ldtr.Sel); AssertRC(rc);
6296 rc = VMXWriteVmcs32(VMX_VMCS32_GUEST_LDTR_LIMIT, pCtx->ldtr.u32Limit); AssertRC(rc);
6297 rc = VMXWriteVmcs32(VMX_VMCS32_GUEST_LDTR_ACCESS_RIGHTS, u32Access); AssertRC(rc);
6298 rc = VMXWriteVmcsNw(VMX_VMCS_GUEST_LDTR_BASE, pCtx->ldtr.u64Base); AssertRC(rc);
6299
6300 /* Validate. */
6301 if (!(u32Access & X86DESCATTR_UNUSABLE))
6302 {
6303 Assert(!(pCtx->ldtr.Sel & RT_BIT(2))); /* TI MBZ. */
6304 Assert(pCtx->ldtr.Attr.n.u4Type == 2); /* Type MB2 (LDT). */
6305 Assert(!pCtx->ldtr.Attr.n.u1DescType); /* System MBZ. */
6306 Assert(pCtx->ldtr.Attr.n.u1Present == 1); /* Present MB1. */
6307 Assert(!pCtx->ldtr.Attr.n.u4LimitHigh); /* 11:8 MBZ. */
6308 Assert(!(pCtx->ldtr.Attr.u & 0xfffe0000)); /* 31:17 MBZ. */
6309 Assert( (pCtx->ldtr.u32Limit & 0xfff) == 0xfff
6310 || !pCtx->ldtr.Attr.n.u1Granularity); /* Granularity MBZ. */
6311 Assert( !(pCtx->ldtr.u32Limit & 0xfff00000)
6312 || pCtx->ldtr.Attr.n.u1Granularity); /* Granularity MB1. */
6313 }
6314
6315 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_LDTR);
6316 Log4Func(("ldtr base=%#RX64 limit=%#RX32\n", pCtx->ldtr.u64Base, pCtx->ldtr.u32Limit));
6317 }
6318
6319 /*
6320 * Guest IDTR.
6321 */
6322 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_IDTR)
6323 {
6324 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_IDTR);
6325
6326 rc = VMXWriteVmcs32(VMX_VMCS32_GUEST_IDTR_LIMIT, pCtx->idtr.cbIdt); AssertRC(rc);
6327 rc = VMXWriteVmcsNw(VMX_VMCS_GUEST_IDTR_BASE, pCtx->idtr.pIdt); AssertRC(rc);
6328
6329 /* Validate. */
6330 Assert(!(pCtx->idtr.cbIdt & 0xffff0000)); /* Bits 31:16 MBZ. */
6331
6332 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_IDTR);
6333 Log4Func(("idtr base=%#RX64 limit=%#RX32\n", pCtx->idtr.pIdt, pCtx->idtr.cbIdt));
6334 }
6335
6336 return VINF_SUCCESS;
6337}
6338
6339
6340/**
6341 * Exports certain guest MSRs into the VM-entry MSR-load and VM-exit MSR-store
6342 * areas.
6343 *
6344 * These MSRs will automatically be loaded to the host CPU on every successful
6345 * VM-entry and stored from the host CPU on every successful VM-exit.
6346 *
6347 * We creates/updates MSR slots for the host MSRs in the VM-exit MSR-load area. The
6348 * actual host MSR values are not- updated here for performance reasons. See
6349 * hmR0VmxExportHostMsrs().
6350 *
6351 * We also exports the guest sysenter MSRs into the guest-state area in the VMCS.
6352 *
6353 * @returns VBox status code.
6354 * @param pVCpu The cross context virtual CPU structure.
6355 * @param pVmxTransient The VMX-transient structure.
6356 *
6357 * @remarks No-long-jump zone!!!
6358 */
6359static int hmR0VmxExportGuestMsrs(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
6360{
6361 AssertPtr(pVCpu);
6362 AssertPtr(pVmxTransient);
6363
6364 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
6365 PCCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
6366
6367 /*
6368 * MSRs that we use the auto-load/store MSR area in the VMCS.
6369 * For 64-bit hosts, we load/restore them lazily, see hmR0VmxLazyLoadGuestMsrs(),
6370 * nothing to do here. The host MSR values are updated when it's safe in
6371 * hmR0VmxLazySaveHostMsrs().
6372 *
6373 * For nested-guests, the guests MSRs from the VM-entry MSR-load area are already
6374 * loaded (into the guest-CPU context) by the VMLAUNCH/VMRESUME instruction
6375 * emulation, nothing to do here.
6376 */
6377 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_VMX_GUEST_AUTO_MSRS)
6378 {
6379 /* No auto-load/store MSRs currently. */
6380 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_VMX_GUEST_AUTO_MSRS);
6381 }
6382
6383 /*
6384 * Guest Sysenter MSRs.
6385 */
6386 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_SYSENTER_MSR_MASK)
6387 {
6388 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_SYSENTER_MSRS);
6389
6390 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_SYSENTER_CS_MSR)
6391 {
6392 int rc = VMXWriteVmcs32(VMX_VMCS32_GUEST_SYSENTER_CS, pCtx->SysEnter.cs);
6393 AssertRC(rc);
6394 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_SYSENTER_CS_MSR);
6395 }
6396
6397 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_SYSENTER_EIP_MSR)
6398 {
6399 int rc = VMXWriteVmcsNw(VMX_VMCS_GUEST_SYSENTER_EIP, pCtx->SysEnter.eip);
6400 AssertRC(rc);
6401 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_SYSENTER_EIP_MSR);
6402 }
6403
6404 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_SYSENTER_ESP_MSR)
6405 {
6406 int rc = VMXWriteVmcsNw(VMX_VMCS_GUEST_SYSENTER_ESP, pCtx->SysEnter.esp);
6407 AssertRC(rc);
6408 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_SYSENTER_ESP_MSR);
6409 }
6410 }
6411
6412 /*
6413 * Guest/host EFER MSR.
6414 */
6415 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_EFER_MSR)
6416 {
6417 /* Whether we are using the VMCS to swap the EFER MSR must have been
6418 determined earlier while exporting VM-entry/VM-exit controls. */
6419 Assert(!(ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_VMX_ENTRY_EXIT_CTLS));
6420 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_EFER);
6421
6422 if (hmR0VmxShouldSwapEferMsr(pVCpu))
6423 {
6424 /*
6425 * If the CPU supports VMCS controls for swapping EFER, use it. Otherwise, we have no option
6426 * but to use the auto-load store MSR area in the VMCS for swapping EFER. See @bugref{7368}.
6427 */
6428 if (pVM->hm.s.vmx.fSupportsVmcsEfer)
6429 {
6430 int rc = VMXWriteVmcs64(VMX_VMCS64_GUEST_EFER_FULL, pCtx->msrEFER);
6431 AssertRC(rc);
6432 }
6433 else
6434 {
6435 /*
6436 * We shall use the auto-load/store MSR area only for loading the EFER MSR but we must
6437 * continue to intercept guest read and write accesses to it, see @bugref{7386#c16}.
6438 */
6439 int rc = hmR0VmxAddAutoLoadStoreMsr(pVCpu, pVmxTransient, MSR_K6_EFER, pCtx->msrEFER,
6440 false /* fSetReadWrite */, false /* fUpdateHostMsr */);
6441 AssertRCReturn(rc, rc);
6442 }
6443 }
6444 else if (!pVM->hm.s.vmx.fSupportsVmcsEfer)
6445 hmR0VmxRemoveAutoLoadStoreMsr(pVCpu, pVmxTransient, MSR_K6_EFER);
6446
6447 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_EFER_MSR);
6448 }
6449
6450 /*
6451 * Other MSRs.
6452 * Speculation Control (R/W).
6453 */
6454 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_OTHER_MSRS)
6455 {
6456 HMVMX_CPUMCTX_ASSERT(pVCpu, HM_CHANGED_GUEST_OTHER_MSRS);
6457 if (pVM->cpum.ro.GuestFeatures.fIbrs)
6458 {
6459 int rc = hmR0VmxAddAutoLoadStoreMsr(pVCpu, pVmxTransient, MSR_IA32_SPEC_CTRL, CPUMGetGuestSpecCtrl(pVCpu),
6460 false /* fSetReadWrite */, false /* fUpdateHostMsr */);
6461 AssertRCReturn(rc, rc);
6462 }
6463 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_OTHER_MSRS);
6464 }
6465
6466 return VINF_SUCCESS;
6467}
6468
6469
6470/**
6471 * Selects up the appropriate function to run guest code.
6472 *
6473 * @returns VBox status code.
6474 * @param pVCpu The cross context virtual CPU structure.
6475 * @param pVmxTransient The VMX-transient structure.
6476 *
6477 * @remarks No-long-jump zone!!!
6478 */
6479static int hmR0VmxSelectVMRunHandler(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
6480{
6481 PCCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
6482 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
6483
6484 if (CPUMIsGuestInLongModeEx(pCtx))
6485 {
6486#ifndef VBOX_WITH_64_BITS_GUESTS
6487 return VERR_PGM_UNSUPPORTED_SHADOW_PAGING_MODE;
6488#else
6489 Assert(pVCpu->CTX_SUFF(pVM)->hm.s.fAllow64BitGuests); /* Guaranteed by hmR3InitFinalizeR0(). */
6490 /* Guest is in long mode, use the 64-bit handler (host is 64-bit). */
6491 pVmcsInfo->pfnStartVM = VMXR0StartVM64;
6492#endif
6493 }
6494 else
6495 {
6496 /* Guest is not in long mode, use the 32-bit handler. */
6497 pVmcsInfo->pfnStartVM = VMXR0StartVM32;
6498 }
6499 Assert(pVmcsInfo->pfnStartVM);
6500 return VINF_SUCCESS;
6501}
6502
6503
6504/**
6505 * Wrapper for running the guest code in VT-x.
6506 *
6507 * @returns VBox status code, no informational status codes.
6508 * @param pVCpu The cross context virtual CPU structure.
6509 * @param pVmxTransient The VMX-transient structure.
6510 *
6511 * @remarks No-long-jump zone!!!
6512 */
6513DECLINLINE(int) hmR0VmxRunGuest(PVMCPUCC pVCpu, PCVMXTRANSIENT pVmxTransient)
6514{
6515 /* Mark that HM is the keeper of all guest-CPU registers now that we're going to execute guest code. */
6516 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
6517 pCtx->fExtrn |= HMVMX_CPUMCTX_EXTRN_ALL | CPUMCTX_EXTRN_KEEPER_HM;
6518
6519 /** @todo Add stats for VMRESUME vs VMLAUNCH. */
6520
6521 /*
6522 * 64-bit Windows uses XMM registers in the kernel as the Microsoft compiler expresses
6523 * floating-point operations using SSE instructions. Some XMM registers (XMM6-XMM15) are
6524 * callee-saved and thus the need for this XMM wrapper.
6525 *
6526 * See MSDN "Configuring Programs for 64-bit/x64 Software Conventions / Register Usage".
6527 */
6528 PCVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
6529 bool const fResumeVM = RT_BOOL(pVmcsInfo->fVmcsState & VMX_V_VMCS_LAUNCH_STATE_LAUNCHED);
6530 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
6531#ifdef VBOX_WITH_KERNEL_USING_XMM
6532 int rc = hmR0VMXStartVMWrapXMM(fResumeVM, pCtx, NULL /*pvUnused*/, pVM, pVCpu, pVmcsInfo->pfnStartVM);
6533#else
6534 int rc = pVmcsInfo->pfnStartVM(fResumeVM, pCtx, NULL /*pvUnused*/, pVM, pVCpu);
6535#endif
6536 AssertMsg(rc <= VINF_SUCCESS, ("%Rrc\n", rc));
6537 return rc;
6538}
6539
6540
6541/**
6542 * Reports world-switch error and dumps some useful debug info.
6543 *
6544 * @param pVCpu The cross context virtual CPU structure.
6545 * @param rcVMRun The return code from VMLAUNCH/VMRESUME.
6546 * @param pVmxTransient The VMX-transient structure (only
6547 * exitReason updated).
6548 */
6549static void hmR0VmxReportWorldSwitchError(PVMCPUCC pVCpu, int rcVMRun, PVMXTRANSIENT pVmxTransient)
6550{
6551 Assert(pVCpu);
6552 Assert(pVmxTransient);
6553 HMVMX_ASSERT_PREEMPT_SAFE(pVCpu);
6554
6555 Log4Func(("VM-entry failure: %Rrc\n", rcVMRun));
6556 switch (rcVMRun)
6557 {
6558 case VERR_VMX_INVALID_VMXON_PTR:
6559 AssertFailed();
6560 break;
6561 case VINF_SUCCESS: /* VMLAUNCH/VMRESUME succeeded but VM-entry failed... yeah, true story. */
6562 case VERR_VMX_UNABLE_TO_START_VM: /* VMLAUNCH/VMRESUME itself failed. */
6563 {
6564 int rc = VMXReadVmcs32(VMX_VMCS32_RO_EXIT_REASON, &pVCpu->hm.s.vmx.LastError.u32ExitReason);
6565 rc |= VMXReadVmcs32(VMX_VMCS32_RO_VM_INSTR_ERROR, &pVCpu->hm.s.vmx.LastError.u32InstrError);
6566 AssertRC(rc);
6567 hmR0VmxReadExitQualVmcs(pVmxTransient);
6568
6569 pVCpu->hm.s.vmx.LastError.idEnteredCpu = pVCpu->hm.s.idEnteredCpu;
6570 /* LastError.idCurrentCpu was already updated in hmR0VmxPreRunGuestCommitted().
6571 Cannot do it here as we may have been long preempted. */
6572
6573#ifdef VBOX_STRICT
6574 PVMXVMCSINFO pVmcsInfo = hmGetVmxActiveVmcsInfo(pVCpu);
6575 Log4(("uExitReason %#RX32 (VmxTransient %#RX16)\n", pVCpu->hm.s.vmx.LastError.u32ExitReason,
6576 pVmxTransient->uExitReason));
6577 Log4(("Exit Qualification %#RX64\n", pVmxTransient->uExitQual));
6578 Log4(("InstrError %#RX32\n", pVCpu->hm.s.vmx.LastError.u32InstrError));
6579 if (pVCpu->hm.s.vmx.LastError.u32InstrError <= HMVMX_INSTR_ERROR_MAX)
6580 Log4(("InstrError Desc. \"%s\"\n", g_apszVmxInstrErrors[pVCpu->hm.s.vmx.LastError.u32InstrError]));
6581 else
6582 Log4(("InstrError Desc. Range exceeded %u\n", HMVMX_INSTR_ERROR_MAX));
6583 Log4(("Entered host CPU %u\n", pVCpu->hm.s.vmx.LastError.idEnteredCpu));
6584 Log4(("Current host CPU %u\n", pVCpu->hm.s.vmx.LastError.idCurrentCpu));
6585
6586 static struct
6587 {
6588 /** Name of the field to log. */
6589 const char *pszName;
6590 /** The VMCS field. */
6591 uint32_t uVmcsField;
6592 /** Whether host support of this field needs to be checked. */
6593 bool fCheckSupport;
6594 } const s_aVmcsFields[] =
6595 {
6596 { "VMX_VMCS32_CTRL_PIN_EXEC", VMX_VMCS32_CTRL_PIN_EXEC, false },
6597 { "VMX_VMCS32_CTRL_PROC_EXEC", VMX_VMCS32_CTRL_PROC_EXEC, false },
6598 { "VMX_VMCS32_CTRL_PROC_EXEC2", VMX_VMCS32_CTRL_PROC_EXEC2, true },
6599 { "VMX_VMCS32_CTRL_ENTRY", VMX_VMCS32_CTRL_ENTRY, false },
6600 { "VMX_VMCS32_CTRL_EXIT", VMX_VMCS32_CTRL_EXIT, false },
6601 { "VMX_VMCS32_CTRL_CR3_TARGET_COUNT", VMX_VMCS32_CTRL_CR3_TARGET_COUNT, false },
6602 { "VMX_VMCS32_CTRL_ENTRY_INTERRUPTION_INFO", VMX_VMCS32_CTRL_ENTRY_INTERRUPTION_INFO, false },
6603 { "VMX_VMCS32_CTRL_ENTRY_EXCEPTION_ERRCODE", VMX_VMCS32_CTRL_ENTRY_EXCEPTION_ERRCODE, false },
6604 { "VMX_VMCS32_CTRL_ENTRY_INSTR_LENGTH", VMX_VMCS32_CTRL_ENTRY_INSTR_LENGTH, false },
6605 { "VMX_VMCS32_CTRL_TPR_THRESHOLD", VMX_VMCS32_CTRL_TPR_THRESHOLD, false },
6606 { "VMX_VMCS32_CTRL_EXIT_MSR_STORE_COUNT", VMX_VMCS32_CTRL_EXIT_MSR_STORE_COUNT, false },
6607 { "VMX_VMCS32_CTRL_EXIT_MSR_LOAD_COUNT", VMX_VMCS32_CTRL_EXIT_MSR_LOAD_COUNT, false },
6608 { "VMX_VMCS32_CTRL_ENTRY_MSR_LOAD_COUNT", VMX_VMCS32_CTRL_ENTRY_MSR_LOAD_COUNT, false },
6609 { "VMX_VMCS32_CTRL_EXCEPTION_BITMAP", VMX_VMCS32_CTRL_EXCEPTION_BITMAP, false },
6610 { "VMX_VMCS32_CTRL_PAGEFAULT_ERROR_MASK", VMX_VMCS32_CTRL_PAGEFAULT_ERROR_MASK, false },
6611 { "VMX_VMCS32_CTRL_PAGEFAULT_ERROR_MATCH", VMX_VMCS32_CTRL_PAGEFAULT_ERROR_MATCH, false },
6612 { "VMX_VMCS_CTRL_CR0_MASK", VMX_VMCS_CTRL_CR0_MASK, false },
6613 { "VMX_VMCS_CTRL_CR0_READ_SHADOW", VMX_VMCS_CTRL_CR0_READ_SHADOW, false },
6614 { "VMX_VMCS_CTRL_CR4_MASK", VMX_VMCS_CTRL_CR4_MASK, false },
6615 { "VMX_VMCS_CTRL_CR4_READ_SHADOW", VMX_VMCS_CTRL_CR4_READ_SHADOW, false },
6616 { "VMX_VMCS64_CTRL_EPTP_FULL", VMX_VMCS64_CTRL_EPTP_FULL, true },
6617 { "VMX_VMCS_GUEST_RIP", VMX_VMCS_GUEST_RIP, false },
6618 { "VMX_VMCS_GUEST_RSP", VMX_VMCS_GUEST_RSP, false },
6619 { "VMX_VMCS_GUEST_RFLAGS", VMX_VMCS_GUEST_RFLAGS, false },
6620 { "VMX_VMCS16_VPID", VMX_VMCS16_VPID, true, },
6621 { "VMX_VMCS_HOST_CR0", VMX_VMCS_HOST_CR0, false },
6622 { "VMX_VMCS_HOST_CR3", VMX_VMCS_HOST_CR3, false },
6623 { "VMX_VMCS_HOST_CR4", VMX_VMCS_HOST_CR4, false },
6624 /* The order of selector fields below are fixed! */
6625 { "VMX_VMCS16_HOST_ES_SEL", VMX_VMCS16_HOST_ES_SEL, false },
6626 { "VMX_VMCS16_HOST_CS_SEL", VMX_VMCS16_HOST_CS_SEL, false },
6627 { "VMX_VMCS16_HOST_SS_SEL", VMX_VMCS16_HOST_SS_SEL, false },
6628 { "VMX_VMCS16_HOST_DS_SEL", VMX_VMCS16_HOST_DS_SEL, false },
6629 { "VMX_VMCS16_HOST_FS_SEL", VMX_VMCS16_HOST_FS_SEL, false },
6630 { "VMX_VMCS16_HOST_GS_SEL", VMX_VMCS16_HOST_GS_SEL, false },
6631 { "VMX_VMCS16_HOST_TR_SEL", VMX_VMCS16_HOST_TR_SEL, false },
6632 /* End of ordered selector fields. */
6633 { "VMX_VMCS_HOST_TR_BASE", VMX_VMCS_HOST_TR_BASE, false },
6634 { "VMX_VMCS_HOST_GDTR_BASE", VMX_VMCS_HOST_GDTR_BASE, false },
6635 { "VMX_VMCS_HOST_IDTR_BASE", VMX_VMCS_HOST_IDTR_BASE, false },
6636 { "VMX_VMCS32_HOST_SYSENTER_CS", VMX_VMCS32_HOST_SYSENTER_CS, false },
6637 { "VMX_VMCS_HOST_SYSENTER_EIP", VMX_VMCS_HOST_SYSENTER_EIP, false },
6638 { "VMX_VMCS_HOST_SYSENTER_ESP", VMX_VMCS_HOST_SYSENTER_ESP, false },
6639 { "VMX_VMCS_HOST_RSP", VMX_VMCS_HOST_RSP, false },
6640 { "VMX_VMCS_HOST_RIP", VMX_VMCS_HOST_RIP, false }
6641 };
6642
6643 RTGDTR HostGdtr;
6644 ASMGetGDTR(&HostGdtr);
6645
6646 uint32_t const cVmcsFields = RT_ELEMENTS(s_aVmcsFields);
6647 for (uint32_t i = 0; i < cVmcsFields; i++)
6648 {
6649 uint32_t const uVmcsField = s_aVmcsFields[i].uVmcsField;
6650
6651 bool fSupported;
6652 if (!s_aVmcsFields[i].fCheckSupport)
6653 fSupported = true;
6654 else
6655 {
6656 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
6657 switch (uVmcsField)
6658 {
6659 case VMX_VMCS64_CTRL_EPTP_FULL: fSupported = pVM->hm.s.fNestedPaging; break;
6660 case VMX_VMCS16_VPID: fSupported = pVM->hm.s.vmx.fVpid; break;
6661 case VMX_VMCS32_CTRL_PROC_EXEC2:
6662 fSupported = RT_BOOL(pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_USE_SECONDARY_CTLS);
6663 break;
6664 default:
6665 AssertMsgFailedReturnVoid(("Failed to provide VMCS field support for %#RX32\n", uVmcsField));
6666 }
6667 }
6668
6669 if (fSupported)
6670 {
6671 uint8_t const uWidth = RT_BF_GET(uVmcsField, VMX_BF_VMCSFIELD_WIDTH);
6672 switch (uWidth)
6673 {
6674 case VMX_VMCSFIELD_WIDTH_16BIT:
6675 {
6676 uint16_t u16Val;
6677 rc = VMXReadVmcs16(uVmcsField, &u16Val);
6678 AssertRC(rc);
6679 Log4(("%-40s = %#RX16\n", s_aVmcsFields[i].pszName, u16Val));
6680
6681 if ( uVmcsField >= VMX_VMCS16_HOST_ES_SEL
6682 && uVmcsField <= VMX_VMCS16_HOST_TR_SEL)
6683 {
6684 if (u16Val < HostGdtr.cbGdt)
6685 {
6686 /* Order of selectors in s_apszSel is fixed and matches the order in s_aVmcsFields. */
6687 static const char * const s_apszSel[] = { "Host ES", "Host CS", "Host SS", "Host DS",
6688 "Host FS", "Host GS", "Host TR" };
6689 uint8_t const idxSel = RT_BF_GET(uVmcsField, VMX_BF_VMCSFIELD_INDEX);
6690 Assert(idxSel < RT_ELEMENTS(s_apszSel));
6691 PCX86DESCHC pDesc = (PCX86DESCHC)(HostGdtr.pGdt + (u16Val & X86_SEL_MASK));
6692 hmR0DumpDescriptor(pDesc, u16Val, s_apszSel[idxSel]);
6693 }
6694 else
6695 Log4((" Selector value exceeds GDT limit!\n"));
6696 }
6697 break;
6698 }
6699
6700 case VMX_VMCSFIELD_WIDTH_32BIT:
6701 {
6702 uint32_t u32Val;
6703 rc = VMXReadVmcs32(uVmcsField, &u32Val);
6704 AssertRC(rc);
6705 Log4(("%-40s = %#RX32\n", s_aVmcsFields[i].pszName, u32Val));
6706 break;
6707 }
6708
6709 case VMX_VMCSFIELD_WIDTH_64BIT:
6710 case VMX_VMCSFIELD_WIDTH_NATURAL:
6711 {
6712 uint64_t u64Val;
6713 rc = VMXReadVmcs64(uVmcsField, &u64Val);
6714 AssertRC(rc);
6715 Log4(("%-40s = %#RX64\n", s_aVmcsFields[i].pszName, u64Val));
6716 break;
6717 }
6718 }
6719 }
6720 }
6721
6722 Log4(("MSR_K6_EFER = %#RX64\n", ASMRdMsr(MSR_K6_EFER)));
6723 Log4(("MSR_K8_CSTAR = %#RX64\n", ASMRdMsr(MSR_K8_CSTAR)));
6724 Log4(("MSR_K8_LSTAR = %#RX64\n", ASMRdMsr(MSR_K8_LSTAR)));
6725 Log4(("MSR_K6_STAR = %#RX64\n", ASMRdMsr(MSR_K6_STAR)));
6726 Log4(("MSR_K8_SF_MASK = %#RX64\n", ASMRdMsr(MSR_K8_SF_MASK)));
6727 Log4(("MSR_K8_KERNEL_GS_BASE = %#RX64\n", ASMRdMsr(MSR_K8_KERNEL_GS_BASE)));
6728#endif /* VBOX_STRICT */
6729 break;
6730 }
6731
6732 default:
6733 /* Impossible */
6734 AssertMsgFailed(("hmR0VmxReportWorldSwitchError %Rrc (%#x)\n", rcVMRun, rcVMRun));
6735 break;
6736 }
6737}
6738
6739
6740/**
6741 * Sets up the usage of TSC-offsetting and updates the VMCS.
6742 *
6743 * If offsetting is not possible, cause VM-exits on RDTSC(P)s. Also sets up the
6744 * VMX-preemption timer.
6745 *
6746 * @returns VBox status code.
6747 * @param pVCpu The cross context virtual CPU structure.
6748 * @param pVmxTransient The VMX-transient structure.
6749 *
6750 * @remarks No-long-jump zone!!!
6751 */
6752static void hmR0VmxUpdateTscOffsettingAndPreemptTimer(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
6753{
6754 bool fOffsettedTsc;
6755 bool fParavirtTsc;
6756 uint64_t uTscOffset;
6757 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
6758 PVMXVMCSINFO pVmcsInfo = hmGetVmxActiveVmcsInfo(pVCpu);
6759
6760 if (pVM->hm.s.vmx.fUsePreemptTimer)
6761 {
6762 uint64_t cTicksToDeadline = TMCpuTickGetDeadlineAndTscOffset(pVM, pVCpu, &uTscOffset, &fOffsettedTsc, &fParavirtTsc);
6763
6764 /* Make sure the returned values have sane upper and lower boundaries. */
6765 uint64_t u64CpuHz = SUPGetCpuHzFromGipBySetIndex(g_pSUPGlobalInfoPage, pVCpu->iHostCpuSet);
6766 cTicksToDeadline = RT_MIN(cTicksToDeadline, u64CpuHz / 64); /* 1/64th of a second */
6767 cTicksToDeadline = RT_MAX(cTicksToDeadline, u64CpuHz / 2048); /* 1/2048th of a second */
6768 cTicksToDeadline >>= pVM->hm.s.vmx.cPreemptTimerShift;
6769
6770 /** @todo r=ramshankar: We need to find a way to integrate nested-guest
6771 * preemption timers here. We probably need to clamp the preemption timer,
6772 * after converting the timer value to the host. */
6773 uint32_t const cPreemptionTickCount = (uint32_t)RT_MIN(cTicksToDeadline, UINT32_MAX - 16);
6774 int rc = VMXWriteVmcs32(VMX_VMCS32_PREEMPT_TIMER_VALUE, cPreemptionTickCount);
6775 AssertRC(rc);
6776 }
6777 else
6778 fOffsettedTsc = TMCpuTickCanUseRealTSC(pVM, pVCpu, &uTscOffset, &fParavirtTsc);
6779
6780 if (fParavirtTsc)
6781 {
6782 /* Currently neither Hyper-V nor KVM need to update their paravirt. TSC
6783 information before every VM-entry, hence disable it for performance sake. */
6784#if 0
6785 int rc = GIMR0UpdateParavirtTsc(pVM, 0 /* u64Offset */);
6786 AssertRC(rc);
6787#endif
6788 STAM_COUNTER_INC(&pVCpu->hm.s.StatTscParavirt);
6789 }
6790
6791 if ( fOffsettedTsc
6792 && RT_LIKELY(!pVCpu->hm.s.fDebugWantRdTscExit))
6793 {
6794 if (pVmxTransient->fIsNestedGuest)
6795 uTscOffset = CPUMApplyNestedGuestTscOffset(pVCpu, uTscOffset);
6796 hmR0VmxSetTscOffsetVmcs(pVmcsInfo, uTscOffset);
6797 hmR0VmxRemoveProcCtlsVmcs(pVCpu, pVmxTransient, VMX_PROC_CTLS_RDTSC_EXIT);
6798 }
6799 else
6800 {
6801 /* We can't use TSC-offsetting (non-fixed TSC, warp drive active etc.), VM-exit on RDTSC(P). */
6802 hmR0VmxSetProcCtlsVmcs(pVmxTransient, VMX_PROC_CTLS_RDTSC_EXIT);
6803 }
6804}
6805
6806
6807/**
6808 * Gets the IEM exception flags for the specified vector and IDT vectoring /
6809 * VM-exit interruption info type.
6810 *
6811 * @returns The IEM exception flags.
6812 * @param uVector The event vector.
6813 * @param uVmxEventType The VMX event type.
6814 *
6815 * @remarks This function currently only constructs flags required for
6816 * IEMEvaluateRecursiveXcpt and not the complete flags (e.g, error-code
6817 * and CR2 aspects of an exception are not included).
6818 */
6819static uint32_t hmR0VmxGetIemXcptFlags(uint8_t uVector, uint32_t uVmxEventType)
6820{
6821 uint32_t fIemXcptFlags;
6822 switch (uVmxEventType)
6823 {
6824 case VMX_IDT_VECTORING_INFO_TYPE_HW_XCPT:
6825 case VMX_IDT_VECTORING_INFO_TYPE_NMI:
6826 fIemXcptFlags = IEM_XCPT_FLAGS_T_CPU_XCPT;
6827 break;
6828
6829 case VMX_IDT_VECTORING_INFO_TYPE_EXT_INT:
6830 fIemXcptFlags = IEM_XCPT_FLAGS_T_EXT_INT;
6831 break;
6832
6833 case VMX_IDT_VECTORING_INFO_TYPE_PRIV_SW_XCPT:
6834 fIemXcptFlags = IEM_XCPT_FLAGS_T_SOFT_INT | IEM_XCPT_FLAGS_ICEBP_INSTR;
6835 break;
6836
6837 case VMX_IDT_VECTORING_INFO_TYPE_SW_XCPT:
6838 {
6839 fIemXcptFlags = IEM_XCPT_FLAGS_T_SOFT_INT;
6840 if (uVector == X86_XCPT_BP)
6841 fIemXcptFlags |= IEM_XCPT_FLAGS_BP_INSTR;
6842 else if (uVector == X86_XCPT_OF)
6843 fIemXcptFlags |= IEM_XCPT_FLAGS_OF_INSTR;
6844 else
6845 {
6846 fIemXcptFlags = 0;
6847 AssertMsgFailed(("Unexpected vector for software exception. uVector=%#x", uVector));
6848 }
6849 break;
6850 }
6851
6852 case VMX_IDT_VECTORING_INFO_TYPE_SW_INT:
6853 fIemXcptFlags = IEM_XCPT_FLAGS_T_SOFT_INT;
6854 break;
6855
6856 default:
6857 fIemXcptFlags = 0;
6858 AssertMsgFailed(("Unexpected vector type! uVmxEventType=%#x uVector=%#x", uVmxEventType, uVector));
6859 break;
6860 }
6861 return fIemXcptFlags;
6862}
6863
6864
6865/**
6866 * Sets an event as a pending event to be injected into the guest.
6867 *
6868 * @param pVCpu The cross context virtual CPU structure.
6869 * @param u32IntInfo The VM-entry interruption-information field.
6870 * @param cbInstr The VM-entry instruction length in bytes (for
6871 * software interrupts, exceptions and privileged
6872 * software exceptions).
6873 * @param u32ErrCode The VM-entry exception error code.
6874 * @param GCPtrFaultAddress The fault-address (CR2) in case it's a
6875 * page-fault.
6876 */
6877DECLINLINE(void) hmR0VmxSetPendingEvent(PVMCPUCC pVCpu, uint32_t u32IntInfo, uint32_t cbInstr, uint32_t u32ErrCode,
6878 RTGCUINTPTR GCPtrFaultAddress)
6879{
6880 Assert(!pVCpu->hm.s.Event.fPending);
6881 pVCpu->hm.s.Event.fPending = true;
6882 pVCpu->hm.s.Event.u64IntInfo = u32IntInfo;
6883 pVCpu->hm.s.Event.u32ErrCode = u32ErrCode;
6884 pVCpu->hm.s.Event.cbInstr = cbInstr;
6885 pVCpu->hm.s.Event.GCPtrFaultAddress = GCPtrFaultAddress;
6886}
6887
6888
6889/**
6890 * Sets an external interrupt as pending-for-injection into the VM.
6891 *
6892 * @param pVCpu The cross context virtual CPU structure.
6893 * @param u8Interrupt The external interrupt vector.
6894 */
6895DECLINLINE(void) hmR0VmxSetPendingExtInt(PVMCPUCC pVCpu, uint8_t u8Interrupt)
6896{
6897 uint32_t const u32IntInfo = RT_BF_MAKE(VMX_BF_EXIT_INT_INFO_VECTOR, u8Interrupt)
6898 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_TYPE, VMX_ENTRY_INT_INFO_TYPE_EXT_INT)
6899 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_ERR_CODE_VALID, 0)
6900 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_VALID, 1);
6901 hmR0VmxSetPendingEvent(pVCpu, u32IntInfo, 0 /* cbInstr */, 0 /* u32ErrCode */, 0 /* GCPtrFaultAddress */);
6902}
6903
6904
6905/**
6906 * Sets an NMI (\#NMI) exception as pending-for-injection into the VM.
6907 *
6908 * @param pVCpu The cross context virtual CPU structure.
6909 */
6910DECLINLINE(void) hmR0VmxSetPendingXcptNmi(PVMCPUCC pVCpu)
6911{
6912 uint32_t const u32IntInfo = RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_VECTOR, X86_XCPT_NMI)
6913 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_TYPE, VMX_ENTRY_INT_INFO_TYPE_NMI)
6914 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_ERR_CODE_VALID, 0)
6915 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_VALID, 1);
6916 hmR0VmxSetPendingEvent(pVCpu, u32IntInfo, 0 /* cbInstr */, 0 /* u32ErrCode */, 0 /* GCPtrFaultAddress */);
6917}
6918
6919
6920/**
6921 * Sets a double-fault (\#DF) exception as pending-for-injection into the VM.
6922 *
6923 * @param pVCpu The cross context virtual CPU structure.
6924 */
6925DECLINLINE(void) hmR0VmxSetPendingXcptDF(PVMCPUCC pVCpu)
6926{
6927 uint32_t const u32IntInfo = RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_VECTOR, X86_XCPT_DF)
6928 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_TYPE, VMX_EXIT_INT_INFO_TYPE_HW_XCPT)
6929 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_ERR_CODE_VALID, 1)
6930 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_VALID, 1);
6931 hmR0VmxSetPendingEvent(pVCpu, u32IntInfo, 0 /* cbInstr */, 0 /* u32ErrCode */, 0 /* GCPtrFaultAddress */);
6932}
6933
6934
6935/**
6936 * Sets an invalid-opcode (\#UD) exception as pending-for-injection into the VM.
6937 *
6938 * @param pVCpu The cross context virtual CPU structure.
6939 */
6940DECLINLINE(void) hmR0VmxSetPendingXcptUD(PVMCPUCC pVCpu)
6941{
6942 uint32_t const u32IntInfo = RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_VECTOR, X86_XCPT_UD)
6943 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_TYPE, VMX_EXIT_INT_INFO_TYPE_HW_XCPT)
6944 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_ERR_CODE_VALID, 0)
6945 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_VALID, 1);
6946 hmR0VmxSetPendingEvent(pVCpu, u32IntInfo, 0 /* cbInstr */, 0 /* u32ErrCode */, 0 /* GCPtrFaultAddress */);
6947}
6948
6949
6950/**
6951 * Sets a debug (\#DB) exception as pending-for-injection into the VM.
6952 *
6953 * @param pVCpu The cross context virtual CPU structure.
6954 */
6955DECLINLINE(void) hmR0VmxSetPendingXcptDB(PVMCPUCC pVCpu)
6956{
6957 uint32_t const u32IntInfo = RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_VECTOR, X86_XCPT_DB)
6958 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_TYPE, VMX_EXIT_INT_INFO_TYPE_HW_XCPT)
6959 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_ERR_CODE_VALID, 0)
6960 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_VALID, 1);
6961 hmR0VmxSetPendingEvent(pVCpu, u32IntInfo, 0 /* cbInstr */, 0 /* u32ErrCode */, 0 /* GCPtrFaultAddress */);
6962}
6963
6964
6965#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
6966/**
6967 * Sets a general-protection (\#GP) exception as pending-for-injection into the VM.
6968 *
6969 * @param pVCpu The cross context virtual CPU structure.
6970 * @param u32ErrCode The error code for the general-protection exception.
6971 */
6972DECLINLINE(void) hmR0VmxSetPendingXcptGP(PVMCPUCC pVCpu, uint32_t u32ErrCode)
6973{
6974 uint32_t const u32IntInfo = RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_VECTOR, X86_XCPT_GP)
6975 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_TYPE, VMX_EXIT_INT_INFO_TYPE_HW_XCPT)
6976 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_ERR_CODE_VALID, 1)
6977 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_VALID, 1);
6978 hmR0VmxSetPendingEvent(pVCpu, u32IntInfo, 0 /* cbInstr */, u32ErrCode, 0 /* GCPtrFaultAddress */);
6979}
6980
6981
6982/**
6983 * Sets a stack (\#SS) exception as pending-for-injection into the VM.
6984 *
6985 * @param pVCpu The cross context virtual CPU structure.
6986 * @param u32ErrCode The error code for the stack exception.
6987 */
6988DECLINLINE(void) hmR0VmxSetPendingXcptSS(PVMCPUCC pVCpu, uint32_t u32ErrCode)
6989{
6990 uint32_t const u32IntInfo = RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_VECTOR, X86_XCPT_SS)
6991 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_TYPE, VMX_EXIT_INT_INFO_TYPE_HW_XCPT)
6992 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_ERR_CODE_VALID, 1)
6993 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_VALID, 1);
6994 hmR0VmxSetPendingEvent(pVCpu, u32IntInfo, 0 /* cbInstr */, u32ErrCode, 0 /* GCPtrFaultAddress */);
6995}
6996#endif /* VBOX_WITH_NESTED_HWVIRT_VMX */
6997
6998
6999/**
7000 * Fixes up attributes for the specified segment register.
7001 *
7002 * @param pVCpu The cross context virtual CPU structure.
7003 * @param pSelReg The segment register that needs fixing.
7004 * @param idxSel The VMCS field for the corresponding segment register.
7005 */
7006static void hmR0VmxFixUnusableSegRegAttr(PVMCPUCC pVCpu, PCPUMSELREG pSelReg, uint32_t idxSel)
7007{
7008 Assert(pSelReg->Attr.u & X86DESCATTR_UNUSABLE);
7009
7010 /*
7011 * If VT-x marks the segment as unusable, most other bits remain undefined:
7012 * - For CS the L, D and G bits have meaning.
7013 * - For SS the DPL has meaning (it -is- the CPL for Intel and VBox).
7014 * - For the remaining data segments no bits are defined.
7015 *
7016 * The present bit and the unusable bit has been observed to be set at the
7017 * same time (the selector was supposed to be invalid as we started executing
7018 * a V8086 interrupt in ring-0).
7019 *
7020 * What should be important for the rest of the VBox code, is that the P bit is
7021 * cleared. Some of the other VBox code recognizes the unusable bit, but
7022 * AMD-V certainly don't, and REM doesn't really either. So, to be on the
7023 * safe side here, we'll strip off P and other bits we don't care about. If
7024 * any code breaks because Attr.u != 0 when Sel < 4, it should be fixed.
7025 *
7026 * See Intel spec. 27.3.2 "Saving Segment Registers and Descriptor-Table Registers".
7027 */
7028#ifdef VBOX_STRICT
7029 uint32_t const uAttr = pSelReg->Attr.u;
7030#endif
7031
7032 /* Masking off: X86DESCATTR_P, X86DESCATTR_LIMIT_HIGH, and X86DESCATTR_AVL. The latter two are really irrelevant. */
7033 pSelReg->Attr.u &= X86DESCATTR_UNUSABLE | X86DESCATTR_L | X86DESCATTR_D | X86DESCATTR_G
7034 | X86DESCATTR_DPL | X86DESCATTR_TYPE | X86DESCATTR_DT;
7035
7036#ifdef VBOX_STRICT
7037 VMMRZCallRing3Disable(pVCpu);
7038 Log4Func(("Unusable %#x: sel=%#x attr=%#x -> %#x\n", idxSel, pSelReg->Sel, uAttr, pSelReg->Attr.u));
7039# ifdef DEBUG_bird
7040 AssertMsg((uAttr & ~X86DESCATTR_P) == pSelReg->Attr.u,
7041 ("%#x: %#x != %#x (sel=%#x base=%#llx limit=%#x)\n",
7042 idxSel, uAttr, pSelReg->Attr.u, pSelReg->Sel, pSelReg->u64Base, pSelReg->u32Limit));
7043# endif
7044 VMMRZCallRing3Enable(pVCpu);
7045 NOREF(uAttr);
7046#endif
7047 RT_NOREF2(pVCpu, idxSel);
7048}
7049
7050
7051/**
7052 * Imports a guest segment register from the current VMCS into the guest-CPU
7053 * context.
7054 *
7055 * @param pVCpu The cross context virtual CPU structure.
7056 * @param iSegReg The segment register number (X86_SREG_XXX).
7057 *
7058 * @remarks Called with interrupts and/or preemption disabled.
7059 */
7060static void hmR0VmxImportGuestSegReg(PVMCPUCC pVCpu, uint8_t iSegReg)
7061{
7062 Assert(iSegReg < X86_SREG_COUNT);
7063
7064 uint32_t const idxSel = g_aVmcsSegSel[iSegReg];
7065 uint32_t const idxLimit = g_aVmcsSegLimit[iSegReg];
7066 uint32_t const idxAttr = g_aVmcsSegAttr[iSegReg];
7067 uint32_t const idxBase = g_aVmcsSegBase[iSegReg];
7068
7069 uint16_t u16Sel;
7070 uint64_t u64Base;
7071 uint32_t u32Limit, u32Attr;
7072 int rc = VMXReadVmcs16(idxSel, &u16Sel); AssertRC(rc);
7073 rc = VMXReadVmcs32(idxLimit, &u32Limit); AssertRC(rc);
7074 rc = VMXReadVmcs32(idxAttr, &u32Attr); AssertRC(rc);
7075 rc = VMXReadVmcsNw(idxBase, &u64Base); AssertRC(rc);
7076
7077 PCPUMSELREG pSelReg = &pVCpu->cpum.GstCtx.aSRegs[iSegReg];
7078 pSelReg->Sel = u16Sel;
7079 pSelReg->ValidSel = u16Sel;
7080 pSelReg->fFlags = CPUMSELREG_FLAGS_VALID;
7081 pSelReg->u32Limit = u32Limit;
7082 pSelReg->u64Base = u64Base;
7083 pSelReg->Attr.u = u32Attr;
7084 if (u32Attr & X86DESCATTR_UNUSABLE)
7085 hmR0VmxFixUnusableSegRegAttr(pVCpu, pSelReg, idxSel);
7086}
7087
7088
7089/**
7090 * Imports the guest LDTR from the current VMCS into the guest-CPU context.
7091 *
7092 * @param pVCpu The cross context virtual CPU structure.
7093 *
7094 * @remarks Called with interrupts and/or preemption disabled.
7095 */
7096static void hmR0VmxImportGuestLdtr(PVMCPUCC pVCpu)
7097{
7098 uint16_t u16Sel;
7099 uint64_t u64Base;
7100 uint32_t u32Limit, u32Attr;
7101 int rc = VMXReadVmcs16(VMX_VMCS16_GUEST_LDTR_SEL, &u16Sel); AssertRC(rc);
7102 rc = VMXReadVmcs32(VMX_VMCS32_GUEST_LDTR_LIMIT, &u32Limit); AssertRC(rc);
7103 rc = VMXReadVmcs32(VMX_VMCS32_GUEST_LDTR_ACCESS_RIGHTS, &u32Attr); AssertRC(rc);
7104 rc = VMXReadVmcsNw(VMX_VMCS_GUEST_LDTR_BASE, &u64Base); AssertRC(rc);
7105
7106 pVCpu->cpum.GstCtx.ldtr.Sel = u16Sel;
7107 pVCpu->cpum.GstCtx.ldtr.ValidSel = u16Sel;
7108 pVCpu->cpum.GstCtx.ldtr.fFlags = CPUMSELREG_FLAGS_VALID;
7109 pVCpu->cpum.GstCtx.ldtr.u32Limit = u32Limit;
7110 pVCpu->cpum.GstCtx.ldtr.u64Base = u64Base;
7111 pVCpu->cpum.GstCtx.ldtr.Attr.u = u32Attr;
7112 if (u32Attr & X86DESCATTR_UNUSABLE)
7113 hmR0VmxFixUnusableSegRegAttr(pVCpu, &pVCpu->cpum.GstCtx.ldtr, VMX_VMCS16_GUEST_LDTR_SEL);
7114}
7115
7116
7117/**
7118 * Imports the guest TR from the current VMCS into the guest-CPU context.
7119 *
7120 * @param pVCpu The cross context virtual CPU structure.
7121 *
7122 * @remarks Called with interrupts and/or preemption disabled.
7123 */
7124static void hmR0VmxImportGuestTr(PVMCPUCC pVCpu)
7125{
7126 uint16_t u16Sel;
7127 uint64_t u64Base;
7128 uint32_t u32Limit, u32Attr;
7129 int rc = VMXReadVmcs16(VMX_VMCS16_GUEST_TR_SEL, &u16Sel); AssertRC(rc);
7130 rc = VMXReadVmcs32(VMX_VMCS32_GUEST_TR_LIMIT, &u32Limit); AssertRC(rc);
7131 rc = VMXReadVmcs32(VMX_VMCS32_GUEST_TR_ACCESS_RIGHTS, &u32Attr); AssertRC(rc);
7132 rc = VMXReadVmcsNw(VMX_VMCS_GUEST_TR_BASE, &u64Base); AssertRC(rc);
7133
7134 pVCpu->cpum.GstCtx.tr.Sel = u16Sel;
7135 pVCpu->cpum.GstCtx.tr.ValidSel = u16Sel;
7136 pVCpu->cpum.GstCtx.tr.fFlags = CPUMSELREG_FLAGS_VALID;
7137 pVCpu->cpum.GstCtx.tr.u32Limit = u32Limit;
7138 pVCpu->cpum.GstCtx.tr.u64Base = u64Base;
7139 pVCpu->cpum.GstCtx.tr.Attr.u = u32Attr;
7140 /* TR is the only selector that can never be unusable. */
7141 Assert(!(u32Attr & X86DESCATTR_UNUSABLE));
7142}
7143
7144
7145/**
7146 * Imports the guest RIP from the VMCS back into the guest-CPU context.
7147 *
7148 * @param pVCpu The cross context virtual CPU structure.
7149 *
7150 * @remarks Called with interrupts and/or preemption disabled, should not assert!
7151 * @remarks Do -not- call this function directly, use hmR0VmxImportGuestState()
7152 * instead!!!
7153 */
7154static void hmR0VmxImportGuestRip(PVMCPUCC pVCpu)
7155{
7156 uint64_t u64Val;
7157 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
7158 if (pCtx->fExtrn & CPUMCTX_EXTRN_RIP)
7159 {
7160 int rc = VMXReadVmcsNw(VMX_VMCS_GUEST_RIP, &u64Val);
7161 AssertRC(rc);
7162
7163 pCtx->rip = u64Val;
7164 EMR0HistoryUpdatePC(pVCpu, pCtx->rip, false);
7165 pCtx->fExtrn &= ~CPUMCTX_EXTRN_RIP;
7166 }
7167}
7168
7169
7170/**
7171 * Imports the guest RFLAGS from the VMCS back into the guest-CPU context.
7172 *
7173 * @param pVCpu The cross context virtual CPU structure.
7174 * @param pVmcsInfo The VMCS info. object.
7175 *
7176 * @remarks Called with interrupts and/or preemption disabled, should not assert!
7177 * @remarks Do -not- call this function directly, use hmR0VmxImportGuestState()
7178 * instead!!!
7179 */
7180static void hmR0VmxImportGuestRFlags(PVMCPUCC pVCpu, PCVMXVMCSINFO pVmcsInfo)
7181{
7182 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
7183 if (pCtx->fExtrn & CPUMCTX_EXTRN_RFLAGS)
7184 {
7185 uint64_t u64Val;
7186 int rc = VMXReadVmcsNw(VMX_VMCS_GUEST_RFLAGS, &u64Val);
7187 AssertRC(rc);
7188
7189 pCtx->rflags.u64 = u64Val;
7190 if (pVmcsInfo->RealMode.fRealOnV86Active)
7191 {
7192 pCtx->eflags.Bits.u1VM = 0;
7193 pCtx->eflags.Bits.u2IOPL = pVmcsInfo->RealMode.Eflags.Bits.u2IOPL;
7194 }
7195 pCtx->fExtrn &= ~CPUMCTX_EXTRN_RFLAGS;
7196 }
7197}
7198
7199
7200/**
7201 * Imports the guest interruptibility-state from the VMCS back into the guest-CPU
7202 * context.
7203 *
7204 * @param pVCpu The cross context virtual CPU structure.
7205 * @param pVmcsInfo The VMCS info. object.
7206 *
7207 * @remarks Called with interrupts and/or preemption disabled, try not to assert and
7208 * do not log!
7209 * @remarks Do -not- call this function directly, use hmR0VmxImportGuestState()
7210 * instead!!!
7211 */
7212static void hmR0VmxImportGuestIntrState(PVMCPUCC pVCpu, PCVMXVMCSINFO pVmcsInfo)
7213{
7214 uint32_t u32Val;
7215 int rc = VMXReadVmcs32(VMX_VMCS32_GUEST_INT_STATE, &u32Val); AssertRC(rc);
7216 if (!u32Val)
7217 {
7218 if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS))
7219 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS);
7220 CPUMSetGuestNmiBlocking(pVCpu, false);
7221 }
7222 else
7223 {
7224 /*
7225 * We must import RIP here to set our EM interrupt-inhibited state.
7226 * We also import RFLAGS as our code that evaluates pending interrupts
7227 * before VM-entry requires it.
7228 */
7229 hmR0VmxImportGuestRip(pVCpu);
7230 hmR0VmxImportGuestRFlags(pVCpu, pVmcsInfo);
7231
7232 if (u32Val & (VMX_VMCS_GUEST_INT_STATE_BLOCK_MOVSS | VMX_VMCS_GUEST_INT_STATE_BLOCK_STI))
7233 EMSetInhibitInterruptsPC(pVCpu, pVCpu->cpum.GstCtx.rip);
7234 else if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS))
7235 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS);
7236
7237 bool const fNmiBlocking = RT_BOOL(u32Val & VMX_VMCS_GUEST_INT_STATE_BLOCK_NMI);
7238 CPUMSetGuestNmiBlocking(pVCpu, fNmiBlocking);
7239 }
7240}
7241
7242
7243/**
7244 * Worker for VMXR0ImportStateOnDemand.
7245 *
7246 * @returns VBox status code.
7247 * @param pVCpu The cross context virtual CPU structure.
7248 * @param pVmcsInfo The VMCS info. object.
7249 * @param fWhat What to import, CPUMCTX_EXTRN_XXX.
7250 */
7251static int hmR0VmxImportGuestState(PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo, uint64_t fWhat)
7252{
7253 int rc = VINF_SUCCESS;
7254 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
7255 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
7256 uint32_t u32Val;
7257
7258 /*
7259 * Note! This is hack to workaround a mysterious BSOD observed with release builds
7260 * on Windows 10 64-bit hosts. Profile and debug builds are not affected and
7261 * neither are other host platforms.
7262 *
7263 * Committing this temporarily as it prevents BSOD.
7264 *
7265 * Update: This is very likely a compiler optimization bug, see @bugref{9180}.
7266 */
7267#ifdef RT_OS_WINDOWS
7268 if (pVM == 0 || pVM == (void *)(uintptr_t)-1)
7269 return VERR_HM_IPE_1;
7270#endif
7271
7272 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatImportGuestState, x);
7273
7274 /*
7275 * We disable interrupts to make the updating of the state and in particular
7276 * the fExtrn modification atomic wrt to preemption hooks.
7277 */
7278 RTCCUINTREG const fEFlags = ASMIntDisableFlags();
7279
7280 fWhat &= pCtx->fExtrn;
7281 if (fWhat)
7282 {
7283 do
7284 {
7285 if (fWhat & CPUMCTX_EXTRN_RIP)
7286 hmR0VmxImportGuestRip(pVCpu);
7287
7288 if (fWhat & CPUMCTX_EXTRN_RFLAGS)
7289 hmR0VmxImportGuestRFlags(pVCpu, pVmcsInfo);
7290
7291 if (fWhat & CPUMCTX_EXTRN_HM_VMX_INT_STATE)
7292 hmR0VmxImportGuestIntrState(pVCpu, pVmcsInfo);
7293
7294 if (fWhat & CPUMCTX_EXTRN_RSP)
7295 {
7296 rc = VMXReadVmcsNw(VMX_VMCS_GUEST_RSP, &pCtx->rsp);
7297 AssertRC(rc);
7298 }
7299
7300 if (fWhat & CPUMCTX_EXTRN_SREG_MASK)
7301 {
7302 bool const fRealOnV86Active = pVmcsInfo->RealMode.fRealOnV86Active;
7303 if (fWhat & CPUMCTX_EXTRN_CS)
7304 {
7305 hmR0VmxImportGuestSegReg(pVCpu, X86_SREG_CS);
7306 hmR0VmxImportGuestRip(pVCpu);
7307 if (fRealOnV86Active)
7308 pCtx->cs.Attr.u = pVmcsInfo->RealMode.AttrCS.u;
7309 EMR0HistoryUpdatePC(pVCpu, pCtx->cs.u64Base + pCtx->rip, true /* fFlattened */);
7310 }
7311 if (fWhat & CPUMCTX_EXTRN_SS)
7312 {
7313 hmR0VmxImportGuestSegReg(pVCpu, X86_SREG_SS);
7314 if (fRealOnV86Active)
7315 pCtx->ss.Attr.u = pVmcsInfo->RealMode.AttrSS.u;
7316 }
7317 if (fWhat & CPUMCTX_EXTRN_DS)
7318 {
7319 hmR0VmxImportGuestSegReg(pVCpu, X86_SREG_DS);
7320 if (fRealOnV86Active)
7321 pCtx->ds.Attr.u = pVmcsInfo->RealMode.AttrDS.u;
7322 }
7323 if (fWhat & CPUMCTX_EXTRN_ES)
7324 {
7325 hmR0VmxImportGuestSegReg(pVCpu, X86_SREG_ES);
7326 if (fRealOnV86Active)
7327 pCtx->es.Attr.u = pVmcsInfo->RealMode.AttrES.u;
7328 }
7329 if (fWhat & CPUMCTX_EXTRN_FS)
7330 {
7331 hmR0VmxImportGuestSegReg(pVCpu, X86_SREG_FS);
7332 if (fRealOnV86Active)
7333 pCtx->fs.Attr.u = pVmcsInfo->RealMode.AttrFS.u;
7334 }
7335 if (fWhat & CPUMCTX_EXTRN_GS)
7336 {
7337 hmR0VmxImportGuestSegReg(pVCpu, X86_SREG_GS);
7338 if (fRealOnV86Active)
7339 pCtx->gs.Attr.u = pVmcsInfo->RealMode.AttrGS.u;
7340 }
7341 }
7342
7343 if (fWhat & CPUMCTX_EXTRN_TABLE_MASK)
7344 {
7345 if (fWhat & CPUMCTX_EXTRN_LDTR)
7346 hmR0VmxImportGuestLdtr(pVCpu);
7347
7348 if (fWhat & CPUMCTX_EXTRN_GDTR)
7349 {
7350 rc = VMXReadVmcsNw(VMX_VMCS_GUEST_GDTR_BASE, &pCtx->gdtr.pGdt); AssertRC(rc);
7351 rc = VMXReadVmcs32(VMX_VMCS32_GUEST_GDTR_LIMIT, &u32Val); AssertRC(rc);
7352 pCtx->gdtr.cbGdt = u32Val;
7353 }
7354
7355 /* Guest IDTR. */
7356 if (fWhat & CPUMCTX_EXTRN_IDTR)
7357 {
7358 rc = VMXReadVmcsNw(VMX_VMCS_GUEST_IDTR_BASE, &pCtx->idtr.pIdt); AssertRC(rc);
7359 rc = VMXReadVmcs32(VMX_VMCS32_GUEST_IDTR_LIMIT, &u32Val); AssertRC(rc);
7360 pCtx->idtr.cbIdt = u32Val;
7361 }
7362
7363 /* Guest TR. */
7364 if (fWhat & CPUMCTX_EXTRN_TR)
7365 {
7366 /* Real-mode emulation using virtual-8086 mode has the fake TSS (pRealModeTSS) in TR,
7367 don't need to import that one. */
7368 if (!pVmcsInfo->RealMode.fRealOnV86Active)
7369 hmR0VmxImportGuestTr(pVCpu);
7370 }
7371 }
7372
7373 if (fWhat & CPUMCTX_EXTRN_DR7)
7374 {
7375 if (!pVCpu->hm.s.fUsingHyperDR7)
7376 rc = VMXReadVmcsNw(VMX_VMCS_GUEST_DR7, &pCtx->dr[7]); AssertRC(rc);
7377 }
7378
7379 if (fWhat & CPUMCTX_EXTRN_SYSENTER_MSRS)
7380 {
7381 rc = VMXReadVmcsNw(VMX_VMCS_GUEST_SYSENTER_EIP, &pCtx->SysEnter.eip); AssertRC(rc);
7382 rc = VMXReadVmcsNw(VMX_VMCS_GUEST_SYSENTER_ESP, &pCtx->SysEnter.esp); AssertRC(rc);
7383 rc = VMXReadVmcs32(VMX_VMCS32_GUEST_SYSENTER_CS, &u32Val); AssertRC(rc);
7384 pCtx->SysEnter.cs = u32Val;
7385 }
7386
7387 if (fWhat & CPUMCTX_EXTRN_KERNEL_GS_BASE)
7388 {
7389 if ( pVM->hm.s.fAllow64BitGuests
7390 && (pVCpu->hm.s.vmx.fLazyMsrs & VMX_LAZY_MSRS_LOADED_GUEST))
7391 pCtx->msrKERNELGSBASE = ASMRdMsr(MSR_K8_KERNEL_GS_BASE);
7392 }
7393
7394 if (fWhat & CPUMCTX_EXTRN_SYSCALL_MSRS)
7395 {
7396 if ( pVM->hm.s.fAllow64BitGuests
7397 && (pVCpu->hm.s.vmx.fLazyMsrs & VMX_LAZY_MSRS_LOADED_GUEST))
7398 {
7399 pCtx->msrLSTAR = ASMRdMsr(MSR_K8_LSTAR);
7400 pCtx->msrSTAR = ASMRdMsr(MSR_K6_STAR);
7401 pCtx->msrSFMASK = ASMRdMsr(MSR_K8_SF_MASK);
7402 }
7403 }
7404
7405 if (fWhat & (CPUMCTX_EXTRN_TSC_AUX | CPUMCTX_EXTRN_OTHER_MSRS))
7406 {
7407 PCVMXAUTOMSR pMsrs = (PCVMXAUTOMSR)pVmcsInfo->pvGuestMsrStore;
7408 uint32_t const cMsrs = pVmcsInfo->cExitMsrStore;
7409 Assert(pMsrs);
7410 Assert(cMsrs <= VMX_MISC_MAX_MSRS(pVM->hm.s.vmx.Msrs.u64Misc));
7411 Assert(sizeof(*pMsrs) * cMsrs <= X86_PAGE_4K_SIZE);
7412 for (uint32_t i = 0; i < cMsrs; i++)
7413 {
7414 uint32_t const idMsr = pMsrs[i].u32Msr;
7415 switch (idMsr)
7416 {
7417 case MSR_K8_TSC_AUX: CPUMSetGuestTscAux(pVCpu, pMsrs[i].u64Value); break;
7418 case MSR_IA32_SPEC_CTRL: CPUMSetGuestSpecCtrl(pVCpu, pMsrs[i].u64Value); break;
7419 case MSR_K6_EFER: /* Can't be changed without causing a VM-exit */ break;
7420 default:
7421 {
7422 pCtx->fExtrn = 0;
7423 pVCpu->hm.s.u32HMError = pMsrs->u32Msr;
7424 ASMSetFlags(fEFlags);
7425 AssertMsgFailed(("Unexpected MSR in auto-load/store area. idMsr=%#RX32 cMsrs=%u\n", idMsr, cMsrs));
7426 return VERR_HM_UNEXPECTED_LD_ST_MSR;
7427 }
7428 }
7429 }
7430 }
7431
7432 if (fWhat & CPUMCTX_EXTRN_CR_MASK)
7433 {
7434 if (fWhat & CPUMCTX_EXTRN_CR0)
7435 {
7436 uint64_t u64Cr0;
7437 uint64_t u64Shadow;
7438 rc = VMXReadVmcsNw(VMX_VMCS_GUEST_CR0, &u64Cr0); AssertRC(rc);
7439 rc = VMXReadVmcsNw(VMX_VMCS_CTRL_CR0_READ_SHADOW, &u64Shadow); AssertRC(rc);
7440 u64Cr0 = (u64Cr0 & ~pVmcsInfo->u64Cr0Mask)
7441 | (u64Shadow & pVmcsInfo->u64Cr0Mask);
7442#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
7443 /*
7444 * Reapply the nested-guest's CR0 fixed bits that might have been altered while
7445 * exporting the nested-guest CR0 for executing using hardware-assisted VMX.
7446 */
7447 if (CPUMIsGuestInVmxNonRootMode(pCtx))
7448 {
7449 u64Cr0 |= pCtx->hwvirt.vmx.Msrs.u64Cr0Fixed0;
7450 u64Cr0 &= pCtx->hwvirt.vmx.Msrs.u64Cr0Fixed1;
7451 }
7452#endif
7453 VMMRZCallRing3Disable(pVCpu); /* May call into PGM which has Log statements. */
7454 CPUMSetGuestCR0(pVCpu, u64Cr0);
7455 VMMRZCallRing3Enable(pVCpu);
7456 }
7457
7458 if (fWhat & CPUMCTX_EXTRN_CR4)
7459 {
7460 uint64_t u64Cr4;
7461 uint64_t u64Shadow;
7462 rc = VMXReadVmcsNw(VMX_VMCS_GUEST_CR4, &u64Cr4); AssertRC(rc);
7463 rc |= VMXReadVmcsNw(VMX_VMCS_CTRL_CR4_READ_SHADOW, &u64Shadow); AssertRC(rc);
7464 u64Cr4 = (u64Cr4 & ~pVmcsInfo->u64Cr4Mask)
7465 | (u64Shadow & pVmcsInfo->u64Cr4Mask);
7466#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
7467 /*
7468 * Reapply the nested-guest's CR4 fixed bits that might have been altered while
7469 * exporting the nested-guest CR4 for executing using hardware-assisted VMX.
7470 */
7471 if (CPUMIsGuestInVmxNonRootMode(pCtx))
7472 {
7473 u64Cr4 |= pCtx->hwvirt.vmx.Msrs.u64Cr4Fixed0;
7474 u64Cr4 &= pCtx->hwvirt.vmx.Msrs.u64Cr4Fixed1;
7475 }
7476#endif
7477 pCtx->cr4 = u64Cr4;
7478 }
7479
7480 if (fWhat & CPUMCTX_EXTRN_CR3)
7481 {
7482 /* CR0.PG bit changes are always intercepted, so it's up to date. */
7483 if ( pVM->hm.s.vmx.fUnrestrictedGuest
7484 || ( pVM->hm.s.fNestedPaging
7485 && CPUMIsGuestPagingEnabledEx(pCtx)))
7486 {
7487 uint64_t u64Cr3;
7488 rc = VMXReadVmcsNw(VMX_VMCS_GUEST_CR3, &u64Cr3); AssertRC(rc);
7489 if (pCtx->cr3 != u64Cr3)
7490 {
7491 pCtx->cr3 = u64Cr3;
7492 VMCPU_FF_SET(pVCpu, VMCPU_FF_HM_UPDATE_CR3);
7493 }
7494
7495 /* If the guest is in PAE mode, sync back the PDPE's into the guest state.
7496 Note: CR4.PAE, CR0.PG, EFER MSR changes are always intercepted, so they're up to date. */
7497 if (CPUMIsGuestInPAEModeEx(pCtx))
7498 {
7499 rc = VMXReadVmcs64(VMX_VMCS64_GUEST_PDPTE0_FULL, &pVCpu->hm.s.aPdpes[0].u); AssertRC(rc);
7500 rc = VMXReadVmcs64(VMX_VMCS64_GUEST_PDPTE1_FULL, &pVCpu->hm.s.aPdpes[1].u); AssertRC(rc);
7501 rc = VMXReadVmcs64(VMX_VMCS64_GUEST_PDPTE2_FULL, &pVCpu->hm.s.aPdpes[2].u); AssertRC(rc);
7502 rc = VMXReadVmcs64(VMX_VMCS64_GUEST_PDPTE3_FULL, &pVCpu->hm.s.aPdpes[3].u); AssertRC(rc);
7503 VMCPU_FF_SET(pVCpu, VMCPU_FF_HM_UPDATE_PAE_PDPES);
7504 }
7505 }
7506 }
7507 }
7508
7509#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
7510 if (fWhat & CPUMCTX_EXTRN_HWVIRT)
7511 {
7512 if ( (pVmcsInfo->u32ProcCtls2 & VMX_PROC_CTLS2_VMCS_SHADOWING)
7513 && !CPUMIsGuestInVmxNonRootMode(pCtx))
7514 {
7515 Assert(CPUMIsGuestInVmxRootMode(pCtx));
7516 rc = hmR0VmxCopyShadowToNstGstVmcs(pVCpu, pVmcsInfo);
7517 if (RT_SUCCESS(rc))
7518 { /* likely */ }
7519 else
7520 break;
7521 }
7522 }
7523#endif
7524 } while (0);
7525
7526 if (RT_SUCCESS(rc))
7527 {
7528 /* Update fExtrn. */
7529 pCtx->fExtrn &= ~fWhat;
7530
7531 /* If everything has been imported, clear the HM keeper bit. */
7532 if (!(pCtx->fExtrn & HMVMX_CPUMCTX_EXTRN_ALL))
7533 {
7534 pCtx->fExtrn &= ~CPUMCTX_EXTRN_KEEPER_HM;
7535 Assert(!pCtx->fExtrn);
7536 }
7537 }
7538 }
7539 else
7540 AssertMsg(!pCtx->fExtrn || (pCtx->fExtrn & HMVMX_CPUMCTX_EXTRN_ALL), ("%#RX64\n", pCtx->fExtrn));
7541
7542 /*
7543 * Restore interrupts.
7544 */
7545 ASMSetFlags(fEFlags);
7546
7547 STAM_PROFILE_ADV_STOP(& pVCpu->hm.s.StatImportGuestState, x);
7548
7549 if (RT_SUCCESS(rc))
7550 { /* likely */ }
7551 else
7552 return rc;
7553
7554 /*
7555 * Honor any pending CR3 updates.
7556 *
7557 * Consider this scenario: VM-exit -> VMMRZCallRing3Enable() -> do stuff that causes a longjmp -> hmR0VmxCallRing3Callback()
7558 * -> VMMRZCallRing3Disable() -> hmR0VmxImportGuestState() -> Sets VMCPU_FF_HM_UPDATE_CR3 pending -> return from the longjmp
7559 * -> continue with VM-exit handling -> hmR0VmxImportGuestState() and here we are.
7560 *
7561 * The reason for such complicated handling is because VM-exits that call into PGM expect CR3 to be up-to-date and thus
7562 * if any CR3-saves -before- the VM-exit (longjmp) postponed the CR3 update via the force-flag, any VM-exit handler that
7563 * calls into PGM when it re-saves CR3 will end up here and we call PGMUpdateCR3(). This is why the code below should
7564 * -NOT- check if CPUMCTX_EXTRN_CR3 is set!
7565 *
7566 * The longjmp exit path can't check these CR3 force-flags and call code that takes a lock again. We cover for it here.
7567 */
7568 if (VMMRZCallRing3IsEnabled(pVCpu))
7569 {
7570 if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_HM_UPDATE_CR3))
7571 {
7572 Assert(!(ASMAtomicUoReadU64(&pCtx->fExtrn) & CPUMCTX_EXTRN_CR3));
7573 PGMUpdateCR3(pVCpu, CPUMGetGuestCR3(pVCpu));
7574 }
7575
7576 if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_HM_UPDATE_PAE_PDPES))
7577 PGMGstUpdatePaePdpes(pVCpu, &pVCpu->hm.s.aPdpes[0]);
7578
7579 Assert(!VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_HM_UPDATE_CR3));
7580 Assert(!VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_HM_UPDATE_PAE_PDPES));
7581 }
7582
7583 return VINF_SUCCESS;
7584}
7585
7586
7587/**
7588 * Saves the guest state from the VMCS into the guest-CPU context.
7589 *
7590 * @returns VBox status code.
7591 * @param pVCpu The cross context virtual CPU structure.
7592 * @param fWhat What to import, CPUMCTX_EXTRN_XXX.
7593 */
7594VMMR0DECL(int) VMXR0ImportStateOnDemand(PVMCPUCC pVCpu, uint64_t fWhat)
7595{
7596 AssertPtr(pVCpu);
7597 PVMXVMCSINFO pVmcsInfo = hmGetVmxActiveVmcsInfo(pVCpu);
7598 return hmR0VmxImportGuestState(pVCpu, pVmcsInfo, fWhat);
7599}
7600
7601
7602/**
7603 * Check per-VM and per-VCPU force flag actions that require us to go back to
7604 * ring-3 for one reason or another.
7605 *
7606 * @returns Strict VBox status code (i.e. informational status codes too)
7607 * @retval VINF_SUCCESS if we don't have any actions that require going back to
7608 * ring-3.
7609 * @retval VINF_PGM_SYNC_CR3 if we have pending PGM CR3 sync.
7610 * @retval VINF_EM_PENDING_REQUEST if we have pending requests (like hardware
7611 * interrupts)
7612 * @retval VINF_PGM_POOL_FLUSH_PENDING if PGM is doing a pool flush and requires
7613 * all EMTs to be in ring-3.
7614 * @retval VINF_EM_RAW_TO_R3 if there is pending DMA requests.
7615 * @retval VINF_EM_NO_MEMORY PGM is out of memory, we need to return
7616 * to the EM loop.
7617 *
7618 * @param pVCpu The cross context virtual CPU structure.
7619 * @param fStepping Whether we are single-stepping the guest using the
7620 * hypervisor debugger.
7621 *
7622 * @remarks This might cause nested-guest VM-exits, caller must check if the guest
7623 * is no longer in VMX non-root mode.
7624 */
7625static VBOXSTRICTRC hmR0VmxCheckForceFlags(PVMCPUCC pVCpu, bool fStepping)
7626{
7627 Assert(VMMRZCallRing3IsEnabled(pVCpu));
7628
7629 /*
7630 * Update pending interrupts into the APIC's IRR.
7631 */
7632 if (VMCPU_FF_TEST_AND_CLEAR(pVCpu, VMCPU_FF_UPDATE_APIC))
7633 APICUpdatePendingInterrupts(pVCpu);
7634
7635 /*
7636 * Anything pending? Should be more likely than not if we're doing a good job.
7637 */
7638 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
7639 if ( !fStepping
7640 ? !VM_FF_IS_ANY_SET(pVM, VM_FF_HP_R0_PRE_HM_MASK)
7641 && !VMCPU_FF_IS_ANY_SET(pVCpu, VMCPU_FF_HP_R0_PRE_HM_MASK)
7642 : !VM_FF_IS_ANY_SET(pVM, VM_FF_HP_R0_PRE_HM_STEP_MASK)
7643 && !VMCPU_FF_IS_ANY_SET(pVCpu, VMCPU_FF_HP_R0_PRE_HM_STEP_MASK) )
7644 return VINF_SUCCESS;
7645
7646 /* Pending PGM C3 sync. */
7647 if (VMCPU_FF_IS_ANY_SET(pVCpu,VMCPU_FF_PGM_SYNC_CR3 | VMCPU_FF_PGM_SYNC_CR3_NON_GLOBAL))
7648 {
7649 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
7650 Assert(!(ASMAtomicUoReadU64(&pCtx->fExtrn) & (CPUMCTX_EXTRN_CR0 | CPUMCTX_EXTRN_CR3 | CPUMCTX_EXTRN_CR4)));
7651 VBOXSTRICTRC rcStrict = PGMSyncCR3(pVCpu, pCtx->cr0, pCtx->cr3, pCtx->cr4,
7652 VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_PGM_SYNC_CR3));
7653 if (rcStrict != VINF_SUCCESS)
7654 {
7655 AssertRC(VBOXSTRICTRC_VAL(rcStrict));
7656 Log4Func(("PGMSyncCR3 forcing us back to ring-3. rc2=%d\n", VBOXSTRICTRC_VAL(rcStrict)));
7657 return rcStrict;
7658 }
7659 }
7660
7661 /* Pending HM-to-R3 operations (critsects, timers, EMT rendezvous etc.) */
7662 if ( VM_FF_IS_ANY_SET(pVM, VM_FF_HM_TO_R3_MASK)
7663 || VMCPU_FF_IS_ANY_SET(pVCpu, VMCPU_FF_HM_TO_R3_MASK))
7664 {
7665 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchHmToR3FF);
7666 int rc = RT_LIKELY(!VM_FF_IS_SET(pVM, VM_FF_PGM_NO_MEMORY)) ? VINF_EM_RAW_TO_R3 : VINF_EM_NO_MEMORY;
7667 Log4Func(("HM_TO_R3 forcing us back to ring-3. rc=%d\n", rc));
7668 return rc;
7669 }
7670
7671 /* Pending VM request packets, such as hardware interrupts. */
7672 if ( VM_FF_IS_SET(pVM, VM_FF_REQUEST)
7673 || VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_REQUEST))
7674 {
7675 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchVmReq);
7676 Log4Func(("Pending VM request forcing us back to ring-3\n"));
7677 return VINF_EM_PENDING_REQUEST;
7678 }
7679
7680 /* Pending PGM pool flushes. */
7681 if (VM_FF_IS_SET(pVM, VM_FF_PGM_POOL_FLUSH_PENDING))
7682 {
7683 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchPgmPoolFlush);
7684 Log4Func(("PGM pool flush pending forcing us back to ring-3\n"));
7685 return VINF_PGM_POOL_FLUSH_PENDING;
7686 }
7687
7688 /* Pending DMA requests. */
7689 if (VM_FF_IS_SET(pVM, VM_FF_PDM_DMA))
7690 {
7691 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchDma);
7692 Log4Func(("Pending DMA request forcing us back to ring-3\n"));
7693 return VINF_EM_RAW_TO_R3;
7694 }
7695
7696#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
7697 /* Pending nested-guest APIC-write (has highest priority among nested-guest FFs). */
7698 if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_VMX_APIC_WRITE))
7699 {
7700 Log4Func(("Pending nested-guest APIC-write\n"));
7701 VBOXSTRICTRC rcStrict = IEMExecVmxVmexitApicWrite(pVCpu);
7702 Assert(rcStrict != VINF_VMX_INTERCEPT_NOT_ACTIVE);
7703 return rcStrict;
7704 }
7705 /** @todo VMCPU_FF_VMX_MTF, VMCPU_FF_VMX_PREEMPT_TIMER */
7706#endif
7707
7708 return VINF_SUCCESS;
7709}
7710
7711
7712/**
7713 * Converts any TRPM trap into a pending HM event. This is typically used when
7714 * entering from ring-3 (not longjmp returns).
7715 *
7716 * @param pVCpu The cross context virtual CPU structure.
7717 */
7718static void hmR0VmxTrpmTrapToPendingEvent(PVMCPUCC pVCpu)
7719{
7720 Assert(TRPMHasTrap(pVCpu));
7721 Assert(!pVCpu->hm.s.Event.fPending);
7722
7723 uint8_t uVector;
7724 TRPMEVENT enmTrpmEvent;
7725 RTGCUINT uErrCode;
7726 RTGCUINTPTR GCPtrFaultAddress;
7727 uint8_t cbInstr;
7728
7729 int rc = TRPMQueryTrapAll(pVCpu, &uVector, &enmTrpmEvent, &uErrCode, &GCPtrFaultAddress, &cbInstr);
7730 AssertRC(rc);
7731
7732 uint32_t u32IntInfo;
7733 u32IntInfo = uVector | VMX_IDT_VECTORING_INFO_VALID;
7734 u32IntInfo |= HMTrpmEventTypeToVmxEventType(uVector, enmTrpmEvent);
7735
7736 rc = TRPMResetTrap(pVCpu);
7737 AssertRC(rc);
7738 Log4(("TRPM->HM event: u32IntInfo=%#RX32 enmTrpmEvent=%d cbInstr=%u uErrCode=%#RX32 GCPtrFaultAddress=%#RGv\n",
7739 u32IntInfo, enmTrpmEvent, cbInstr, uErrCode, GCPtrFaultAddress));
7740
7741 hmR0VmxSetPendingEvent(pVCpu, u32IntInfo, cbInstr, uErrCode, GCPtrFaultAddress);
7742}
7743
7744
7745/**
7746 * Converts the pending HM event into a TRPM trap.
7747 *
7748 * @param pVCpu The cross context virtual CPU structure.
7749 */
7750static void hmR0VmxPendingEventToTrpmTrap(PVMCPUCC pVCpu)
7751{
7752 Assert(pVCpu->hm.s.Event.fPending);
7753
7754 /* If a trap was already pending, we did something wrong! */
7755 Assert(TRPMQueryTrap(pVCpu, NULL /* pu8TrapNo */, NULL /* pEnmType */) == VERR_TRPM_NO_ACTIVE_TRAP);
7756
7757 uint32_t const u32IntInfo = pVCpu->hm.s.Event.u64IntInfo;
7758 uint32_t const uVector = VMX_IDT_VECTORING_INFO_VECTOR(u32IntInfo);
7759 TRPMEVENT const enmTrapType = HMVmxEventTypeToTrpmEventType(u32IntInfo);
7760
7761 Log4(("HM event->TRPM: uVector=%#x enmTrapType=%d\n", uVector, enmTrapType));
7762
7763 int rc = TRPMAssertTrap(pVCpu, uVector, enmTrapType);
7764 AssertRC(rc);
7765
7766 if (VMX_IDT_VECTORING_INFO_IS_ERROR_CODE_VALID(u32IntInfo))
7767 TRPMSetErrorCode(pVCpu, pVCpu->hm.s.Event.u32ErrCode);
7768
7769 if (VMX_IDT_VECTORING_INFO_IS_XCPT_PF(u32IntInfo))
7770 TRPMSetFaultAddress(pVCpu, pVCpu->hm.s.Event.GCPtrFaultAddress);
7771 else if (VMX_IDT_VECTORING_INFO_TYPE(u32IntInfo) == VMX_IDT_VECTORING_INFO_TYPE_SW_INT)
7772 TRPMSetInstrLength(pVCpu, pVCpu->hm.s.Event.cbInstr);
7773
7774 /* We're now done converting the pending event. */
7775 pVCpu->hm.s.Event.fPending = false;
7776}
7777
7778
7779/**
7780 * Sets the interrupt-window exiting control in the VMCS which instructs VT-x to
7781 * cause a VM-exit as soon as the guest is in a state to receive interrupts.
7782 *
7783 * @param pVCpu The cross context virtual CPU structure.
7784 * @param pVmcsInfo The VMCS info. object.
7785 */
7786static void hmR0VmxSetIntWindowExitVmcs(PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo)
7787{
7788 if (pVCpu->CTX_SUFF(pVM)->hm.s.vmx.Msrs.ProcCtls.n.allowed1 & VMX_PROC_CTLS_INT_WINDOW_EXIT)
7789 {
7790 if (!(pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_INT_WINDOW_EXIT))
7791 {
7792 pVmcsInfo->u32ProcCtls |= VMX_PROC_CTLS_INT_WINDOW_EXIT;
7793 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, pVmcsInfo->u32ProcCtls);
7794 AssertRC(rc);
7795 }
7796 } /* else we will deliver interrupts whenever the guest Vm-exits next and is in a state to receive the interrupt. */
7797}
7798
7799
7800/**
7801 * Clears the interrupt-window exiting control in the VMCS.
7802 *
7803 * @param pVmcsInfo The VMCS info. object.
7804 */
7805DECLINLINE(void) hmR0VmxClearIntWindowExitVmcs(PVMXVMCSINFO pVmcsInfo)
7806{
7807 if (pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_INT_WINDOW_EXIT)
7808 {
7809 pVmcsInfo->u32ProcCtls &= ~VMX_PROC_CTLS_INT_WINDOW_EXIT;
7810 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, pVmcsInfo->u32ProcCtls);
7811 AssertRC(rc);
7812 }
7813}
7814
7815
7816/**
7817 * Sets the NMI-window exiting control in the VMCS which instructs VT-x to
7818 * cause a VM-exit as soon as the guest is in a state to receive NMIs.
7819 *
7820 * @param pVCpu The cross context virtual CPU structure.
7821 * @param pVmcsInfo The VMCS info. object.
7822 */
7823static void hmR0VmxSetNmiWindowExitVmcs(PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo)
7824{
7825 if (pVCpu->CTX_SUFF(pVM)->hm.s.vmx.Msrs.ProcCtls.n.allowed1 & VMX_PROC_CTLS_NMI_WINDOW_EXIT)
7826 {
7827 if (!(pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_NMI_WINDOW_EXIT))
7828 {
7829 pVmcsInfo->u32ProcCtls |= VMX_PROC_CTLS_NMI_WINDOW_EXIT;
7830 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, pVmcsInfo->u32ProcCtls);
7831 AssertRC(rc);
7832 Log4Func(("Setup NMI-window exiting\n"));
7833 }
7834 } /* else we will deliver NMIs whenever we VM-exit next, even possibly nesting NMIs. Can't be helped on ancient CPUs. */
7835}
7836
7837
7838/**
7839 * Clears the NMI-window exiting control in the VMCS.
7840 *
7841 * @param pVmcsInfo The VMCS info. object.
7842 */
7843DECLINLINE(void) hmR0VmxClearNmiWindowExitVmcs(PVMXVMCSINFO pVmcsInfo)
7844{
7845 if (pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_NMI_WINDOW_EXIT)
7846 {
7847 pVmcsInfo->u32ProcCtls &= ~VMX_PROC_CTLS_NMI_WINDOW_EXIT;
7848 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, pVmcsInfo->u32ProcCtls);
7849 AssertRC(rc);
7850 }
7851}
7852
7853
7854/**
7855 * Does the necessary state syncing before returning to ring-3 for any reason
7856 * (longjmp, preemption, voluntary exits to ring-3) from VT-x.
7857 *
7858 * @returns VBox status code.
7859 * @param pVCpu The cross context virtual CPU structure.
7860 * @param fImportState Whether to import the guest state from the VMCS back
7861 * to the guest-CPU context.
7862 *
7863 * @remarks No-long-jmp zone!!!
7864 */
7865static int hmR0VmxLeave(PVMCPUCC pVCpu, bool fImportState)
7866{
7867 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
7868 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
7869
7870 RTCPUID const idCpu = RTMpCpuId();
7871 Log4Func(("HostCpuId=%u\n", idCpu));
7872
7873 /*
7874 * !!! IMPORTANT !!!
7875 * If you modify code here, check whether hmR0VmxCallRing3Callback() needs to be updated too.
7876 */
7877
7878 /* Save the guest state if necessary. */
7879 PVMXVMCSINFO pVmcsInfo = hmGetVmxActiveVmcsInfo(pVCpu);
7880 if (fImportState)
7881 {
7882 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, HMVMX_CPUMCTX_EXTRN_ALL);
7883 AssertRCReturn(rc, rc);
7884 }
7885
7886 /* Restore host FPU state if necessary. We will resync on next R0 reentry. */
7887 CPUMR0FpuStateMaybeSaveGuestAndRestoreHost(pVCpu);
7888 Assert(!CPUMIsGuestFPUStateActive(pVCpu));
7889
7890 /* Restore host debug registers if necessary. We will resync on next R0 reentry. */
7891#ifdef VBOX_STRICT
7892 if (CPUMIsHyperDebugStateActive(pVCpu))
7893 Assert(pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_MOV_DR_EXIT);
7894#endif
7895 CPUMR0DebugStateMaybeSaveGuestAndRestoreHost(pVCpu, true /* save DR6 */);
7896 Assert(!CPUMIsGuestDebugStateActive(pVCpu) && !CPUMIsGuestDebugStateActivePending(pVCpu));
7897 Assert(!CPUMIsHyperDebugStateActive(pVCpu) && !CPUMIsHyperDebugStateActivePending(pVCpu));
7898
7899 /* Restore host-state bits that VT-x only restores partially. */
7900 if ( (pVCpu->hm.s.vmx.fRestoreHostFlags & VMX_RESTORE_HOST_REQUIRED)
7901 && (pVCpu->hm.s.vmx.fRestoreHostFlags & ~VMX_RESTORE_HOST_REQUIRED))
7902 {
7903 Log4Func(("Restoring Host State: fRestoreHostFlags=%#RX32 HostCpuId=%u\n", pVCpu->hm.s.vmx.fRestoreHostFlags, idCpu));
7904 VMXRestoreHostState(pVCpu->hm.s.vmx.fRestoreHostFlags, &pVCpu->hm.s.vmx.RestoreHost);
7905 }
7906 pVCpu->hm.s.vmx.fRestoreHostFlags = 0;
7907
7908 /* Restore the lazy host MSRs as we're leaving VT-x context. */
7909 if (pVCpu->hm.s.vmx.fLazyMsrs & VMX_LAZY_MSRS_LOADED_GUEST)
7910 {
7911 /* We shouldn't restore the host MSRs without saving the guest MSRs first. */
7912 if (!fImportState)
7913 {
7914 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, CPUMCTX_EXTRN_KERNEL_GS_BASE | CPUMCTX_EXTRN_SYSCALL_MSRS);
7915 AssertRCReturn(rc, rc);
7916 }
7917 hmR0VmxLazyRestoreHostMsrs(pVCpu);
7918 Assert(!pVCpu->hm.s.vmx.fLazyMsrs);
7919 }
7920 else
7921 pVCpu->hm.s.vmx.fLazyMsrs = 0;
7922
7923 /* Update auto-load/store host MSRs values when we re-enter VT-x (as we could be on a different CPU). */
7924 pVCpu->hm.s.vmx.fUpdatedHostAutoMsrs = false;
7925
7926 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatEntry);
7927 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatImportGuestState);
7928 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatExportGuestState);
7929 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatPreExit);
7930 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatExitHandling);
7931 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatExitIO);
7932 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatExitMovCRx);
7933 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatExitXcptNmi);
7934 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatExitVmentry);
7935 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchLongJmpToR3);
7936
7937 VMCPU_CMPXCHG_STATE(pVCpu, VMCPUSTATE_STARTED_HM, VMCPUSTATE_STARTED_EXEC);
7938
7939 /** @todo This partially defeats the purpose of having preemption hooks.
7940 * The problem is, deregistering the hooks should be moved to a place that
7941 * lasts until the EMT is about to be destroyed not everytime while leaving HM
7942 * context.
7943 */
7944 int rc = hmR0VmxClearVmcs(pVmcsInfo);
7945 AssertRCReturn(rc, rc);
7946
7947#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
7948 /*
7949 * A valid shadow VMCS is made active as part of VM-entry. It is necessary to
7950 * clear a shadow VMCS before allowing that VMCS to become active on another
7951 * logical processor. We may or may not be importing guest state which clears
7952 * it, so cover for it here.
7953 *
7954 * See Intel spec. 24.11.1 "Software Use of Virtual-Machine Control Structures".
7955 */
7956 if ( pVmcsInfo->pvShadowVmcs
7957 && pVmcsInfo->fShadowVmcsState != VMX_V_VMCS_LAUNCH_STATE_CLEAR)
7958 {
7959 rc = hmR0VmxClearShadowVmcs(pVmcsInfo);
7960 AssertRCReturn(rc, rc);
7961 }
7962
7963 /*
7964 * Flag that we need to re-export the host state if we switch to this VMCS before
7965 * executing guest or nested-guest code.
7966 */
7967 pVmcsInfo->idHostCpuState = NIL_RTCPUID;
7968#endif
7969
7970 Log4Func(("Cleared Vmcs. HostCpuId=%u\n", idCpu));
7971 NOREF(idCpu);
7972 return VINF_SUCCESS;
7973}
7974
7975
7976/**
7977 * Leaves the VT-x session.
7978 *
7979 * @returns VBox status code.
7980 * @param pVCpu The cross context virtual CPU structure.
7981 *
7982 * @remarks No-long-jmp zone!!!
7983 */
7984static int hmR0VmxLeaveSession(PVMCPUCC pVCpu)
7985{
7986 HM_DISABLE_PREEMPT(pVCpu);
7987 HMVMX_ASSERT_CPU_SAFE(pVCpu);
7988 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
7989 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
7990
7991 /* When thread-context hooks are used, we can avoid doing the leave again if we had been preempted before
7992 and done this from the VMXR0ThreadCtxCallback(). */
7993 if (!pVCpu->hm.s.fLeaveDone)
7994 {
7995 int rc2 = hmR0VmxLeave(pVCpu, true /* fImportState */);
7996 AssertRCReturnStmt(rc2, HM_RESTORE_PREEMPT(), rc2);
7997 pVCpu->hm.s.fLeaveDone = true;
7998 }
7999 Assert(!pVCpu->cpum.GstCtx.fExtrn);
8000
8001 /*
8002 * !!! IMPORTANT !!!
8003 * If you modify code here, make sure to check whether hmR0VmxCallRing3Callback() needs to be updated too.
8004 */
8005
8006 /* Deregister hook now that we've left HM context before re-enabling preemption. */
8007 /** @todo Deregistering here means we need to VMCLEAR always
8008 * (longjmp/exit-to-r3) in VT-x which is not efficient, eliminate need
8009 * for calling VMMR0ThreadCtxHookDisable here! */
8010 VMMR0ThreadCtxHookDisable(pVCpu);
8011
8012 /* Leave HM context. This takes care of local init (term). */
8013 int rc = HMR0LeaveCpu(pVCpu);
8014
8015 HM_RESTORE_PREEMPT();
8016 return rc;
8017}
8018
8019
8020/**
8021 * Does the necessary state syncing before doing a longjmp to ring-3.
8022 *
8023 * @returns VBox status code.
8024 * @param pVCpu The cross context virtual CPU structure.
8025 *
8026 * @remarks No-long-jmp zone!!!
8027 */
8028DECLINLINE(int) hmR0VmxLongJmpToRing3(PVMCPUCC pVCpu)
8029{
8030 return hmR0VmxLeaveSession(pVCpu);
8031}
8032
8033
8034/**
8035 * Take necessary actions before going back to ring-3.
8036 *
8037 * An action requires us to go back to ring-3. This function does the necessary
8038 * steps before we can safely return to ring-3. This is not the same as longjmps
8039 * to ring-3, this is voluntary and prepares the guest so it may continue
8040 * executing outside HM (recompiler/IEM).
8041 *
8042 * @returns VBox status code.
8043 * @param pVCpu The cross context virtual CPU structure.
8044 * @param rcExit The reason for exiting to ring-3. Can be
8045 * VINF_VMM_UNKNOWN_RING3_CALL.
8046 */
8047static int hmR0VmxExitToRing3(PVMCPUCC pVCpu, VBOXSTRICTRC rcExit)
8048{
8049 HMVMX_ASSERT_PREEMPT_SAFE(pVCpu);
8050
8051 PVMXVMCSINFO pVmcsInfo = hmGetVmxActiveVmcsInfo(pVCpu);
8052 if (RT_UNLIKELY(rcExit == VERR_VMX_INVALID_VMCS_PTR))
8053 {
8054 VMXGetCurrentVmcs(&pVCpu->hm.s.vmx.LastError.HCPhysCurrentVmcs);
8055 pVCpu->hm.s.vmx.LastError.u32VmcsRev = *(uint32_t *)pVmcsInfo->pvVmcs;
8056 pVCpu->hm.s.vmx.LastError.idEnteredCpu = pVCpu->hm.s.idEnteredCpu;
8057 /* LastError.idCurrentCpu was updated in hmR0VmxPreRunGuestCommitted(). */
8058 }
8059
8060 /* Please, no longjumps here (any logging shouldn't flush jump back to ring-3). NO LOGGING BEFORE THIS POINT! */
8061 VMMRZCallRing3Disable(pVCpu);
8062 Log4Func(("rcExit=%d\n", VBOXSTRICTRC_VAL(rcExit)));
8063
8064 /*
8065 * Convert any pending HM events back to TRPM due to premature exits to ring-3.
8066 * We need to do this only on returns to ring-3 and not for longjmps to ring3.
8067 *
8068 * This is because execution may continue from ring-3 and we would need to inject
8069 * the event from there (hence place it back in TRPM).
8070 */
8071 if (pVCpu->hm.s.Event.fPending)
8072 {
8073 hmR0VmxPendingEventToTrpmTrap(pVCpu);
8074 Assert(!pVCpu->hm.s.Event.fPending);
8075
8076 /* Clear the events from the VMCS. */
8077 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_ENTRY_INTERRUPTION_INFO, 0);
8078 AssertRC(rc);
8079 }
8080#ifdef VBOX_STRICT
8081 else
8082 {
8083 /*
8084 * Ensure we don't accidentally clear a pending HM event without clearing the VMCS.
8085 * This can be pretty hard to debug otherwise, interrupts might get injected twice
8086 * occasionally, see @bugref{9180#c42}.
8087 *
8088 * However, if the VM-entry failed, any VM entry-interruption info. field would
8089 * be left unmodified as the event would not have been injected to the guest. In
8090 * such cases, don't assert, we're not going to continue guest execution anyway.
8091 */
8092 uint32_t uExitReason;
8093 uint32_t uEntryIntInfo;
8094 int rc = VMXReadVmcs32(VMX_VMCS32_RO_EXIT_REASON, &uExitReason);
8095 rc |= VMXReadVmcs32(VMX_VMCS32_CTRL_ENTRY_INTERRUPTION_INFO, &uEntryIntInfo);
8096 AssertRC(rc);
8097 Assert(VMX_EXIT_REASON_HAS_ENTRY_FAILED(uExitReason) || !VMX_ENTRY_INT_INFO_IS_VALID(uEntryIntInfo));
8098 }
8099#endif
8100
8101 /*
8102 * Clear the interrupt-window and NMI-window VMCS controls as we could have got
8103 * a VM-exit with higher priority than interrupt-window or NMI-window VM-exits
8104 * (e.g. TPR below threshold).
8105 */
8106 if (!CPUMIsGuestInVmxNonRootMode(&pVCpu->cpum.GstCtx))
8107 {
8108 hmR0VmxClearIntWindowExitVmcs(pVmcsInfo);
8109 hmR0VmxClearNmiWindowExitVmcs(pVmcsInfo);
8110 }
8111
8112 /* If we're emulating an instruction, we shouldn't have any TRPM traps pending
8113 and if we're injecting an event we should have a TRPM trap pending. */
8114 AssertMsg(rcExit != VINF_EM_RAW_INJECT_TRPM_EVENT || TRPMHasTrap(pVCpu), ("%Rrc\n", VBOXSTRICTRC_VAL(rcExit)));
8115#ifndef DEBUG_bird /* Triggered after firing an NMI against NT4SP1, possibly a triple fault in progress. */
8116 AssertMsg(rcExit != VINF_EM_RAW_EMULATE_INSTR || !TRPMHasTrap(pVCpu), ("%Rrc\n", VBOXSTRICTRC_VAL(rcExit)));
8117#endif
8118
8119 /* Save guest state and restore host state bits. */
8120 int rc = hmR0VmxLeaveSession(pVCpu);
8121 AssertRCReturn(rc, rc);
8122 STAM_COUNTER_DEC(&pVCpu->hm.s.StatSwitchLongJmpToR3);
8123
8124 /* Thread-context hooks are unregistered at this point!!! */
8125
8126 /* Sync recompiler state. */
8127 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_TO_R3);
8128 CPUMSetChangedFlags(pVCpu, CPUM_CHANGED_SYSENTER_MSR
8129 | CPUM_CHANGED_LDTR
8130 | CPUM_CHANGED_GDTR
8131 | CPUM_CHANGED_IDTR
8132 | CPUM_CHANGED_TR
8133 | CPUM_CHANGED_HIDDEN_SEL_REGS);
8134 if ( pVCpu->CTX_SUFF(pVM)->hm.s.fNestedPaging
8135 && CPUMIsGuestPagingEnabledEx(&pVCpu->cpum.GstCtx))
8136 CPUMSetChangedFlags(pVCpu, CPUM_CHANGED_GLOBAL_TLB_FLUSH);
8137
8138 Assert(!pVCpu->hm.s.fClearTrapFlag);
8139
8140 /* Update the exit-to-ring 3 reason. */
8141 pVCpu->hm.s.rcLastExitToR3 = VBOXSTRICTRC_VAL(rcExit);
8142
8143 /* On our way back from ring-3 reload the guest state if there is a possibility of it being changed. */
8144 if ( rcExit != VINF_EM_RAW_INTERRUPT
8145 || CPUMIsGuestInVmxNonRootMode(&pVCpu->cpum.GstCtx))
8146 {
8147 Assert(!(pVCpu->cpum.GstCtx.fExtrn & HMVMX_CPUMCTX_EXTRN_ALL));
8148 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_ALL_GUEST);
8149 }
8150
8151 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchExitToR3);
8152
8153 /* We do -not- want any longjmp notifications after this! We must return to ring-3 ASAP. */
8154 VMMRZCallRing3RemoveNotification(pVCpu);
8155 VMMRZCallRing3Enable(pVCpu);
8156
8157 return rc;
8158}
8159
8160
8161/**
8162 * VMMRZCallRing3() callback wrapper which saves the guest state before we
8163 * longjump to ring-3 and possibly get preempted.
8164 *
8165 * @returns VBox status code.
8166 * @param pVCpu The cross context virtual CPU structure.
8167 * @param enmOperation The operation causing the ring-3 longjump.
8168 * @param pvUser User argument, currently unused, NULL.
8169 */
8170static DECLCALLBACK(int) hmR0VmxCallRing3Callback(PVMCPUCC pVCpu, VMMCALLRING3 enmOperation, void *pvUser)
8171{
8172 RT_NOREF(pvUser);
8173 if (enmOperation == VMMCALLRING3_VM_R0_ASSERTION)
8174 {
8175 /*
8176 * !!! IMPORTANT !!!
8177 * If you modify code here, check whether hmR0VmxLeave() and hmR0VmxLeaveSession() needs to be updated too.
8178 * This is a stripped down version which gets out ASAP, trying to not trigger any further assertions.
8179 */
8180 VMMRZCallRing3RemoveNotification(pVCpu);
8181 VMMRZCallRing3Disable(pVCpu);
8182 RTTHREADPREEMPTSTATE PreemptState = RTTHREADPREEMPTSTATE_INITIALIZER;
8183 RTThreadPreemptDisable(&PreemptState);
8184
8185 PVMXVMCSINFO pVmcsInfo = hmGetVmxActiveVmcsInfo(pVCpu);
8186 hmR0VmxImportGuestState(pVCpu, pVmcsInfo, HMVMX_CPUMCTX_EXTRN_ALL);
8187 CPUMR0FpuStateMaybeSaveGuestAndRestoreHost(pVCpu);
8188 CPUMR0DebugStateMaybeSaveGuestAndRestoreHost(pVCpu, true /* save DR6 */);
8189
8190 /* Restore host-state bits that VT-x only restores partially. */
8191 if ( (pVCpu->hm.s.vmx.fRestoreHostFlags & VMX_RESTORE_HOST_REQUIRED)
8192 && (pVCpu->hm.s.vmx.fRestoreHostFlags & ~VMX_RESTORE_HOST_REQUIRED))
8193 VMXRestoreHostState(pVCpu->hm.s.vmx.fRestoreHostFlags, &pVCpu->hm.s.vmx.RestoreHost);
8194 pVCpu->hm.s.vmx.fRestoreHostFlags = 0;
8195
8196 /* Restore the lazy host MSRs as we're leaving VT-x context. */
8197 if (pVCpu->hm.s.vmx.fLazyMsrs & VMX_LAZY_MSRS_LOADED_GUEST)
8198 hmR0VmxLazyRestoreHostMsrs(pVCpu);
8199
8200 /* Update auto-load/store host MSRs values when we re-enter VT-x (as we could be on a different CPU). */
8201 pVCpu->hm.s.vmx.fUpdatedHostAutoMsrs = false;
8202 VMCPU_CMPXCHG_STATE(pVCpu, VMCPUSTATE_STARTED_HM, VMCPUSTATE_STARTED_EXEC);
8203
8204 /* Clear the current VMCS data back to memory (shadow VMCS if any would have been
8205 cleared as part of importing the guest state above. */
8206 hmR0VmxClearVmcs(pVmcsInfo);
8207
8208 /** @todo eliminate the need for calling VMMR0ThreadCtxHookDisable here! */
8209 VMMR0ThreadCtxHookDisable(pVCpu);
8210 HMR0LeaveCpu(pVCpu);
8211 RTThreadPreemptRestore(&PreemptState);
8212 return VINF_SUCCESS;
8213 }
8214
8215 Assert(pVCpu);
8216 Assert(pvUser);
8217 Assert(VMMRZCallRing3IsEnabled(pVCpu));
8218 HMVMX_ASSERT_PREEMPT_SAFE(pVCpu);
8219
8220 VMMRZCallRing3Disable(pVCpu);
8221 Assert(VMMR0IsLogFlushDisabled(pVCpu));
8222
8223 Log4Func(("-> hmR0VmxLongJmpToRing3 enmOperation=%d\n", enmOperation));
8224
8225 int rc = hmR0VmxLongJmpToRing3(pVCpu);
8226 AssertRCReturn(rc, rc);
8227
8228 VMMRZCallRing3Enable(pVCpu);
8229 return VINF_SUCCESS;
8230}
8231
8232
8233/**
8234 * Pushes a 2-byte value onto the real-mode (in virtual-8086 mode) guest's
8235 * stack.
8236 *
8237 * @returns Strict VBox status code (i.e. informational status codes too).
8238 * @retval VINF_EM_RESET if pushing a value to the stack caused a triple-fault.
8239 * @param pVCpu The cross context virtual CPU structure.
8240 * @param uValue The value to push to the guest stack.
8241 */
8242static VBOXSTRICTRC hmR0VmxRealModeGuestStackPush(PVMCPUCC pVCpu, uint16_t uValue)
8243{
8244 /*
8245 * The stack limit is 0xffff in real-on-virtual 8086 mode. Real-mode with weird stack limits cannot be run in
8246 * virtual 8086 mode in VT-x. See Intel spec. 26.3.1.2 "Checks on Guest Segment Registers".
8247 * See Intel Instruction reference for PUSH and Intel spec. 22.33.1 "Segment Wraparound".
8248 */
8249 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
8250 if (pCtx->sp == 1)
8251 return VINF_EM_RESET;
8252 pCtx->sp -= sizeof(uint16_t); /* May wrap around which is expected behaviour. */
8253 int rc = PGMPhysSimpleWriteGCPhys(pVCpu->CTX_SUFF(pVM), pCtx->ss.u64Base + pCtx->sp, &uValue, sizeof(uint16_t));
8254 AssertRC(rc);
8255 return rc;
8256}
8257
8258
8259/**
8260 * Injects an event into the guest upon VM-entry by updating the relevant fields
8261 * in the VM-entry area in the VMCS.
8262 *
8263 * @returns Strict VBox status code (i.e. informational status codes too).
8264 * @retval VINF_SUCCESS if the event is successfully injected into the VMCS.
8265 * @retval VINF_EM_RESET if event injection resulted in a triple-fault.
8266 *
8267 * @param pVCpu The cross context virtual CPU structure.
8268 * @param pVmxTransient The VMX-transient structure.
8269 * @param pEvent The event being injected.
8270 * @param pfIntrState Pointer to the VT-x guest-interruptibility-state. This
8271 * will be updated if necessary. This cannot not be NULL.
8272 * @param fStepping Whether we're single-stepping guest execution and should
8273 * return VINF_EM_DBG_STEPPED if the event is injected
8274 * directly (registers modified by us, not by hardware on
8275 * VM-entry).
8276 */
8277static VBOXSTRICTRC hmR0VmxInjectEventVmcs(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient, PCHMEVENT pEvent, bool fStepping,
8278 uint32_t *pfIntrState)
8279{
8280 /* Intel spec. 24.8.3 "VM-Entry Controls for Event Injection" specifies the interruption-information field to be 32-bits. */
8281 AssertMsg(!RT_HI_U32(pEvent->u64IntInfo), ("%#RX64\n", pEvent->u64IntInfo));
8282 Assert(pfIntrState);
8283
8284 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
8285 uint32_t u32IntInfo = pEvent->u64IntInfo;
8286 uint32_t const u32ErrCode = pEvent->u32ErrCode;
8287 uint32_t const cbInstr = pEvent->cbInstr;
8288 RTGCUINTPTR const GCPtrFault = pEvent->GCPtrFaultAddress;
8289 uint8_t const uVector = VMX_ENTRY_INT_INFO_VECTOR(u32IntInfo);
8290 uint32_t const uIntType = VMX_ENTRY_INT_INFO_TYPE(u32IntInfo);
8291
8292#ifdef VBOX_STRICT
8293 /*
8294 * Validate the error-code-valid bit for hardware exceptions.
8295 * No error codes for exceptions in real-mode.
8296 *
8297 * See Intel spec. 20.1.4 "Interrupt and Exception Handling"
8298 */
8299 if ( uIntType == VMX_EXIT_INT_INFO_TYPE_HW_XCPT
8300 && !CPUMIsGuestInRealModeEx(pCtx))
8301 {
8302 switch (uVector)
8303 {
8304 case X86_XCPT_PF:
8305 case X86_XCPT_DF:
8306 case X86_XCPT_TS:
8307 case X86_XCPT_NP:
8308 case X86_XCPT_SS:
8309 case X86_XCPT_GP:
8310 case X86_XCPT_AC:
8311 AssertMsg(VMX_ENTRY_INT_INFO_IS_ERROR_CODE_VALID(u32IntInfo),
8312 ("Error-code-valid bit not set for exception that has an error code uVector=%#x\n", uVector));
8313 RT_FALL_THRU();
8314 default:
8315 break;
8316 }
8317 }
8318
8319 /* Cannot inject an NMI when block-by-MOV SS is in effect. */
8320 Assert( uIntType != VMX_EXIT_INT_INFO_TYPE_NMI
8321 || !(*pfIntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_MOVSS));
8322#endif
8323
8324 STAM_COUNTER_INC(&pVCpu->hm.s.paStatInjectedIrqsR0[uVector & MASK_INJECT_IRQ_STAT]);
8325
8326 /*
8327 * Hardware interrupts & exceptions cannot be delivered through the software interrupt
8328 * redirection bitmap to the real mode task in virtual-8086 mode. We must jump to the
8329 * interrupt handler in the (real-mode) guest.
8330 *
8331 * See Intel spec. 20.3 "Interrupt and Exception handling in Virtual-8086 Mode".
8332 * See Intel spec. 20.1.4 "Interrupt and Exception Handling" for real-mode interrupt handling.
8333 */
8334 if (CPUMIsGuestInRealModeEx(pCtx)) /* CR0.PE bit changes are always intercepted, so it's up to date. */
8335 {
8336 if (pVCpu->CTX_SUFF(pVM)->hm.s.vmx.fUnrestrictedGuest)
8337 {
8338 /*
8339 * For CPUs with unrestricted guest execution enabled and with the guest
8340 * in real-mode, we must not set the deliver-error-code bit.
8341 *
8342 * See Intel spec. 26.2.1.3 "VM-Entry Control Fields".
8343 */
8344 u32IntInfo &= ~VMX_ENTRY_INT_INFO_ERROR_CODE_VALID;
8345 }
8346 else
8347 {
8348 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
8349 Assert(PDMVmmDevHeapIsEnabled(pVM));
8350 Assert(pVM->hm.s.vmx.pRealModeTSS);
8351 Assert(!CPUMIsGuestInVmxNonRootMode(&pVCpu->cpum.GstCtx));
8352
8353 /* We require RIP, RSP, RFLAGS, CS, IDTR, import them. */
8354 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
8355 int rc2 = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, CPUMCTX_EXTRN_SREG_MASK | CPUMCTX_EXTRN_TABLE_MASK
8356 | CPUMCTX_EXTRN_RIP | CPUMCTX_EXTRN_RSP | CPUMCTX_EXTRN_RFLAGS);
8357 AssertRCReturn(rc2, rc2);
8358
8359 /* Check if the interrupt handler is present in the IVT (real-mode IDT). IDT limit is (4N - 1). */
8360 size_t const cbIdtEntry = sizeof(X86IDTR16);
8361 if (uVector * cbIdtEntry + (cbIdtEntry - 1) > pCtx->idtr.cbIdt)
8362 {
8363 /* If we are trying to inject a #DF with no valid IDT entry, return a triple-fault. */
8364 if (uVector == X86_XCPT_DF)
8365 return VINF_EM_RESET;
8366
8367 /* If we're injecting a #GP with no valid IDT entry, inject a double-fault.
8368 No error codes for exceptions in real-mode. */
8369 if (uVector == X86_XCPT_GP)
8370 {
8371 uint32_t const uXcptDfInfo = RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_VECTOR, X86_XCPT_DF)
8372 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_TYPE, VMX_ENTRY_INT_INFO_TYPE_HW_XCPT)
8373 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_ERR_CODE_VALID, 0)
8374 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_VALID, 1);
8375 HMEVENT EventXcptDf;
8376 RT_ZERO(EventXcptDf);
8377 EventXcptDf.u64IntInfo = uXcptDfInfo;
8378 return hmR0VmxInjectEventVmcs(pVCpu, pVmxTransient, &EventXcptDf, fStepping, pfIntrState);
8379 }
8380
8381 /*
8382 * If we're injecting an event with no valid IDT entry, inject a #GP.
8383 * No error codes for exceptions in real-mode.
8384 *
8385 * See Intel spec. 20.1.4 "Interrupt and Exception Handling"
8386 */
8387 uint32_t const uXcptGpInfo = RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_VECTOR, X86_XCPT_GP)
8388 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_TYPE, VMX_ENTRY_INT_INFO_TYPE_HW_XCPT)
8389 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_ERR_CODE_VALID, 0)
8390 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_VALID, 1);
8391 HMEVENT EventXcptGp;
8392 RT_ZERO(EventXcptGp);
8393 EventXcptGp.u64IntInfo = uXcptGpInfo;
8394 return hmR0VmxInjectEventVmcs(pVCpu, pVmxTransient, &EventXcptGp, fStepping, pfIntrState);
8395 }
8396
8397 /* Software exceptions (#BP and #OF exceptions thrown as a result of INT3 or INTO) */
8398 uint16_t uGuestIp = pCtx->ip;
8399 if (uIntType == VMX_ENTRY_INT_INFO_TYPE_SW_XCPT)
8400 {
8401 Assert(uVector == X86_XCPT_BP || uVector == X86_XCPT_OF);
8402 /* #BP and #OF are both benign traps, we need to resume the next instruction. */
8403 uGuestIp = pCtx->ip + (uint16_t)cbInstr;
8404 }
8405 else if (uIntType == VMX_ENTRY_INT_INFO_TYPE_SW_INT)
8406 uGuestIp = pCtx->ip + (uint16_t)cbInstr;
8407
8408 /* Get the code segment selector and offset from the IDT entry for the interrupt handler. */
8409 X86IDTR16 IdtEntry;
8410 RTGCPHYS const GCPhysIdtEntry = (RTGCPHYS)pCtx->idtr.pIdt + uVector * cbIdtEntry;
8411 rc2 = PGMPhysSimpleReadGCPhys(pVM, &IdtEntry, GCPhysIdtEntry, cbIdtEntry);
8412 AssertRCReturn(rc2, rc2);
8413
8414 /* Construct the stack frame for the interrupt/exception handler. */
8415 VBOXSTRICTRC rcStrict;
8416 rcStrict = hmR0VmxRealModeGuestStackPush(pVCpu, pCtx->eflags.u32);
8417 if (rcStrict == VINF_SUCCESS)
8418 {
8419 rcStrict = hmR0VmxRealModeGuestStackPush(pVCpu, pCtx->cs.Sel);
8420 if (rcStrict == VINF_SUCCESS)
8421 rcStrict = hmR0VmxRealModeGuestStackPush(pVCpu, uGuestIp);
8422 }
8423
8424 /* Clear the required eflag bits and jump to the interrupt/exception handler. */
8425 if (rcStrict == VINF_SUCCESS)
8426 {
8427 pCtx->eflags.u32 &= ~(X86_EFL_IF | X86_EFL_TF | X86_EFL_RF | X86_EFL_AC);
8428 pCtx->rip = IdtEntry.offSel;
8429 pCtx->cs.Sel = IdtEntry.uSel;
8430 pCtx->cs.ValidSel = IdtEntry.uSel;
8431 pCtx->cs.u64Base = IdtEntry.uSel << cbIdtEntry;
8432 if ( uIntType == VMX_ENTRY_INT_INFO_TYPE_HW_XCPT
8433 && uVector == X86_XCPT_PF)
8434 pCtx->cr2 = GCPtrFault;
8435
8436 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_CS | HM_CHANGED_GUEST_CR2
8437 | HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS
8438 | HM_CHANGED_GUEST_RSP);
8439
8440 /*
8441 * If we delivered a hardware exception (other than an NMI) and if there was
8442 * block-by-STI in effect, we should clear it.
8443 */
8444 if (*pfIntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_STI)
8445 {
8446 Assert( uIntType != VMX_ENTRY_INT_INFO_TYPE_NMI
8447 && uIntType != VMX_ENTRY_INT_INFO_TYPE_EXT_INT);
8448 Log4Func(("Clearing inhibition due to STI\n"));
8449 *pfIntrState &= ~VMX_VMCS_GUEST_INT_STATE_BLOCK_STI;
8450 }
8451
8452 Log4(("Injected real-mode: u32IntInfo=%#x u32ErrCode=%#x cbInstr=%#x Eflags=%#x CS:EIP=%04x:%04x\n",
8453 u32IntInfo, u32ErrCode, cbInstr, pCtx->eflags.u, pCtx->cs.Sel, pCtx->eip));
8454
8455 /*
8456 * The event has been truly dispatched to the guest. Mark it as no longer pending so
8457 * we don't attempt to undo it if we are returning to ring-3 before executing guest code.
8458 */
8459 pVCpu->hm.s.Event.fPending = false;
8460
8461 /*
8462 * If we eventually support nested-guest execution without unrestricted guest execution,
8463 * we should set fInterceptEvents here.
8464 */
8465 Assert(!pVmxTransient->fIsNestedGuest);
8466
8467 /* If we're stepping and we've changed cs:rip above, bail out of the VMX R0 execution loop. */
8468 if (fStepping)
8469 rcStrict = VINF_EM_DBG_STEPPED;
8470 }
8471 AssertMsg(rcStrict == VINF_SUCCESS || rcStrict == VINF_EM_RESET || (rcStrict == VINF_EM_DBG_STEPPED && fStepping),
8472 ("%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
8473 return rcStrict;
8474 }
8475 }
8476
8477 /*
8478 * Validate.
8479 */
8480 Assert(VMX_ENTRY_INT_INFO_IS_VALID(u32IntInfo)); /* Bit 31 (Valid bit) must be set by caller. */
8481 Assert(!(u32IntInfo & VMX_BF_ENTRY_INT_INFO_RSVD_12_30_MASK)); /* Bits 30:12 MBZ. */
8482
8483 /*
8484 * Inject the event into the VMCS.
8485 */
8486 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_ENTRY_INTERRUPTION_INFO, u32IntInfo);
8487 if (VMX_ENTRY_INT_INFO_IS_ERROR_CODE_VALID(u32IntInfo))
8488 rc |= VMXWriteVmcs32(VMX_VMCS32_CTRL_ENTRY_EXCEPTION_ERRCODE, u32ErrCode);
8489 rc |= VMXWriteVmcs32(VMX_VMCS32_CTRL_ENTRY_INSTR_LENGTH, cbInstr);
8490 AssertRC(rc);
8491
8492 /*
8493 * Update guest CR2 if this is a page-fault.
8494 */
8495 if (VMX_ENTRY_INT_INFO_IS_XCPT_PF(u32IntInfo))
8496 pCtx->cr2 = GCPtrFault;
8497
8498 Log4(("Injecting u32IntInfo=%#x u32ErrCode=%#x cbInstr=%#x CR2=%#RX64\n", u32IntInfo, u32ErrCode, cbInstr, pCtx->cr2));
8499 return VINF_SUCCESS;
8500}
8501
8502
8503/**
8504 * Evaluates the event to be delivered to the guest and sets it as the pending
8505 * event.
8506 *
8507 * @returns Strict VBox status code (i.e. informational status codes too).
8508 * @param pVCpu The cross context virtual CPU structure.
8509 * @param pVmxTransient The VMX-transient structure.
8510 * @param pfIntrState Where to store the VT-x guest-interruptibility state.
8511 */
8512static VBOXSTRICTRC hmR0VmxEvaluatePendingEvent(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient, uint32_t *pfIntrState)
8513{
8514 Assert(pfIntrState);
8515 Assert(!TRPMHasTrap(pVCpu));
8516
8517 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
8518 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
8519 bool const fIsNestedGuest = pVmxTransient->fIsNestedGuest;
8520
8521 /*
8522 * Get the current interruptibility-state of the guest or nested-guest and
8523 * then figure out what needs to be injected.
8524 */
8525 uint32_t const fIntrState = hmR0VmxGetGuestIntrState(pVCpu, pVmxTransient);
8526 bool const fBlockMovSS = RT_BOOL(fIntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_MOVSS);
8527 bool const fBlockSti = RT_BOOL(fIntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_STI);
8528 bool const fBlockNmi = RT_BOOL(fIntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_NMI);
8529
8530 /* We don't support block-by-SMI yet.*/
8531 Assert(!(fIntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_SMI));
8532
8533 /* Block-by-STI must not be set when interrupts are disabled. */
8534 if (fBlockSti)
8535 {
8536 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_RFLAGS);
8537 Assert(pCtx->eflags.Bits.u1IF);
8538 }
8539
8540 /* Update interruptibility state to the caller. */
8541 *pfIntrState = fIntrState;
8542
8543 /*
8544 * Toggling of interrupt force-flags here is safe since we update TRPM on
8545 * premature exits to ring-3 before executing guest code, see hmR0VmxExitToRing3().
8546 * We must NOT restore these force-flags.
8547 */
8548
8549 /** @todo SMI. SMIs take priority over NMIs. */
8550
8551 /*
8552 * Check if an NMI is pending and if the guest or nested-guest can receive them.
8553 * NMIs take priority over external interrupts.
8554 */
8555 if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_INTERRUPT_NMI))
8556 {
8557 /* On some CPUs block-by-STI also blocks NMIs. See Intel spec. 26.3.1.5 "Checks On Guest Non-Register State". */
8558 if ( !pVCpu->hm.s.Event.fPending
8559 && !fBlockNmi
8560 && !fBlockSti
8561 && !fBlockMovSS)
8562 {
8563#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
8564 if ( fIsNestedGuest
8565 && CPUMIsGuestVmxPinCtlsSet(pVCpu, pCtx, VMX_PIN_CTLS_NMI_EXIT))
8566 return IEMExecVmxVmexitXcptNmi(pVCpu);
8567#endif
8568 hmR0VmxSetPendingXcptNmi(pVCpu);
8569 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INTERRUPT_NMI);
8570 Log4Func(("Pending NMI\n"));
8571 }
8572 else if (!fIsNestedGuest)
8573 hmR0VmxSetNmiWindowExitVmcs(pVCpu, pVmcsInfo);
8574 /* else: for nested-guests, NMI-window exiting will be picked up when merging VMCS controls. */
8575 }
8576 /*
8577 * Check if an external interrupt (PIC/APIC) is pending and if the guest or nested-guest
8578 * can receive them. Once PDMGetInterrupt() returns a valid interrupt we -must- deliver
8579 * the interrupt. We can no longer re-request it from the APIC.
8580 */
8581 else if ( VMCPU_FF_IS_ANY_SET(pVCpu, VMCPU_FF_INTERRUPT_APIC | VMCPU_FF_INTERRUPT_PIC)
8582 && !pVCpu->hm.s.fSingleInstruction)
8583 {
8584 Assert(!DBGFIsStepping(pVCpu));
8585 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, CPUMCTX_EXTRN_RFLAGS);
8586 AssertRCReturn(rc, rc);
8587
8588 bool const fBlockInt = !(pCtx->eflags.u32 & X86_EFL_IF);
8589 if ( !pVCpu->hm.s.Event.fPending
8590 && !fBlockInt
8591 && !fBlockSti
8592 && !fBlockMovSS)
8593 {
8594#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
8595 if ( fIsNestedGuest
8596 && CPUMIsGuestVmxPinCtlsSet(pVCpu, pCtx, VMX_PIN_CTLS_EXT_INT_EXIT)
8597 && !CPUMIsGuestVmxExitCtlsSet(pVCpu, pCtx, VMX_EXIT_CTLS_ACK_EXT_INT))
8598 {
8599 VBOXSTRICTRC rcStrict = IEMExecVmxVmexitExtInt(pVCpu, 0 /* uVector */, true /* fIntPending */);
8600 Assert(rcStrict != VINF_VMX_INTERCEPT_NOT_ACTIVE);
8601 return rcStrict;
8602 }
8603#endif
8604 uint8_t u8Interrupt;
8605 rc = PDMGetInterrupt(pVCpu, &u8Interrupt);
8606 if (RT_SUCCESS(rc))
8607 {
8608#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
8609 if ( fIsNestedGuest
8610 && CPUMIsGuestVmxPinCtlsSet(pVCpu, pCtx, VMX_PIN_CTLS_EXT_INT_EXIT)
8611 && CPUMIsGuestVmxExitCtlsSet(pVCpu, pCtx, VMX_EXIT_CTLS_ACK_EXT_INT))
8612 {
8613 VBOXSTRICTRC rcStrict = IEMExecVmxVmexitExtInt(pVCpu, u8Interrupt, false /* fIntPending */);
8614 Assert(rcStrict != VINF_VMX_INTERCEPT_NOT_ACTIVE);
8615 return rcStrict;
8616 }
8617#endif
8618 hmR0VmxSetPendingExtInt(pVCpu, u8Interrupt);
8619 Log4Func(("Pending external interrupt vector %#x\n", u8Interrupt));
8620 }
8621 else if (rc == VERR_APIC_INTR_MASKED_BY_TPR)
8622 {
8623 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchTprMaskedIrq);
8624
8625 if ( !fIsNestedGuest
8626 && (pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_USE_TPR_SHADOW))
8627 hmR0VmxApicSetTprThreshold(pVmcsInfo, u8Interrupt >> 4);
8628 /* else: for nested-guests, TPR threshold is picked up while merging VMCS controls. */
8629
8630 /*
8631 * If the CPU doesn't have TPR shadowing, we will always get a VM-exit on TPR changes and
8632 * APICSetTpr() will end up setting the VMCPU_FF_INTERRUPT_APIC if required, so there is no
8633 * need to re-set this force-flag here.
8634 */
8635 }
8636 else
8637 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchGuestIrq);
8638 }
8639 else if (!fIsNestedGuest)
8640 hmR0VmxSetIntWindowExitVmcs(pVCpu, pVmcsInfo);
8641 /* else: for nested-guests, interrupt-window exiting will be picked up when merging VMCS controls. */
8642 }
8643
8644 return VINF_SUCCESS;
8645}
8646
8647
8648/**
8649 * Injects any pending events into the guest if the guest is in a state to
8650 * receive them.
8651 *
8652 * @returns Strict VBox status code (i.e. informational status codes too).
8653 * @param pVCpu The cross context virtual CPU structure.
8654 * @param pVmxTransient The VMX-transient structure.
8655 * @param fIntrState The VT-x guest-interruptibility state.
8656 * @param fStepping Whether we are single-stepping the guest using the
8657 * hypervisor debugger and should return
8658 * VINF_EM_DBG_STEPPED if the event was dispatched
8659 * directly.
8660 */
8661static VBOXSTRICTRC hmR0VmxInjectPendingEvent(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient, uint32_t fIntrState, bool fStepping)
8662{
8663 HMVMX_ASSERT_PREEMPT_SAFE(pVCpu);
8664 Assert(VMMRZCallRing3IsEnabled(pVCpu));
8665
8666 bool const fBlockMovSS = RT_BOOL(fIntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_MOVSS);
8667 bool const fBlockSti = RT_BOOL(fIntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_STI);
8668
8669 Assert(!fBlockSti || !(ASMAtomicUoReadU64(&pVCpu->cpum.GstCtx.fExtrn) & CPUMCTX_EXTRN_RFLAGS));
8670 Assert(!fBlockSti || pVCpu->cpum.GstCtx.eflags.Bits.u1IF); /* Cannot set block-by-STI when interrupts are disabled. */
8671 Assert(!(fIntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_SMI)); /* We don't support block-by-SMI yet.*/
8672 Assert(!TRPMHasTrap(pVCpu));
8673
8674 VBOXSTRICTRC rcStrict = VINF_SUCCESS;
8675 if (pVCpu->hm.s.Event.fPending)
8676 {
8677 /*
8678 * Do -not- clear any interrupt-window exiting control here. We might have an interrupt
8679 * pending even while injecting an event and in this case, we want a VM-exit as soon as
8680 * the guest is ready for the next interrupt, see @bugref{6208#c45}.
8681 *
8682 * See Intel spec. 26.6.5 "Interrupt-Window Exiting and Virtual-Interrupt Delivery".
8683 */
8684 uint32_t const uIntType = VMX_ENTRY_INT_INFO_TYPE(pVCpu->hm.s.Event.u64IntInfo);
8685#ifdef VBOX_STRICT
8686 if (uIntType == VMX_ENTRY_INT_INFO_TYPE_EXT_INT)
8687 {
8688 bool const fBlockInt = !(pVCpu->cpum.GstCtx.eflags.u32 & X86_EFL_IF);
8689 Assert(!fBlockInt);
8690 Assert(!fBlockSti);
8691 Assert(!fBlockMovSS);
8692 }
8693 else if (uIntType == VMX_ENTRY_INT_INFO_TYPE_NMI)
8694 {
8695 bool const fBlockNmi = RT_BOOL(fIntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_NMI);
8696 Assert(!fBlockSti);
8697 Assert(!fBlockMovSS);
8698 Assert(!fBlockNmi);
8699 }
8700#endif
8701 Log4(("Injecting pending event vcpu[%RU32] u64IntInfo=%#RX64 Type=%#RX32\n", pVCpu->idCpu, pVCpu->hm.s.Event.u64IntInfo,
8702 uIntType));
8703
8704 /*
8705 * Inject the event and get any changes to the guest-interruptibility state.
8706 *
8707 * The guest-interruptibility state may need to be updated if we inject the event
8708 * into the guest IDT ourselves (for real-on-v86 guest injecting software interrupts).
8709 */
8710 rcStrict = hmR0VmxInjectEventVmcs(pVCpu, pVmxTransient, &pVCpu->hm.s.Event, fStepping, &fIntrState);
8711 AssertRCReturn(VBOXSTRICTRC_VAL(rcStrict), rcStrict);
8712
8713 if (uIntType == VMX_ENTRY_INT_INFO_TYPE_EXT_INT)
8714 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectInterrupt);
8715 else
8716 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectXcpt);
8717 }
8718
8719 /*
8720 * Update the guest-interruptibility state.
8721 *
8722 * This is required for the real-on-v86 software interrupt injection case above, as well as
8723 * updates to the guest state from ring-3 or IEM/REM.
8724 */
8725 int rc = VMXWriteVmcs32(VMX_VMCS32_GUEST_INT_STATE, fIntrState);
8726 AssertRC(rc);
8727
8728 /*
8729 * There's no need to clear the VM-entry interruption-information field here if we're not
8730 * injecting anything. VT-x clears the valid bit on every VM-exit.
8731 *
8732 * See Intel spec. 24.8.3 "VM-Entry Controls for Event Injection".
8733 */
8734
8735 Assert(rcStrict == VINF_SUCCESS || rcStrict == VINF_EM_RESET || (rcStrict == VINF_EM_DBG_STEPPED && fStepping));
8736 NOREF(fBlockMovSS); NOREF(fBlockSti);
8737 return rcStrict;
8738}
8739
8740
8741/**
8742 * Enters the VT-x session.
8743 *
8744 * @returns VBox status code.
8745 * @param pVCpu The cross context virtual CPU structure.
8746 */
8747VMMR0DECL(int) VMXR0Enter(PVMCPUCC pVCpu)
8748{
8749 AssertPtr(pVCpu);
8750 Assert(pVCpu->CTX_SUFF(pVM)->hm.s.vmx.fSupported);
8751 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
8752
8753 LogFlowFunc(("pVCpu=%p\n", pVCpu));
8754 Assert((pVCpu->hm.s.fCtxChanged & (HM_CHANGED_HOST_CONTEXT | HM_CHANGED_VMX_HOST_GUEST_SHARED_STATE))
8755 == (HM_CHANGED_HOST_CONTEXT | HM_CHANGED_VMX_HOST_GUEST_SHARED_STATE));
8756
8757#ifdef VBOX_STRICT
8758 /* At least verify VMX is enabled, since we can't check if we're in VMX root mode without #GP'ing. */
8759 RTCCUINTREG uHostCr4 = ASMGetCR4();
8760 if (!(uHostCr4 & X86_CR4_VMXE))
8761 {
8762 LogRelFunc(("X86_CR4_VMXE bit in CR4 is not set!\n"));
8763 return VERR_VMX_X86_CR4_VMXE_CLEARED;
8764 }
8765#endif
8766
8767 /*
8768 * Load the appropriate VMCS as the current and active one.
8769 */
8770 PVMXVMCSINFO pVmcsInfo;
8771 bool const fInNestedGuestMode = CPUMIsGuestInVmxNonRootMode(&pVCpu->cpum.GstCtx);
8772 if (!fInNestedGuestMode)
8773 pVmcsInfo = &pVCpu->hm.s.vmx.VmcsInfo;
8774 else
8775 pVmcsInfo = &pVCpu->hm.s.vmx.VmcsInfoNstGst;
8776 int rc = hmR0VmxLoadVmcs(pVmcsInfo);
8777 if (RT_SUCCESS(rc))
8778 {
8779 pVCpu->hm.s.vmx.fSwitchedToNstGstVmcs = fInNestedGuestMode;
8780 pVCpu->hm.s.fLeaveDone = false;
8781 Log4Func(("Loaded Vmcs. HostCpuId=%u\n", RTMpCpuId()));
8782
8783 /*
8784 * Do the EMT scheduled L1D flush here if needed.
8785 */
8786 if (pVCpu->CTX_SUFF(pVM)->hm.s.fL1dFlushOnSched)
8787 ASMWrMsr(MSR_IA32_FLUSH_CMD, MSR_IA32_FLUSH_CMD_F_L1D);
8788 else if (pVCpu->CTX_SUFF(pVM)->hm.s.fMdsClearOnSched)
8789 hmR0MdsClear();
8790 }
8791 return rc;
8792}
8793
8794
8795/**
8796 * The thread-context callback (only on platforms which support it).
8797 *
8798 * @param enmEvent The thread-context event.
8799 * @param pVCpu The cross context virtual CPU structure.
8800 * @param fGlobalInit Whether global VT-x/AMD-V init. was used.
8801 * @thread EMT(pVCpu)
8802 */
8803VMMR0DECL(void) VMXR0ThreadCtxCallback(RTTHREADCTXEVENT enmEvent, PVMCPUCC pVCpu, bool fGlobalInit)
8804{
8805 AssertPtr(pVCpu);
8806 RT_NOREF1(fGlobalInit);
8807
8808 switch (enmEvent)
8809 {
8810 case RTTHREADCTXEVENT_OUT:
8811 {
8812 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
8813 Assert(VMMR0ThreadCtxHookIsEnabled(pVCpu));
8814 VMCPU_ASSERT_EMT(pVCpu);
8815
8816 /* No longjmps (logger flushes, locks) in this fragile context. */
8817 VMMRZCallRing3Disable(pVCpu);
8818 Log4Func(("Preempting: HostCpuId=%u\n", RTMpCpuId()));
8819
8820 /* Restore host-state (FPU, debug etc.) */
8821 if (!pVCpu->hm.s.fLeaveDone)
8822 {
8823 /*
8824 * Do -not- import the guest-state here as we might already be in the middle of importing
8825 * it, esp. bad if we're holding the PGM lock, see comment in hmR0VmxImportGuestState().
8826 */
8827 hmR0VmxLeave(pVCpu, false /* fImportState */);
8828 pVCpu->hm.s.fLeaveDone = true;
8829 }
8830
8831 /* Leave HM context, takes care of local init (term). */
8832 int rc = HMR0LeaveCpu(pVCpu);
8833 AssertRC(rc);
8834
8835 /* Restore longjmp state. */
8836 VMMRZCallRing3Enable(pVCpu);
8837 STAM_REL_COUNTER_INC(&pVCpu->hm.s.StatSwitchPreempt);
8838 break;
8839 }
8840
8841 case RTTHREADCTXEVENT_IN:
8842 {
8843 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
8844 Assert(VMMR0ThreadCtxHookIsEnabled(pVCpu));
8845 VMCPU_ASSERT_EMT(pVCpu);
8846
8847 /* No longjmps here, as we don't want to trigger preemption (& its hook) while resuming. */
8848 VMMRZCallRing3Disable(pVCpu);
8849 Log4Func(("Resumed: HostCpuId=%u\n", RTMpCpuId()));
8850
8851 /* Initialize the bare minimum state required for HM. This takes care of
8852 initializing VT-x if necessary (onlined CPUs, local init etc.) */
8853 int rc = hmR0EnterCpu(pVCpu);
8854 AssertRC(rc);
8855 Assert( (pVCpu->hm.s.fCtxChanged & (HM_CHANGED_HOST_CONTEXT | HM_CHANGED_VMX_HOST_GUEST_SHARED_STATE))
8856 == (HM_CHANGED_HOST_CONTEXT | HM_CHANGED_VMX_HOST_GUEST_SHARED_STATE));
8857
8858 /* Load the active VMCS as the current one. */
8859 PVMXVMCSINFO pVmcsInfo = hmGetVmxActiveVmcsInfo(pVCpu);
8860 rc = hmR0VmxLoadVmcs(pVmcsInfo);
8861 AssertRC(rc);
8862 Log4Func(("Resumed: Loaded Vmcs. HostCpuId=%u\n", RTMpCpuId()));
8863 pVCpu->hm.s.fLeaveDone = false;
8864
8865 /* Do the EMT scheduled L1D flush if needed. */
8866 if (pVCpu->CTX_SUFF(pVM)->hm.s.fL1dFlushOnSched)
8867 ASMWrMsr(MSR_IA32_FLUSH_CMD, MSR_IA32_FLUSH_CMD_F_L1D);
8868
8869 /* Restore longjmp state. */
8870 VMMRZCallRing3Enable(pVCpu);
8871 break;
8872 }
8873
8874 default:
8875 break;
8876 }
8877}
8878
8879
8880/**
8881 * Exports the host state into the VMCS host-state area.
8882 * Sets up the VM-exit MSR-load area.
8883 *
8884 * The CPU state will be loaded from these fields on every successful VM-exit.
8885 *
8886 * @returns VBox status code.
8887 * @param pVCpu The cross context virtual CPU structure.
8888 *
8889 * @remarks No-long-jump zone!!!
8890 */
8891static int hmR0VmxExportHostState(PVMCPUCC pVCpu)
8892{
8893 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
8894
8895 int rc = VINF_SUCCESS;
8896 if (pVCpu->hm.s.fCtxChanged & HM_CHANGED_HOST_CONTEXT)
8897 {
8898 hmR0VmxExportHostControlRegs();
8899
8900 rc = hmR0VmxExportHostSegmentRegs(pVCpu);
8901 AssertLogRelMsgRCReturn(rc, ("rc=%Rrc\n", rc), rc);
8902
8903 hmR0VmxExportHostMsrs(pVCpu);
8904
8905 pVCpu->hm.s.fCtxChanged &= ~HM_CHANGED_HOST_CONTEXT;
8906 }
8907 return rc;
8908}
8909
8910
8911/**
8912 * Saves the host state in the VMCS host-state.
8913 *
8914 * @returns VBox status code.
8915 * @param pVCpu The cross context virtual CPU structure.
8916 *
8917 * @remarks No-long-jump zone!!!
8918 */
8919VMMR0DECL(int) VMXR0ExportHostState(PVMCPUCC pVCpu)
8920{
8921 AssertPtr(pVCpu);
8922 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
8923
8924 /*
8925 * Export the host state here while entering HM context.
8926 * When thread-context hooks are used, we might get preempted and have to re-save the host
8927 * state but most of the time we won't be, so do it here before we disable interrupts.
8928 */
8929 return hmR0VmxExportHostState(pVCpu);
8930}
8931
8932
8933/**
8934 * Exports the guest state into the VMCS guest-state area.
8935 *
8936 * The will typically be done before VM-entry when the guest-CPU state and the
8937 * VMCS state may potentially be out of sync.
8938 *
8939 * Sets up the VM-entry MSR-load and VM-exit MSR-store areas. Sets up the
8940 * VM-entry controls.
8941 * Sets up the appropriate VMX non-root function to execute guest code based on
8942 * the guest CPU mode.
8943 *
8944 * @returns VBox strict status code.
8945 * @retval VINF_EM_RESCHEDULE_REM if we try to emulate non-paged guest code
8946 * without unrestricted guest execution and the VMMDev is not presently
8947 * mapped (e.g. EFI32).
8948 *
8949 * @param pVCpu The cross context virtual CPU structure.
8950 * @param pVmxTransient The VMX-transient structure.
8951 *
8952 * @remarks No-long-jump zone!!!
8953 */
8954static VBOXSTRICTRC hmR0VmxExportGuestState(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
8955{
8956 AssertPtr(pVCpu);
8957 HMVMX_ASSERT_PREEMPT_SAFE(pVCpu);
8958 LogFlowFunc(("pVCpu=%p\n", pVCpu));
8959
8960 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatExportGuestState, x);
8961
8962 /*
8963 * Determine real-on-v86 mode.
8964 * Used when the guest is in real-mode and unrestricted guest execution is not used.
8965 */
8966 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
8967 if ( pVCpu->CTX_SUFF(pVM)->hm.s.vmx.fUnrestrictedGuest
8968 || !CPUMIsGuestInRealModeEx(&pVCpu->cpum.GstCtx))
8969 pVmcsInfo->RealMode. fRealOnV86Active = false;
8970 else
8971 {
8972 Assert(!pVmxTransient->fIsNestedGuest);
8973 pVmcsInfo->RealMode.fRealOnV86Active = true;
8974 }
8975
8976 /*
8977 * Any ordering dependency among the sub-functions below must be explicitly stated using comments.
8978 * Ideally, assert that the cross-dependent bits are up-to-date at the point of using it.
8979 */
8980 /** @todo r=ramshankar: Move hmR0VmxSelectVMRunHandler inside
8981 * hmR0VmxExportGuestEntryExitCtls and do it conditionally. There shouldn't
8982 * be a need to evaluate this everytime since I'm pretty sure we intercept
8983 * all guest paging mode changes. */
8984 int rc = hmR0VmxSelectVMRunHandler(pVCpu, pVmxTransient);
8985 AssertLogRelMsgRCReturn(rc, ("rc=%Rrc\n", rc), rc);
8986
8987 rc = hmR0VmxExportGuestEntryExitCtls(pVCpu, pVmxTransient);
8988 AssertLogRelMsgRCReturn(rc, ("rc=%Rrc\n", rc), rc);
8989
8990 rc = hmR0VmxExportGuestCR0(pVCpu, pVmxTransient);
8991 AssertLogRelMsgRCReturn(rc, ("rc=%Rrc\n", rc), rc);
8992
8993 VBOXSTRICTRC rcStrict = hmR0VmxExportGuestCR3AndCR4(pVCpu, pVmxTransient);
8994 if (rcStrict == VINF_SUCCESS)
8995 { /* likely */ }
8996 else
8997 {
8998 Assert(rcStrict == VINF_EM_RESCHEDULE_REM || RT_FAILURE_NP(rcStrict));
8999 return rcStrict;
9000 }
9001
9002 rc = hmR0VmxExportGuestSegRegsXdtr(pVCpu, pVmxTransient);
9003 AssertLogRelMsgRCReturn(rc, ("rc=%Rrc\n", rc), rc);
9004
9005 rc = hmR0VmxExportGuestMsrs(pVCpu, pVmxTransient);
9006 AssertLogRelMsgRCReturn(rc, ("rc=%Rrc\n", rc), rc);
9007
9008 rc = hmR0VmxExportGuestApicTpr(pVCpu, pVmxTransient);
9009 AssertLogRelMsgRCReturn(rc, ("rc=%Rrc\n", rc), rc);
9010
9011 rc = hmR0VmxExportGuestXcptIntercepts(pVCpu, pVmxTransient);
9012 AssertLogRelMsgRCReturn(rc, ("rc=%Rrc\n", rc), rc);
9013
9014 rc = hmR0VmxExportGuestRip(pVCpu);
9015 rc |= hmR0VmxExportGuestRsp(pVCpu);
9016 rc |= hmR0VmxExportGuestRflags(pVCpu, pVmxTransient);
9017 AssertLogRelMsgRCReturn(rc, ("rc=%Rrc\n", rc), rc);
9018
9019 rc = hmR0VmxExportGuestHwvirtState(pVCpu, pVmxTransient);
9020 AssertLogRelMsgRCReturn(rc, ("rc=%Rrc\n", rc), rc);
9021
9022 /* Clear any bits that may be set but exported unconditionally or unused/reserved bits. */
9023 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~( (HM_CHANGED_GUEST_GPRS_MASK & ~HM_CHANGED_GUEST_RSP)
9024 | HM_CHANGED_GUEST_CR2
9025 | (HM_CHANGED_GUEST_DR_MASK & ~HM_CHANGED_GUEST_DR7)
9026 | HM_CHANGED_GUEST_X87
9027 | HM_CHANGED_GUEST_SSE_AVX
9028 | HM_CHANGED_GUEST_OTHER_XSAVE
9029 | HM_CHANGED_GUEST_XCRx
9030 | HM_CHANGED_GUEST_KERNEL_GS_BASE /* Part of lazy or auto load-store MSRs. */
9031 | HM_CHANGED_GUEST_SYSCALL_MSRS /* Part of lazy or auto load-store MSRs. */
9032 | HM_CHANGED_GUEST_TSC_AUX
9033 | HM_CHANGED_GUEST_OTHER_MSRS
9034 | (HM_CHANGED_KEEPER_STATE_MASK & ~HM_CHANGED_VMX_MASK)));
9035
9036 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExportGuestState, x);
9037 return rc;
9038}
9039
9040
9041/**
9042 * Exports the state shared between the host and guest into the VMCS.
9043 *
9044 * @param pVCpu The cross context virtual CPU structure.
9045 * @param pVmxTransient The VMX-transient structure.
9046 *
9047 * @remarks No-long-jump zone!!!
9048 */
9049static void hmR0VmxExportSharedState(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
9050{
9051 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
9052 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
9053
9054 if (pVCpu->hm.s.fCtxChanged & HM_CHANGED_GUEST_DR_MASK)
9055 {
9056 int rc = hmR0VmxExportSharedDebugState(pVCpu, pVmxTransient);
9057 AssertRC(rc);
9058 pVCpu->hm.s.fCtxChanged &= ~HM_CHANGED_GUEST_DR_MASK;
9059
9060 /* Loading shared debug bits might have changed eflags.TF bit for debugging purposes. */
9061 if (pVCpu->hm.s.fCtxChanged & HM_CHANGED_GUEST_RFLAGS)
9062 {
9063 rc = hmR0VmxExportGuestRflags(pVCpu, pVmxTransient);
9064 AssertRC(rc);
9065 }
9066 }
9067
9068 if (pVCpu->hm.s.fCtxChanged & HM_CHANGED_VMX_GUEST_LAZY_MSRS)
9069 {
9070 hmR0VmxLazyLoadGuestMsrs(pVCpu);
9071 pVCpu->hm.s.fCtxChanged &= ~HM_CHANGED_VMX_GUEST_LAZY_MSRS;
9072 }
9073
9074 AssertMsg(!(pVCpu->hm.s.fCtxChanged & HM_CHANGED_VMX_HOST_GUEST_SHARED_STATE),
9075 ("fCtxChanged=%#RX64\n", pVCpu->hm.s.fCtxChanged));
9076}
9077
9078
9079/**
9080 * Worker for loading the guest-state bits in the inner VT-x execution loop.
9081 *
9082 * @returns Strict VBox status code (i.e. informational status codes too).
9083 * @retval VINF_EM_RESCHEDULE_REM if we try to emulate non-paged guest code
9084 * without unrestricted guest execution and the VMMDev is not presently
9085 * mapped (e.g. EFI32).
9086 *
9087 * @param pVCpu The cross context virtual CPU structure.
9088 * @param pVmxTransient The VMX-transient structure.
9089 *
9090 * @remarks No-long-jump zone!!!
9091 */
9092static VBOXSTRICTRC hmR0VmxExportGuestStateOptimal(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
9093{
9094 HMVMX_ASSERT_PREEMPT_SAFE(pVCpu);
9095 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
9096 Assert(VMMR0IsLogFlushDisabled(pVCpu));
9097
9098#ifdef HMVMX_ALWAYS_SYNC_FULL_GUEST_STATE
9099 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_ALL_GUEST);
9100#endif
9101
9102 /*
9103 * For many exits it's only RIP that changes and hence try to export it first
9104 * without going through a lot of change flag checks.
9105 */
9106 VBOXSTRICTRC rcStrict;
9107 uint64_t fCtxChanged = ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged);
9108 RT_UNTRUSTED_NONVOLATILE_COPY_FENCE();
9109 if ((fCtxChanged & (HM_CHANGED_ALL_GUEST & ~HM_CHANGED_VMX_HOST_GUEST_SHARED_STATE)) == HM_CHANGED_GUEST_RIP)
9110 {
9111 rcStrict = hmR0VmxExportGuestRip(pVCpu);
9112 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
9113 { /* likely */}
9114 else
9115 AssertMsgFailedReturn(("Failed to export guest RIP! rc=%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)), rcStrict);
9116 STAM_COUNTER_INC(&pVCpu->hm.s.StatExportMinimal);
9117 }
9118 else if (fCtxChanged & (HM_CHANGED_ALL_GUEST & ~HM_CHANGED_VMX_HOST_GUEST_SHARED_STATE))
9119 {
9120 rcStrict = hmR0VmxExportGuestState(pVCpu, pVmxTransient);
9121 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
9122 { /* likely */}
9123 else
9124 {
9125 AssertMsg(rcStrict == VINF_EM_RESCHEDULE_REM, ("Failed to export guest state! rc=%Rrc\n",
9126 VBOXSTRICTRC_VAL(rcStrict)));
9127 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
9128 return rcStrict;
9129 }
9130 STAM_COUNTER_INC(&pVCpu->hm.s.StatExportFull);
9131 }
9132 else
9133 rcStrict = VINF_SUCCESS;
9134
9135#ifdef VBOX_STRICT
9136 /* All the guest state bits should be loaded except maybe the host context and/or the shared host/guest bits. */
9137 fCtxChanged = ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged);
9138 RT_UNTRUSTED_NONVOLATILE_COPY_FENCE();
9139 AssertMsg(!(fCtxChanged & (HM_CHANGED_ALL_GUEST & ~HM_CHANGED_VMX_HOST_GUEST_SHARED_STATE)),
9140 ("fCtxChanged=%#RX64\n", fCtxChanged));
9141#endif
9142 return rcStrict;
9143}
9144
9145
9146/**
9147 * Tries to determine what part of the guest-state VT-x has deemed as invalid
9148 * and update error record fields accordingly.
9149 *
9150 * @returns VMX_IGS_* error codes.
9151 * @retval VMX_IGS_REASON_NOT_FOUND if this function could not find anything
9152 * wrong with the guest state.
9153 *
9154 * @param pVCpu The cross context virtual CPU structure.
9155 * @param pVmcsInfo The VMCS info. object.
9156 *
9157 * @remarks This function assumes our cache of the VMCS controls
9158 * are valid, i.e. hmR0VmxCheckVmcsCtls() succeeded.
9159 */
9160static uint32_t hmR0VmxCheckGuestState(PVMCPUCC pVCpu, PCVMXVMCSINFO pVmcsInfo)
9161{
9162#define HMVMX_ERROR_BREAK(err) { uError = (err); break; }
9163#define HMVMX_CHECK_BREAK(expr, err) do { \
9164 if (!(expr)) { uError = (err); break; } \
9165 } while (0)
9166
9167 int rc;
9168 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
9169 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
9170 uint32_t uError = VMX_IGS_ERROR;
9171 uint32_t u32Val;
9172 bool const fUnrestrictedGuest = pVM->hm.s.vmx.fUnrestrictedGuest;
9173
9174 do
9175 {
9176 /*
9177 * CR0.
9178 */
9179 /** @todo Why do we need to OR and AND the fixed-0 and fixed-1 bits below? */
9180 uint64_t fSetCr0 = (pVM->hm.s.vmx.Msrs.u64Cr0Fixed0 & pVM->hm.s.vmx.Msrs.u64Cr0Fixed1);
9181 uint64_t const fZapCr0 = (pVM->hm.s.vmx.Msrs.u64Cr0Fixed0 | pVM->hm.s.vmx.Msrs.u64Cr0Fixed1);
9182 /* Exceptions for unrestricted guest execution for fixed CR0 bits (PE, PG).
9183 See Intel spec. 26.3.1 "Checks on Guest Control Registers, Debug Registers and MSRs." */
9184 if (fUnrestrictedGuest)
9185 fSetCr0 &= ~(uint64_t)(X86_CR0_PE | X86_CR0_PG);
9186
9187 uint64_t u64GuestCr0;
9188 rc = VMXReadVmcsNw(VMX_VMCS_GUEST_CR0, &u64GuestCr0);
9189 AssertRC(rc);
9190 HMVMX_CHECK_BREAK((u64GuestCr0 & fSetCr0) == fSetCr0, VMX_IGS_CR0_FIXED1);
9191 HMVMX_CHECK_BREAK(!(u64GuestCr0 & ~fZapCr0), VMX_IGS_CR0_FIXED0);
9192 if ( !fUnrestrictedGuest
9193 && (u64GuestCr0 & X86_CR0_PG)
9194 && !(u64GuestCr0 & X86_CR0_PE))
9195 {
9196 HMVMX_ERROR_BREAK(VMX_IGS_CR0_PG_PE_COMBO);
9197 }
9198
9199 /*
9200 * CR4.
9201 */
9202 /** @todo Why do we need to OR and AND the fixed-0 and fixed-1 bits below? */
9203 uint64_t const fSetCr4 = (pVM->hm.s.vmx.Msrs.u64Cr4Fixed0 & pVM->hm.s.vmx.Msrs.u64Cr4Fixed1);
9204 uint64_t const fZapCr4 = (pVM->hm.s.vmx.Msrs.u64Cr4Fixed0 | pVM->hm.s.vmx.Msrs.u64Cr4Fixed1);
9205
9206 uint64_t u64GuestCr4;
9207 rc = VMXReadVmcsNw(VMX_VMCS_GUEST_CR4, &u64GuestCr4);
9208 AssertRC(rc);
9209 HMVMX_CHECK_BREAK((u64GuestCr4 & fSetCr4) == fSetCr4, VMX_IGS_CR4_FIXED1);
9210 HMVMX_CHECK_BREAK(!(u64GuestCr4 & ~fZapCr4), VMX_IGS_CR4_FIXED0);
9211
9212 /*
9213 * IA32_DEBUGCTL MSR.
9214 */
9215 uint64_t u64Val;
9216 rc = VMXReadVmcs64(VMX_VMCS64_GUEST_DEBUGCTL_FULL, &u64Val);
9217 AssertRC(rc);
9218 if ( (pVmcsInfo->u32EntryCtls & VMX_ENTRY_CTLS_LOAD_DEBUG)
9219 && (u64Val & 0xfffffe3c)) /* Bits 31:9, bits 5:2 MBZ. */
9220 {
9221 HMVMX_ERROR_BREAK(VMX_IGS_DEBUGCTL_MSR_RESERVED);
9222 }
9223 uint64_t u64DebugCtlMsr = u64Val;
9224
9225#ifdef VBOX_STRICT
9226 rc = VMXReadVmcs32(VMX_VMCS32_CTRL_ENTRY, &u32Val);
9227 AssertRC(rc);
9228 Assert(u32Val == pVmcsInfo->u32EntryCtls);
9229#endif
9230 bool const fLongModeGuest = RT_BOOL(pVmcsInfo->u32EntryCtls & VMX_ENTRY_CTLS_IA32E_MODE_GUEST);
9231
9232 /*
9233 * RIP and RFLAGS.
9234 */
9235 rc = VMXReadVmcsNw(VMX_VMCS_GUEST_RIP, &u64Val);
9236 AssertRC(rc);
9237 /* pCtx->rip can be different than the one in the VMCS (e.g. run guest code and VM-exits that don't update it). */
9238 if ( !fLongModeGuest
9239 || !pCtx->cs.Attr.n.u1Long)
9240 {
9241 HMVMX_CHECK_BREAK(!(u64Val & UINT64_C(0xffffffff00000000)), VMX_IGS_LONGMODE_RIP_INVALID);
9242 }
9243 /** @todo If the processor supports N < 64 linear-address bits, bits 63:N
9244 * must be identical if the "IA-32e mode guest" VM-entry
9245 * control is 1 and CS.L is 1. No check applies if the
9246 * CPU supports 64 linear-address bits. */
9247
9248 /* Flags in pCtx can be different (real-on-v86 for instance). We are only concerned about the VMCS contents here. */
9249 rc = VMXReadVmcsNw(VMX_VMCS_GUEST_RFLAGS, &u64Val);
9250 AssertRC(rc);
9251 HMVMX_CHECK_BREAK(!(u64Val & UINT64_C(0xffffffffffc08028)), /* Bit 63:22, Bit 15, 5, 3 MBZ. */
9252 VMX_IGS_RFLAGS_RESERVED);
9253 HMVMX_CHECK_BREAK((u64Val & X86_EFL_RA1_MASK), VMX_IGS_RFLAGS_RESERVED1); /* Bit 1 MB1. */
9254 uint32_t const u32Eflags = u64Val;
9255
9256 if ( fLongModeGuest
9257 || ( fUnrestrictedGuest
9258 && !(u64GuestCr0 & X86_CR0_PE)))
9259 {
9260 HMVMX_CHECK_BREAK(!(u32Eflags & X86_EFL_VM), VMX_IGS_RFLAGS_VM_INVALID);
9261 }
9262
9263 uint32_t u32EntryInfo;
9264 rc = VMXReadVmcs32(VMX_VMCS32_CTRL_ENTRY_INTERRUPTION_INFO, &u32EntryInfo);
9265 AssertRC(rc);
9266 if (VMX_ENTRY_INT_INFO_IS_EXT_INT(u32EntryInfo))
9267 HMVMX_CHECK_BREAK(u32Eflags & X86_EFL_IF, VMX_IGS_RFLAGS_IF_INVALID);
9268
9269 /*
9270 * 64-bit checks.
9271 */
9272 if (fLongModeGuest)
9273 {
9274 HMVMX_CHECK_BREAK(u64GuestCr0 & X86_CR0_PG, VMX_IGS_CR0_PG_LONGMODE);
9275 HMVMX_CHECK_BREAK(u64GuestCr4 & X86_CR4_PAE, VMX_IGS_CR4_PAE_LONGMODE);
9276 }
9277
9278 if ( !fLongModeGuest
9279 && (u64GuestCr4 & X86_CR4_PCIDE))
9280 {
9281 HMVMX_ERROR_BREAK(VMX_IGS_CR4_PCIDE);
9282 }
9283
9284 /** @todo CR3 field must be such that bits 63:52 and bits in the range
9285 * 51:32 beyond the processor's physical-address width are 0. */
9286
9287 if ( (pVmcsInfo->u32EntryCtls & VMX_ENTRY_CTLS_LOAD_DEBUG)
9288 && (pCtx->dr[7] & X86_DR7_MBZ_MASK))
9289 {
9290 HMVMX_ERROR_BREAK(VMX_IGS_DR7_RESERVED);
9291 }
9292
9293 rc = VMXReadVmcsNw(VMX_VMCS_HOST_SYSENTER_ESP, &u64Val);
9294 AssertRC(rc);
9295 HMVMX_CHECK_BREAK(X86_IS_CANONICAL(u64Val), VMX_IGS_SYSENTER_ESP_NOT_CANONICAL);
9296
9297 rc = VMXReadVmcsNw(VMX_VMCS_HOST_SYSENTER_EIP, &u64Val);
9298 AssertRC(rc);
9299 HMVMX_CHECK_BREAK(X86_IS_CANONICAL(u64Val), VMX_IGS_SYSENTER_EIP_NOT_CANONICAL);
9300
9301 /*
9302 * PERF_GLOBAL MSR.
9303 */
9304 if (pVmcsInfo->u32EntryCtls & VMX_ENTRY_CTLS_LOAD_PERF_MSR)
9305 {
9306 rc = VMXReadVmcs64(VMX_VMCS64_GUEST_PERF_GLOBAL_CTRL_FULL, &u64Val);
9307 AssertRC(rc);
9308 HMVMX_CHECK_BREAK(!(u64Val & UINT64_C(0xfffffff8fffffffc)),
9309 VMX_IGS_PERF_GLOBAL_MSR_RESERVED); /* Bits 63:35, bits 31:2 MBZ. */
9310 }
9311
9312 /*
9313 * PAT MSR.
9314 */
9315 if (pVmcsInfo->u32EntryCtls & VMX_ENTRY_CTLS_LOAD_PAT_MSR)
9316 {
9317 rc = VMXReadVmcs64(VMX_VMCS64_GUEST_PAT_FULL, &u64Val);
9318 AssertRC(rc);
9319 HMVMX_CHECK_BREAK(!(u64Val & UINT64_C(0x707070707070707)), VMX_IGS_PAT_MSR_RESERVED);
9320 for (unsigned i = 0; i < 8; i++)
9321 {
9322 uint8_t u8Val = (u64Val & 0xff);
9323 if ( u8Val != 0 /* UC */
9324 && u8Val != 1 /* WC */
9325 && u8Val != 4 /* WT */
9326 && u8Val != 5 /* WP */
9327 && u8Val != 6 /* WB */
9328 && u8Val != 7 /* UC- */)
9329 {
9330 HMVMX_ERROR_BREAK(VMX_IGS_PAT_MSR_INVALID);
9331 }
9332 u64Val >>= 8;
9333 }
9334 }
9335
9336 /*
9337 * EFER MSR.
9338 */
9339 if (pVmcsInfo->u32EntryCtls & VMX_ENTRY_CTLS_LOAD_EFER_MSR)
9340 {
9341 Assert(pVM->hm.s.vmx.fSupportsVmcsEfer);
9342 rc = VMXReadVmcs64(VMX_VMCS64_GUEST_EFER_FULL, &u64Val);
9343 AssertRC(rc);
9344 HMVMX_CHECK_BREAK(!(u64Val & UINT64_C(0xfffffffffffff2fe)),
9345 VMX_IGS_EFER_MSR_RESERVED); /* Bits 63:12, bit 9, bits 7:1 MBZ. */
9346 HMVMX_CHECK_BREAK(RT_BOOL(u64Val & MSR_K6_EFER_LMA) == RT_BOOL( pVmcsInfo->u32EntryCtls
9347 & VMX_ENTRY_CTLS_IA32E_MODE_GUEST),
9348 VMX_IGS_EFER_LMA_GUEST_MODE_MISMATCH);
9349 /** @todo r=ramshankar: Unrestricted check here is probably wrong, see
9350 * iemVmxVmentryCheckGuestState(). */
9351 HMVMX_CHECK_BREAK( fUnrestrictedGuest
9352 || !(u64GuestCr0 & X86_CR0_PG)
9353 || RT_BOOL(u64Val & MSR_K6_EFER_LMA) == RT_BOOL(u64Val & MSR_K6_EFER_LME),
9354 VMX_IGS_EFER_LMA_LME_MISMATCH);
9355 }
9356
9357 /*
9358 * Segment registers.
9359 */
9360 HMVMX_CHECK_BREAK( (pCtx->ldtr.Attr.u & X86DESCATTR_UNUSABLE)
9361 || !(pCtx->ldtr.Sel & X86_SEL_LDT), VMX_IGS_LDTR_TI_INVALID);
9362 if (!(u32Eflags & X86_EFL_VM))
9363 {
9364 /* CS */
9365 HMVMX_CHECK_BREAK(pCtx->cs.Attr.n.u1Present, VMX_IGS_CS_ATTR_P_INVALID);
9366 HMVMX_CHECK_BREAK(!(pCtx->cs.Attr.u & 0xf00), VMX_IGS_CS_ATTR_RESERVED);
9367 HMVMX_CHECK_BREAK(!(pCtx->cs.Attr.u & 0xfffe0000), VMX_IGS_CS_ATTR_RESERVED);
9368 HMVMX_CHECK_BREAK( (pCtx->cs.u32Limit & 0xfff) == 0xfff
9369 || !(pCtx->cs.Attr.n.u1Granularity), VMX_IGS_CS_ATTR_G_INVALID);
9370 HMVMX_CHECK_BREAK( !(pCtx->cs.u32Limit & 0xfff00000)
9371 || (pCtx->cs.Attr.n.u1Granularity), VMX_IGS_CS_ATTR_G_INVALID);
9372 /* CS cannot be loaded with NULL in protected mode. */
9373 HMVMX_CHECK_BREAK(pCtx->cs.Attr.u && !(pCtx->cs.Attr.u & X86DESCATTR_UNUSABLE), VMX_IGS_CS_ATTR_UNUSABLE);
9374 HMVMX_CHECK_BREAK(pCtx->cs.Attr.n.u1DescType, VMX_IGS_CS_ATTR_S_INVALID);
9375 if (pCtx->cs.Attr.n.u4Type == 9 || pCtx->cs.Attr.n.u4Type == 11)
9376 HMVMX_CHECK_BREAK(pCtx->cs.Attr.n.u2Dpl == pCtx->ss.Attr.n.u2Dpl, VMX_IGS_CS_SS_ATTR_DPL_UNEQUAL);
9377 else if (pCtx->cs.Attr.n.u4Type == 13 || pCtx->cs.Attr.n.u4Type == 15)
9378 HMVMX_CHECK_BREAK(pCtx->cs.Attr.n.u2Dpl <= pCtx->ss.Attr.n.u2Dpl, VMX_IGS_CS_SS_ATTR_DPL_MISMATCH);
9379 else if (pVM->hm.s.vmx.fUnrestrictedGuest && pCtx->cs.Attr.n.u4Type == 3)
9380 HMVMX_CHECK_BREAK(pCtx->cs.Attr.n.u2Dpl == 0, VMX_IGS_CS_ATTR_DPL_INVALID);
9381 else
9382 HMVMX_ERROR_BREAK(VMX_IGS_CS_ATTR_TYPE_INVALID);
9383
9384 /* SS */
9385 HMVMX_CHECK_BREAK( pVM->hm.s.vmx.fUnrestrictedGuest
9386 || (pCtx->ss.Sel & X86_SEL_RPL) == (pCtx->cs.Sel & X86_SEL_RPL), VMX_IGS_SS_CS_RPL_UNEQUAL);
9387 HMVMX_CHECK_BREAK(pCtx->ss.Attr.n.u2Dpl == (pCtx->ss.Sel & X86_SEL_RPL), VMX_IGS_SS_ATTR_DPL_RPL_UNEQUAL);
9388 if ( !(pCtx->cr0 & X86_CR0_PE)
9389 || pCtx->cs.Attr.n.u4Type == 3)
9390 {
9391 HMVMX_CHECK_BREAK(!pCtx->ss.Attr.n.u2Dpl, VMX_IGS_SS_ATTR_DPL_INVALID);
9392 }
9393 if (!(pCtx->ss.Attr.u & X86DESCATTR_UNUSABLE))
9394 {
9395 HMVMX_CHECK_BREAK(pCtx->ss.Attr.n.u4Type == 3 || pCtx->ss.Attr.n.u4Type == 7, VMX_IGS_SS_ATTR_TYPE_INVALID);
9396 HMVMX_CHECK_BREAK(pCtx->ss.Attr.n.u1Present, VMX_IGS_SS_ATTR_P_INVALID);
9397 HMVMX_CHECK_BREAK(!(pCtx->ss.Attr.u & 0xf00), VMX_IGS_SS_ATTR_RESERVED);
9398 HMVMX_CHECK_BREAK(!(pCtx->ss.Attr.u & 0xfffe0000), VMX_IGS_SS_ATTR_RESERVED);
9399 HMVMX_CHECK_BREAK( (pCtx->ss.u32Limit & 0xfff) == 0xfff
9400 || !(pCtx->ss.Attr.n.u1Granularity), VMX_IGS_SS_ATTR_G_INVALID);
9401 HMVMX_CHECK_BREAK( !(pCtx->ss.u32Limit & 0xfff00000)
9402 || (pCtx->ss.Attr.n.u1Granularity), VMX_IGS_SS_ATTR_G_INVALID);
9403 }
9404
9405 /* DS, ES, FS, GS - only check for usable selectors, see hmR0VmxExportGuestSReg(). */
9406 if (!(pCtx->ds.Attr.u & X86DESCATTR_UNUSABLE))
9407 {
9408 HMVMX_CHECK_BREAK(pCtx->ds.Attr.n.u4Type & X86_SEL_TYPE_ACCESSED, VMX_IGS_DS_ATTR_A_INVALID);
9409 HMVMX_CHECK_BREAK(pCtx->ds.Attr.n.u1Present, VMX_IGS_DS_ATTR_P_INVALID);
9410 HMVMX_CHECK_BREAK( pVM->hm.s.vmx.fUnrestrictedGuest
9411 || pCtx->ds.Attr.n.u4Type > 11
9412 || pCtx->ds.Attr.n.u2Dpl >= (pCtx->ds.Sel & X86_SEL_RPL), VMX_IGS_DS_ATTR_DPL_RPL_UNEQUAL);
9413 HMVMX_CHECK_BREAK(!(pCtx->ds.Attr.u & 0xf00), VMX_IGS_DS_ATTR_RESERVED);
9414 HMVMX_CHECK_BREAK(!(pCtx->ds.Attr.u & 0xfffe0000), VMX_IGS_DS_ATTR_RESERVED);
9415 HMVMX_CHECK_BREAK( (pCtx->ds.u32Limit & 0xfff) == 0xfff
9416 || !(pCtx->ds.Attr.n.u1Granularity), VMX_IGS_DS_ATTR_G_INVALID);
9417 HMVMX_CHECK_BREAK( !(pCtx->ds.u32Limit & 0xfff00000)
9418 || (pCtx->ds.Attr.n.u1Granularity), VMX_IGS_DS_ATTR_G_INVALID);
9419 HMVMX_CHECK_BREAK( !(pCtx->ds.Attr.n.u4Type & X86_SEL_TYPE_CODE)
9420 || (pCtx->ds.Attr.n.u4Type & X86_SEL_TYPE_READ), VMX_IGS_DS_ATTR_TYPE_INVALID);
9421 }
9422 if (!(pCtx->es.Attr.u & X86DESCATTR_UNUSABLE))
9423 {
9424 HMVMX_CHECK_BREAK(pCtx->es.Attr.n.u4Type & X86_SEL_TYPE_ACCESSED, VMX_IGS_ES_ATTR_A_INVALID);
9425 HMVMX_CHECK_BREAK(pCtx->es.Attr.n.u1Present, VMX_IGS_ES_ATTR_P_INVALID);
9426 HMVMX_CHECK_BREAK( pVM->hm.s.vmx.fUnrestrictedGuest
9427 || pCtx->es.Attr.n.u4Type > 11
9428 || pCtx->es.Attr.n.u2Dpl >= (pCtx->es.Sel & X86_SEL_RPL), VMX_IGS_DS_ATTR_DPL_RPL_UNEQUAL);
9429 HMVMX_CHECK_BREAK(!(pCtx->es.Attr.u & 0xf00), VMX_IGS_ES_ATTR_RESERVED);
9430 HMVMX_CHECK_BREAK(!(pCtx->es.Attr.u & 0xfffe0000), VMX_IGS_ES_ATTR_RESERVED);
9431 HMVMX_CHECK_BREAK( (pCtx->es.u32Limit & 0xfff) == 0xfff
9432 || !(pCtx->es.Attr.n.u1Granularity), VMX_IGS_ES_ATTR_G_INVALID);
9433 HMVMX_CHECK_BREAK( !(pCtx->es.u32Limit & 0xfff00000)
9434 || (pCtx->es.Attr.n.u1Granularity), VMX_IGS_ES_ATTR_G_INVALID);
9435 HMVMX_CHECK_BREAK( !(pCtx->es.Attr.n.u4Type & X86_SEL_TYPE_CODE)
9436 || (pCtx->es.Attr.n.u4Type & X86_SEL_TYPE_READ), VMX_IGS_ES_ATTR_TYPE_INVALID);
9437 }
9438 if (!(pCtx->fs.Attr.u & X86DESCATTR_UNUSABLE))
9439 {
9440 HMVMX_CHECK_BREAK(pCtx->fs.Attr.n.u4Type & X86_SEL_TYPE_ACCESSED, VMX_IGS_FS_ATTR_A_INVALID);
9441 HMVMX_CHECK_BREAK(pCtx->fs.Attr.n.u1Present, VMX_IGS_FS_ATTR_P_INVALID);
9442 HMVMX_CHECK_BREAK( pVM->hm.s.vmx.fUnrestrictedGuest
9443 || pCtx->fs.Attr.n.u4Type > 11
9444 || pCtx->fs.Attr.n.u2Dpl >= (pCtx->fs.Sel & X86_SEL_RPL), VMX_IGS_FS_ATTR_DPL_RPL_UNEQUAL);
9445 HMVMX_CHECK_BREAK(!(pCtx->fs.Attr.u & 0xf00), VMX_IGS_FS_ATTR_RESERVED);
9446 HMVMX_CHECK_BREAK(!(pCtx->fs.Attr.u & 0xfffe0000), VMX_IGS_FS_ATTR_RESERVED);
9447 HMVMX_CHECK_BREAK( (pCtx->fs.u32Limit & 0xfff) == 0xfff
9448 || !(pCtx->fs.Attr.n.u1Granularity), VMX_IGS_FS_ATTR_G_INVALID);
9449 HMVMX_CHECK_BREAK( !(pCtx->fs.u32Limit & 0xfff00000)
9450 || (pCtx->fs.Attr.n.u1Granularity), VMX_IGS_FS_ATTR_G_INVALID);
9451 HMVMX_CHECK_BREAK( !(pCtx->fs.Attr.n.u4Type & X86_SEL_TYPE_CODE)
9452 || (pCtx->fs.Attr.n.u4Type & X86_SEL_TYPE_READ), VMX_IGS_FS_ATTR_TYPE_INVALID);
9453 }
9454 if (!(pCtx->gs.Attr.u & X86DESCATTR_UNUSABLE))
9455 {
9456 HMVMX_CHECK_BREAK(pCtx->gs.Attr.n.u4Type & X86_SEL_TYPE_ACCESSED, VMX_IGS_GS_ATTR_A_INVALID);
9457 HMVMX_CHECK_BREAK(pCtx->gs.Attr.n.u1Present, VMX_IGS_GS_ATTR_P_INVALID);
9458 HMVMX_CHECK_BREAK( pVM->hm.s.vmx.fUnrestrictedGuest
9459 || pCtx->gs.Attr.n.u4Type > 11
9460 || pCtx->gs.Attr.n.u2Dpl >= (pCtx->gs.Sel & X86_SEL_RPL), VMX_IGS_GS_ATTR_DPL_RPL_UNEQUAL);
9461 HMVMX_CHECK_BREAK(!(pCtx->gs.Attr.u & 0xf00), VMX_IGS_GS_ATTR_RESERVED);
9462 HMVMX_CHECK_BREAK(!(pCtx->gs.Attr.u & 0xfffe0000), VMX_IGS_GS_ATTR_RESERVED);
9463 HMVMX_CHECK_BREAK( (pCtx->gs.u32Limit & 0xfff) == 0xfff
9464 || !(pCtx->gs.Attr.n.u1Granularity), VMX_IGS_GS_ATTR_G_INVALID);
9465 HMVMX_CHECK_BREAK( !(pCtx->gs.u32Limit & 0xfff00000)
9466 || (pCtx->gs.Attr.n.u1Granularity), VMX_IGS_GS_ATTR_G_INVALID);
9467 HMVMX_CHECK_BREAK( !(pCtx->gs.Attr.n.u4Type & X86_SEL_TYPE_CODE)
9468 || (pCtx->gs.Attr.n.u4Type & X86_SEL_TYPE_READ), VMX_IGS_GS_ATTR_TYPE_INVALID);
9469 }
9470 /* 64-bit capable CPUs. */
9471 HMVMX_CHECK_BREAK(X86_IS_CANONICAL(pCtx->fs.u64Base), VMX_IGS_FS_BASE_NOT_CANONICAL);
9472 HMVMX_CHECK_BREAK(X86_IS_CANONICAL(pCtx->gs.u64Base), VMX_IGS_GS_BASE_NOT_CANONICAL);
9473 HMVMX_CHECK_BREAK( (pCtx->ldtr.Attr.u & X86DESCATTR_UNUSABLE)
9474 || X86_IS_CANONICAL(pCtx->ldtr.u64Base), VMX_IGS_LDTR_BASE_NOT_CANONICAL);
9475 HMVMX_CHECK_BREAK(!RT_HI_U32(pCtx->cs.u64Base), VMX_IGS_LONGMODE_CS_BASE_INVALID);
9476 HMVMX_CHECK_BREAK((pCtx->ss.Attr.u & X86DESCATTR_UNUSABLE) || !RT_HI_U32(pCtx->ss.u64Base),
9477 VMX_IGS_LONGMODE_SS_BASE_INVALID);
9478 HMVMX_CHECK_BREAK((pCtx->ds.Attr.u & X86DESCATTR_UNUSABLE) || !RT_HI_U32(pCtx->ds.u64Base),
9479 VMX_IGS_LONGMODE_DS_BASE_INVALID);
9480 HMVMX_CHECK_BREAK((pCtx->es.Attr.u & X86DESCATTR_UNUSABLE) || !RT_HI_U32(pCtx->es.u64Base),
9481 VMX_IGS_LONGMODE_ES_BASE_INVALID);
9482 }
9483 else
9484 {
9485 /* V86 mode checks. */
9486 uint32_t u32CSAttr, u32SSAttr, u32DSAttr, u32ESAttr, u32FSAttr, u32GSAttr;
9487 if (pVmcsInfo->RealMode.fRealOnV86Active)
9488 {
9489 u32CSAttr = 0xf3; u32SSAttr = 0xf3;
9490 u32DSAttr = 0xf3; u32ESAttr = 0xf3;
9491 u32FSAttr = 0xf3; u32GSAttr = 0xf3;
9492 }
9493 else
9494 {
9495 u32CSAttr = pCtx->cs.Attr.u; u32SSAttr = pCtx->ss.Attr.u;
9496 u32DSAttr = pCtx->ds.Attr.u; u32ESAttr = pCtx->es.Attr.u;
9497 u32FSAttr = pCtx->fs.Attr.u; u32GSAttr = pCtx->gs.Attr.u;
9498 }
9499
9500 /* CS */
9501 HMVMX_CHECK_BREAK((pCtx->cs.u64Base == (uint64_t)pCtx->cs.Sel << 4), VMX_IGS_V86_CS_BASE_INVALID);
9502 HMVMX_CHECK_BREAK(pCtx->cs.u32Limit == 0xffff, VMX_IGS_V86_CS_LIMIT_INVALID);
9503 HMVMX_CHECK_BREAK(u32CSAttr == 0xf3, VMX_IGS_V86_CS_ATTR_INVALID);
9504 /* SS */
9505 HMVMX_CHECK_BREAK((pCtx->ss.u64Base == (uint64_t)pCtx->ss.Sel << 4), VMX_IGS_V86_SS_BASE_INVALID);
9506 HMVMX_CHECK_BREAK(pCtx->ss.u32Limit == 0xffff, VMX_IGS_V86_SS_LIMIT_INVALID);
9507 HMVMX_CHECK_BREAK(u32SSAttr == 0xf3, VMX_IGS_V86_SS_ATTR_INVALID);
9508 /* DS */
9509 HMVMX_CHECK_BREAK((pCtx->ds.u64Base == (uint64_t)pCtx->ds.Sel << 4), VMX_IGS_V86_DS_BASE_INVALID);
9510 HMVMX_CHECK_BREAK(pCtx->ds.u32Limit == 0xffff, VMX_IGS_V86_DS_LIMIT_INVALID);
9511 HMVMX_CHECK_BREAK(u32DSAttr == 0xf3, VMX_IGS_V86_DS_ATTR_INVALID);
9512 /* ES */
9513 HMVMX_CHECK_BREAK((pCtx->es.u64Base == (uint64_t)pCtx->es.Sel << 4), VMX_IGS_V86_ES_BASE_INVALID);
9514 HMVMX_CHECK_BREAK(pCtx->es.u32Limit == 0xffff, VMX_IGS_V86_ES_LIMIT_INVALID);
9515 HMVMX_CHECK_BREAK(u32ESAttr == 0xf3, VMX_IGS_V86_ES_ATTR_INVALID);
9516 /* FS */
9517 HMVMX_CHECK_BREAK((pCtx->fs.u64Base == (uint64_t)pCtx->fs.Sel << 4), VMX_IGS_V86_FS_BASE_INVALID);
9518 HMVMX_CHECK_BREAK(pCtx->fs.u32Limit == 0xffff, VMX_IGS_V86_FS_LIMIT_INVALID);
9519 HMVMX_CHECK_BREAK(u32FSAttr == 0xf3, VMX_IGS_V86_FS_ATTR_INVALID);
9520 /* GS */
9521 HMVMX_CHECK_BREAK((pCtx->gs.u64Base == (uint64_t)pCtx->gs.Sel << 4), VMX_IGS_V86_GS_BASE_INVALID);
9522 HMVMX_CHECK_BREAK(pCtx->gs.u32Limit == 0xffff, VMX_IGS_V86_GS_LIMIT_INVALID);
9523 HMVMX_CHECK_BREAK(u32GSAttr == 0xf3, VMX_IGS_V86_GS_ATTR_INVALID);
9524 /* 64-bit capable CPUs. */
9525 HMVMX_CHECK_BREAK(X86_IS_CANONICAL(pCtx->fs.u64Base), VMX_IGS_FS_BASE_NOT_CANONICAL);
9526 HMVMX_CHECK_BREAK(X86_IS_CANONICAL(pCtx->gs.u64Base), VMX_IGS_GS_BASE_NOT_CANONICAL);
9527 HMVMX_CHECK_BREAK( (pCtx->ldtr.Attr.u & X86DESCATTR_UNUSABLE)
9528 || X86_IS_CANONICAL(pCtx->ldtr.u64Base), VMX_IGS_LDTR_BASE_NOT_CANONICAL);
9529 HMVMX_CHECK_BREAK(!RT_HI_U32(pCtx->cs.u64Base), VMX_IGS_LONGMODE_CS_BASE_INVALID);
9530 HMVMX_CHECK_BREAK((pCtx->ss.Attr.u & X86DESCATTR_UNUSABLE) || !RT_HI_U32(pCtx->ss.u64Base),
9531 VMX_IGS_LONGMODE_SS_BASE_INVALID);
9532 HMVMX_CHECK_BREAK((pCtx->ds.Attr.u & X86DESCATTR_UNUSABLE) || !RT_HI_U32(pCtx->ds.u64Base),
9533 VMX_IGS_LONGMODE_DS_BASE_INVALID);
9534 HMVMX_CHECK_BREAK((pCtx->es.Attr.u & X86DESCATTR_UNUSABLE) || !RT_HI_U32(pCtx->es.u64Base),
9535 VMX_IGS_LONGMODE_ES_BASE_INVALID);
9536 }
9537
9538 /*
9539 * TR.
9540 */
9541 HMVMX_CHECK_BREAK(!(pCtx->tr.Sel & X86_SEL_LDT), VMX_IGS_TR_TI_INVALID);
9542 /* 64-bit capable CPUs. */
9543 HMVMX_CHECK_BREAK(X86_IS_CANONICAL(pCtx->tr.u64Base), VMX_IGS_TR_BASE_NOT_CANONICAL);
9544 if (fLongModeGuest)
9545 {
9546 HMVMX_CHECK_BREAK(pCtx->tr.Attr.n.u4Type == 11, /* 64-bit busy TSS. */
9547 VMX_IGS_LONGMODE_TR_ATTR_TYPE_INVALID);
9548 }
9549 else
9550 {
9551 HMVMX_CHECK_BREAK( pCtx->tr.Attr.n.u4Type == 3 /* 16-bit busy TSS. */
9552 || pCtx->tr.Attr.n.u4Type == 11, /* 32-bit busy TSS.*/
9553 VMX_IGS_TR_ATTR_TYPE_INVALID);
9554 }
9555 HMVMX_CHECK_BREAK(!pCtx->tr.Attr.n.u1DescType, VMX_IGS_TR_ATTR_S_INVALID);
9556 HMVMX_CHECK_BREAK(pCtx->tr.Attr.n.u1Present, VMX_IGS_TR_ATTR_P_INVALID);
9557 HMVMX_CHECK_BREAK(!(pCtx->tr.Attr.u & 0xf00), VMX_IGS_TR_ATTR_RESERVED); /* Bits 11:8 MBZ. */
9558 HMVMX_CHECK_BREAK( (pCtx->tr.u32Limit & 0xfff) == 0xfff
9559 || !(pCtx->tr.Attr.n.u1Granularity), VMX_IGS_TR_ATTR_G_INVALID);
9560 HMVMX_CHECK_BREAK( !(pCtx->tr.u32Limit & 0xfff00000)
9561 || (pCtx->tr.Attr.n.u1Granularity), VMX_IGS_TR_ATTR_G_INVALID);
9562 HMVMX_CHECK_BREAK(!(pCtx->tr.Attr.u & X86DESCATTR_UNUSABLE), VMX_IGS_TR_ATTR_UNUSABLE);
9563
9564 /*
9565 * GDTR and IDTR (64-bit capable checks).
9566 */
9567 rc = VMXReadVmcsNw(VMX_VMCS_GUEST_GDTR_BASE, &u64Val);
9568 AssertRC(rc);
9569 HMVMX_CHECK_BREAK(X86_IS_CANONICAL(u64Val), VMX_IGS_GDTR_BASE_NOT_CANONICAL);
9570
9571 rc = VMXReadVmcsNw(VMX_VMCS_GUEST_IDTR_BASE, &u64Val);
9572 AssertRC(rc);
9573 HMVMX_CHECK_BREAK(X86_IS_CANONICAL(u64Val), VMX_IGS_IDTR_BASE_NOT_CANONICAL);
9574
9575 rc = VMXReadVmcs32(VMX_VMCS32_GUEST_GDTR_LIMIT, &u32Val);
9576 AssertRC(rc);
9577 HMVMX_CHECK_BREAK(!(u32Val & 0xffff0000), VMX_IGS_GDTR_LIMIT_INVALID); /* Bits 31:16 MBZ. */
9578
9579 rc = VMXReadVmcs32(VMX_VMCS32_GUEST_IDTR_LIMIT, &u32Val);
9580 AssertRC(rc);
9581 HMVMX_CHECK_BREAK(!(u32Val & 0xffff0000), VMX_IGS_IDTR_LIMIT_INVALID); /* Bits 31:16 MBZ. */
9582
9583 /*
9584 * Guest Non-Register State.
9585 */
9586 /* Activity State. */
9587 uint32_t u32ActivityState;
9588 rc = VMXReadVmcs32(VMX_VMCS32_GUEST_ACTIVITY_STATE, &u32ActivityState);
9589 AssertRC(rc);
9590 HMVMX_CHECK_BREAK( !u32ActivityState
9591 || (u32ActivityState & RT_BF_GET(pVM->hm.s.vmx.Msrs.u64Misc, VMX_BF_MISC_ACTIVITY_STATES)),
9592 VMX_IGS_ACTIVITY_STATE_INVALID);
9593 HMVMX_CHECK_BREAK( !(pCtx->ss.Attr.n.u2Dpl)
9594 || u32ActivityState != VMX_VMCS_GUEST_ACTIVITY_HLT, VMX_IGS_ACTIVITY_STATE_HLT_INVALID);
9595 uint32_t u32IntrState;
9596 rc = VMXReadVmcs32(VMX_VMCS32_GUEST_INT_STATE, &u32IntrState);
9597 AssertRC(rc);
9598 if ( u32IntrState == VMX_VMCS_GUEST_INT_STATE_BLOCK_MOVSS
9599 || u32IntrState == VMX_VMCS_GUEST_INT_STATE_BLOCK_STI)
9600 {
9601 HMVMX_CHECK_BREAK(u32ActivityState == VMX_VMCS_GUEST_ACTIVITY_ACTIVE, VMX_IGS_ACTIVITY_STATE_ACTIVE_INVALID);
9602 }
9603
9604 /** @todo Activity state and injecting interrupts. Left as a todo since we
9605 * currently don't use activity states but ACTIVE. */
9606
9607 HMVMX_CHECK_BREAK( !(pVmcsInfo->u32EntryCtls & VMX_ENTRY_CTLS_ENTRY_TO_SMM)
9608 || u32ActivityState != VMX_VMCS_GUEST_ACTIVITY_SIPI_WAIT, VMX_IGS_ACTIVITY_STATE_SIPI_WAIT_INVALID);
9609
9610 /* Guest interruptibility-state. */
9611 HMVMX_CHECK_BREAK(!(u32IntrState & 0xffffffe0), VMX_IGS_INTERRUPTIBILITY_STATE_RESERVED);
9612 HMVMX_CHECK_BREAK((u32IntrState & (VMX_VMCS_GUEST_INT_STATE_BLOCK_STI | VMX_VMCS_GUEST_INT_STATE_BLOCK_MOVSS))
9613 != (VMX_VMCS_GUEST_INT_STATE_BLOCK_STI | VMX_VMCS_GUEST_INT_STATE_BLOCK_MOVSS),
9614 VMX_IGS_INTERRUPTIBILITY_STATE_STI_MOVSS_INVALID);
9615 HMVMX_CHECK_BREAK( (u32Eflags & X86_EFL_IF)
9616 || !(u32IntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_STI),
9617 VMX_IGS_INTERRUPTIBILITY_STATE_STI_EFL_INVALID);
9618 if (VMX_ENTRY_INT_INFO_IS_EXT_INT(u32EntryInfo))
9619 {
9620 HMVMX_CHECK_BREAK( !(u32IntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_STI)
9621 && !(u32IntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_MOVSS),
9622 VMX_IGS_INTERRUPTIBILITY_STATE_EXT_INT_INVALID);
9623 }
9624 else if (VMX_ENTRY_INT_INFO_IS_XCPT_NMI(u32EntryInfo))
9625 {
9626 HMVMX_CHECK_BREAK(!(u32IntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_MOVSS),
9627 VMX_IGS_INTERRUPTIBILITY_STATE_MOVSS_INVALID);
9628 HMVMX_CHECK_BREAK(!(u32IntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_STI),
9629 VMX_IGS_INTERRUPTIBILITY_STATE_STI_INVALID);
9630 }
9631 /** @todo Assumes the processor is not in SMM. */
9632 HMVMX_CHECK_BREAK(!(u32IntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_SMI),
9633 VMX_IGS_INTERRUPTIBILITY_STATE_SMI_INVALID);
9634 HMVMX_CHECK_BREAK( !(pVmcsInfo->u32EntryCtls & VMX_ENTRY_CTLS_ENTRY_TO_SMM)
9635 || (u32IntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_SMI),
9636 VMX_IGS_INTERRUPTIBILITY_STATE_SMI_SMM_INVALID);
9637 if ( (pVmcsInfo->u32PinCtls & VMX_PIN_CTLS_VIRT_NMI)
9638 && VMX_ENTRY_INT_INFO_IS_XCPT_NMI(u32EntryInfo))
9639 {
9640 HMVMX_CHECK_BREAK(!(u32IntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_NMI),
9641 VMX_IGS_INTERRUPTIBILITY_STATE_NMI_INVALID);
9642 }
9643
9644 /* Pending debug exceptions. */
9645 rc = VMXReadVmcsNw(VMX_VMCS_GUEST_PENDING_DEBUG_XCPTS, &u64Val);
9646 AssertRC(rc);
9647 /* Bits 63:15, Bit 13, Bits 11:4 MBZ. */
9648 HMVMX_CHECK_BREAK(!(u64Val & UINT64_C(0xffffffffffffaff0)), VMX_IGS_LONGMODE_PENDING_DEBUG_RESERVED);
9649 u32Val = u64Val; /* For pending debug exceptions checks below. */
9650
9651 if ( (u32IntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_STI)
9652 || (u32IntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_MOVSS)
9653 || u32ActivityState == VMX_VMCS_GUEST_ACTIVITY_HLT)
9654 {
9655 if ( (u32Eflags & X86_EFL_TF)
9656 && !(u64DebugCtlMsr & RT_BIT_64(1))) /* Bit 1 is IA32_DEBUGCTL.BTF. */
9657 {
9658 /* Bit 14 is PendingDebug.BS. */
9659 HMVMX_CHECK_BREAK(u32Val & RT_BIT(14), VMX_IGS_PENDING_DEBUG_XCPT_BS_NOT_SET);
9660 }
9661 if ( !(u32Eflags & X86_EFL_TF)
9662 || (u64DebugCtlMsr & RT_BIT_64(1))) /* Bit 1 is IA32_DEBUGCTL.BTF. */
9663 {
9664 /* Bit 14 is PendingDebug.BS. */
9665 HMVMX_CHECK_BREAK(!(u32Val & RT_BIT(14)), VMX_IGS_PENDING_DEBUG_XCPT_BS_NOT_CLEAR);
9666 }
9667 }
9668
9669 /* VMCS link pointer. */
9670 rc = VMXReadVmcs64(VMX_VMCS64_GUEST_VMCS_LINK_PTR_FULL, &u64Val);
9671 AssertRC(rc);
9672 if (u64Val != UINT64_C(0xffffffffffffffff))
9673 {
9674 HMVMX_CHECK_BREAK(!(u64Val & 0xfff), VMX_IGS_VMCS_LINK_PTR_RESERVED);
9675 /** @todo Bits beyond the processor's physical-address width MBZ. */
9676 /** @todo SMM checks. */
9677 Assert(pVmcsInfo->HCPhysShadowVmcs == u64Val);
9678 Assert(pVmcsInfo->pvShadowVmcs);
9679 VMXVMCSREVID VmcsRevId;
9680 VmcsRevId.u = *(uint32_t *)pVmcsInfo->pvShadowVmcs;
9681 HMVMX_CHECK_BREAK(VmcsRevId.n.u31RevisionId == RT_BF_GET(pVM->hm.s.vmx.Msrs.u64Basic, VMX_BF_BASIC_VMCS_ID),
9682 VMX_IGS_VMCS_LINK_PTR_SHADOW_VMCS_ID_INVALID);
9683 HMVMX_CHECK_BREAK(VmcsRevId.n.fIsShadowVmcs == (uint32_t)!!(pVmcsInfo->u32ProcCtls2 & VMX_PROC_CTLS2_VMCS_SHADOWING),
9684 VMX_IGS_VMCS_LINK_PTR_NOT_SHADOW);
9685 }
9686
9687 /** @todo Checks on Guest Page-Directory-Pointer-Table Entries when guest is
9688 * not using nested paging? */
9689 if ( pVM->hm.s.fNestedPaging
9690 && !fLongModeGuest
9691 && CPUMIsGuestInPAEModeEx(pCtx))
9692 {
9693 rc = VMXReadVmcs64(VMX_VMCS64_GUEST_PDPTE0_FULL, &u64Val);
9694 AssertRC(rc);
9695 HMVMX_CHECK_BREAK(!(u64Val & X86_PDPE_PAE_MBZ_MASK), VMX_IGS_PAE_PDPTE_RESERVED);
9696
9697 rc = VMXReadVmcs64(VMX_VMCS64_GUEST_PDPTE1_FULL, &u64Val);
9698 AssertRC(rc);
9699 HMVMX_CHECK_BREAK(!(u64Val & X86_PDPE_PAE_MBZ_MASK), VMX_IGS_PAE_PDPTE_RESERVED);
9700
9701 rc = VMXReadVmcs64(VMX_VMCS64_GUEST_PDPTE2_FULL, &u64Val);
9702 AssertRC(rc);
9703 HMVMX_CHECK_BREAK(!(u64Val & X86_PDPE_PAE_MBZ_MASK), VMX_IGS_PAE_PDPTE_RESERVED);
9704
9705 rc = VMXReadVmcs64(VMX_VMCS64_GUEST_PDPTE3_FULL, &u64Val);
9706 AssertRC(rc);
9707 HMVMX_CHECK_BREAK(!(u64Val & X86_PDPE_PAE_MBZ_MASK), VMX_IGS_PAE_PDPTE_RESERVED);
9708 }
9709
9710 /* Shouldn't happen but distinguish it from AssertRCBreak() errors. */
9711 if (uError == VMX_IGS_ERROR)
9712 uError = VMX_IGS_REASON_NOT_FOUND;
9713 } while (0);
9714
9715 pVCpu->hm.s.u32HMError = uError;
9716 return uError;
9717
9718#undef HMVMX_ERROR_BREAK
9719#undef HMVMX_CHECK_BREAK
9720}
9721
9722
9723/**
9724 * Map the APIC-access page for virtualizing APIC accesses.
9725 *
9726 * This can cause a longjumps to R3 due to the acquisition of the PGM lock. Hence,
9727 * this not done as part of exporting guest state, see @bugref{8721}.
9728 *
9729 * @returns VBox status code.
9730 * @param pVCpu The cross context virtual CPU structure.
9731 */
9732static int hmR0VmxMapHCApicAccessPage(PVMCPUCC pVCpu)
9733{
9734 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
9735 uint64_t const u64MsrApicBase = APICGetBaseMsrNoCheck(pVCpu);
9736
9737 Assert(PDMHasApic(pVM));
9738 Assert(u64MsrApicBase);
9739
9740 RTGCPHYS const GCPhysApicBase = u64MsrApicBase & PAGE_BASE_GC_MASK;
9741 Log4Func(("Mappping HC APIC-access page at %#RGp\n", GCPhysApicBase));
9742
9743 /* Unalias the existing mapping. */
9744 int rc = PGMHandlerPhysicalReset(pVM, GCPhysApicBase);
9745 AssertRCReturn(rc, rc);
9746
9747 /* Map the HC APIC-access page in place of the MMIO page, also updates the shadow page tables if necessary. */
9748 Assert(pVM->hm.s.vmx.HCPhysApicAccess != NIL_RTHCPHYS);
9749 rc = IOMMMIOMapMMIOHCPage(pVM, pVCpu, GCPhysApicBase, pVM->hm.s.vmx.HCPhysApicAccess, X86_PTE_RW | X86_PTE_P);
9750 AssertRCReturn(rc, rc);
9751
9752 /* Update the per-VCPU cache of the APIC base MSR. */
9753 pVCpu->hm.s.vmx.u64GstMsrApicBase = u64MsrApicBase;
9754 return VINF_SUCCESS;
9755}
9756
9757
9758/**
9759 * Worker function passed to RTMpOnSpecific() that is to be called on the target
9760 * CPU.
9761 *
9762 * @param idCpu The ID for the CPU the function is called on.
9763 * @param pvUser1 Null, not used.
9764 * @param pvUser2 Null, not used.
9765 */
9766static DECLCALLBACK(void) hmR0DispatchHostNmi(RTCPUID idCpu, void *pvUser1, void *pvUser2)
9767{
9768 RT_NOREF3(idCpu, pvUser1, pvUser2);
9769 VMXDispatchHostNmi();
9770}
9771
9772
9773/**
9774 * Dispatching an NMI on the host CPU that received it.
9775 *
9776 * @returns VBox status code.
9777 * @param pVCpu The cross context virtual CPU structure.
9778 * @param pVmcsInfo The VMCS info. object corresponding to the VMCS that was
9779 * executing when receiving the host NMI in VMX non-root
9780 * operation.
9781 */
9782static int hmR0VmxExitHostNmi(PVMCPUCC pVCpu, PCVMXVMCSINFO pVmcsInfo)
9783{
9784 RTCPUID const idCpu = pVmcsInfo->idHostCpuExec;
9785 Assert(idCpu != NIL_RTCPUID);
9786
9787 /*
9788 * We don't want to delay dispatching the NMI any more than we have to. However,
9789 * we have already chosen -not- to dispatch NMIs when interrupts were still disabled
9790 * after executing guest or nested-guest code for the following reasons:
9791 *
9792 * - We would need to perform VMREADs with interrupts disabled and is orders of
9793 * magnitude worse when we run as a guest hypervisor without VMCS shadowing
9794 * supported by the host hypervisor.
9795 *
9796 * - It affects the common VM-exit scenario and keeps interrupts disabled for a
9797 * longer period of time just for handling an edge case like host NMIs which do
9798 * not occur nearly as frequently as other VM-exits.
9799 *
9800 * Let's cover the most likely scenario first. Check if we are on the target CPU
9801 * and dispatch the NMI right away. This should be much faster than calling into
9802 * RTMpOnSpecific() machinery.
9803 */
9804 bool fDispatched = false;
9805 RTCCUINTREG const fEFlags = ASMIntDisableFlags();
9806 if (idCpu == RTMpCpuId())
9807 {
9808 VMXDispatchHostNmi();
9809 fDispatched = true;
9810 }
9811 ASMSetFlags(fEFlags);
9812 if (fDispatched)
9813 {
9814 STAM_REL_COUNTER_INC(&pVCpu->hm.s.StatExitHostNmiInGC);
9815 return VINF_SUCCESS;
9816 }
9817
9818 /*
9819 * RTMpOnSpecific() waits until the worker function has run on the target CPU. So
9820 * there should be no race or recursion even if we are unlucky enough to be preempted
9821 * (to the target CPU) without dispatching the host NMI above.
9822 */
9823 STAM_REL_COUNTER_INC(&pVCpu->hm.s.StatExitHostNmiInGCIpi);
9824 return RTMpOnSpecific(idCpu, &hmR0DispatchHostNmi, NULL /* pvUser1 */, NULL /* pvUser2 */);
9825}
9826
9827
9828#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
9829/**
9830 * Merges the guest with the nested-guest MSR bitmap in preparation of executing the
9831 * nested-guest using hardware-assisted VMX.
9832 *
9833 * @param pVCpu The cross context virtual CPU structure.
9834 * @param pVmcsInfoNstGst The nested-guest VMCS info. object.
9835 * @param pVmcsInfoGst The guest VMCS info. object.
9836 */
9837static void hmR0VmxMergeMsrBitmapNested(PCVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfoNstGst, PCVMXVMCSINFO pVmcsInfoGst)
9838{
9839 uint32_t const cbMsrBitmap = X86_PAGE_4K_SIZE;
9840 uint64_t *pu64MsrBitmap = (uint64_t *)pVmcsInfoNstGst->pvMsrBitmap;
9841 Assert(pu64MsrBitmap);
9842
9843 /*
9844 * We merge the guest MSR bitmap with the nested-guest MSR bitmap such that any
9845 * MSR that is intercepted by the guest is also intercepted while executing the
9846 * nested-guest using hardware-assisted VMX.
9847 *
9848 * Note! If the nested-guest is not using an MSR bitmap, ever MSR must cause a
9849 * nested-guest VM-exit even if the outer guest is not intercepting some
9850 * MSRs. We cannot assume the caller has initialized the nested-guest
9851 * MSR bitmap in this case.
9852 *
9853 * The guest hypervisor may also switch whether it uses MSR bitmaps for
9854 * each VM-entry, hence initializing it once per-VM while setting up the
9855 * nested-guest VMCS is not sufficient.
9856 */
9857 PCVMXVVMCS pVmcsNstGst = pVCpu->cpum.GstCtx.hwvirt.vmx.CTX_SUFF(pVmcs);
9858 if (pVmcsNstGst->u32ProcCtls & VMX_PROC_CTLS_USE_MSR_BITMAPS)
9859 {
9860 uint64_t const *pu64MsrBitmapNstGst = (uint64_t const *)pVCpu->cpum.GstCtx.hwvirt.vmx.CTX_SUFF(pvMsrBitmap);
9861 uint64_t const *pu64MsrBitmapGst = (uint64_t const *)pVmcsInfoGst->pvMsrBitmap;
9862 Assert(pu64MsrBitmapNstGst);
9863 Assert(pu64MsrBitmapGst);
9864
9865 uint32_t const cFrags = cbMsrBitmap / sizeof(uint64_t);
9866 for (uint32_t i = 0; i < cFrags; i++)
9867 pu64MsrBitmap[i] = pu64MsrBitmapNstGst[i] | pu64MsrBitmapGst[i];
9868 }
9869 else
9870 ASMMemFill32(pu64MsrBitmap, cbMsrBitmap, UINT32_C(0xffffffff));
9871}
9872
9873
9874/**
9875 * Merges the guest VMCS in to the nested-guest VMCS controls in preparation of
9876 * hardware-assisted VMX execution of the nested-guest.
9877 *
9878 * For a guest, we don't modify these controls once we set up the VMCS and hence
9879 * this function is never called.
9880 *
9881 * For nested-guests since the guest hypervisor provides these controls on every
9882 * nested-guest VM-entry and could potentially change them everytime we need to
9883 * merge them before every nested-guest VM-entry.
9884 *
9885 * @returns VBox status code.
9886 * @param pVCpu The cross context virtual CPU structure.
9887 */
9888static int hmR0VmxMergeVmcsNested(PVMCPUCC pVCpu)
9889{
9890 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
9891 PCVMXVMCSINFO pVmcsInfoGst = &pVCpu->hm.s.vmx.VmcsInfo;
9892 PCVMXVVMCS pVmcsNstGst = pVCpu->cpum.GstCtx.hwvirt.vmx.CTX_SUFF(pVmcs);
9893 Assert(pVmcsNstGst);
9894
9895 /*
9896 * Merge the controls with the requirements of the guest VMCS.
9897 *
9898 * We do not need to validate the nested-guest VMX features specified in the nested-guest
9899 * VMCS with the features supported by the physical CPU as it's already done by the
9900 * VMLAUNCH/VMRESUME instruction emulation.
9901 *
9902 * This is because the VMX features exposed by CPUM (through CPUID/MSRs) to the guest are
9903 * derived from the VMX features supported by the physical CPU.
9904 */
9905
9906 /* Pin-based VM-execution controls. */
9907 uint32_t const u32PinCtls = pVmcsNstGst->u32PinCtls | pVmcsInfoGst->u32PinCtls;
9908
9909 /* Processor-based VM-execution controls. */
9910 uint32_t u32ProcCtls = (pVmcsNstGst->u32ProcCtls & ~VMX_PROC_CTLS_USE_IO_BITMAPS)
9911 | (pVmcsInfoGst->u32ProcCtls & ~( VMX_PROC_CTLS_INT_WINDOW_EXIT
9912 | VMX_PROC_CTLS_NMI_WINDOW_EXIT
9913 | VMX_PROC_CTLS_USE_TPR_SHADOW
9914 | VMX_PROC_CTLS_MONITOR_TRAP_FLAG));
9915
9916 /* Secondary processor-based VM-execution controls. */
9917 uint32_t const u32ProcCtls2 = (pVmcsNstGst->u32ProcCtls2 & ~VMX_PROC_CTLS2_VPID)
9918 | (pVmcsInfoGst->u32ProcCtls2 & ~( VMX_PROC_CTLS2_VIRT_APIC_ACCESS
9919 | VMX_PROC_CTLS2_INVPCID
9920 | VMX_PROC_CTLS2_VMCS_SHADOWING
9921 | VMX_PROC_CTLS2_RDTSCP
9922 | VMX_PROC_CTLS2_XSAVES_XRSTORS
9923 | VMX_PROC_CTLS2_APIC_REG_VIRT
9924 | VMX_PROC_CTLS2_VIRT_INT_DELIVERY
9925 | VMX_PROC_CTLS2_VMFUNC));
9926
9927 /*
9928 * VM-entry controls:
9929 * These controls contains state that depends on the nested-guest state (primarily
9930 * EFER MSR) and is thus not constant between VMLAUNCH/VMRESUME and the nested-guest
9931 * VM-exit. Although the guest hypervisor cannot change it, we need to in order to
9932 * properly continue executing the nested-guest if the EFER MSR changes but does not
9933 * cause a nested-guest VM-exits.
9934 *
9935 * VM-exit controls:
9936 * These controls specify the host state on return. We cannot use the controls from
9937 * the guest hypervisor state as is as it would contain the guest state rather than
9938 * the host state. Since the host state is subject to change (e.g. preemption, trips
9939 * to ring-3, longjmp and rescheduling to a different host CPU) they are not constant
9940 * through VMLAUNCH/VMRESUME and the nested-guest VM-exit.
9941 *
9942 * VM-entry MSR-load:
9943 * The guest MSRs from the VM-entry MSR-load area are already loaded into the guest-CPU
9944 * context by the VMLAUNCH/VMRESUME instruction emulation.
9945 *
9946 * VM-exit MSR-store:
9947 * The VM-exit emulation will take care of populating the MSRs from the guest-CPU context
9948 * back into the VM-exit MSR-store area.
9949 *
9950 * VM-exit MSR-load areas:
9951 * This must contain the real host MSRs with hardware-assisted VMX execution. Hence, we
9952 * can entirely ignore what the guest hypervisor wants to load here.
9953 */
9954
9955 /*
9956 * Exception bitmap.
9957 *
9958 * We could remove #UD from the guest bitmap and merge it with the nested-guest bitmap
9959 * here (and avoid doing anything while exporting nested-guest state), but to keep the
9960 * code more flexible if intercepting exceptions become more dynamic in the future we do
9961 * it as part of exporting the nested-guest state.
9962 */
9963 uint32_t const u32XcptBitmap = pVmcsNstGst->u32XcptBitmap | pVmcsInfoGst->u32XcptBitmap;
9964
9965 /*
9966 * CR0/CR4 guest/host mask.
9967 *
9968 * Modifications by the nested-guest to CR0/CR4 bits owned by the host and the guest must
9969 * cause VM-exits, so we need to merge them here.
9970 */
9971 uint64_t const u64Cr0Mask = pVmcsNstGst->u64Cr0Mask.u | pVmcsInfoGst->u64Cr0Mask;
9972 uint64_t const u64Cr4Mask = pVmcsNstGst->u64Cr4Mask.u | pVmcsInfoGst->u64Cr4Mask;
9973
9974 /*
9975 * Page-fault error-code mask and match.
9976 *
9977 * Although we require unrestricted guest execution (and thereby nested-paging) for
9978 * hardware-assisted VMX execution of nested-guests and thus the outer guest doesn't
9979 * normally intercept #PFs, it might intercept them for debugging purposes.
9980 *
9981 * If the outer guest is not intercepting #PFs, we can use the nested-guest #PF filters.
9982 * If the outer guest is intercepting #PFs, we must intercept all #PFs.
9983 */
9984 uint32_t u32XcptPFMask;
9985 uint32_t u32XcptPFMatch;
9986 if (!(pVmcsInfoGst->u32XcptBitmap & RT_BIT(X86_XCPT_PF)))
9987 {
9988 u32XcptPFMask = pVmcsNstGst->u32XcptPFMask;
9989 u32XcptPFMatch = pVmcsNstGst->u32XcptPFMatch;
9990 }
9991 else
9992 {
9993 u32XcptPFMask = 0;
9994 u32XcptPFMatch = 0;
9995 }
9996
9997 /*
9998 * Pause-Loop exiting.
9999 */
10000 uint32_t const cPleGapTicks = RT_MIN(pVM->hm.s.vmx.cPleGapTicks, pVmcsNstGst->u32PleGap);
10001 uint32_t const cPleWindowTicks = RT_MIN(pVM->hm.s.vmx.cPleWindowTicks, pVmcsNstGst->u32PleWindow);
10002
10003 /*
10004 * Pending debug exceptions.
10005 * Currently just copy whatever the nested-guest provides us.
10006 */
10007 uint64_t const uPendingDbgXcpts = pVmcsNstGst->u64GuestPendingDbgXcpts.u;
10008
10009 /*
10010 * I/O Bitmap.
10011 *
10012 * We do not use the I/O bitmap that may be provided by the guest hypervisor as we always
10013 * intercept all I/O port accesses.
10014 */
10015 Assert(u32ProcCtls & VMX_PROC_CTLS_UNCOND_IO_EXIT);
10016 Assert(!(u32ProcCtls & VMX_PROC_CTLS_USE_IO_BITMAPS));
10017
10018 /*
10019 * VMCS shadowing.
10020 *
10021 * We do not yet expose VMCS shadowing to the guest and thus VMCS shadowing should not be
10022 * enabled while executing the nested-guest.
10023 */
10024 Assert(!(u32ProcCtls2 & VMX_PROC_CTLS2_VMCS_SHADOWING));
10025
10026 /*
10027 * APIC-access page.
10028 */
10029 RTHCPHYS HCPhysApicAccess;
10030 if (u32ProcCtls2 & VMX_PROC_CTLS2_VIRT_APIC_ACCESS)
10031 {
10032 Assert(pVM->hm.s.vmx.Msrs.ProcCtls2.n.allowed1 & VMX_PROC_CTLS2_VIRT_APIC_ACCESS);
10033 RTGCPHYS const GCPhysApicAccess = pVmcsNstGst->u64AddrApicAccess.u;
10034
10035 /** @todo NSTVMX: This is not really correct but currently is required to make
10036 * things work. We need to re-enable the page handler when we fallback to
10037 * IEM execution of the nested-guest! */
10038 PGMHandlerPhysicalPageTempOff(pVM, GCPhysApicAccess, GCPhysApicAccess);
10039
10040 void *pvPage;
10041 PGMPAGEMAPLOCK PgLockApicAccess;
10042 int rc = PGMPhysGCPhys2CCPtr(pVM, GCPhysApicAccess, &pvPage, &PgLockApicAccess);
10043 if (RT_SUCCESS(rc))
10044 {
10045 rc = PGMPhysGCPhys2HCPhys(pVM, GCPhysApicAccess, &HCPhysApicAccess);
10046 AssertMsgRCReturn(rc, ("Failed to get host-physical address for APIC-access page at %#RGp\n", GCPhysApicAccess), rc);
10047
10048 /** @todo Handle proper releasing of page-mapping lock later. */
10049 PGMPhysReleasePageMappingLock(pVCpu->CTX_SUFF(pVM), &PgLockApicAccess);
10050 }
10051 else
10052 return rc;
10053 }
10054 else
10055 HCPhysApicAccess = 0;
10056
10057 /*
10058 * Virtual-APIC page and TPR threshold.
10059 */
10060 PVMXVMCSINFO pVmcsInfoNstGst = &pVCpu->hm.s.vmx.VmcsInfoNstGst;
10061 RTHCPHYS HCPhysVirtApic;
10062 uint32_t u32TprThreshold;
10063 if (u32ProcCtls & VMX_PROC_CTLS_USE_TPR_SHADOW)
10064 {
10065 Assert(pVM->hm.s.vmx.Msrs.ProcCtls.n.allowed1 & VMX_PROC_CTLS_USE_TPR_SHADOW);
10066 RTGCPHYS const GCPhysVirtApic = pVmcsNstGst->u64AddrVirtApic.u;
10067
10068 void *pvPage;
10069 PGMPAGEMAPLOCK PgLockVirtApic;
10070 int rc = PGMPhysGCPhys2CCPtr(pVM, GCPhysVirtApic, &pvPage, &PgLockVirtApic);
10071 if (RT_SUCCESS(rc))
10072 {
10073 rc = PGMPhysGCPhys2HCPhys(pVM, GCPhysVirtApic, &HCPhysVirtApic);
10074 AssertMsgRCReturn(rc, ("Failed to get host-physical address for virtual-APIC page at %#RGp\n", GCPhysVirtApic), rc);
10075
10076 /** @todo Handle proper releasing of page-mapping lock later. */
10077 PGMPhysReleasePageMappingLock(pVCpu->CTX_SUFF(pVM), &PgLockVirtApic);
10078 }
10079 else
10080 return rc;
10081
10082 u32TprThreshold = pVmcsNstGst->u32TprThreshold;
10083 }
10084 else
10085 {
10086 HCPhysVirtApic = 0;
10087 u32TprThreshold = 0;
10088
10089 /*
10090 * We must make sure CR8 reads/write must cause VM-exits when TPR shadowing is not
10091 * used by the guest hypervisor. Preventing MMIO accesses to the physical APIC will
10092 * be taken care of by EPT/shadow paging.
10093 */
10094 if (pVM->hm.s.fAllow64BitGuests)
10095 {
10096 u32ProcCtls |= VMX_PROC_CTLS_CR8_STORE_EXIT
10097 | VMX_PROC_CTLS_CR8_LOAD_EXIT;
10098 }
10099 }
10100
10101 /*
10102 * Validate basic assumptions.
10103 */
10104 Assert(pVM->hm.s.vmx.fAllowUnrestricted);
10105 Assert(pVM->hm.s.vmx.Msrs.ProcCtls.n.allowed1 & VMX_PROC_CTLS_USE_SECONDARY_CTLS);
10106 Assert(hmGetVmxActiveVmcsInfo(pVCpu) == pVmcsInfoNstGst);
10107
10108 /*
10109 * Commit it to the nested-guest VMCS.
10110 */
10111 int rc = VINF_SUCCESS;
10112 if (pVmcsInfoNstGst->u32PinCtls != u32PinCtls)
10113 rc |= VMXWriteVmcs32(VMX_VMCS32_CTRL_PIN_EXEC, u32PinCtls);
10114 if (pVmcsInfoNstGst->u32ProcCtls != u32ProcCtls)
10115 rc |= VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, u32ProcCtls);
10116 if (pVmcsInfoNstGst->u32ProcCtls2 != u32ProcCtls2)
10117 rc |= VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC2, u32ProcCtls2);
10118 if (pVmcsInfoNstGst->u32XcptBitmap != u32XcptBitmap)
10119 rc |= VMXWriteVmcs32(VMX_VMCS32_CTRL_EXCEPTION_BITMAP, u32XcptBitmap);
10120 if (pVmcsInfoNstGst->u64Cr0Mask != u64Cr0Mask)
10121 rc |= VMXWriteVmcsNw(VMX_VMCS_CTRL_CR0_MASK, u64Cr0Mask);
10122 if (pVmcsInfoNstGst->u64Cr4Mask != u64Cr4Mask)
10123 rc |= VMXWriteVmcsNw(VMX_VMCS_CTRL_CR4_MASK, u64Cr4Mask);
10124 if (pVmcsInfoNstGst->u32XcptPFMask != u32XcptPFMask)
10125 rc |= VMXWriteVmcs32(VMX_VMCS32_CTRL_PAGEFAULT_ERROR_MASK, u32XcptPFMask);
10126 if (pVmcsInfoNstGst->u32XcptPFMatch != u32XcptPFMatch)
10127 rc |= VMXWriteVmcs32(VMX_VMCS32_CTRL_PAGEFAULT_ERROR_MATCH, u32XcptPFMatch);
10128 if ( !(u32ProcCtls & VMX_PROC_CTLS_PAUSE_EXIT)
10129 && (u32ProcCtls2 & VMX_PROC_CTLS2_PAUSE_LOOP_EXIT))
10130 {
10131 Assert(pVM->hm.s.vmx.Msrs.ProcCtls2.n.allowed1 & VMX_PROC_CTLS2_PAUSE_LOOP_EXIT);
10132 rc |= VMXWriteVmcs32(VMX_VMCS32_CTRL_PLE_GAP, cPleGapTicks);
10133 rc |= VMXWriteVmcs32(VMX_VMCS32_CTRL_PLE_WINDOW, cPleWindowTicks);
10134 }
10135 if (u32ProcCtls & VMX_PROC_CTLS_USE_TPR_SHADOW)
10136 {
10137 rc |= VMXWriteVmcs32(VMX_VMCS32_CTRL_TPR_THRESHOLD, u32TprThreshold);
10138 rc |= VMXWriteVmcs64(VMX_VMCS64_CTRL_VIRT_APIC_PAGEADDR_FULL, HCPhysVirtApic);
10139 }
10140 if (u32ProcCtls2 & VMX_PROC_CTLS2_VIRT_APIC_ACCESS)
10141 rc |= VMXWriteVmcs64(VMX_VMCS64_CTRL_APIC_ACCESSADDR_FULL, HCPhysApicAccess);
10142 rc |= VMXWriteVmcsNw(VMX_VMCS_GUEST_PENDING_DEBUG_XCPTS, uPendingDbgXcpts);
10143 AssertRC(rc);
10144
10145 /*
10146 * Update the nested-guest VMCS cache.
10147 */
10148 pVmcsInfoNstGst->u32PinCtls = u32PinCtls;
10149 pVmcsInfoNstGst->u32ProcCtls = u32ProcCtls;
10150 pVmcsInfoNstGst->u32ProcCtls2 = u32ProcCtls2;
10151 pVmcsInfoNstGst->u32XcptBitmap = u32XcptBitmap;
10152 pVmcsInfoNstGst->u64Cr0Mask = u64Cr0Mask;
10153 pVmcsInfoNstGst->u64Cr4Mask = u64Cr4Mask;
10154 pVmcsInfoNstGst->u32XcptPFMask = u32XcptPFMask;
10155 pVmcsInfoNstGst->u32XcptPFMatch = u32XcptPFMatch;
10156 pVmcsInfoNstGst->HCPhysVirtApic = HCPhysVirtApic;
10157
10158 /*
10159 * We need to flush the TLB if we are switching the APIC-access page address.
10160 * See Intel spec. 28.3.3.4 "Guidelines for Use of the INVEPT Instruction".
10161 */
10162 if (u32ProcCtls2 & VMX_PROC_CTLS2_VIRT_APIC_ACCESS)
10163 pVCpu->hm.s.vmx.fSwitchedNstGstFlushTlb = true;
10164
10165 /*
10166 * MSR bitmap.
10167 *
10168 * The MSR bitmap address has already been initialized while setting up the nested-guest
10169 * VMCS, here we need to merge the MSR bitmaps.
10170 */
10171 if (u32ProcCtls & VMX_PROC_CTLS_USE_MSR_BITMAPS)
10172 hmR0VmxMergeMsrBitmapNested(pVCpu, pVmcsInfoNstGst, pVmcsInfoGst);
10173
10174 return VINF_SUCCESS;
10175}
10176#endif /* VBOX_WITH_NESTED_HWVIRT_VMX */
10177
10178
10179/**
10180 * Does the preparations before executing guest code in VT-x.
10181 *
10182 * This may cause longjmps to ring-3 and may even result in rescheduling to the
10183 * recompiler/IEM. We must be cautious what we do here regarding committing
10184 * guest-state information into the VMCS assuming we assuredly execute the
10185 * guest in VT-x mode.
10186 *
10187 * If we fall back to the recompiler/IEM after updating the VMCS and clearing
10188 * the common-state (TRPM/forceflags), we must undo those changes so that the
10189 * recompiler/IEM can (and should) use them when it resumes guest execution.
10190 * Otherwise such operations must be done when we can no longer exit to ring-3.
10191 *
10192 * @returns Strict VBox status code (i.e. informational status codes too).
10193 * @retval VINF_SUCCESS if we can proceed with running the guest, interrupts
10194 * have been disabled.
10195 * @retval VINF_VMX_VMEXIT if a nested-guest VM-exit occurs (e.g., while evaluating
10196 * pending events).
10197 * @retval VINF_EM_RESET if a triple-fault occurs while injecting a
10198 * double-fault into the guest.
10199 * @retval VINF_EM_DBG_STEPPED if @a fStepping is true and an event was
10200 * dispatched directly.
10201 * @retval VINF_* scheduling changes, we have to go back to ring-3.
10202 *
10203 * @param pVCpu The cross context virtual CPU structure.
10204 * @param pVmxTransient The VMX-transient structure.
10205 * @param fStepping Whether we are single-stepping the guest in the
10206 * hypervisor debugger. Makes us ignore some of the reasons
10207 * for returning to ring-3, and return VINF_EM_DBG_STEPPED
10208 * if event dispatching took place.
10209 */
10210static VBOXSTRICTRC hmR0VmxPreRunGuest(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient, bool fStepping)
10211{
10212 Assert(VMMRZCallRing3IsEnabled(pVCpu));
10213
10214 Log4Func(("fIsNested=%RTbool fStepping=%RTbool\n", pVmxTransient->fIsNestedGuest, fStepping));
10215
10216#ifdef VBOX_WITH_NESTED_HWVIRT_ONLY_IN_IEM
10217 if (pVmxTransient->fIsNestedGuest)
10218 {
10219 RT_NOREF2(pVCpu, fStepping);
10220 Log2Func(("Rescheduling to IEM due to nested-hwvirt or forced IEM exec -> VINF_EM_RESCHEDULE_REM\n"));
10221 return VINF_EM_RESCHEDULE_REM;
10222 }
10223#endif
10224
10225#ifdef VBOX_WITH_2X_4GB_ADDR_SPACE_IN_R0
10226 PGMRZDynMapFlushAutoSet(pVCpu);
10227#endif
10228
10229 /*
10230 * Check and process force flag actions, some of which might require us to go back to ring-3.
10231 */
10232 VBOXSTRICTRC rcStrict = hmR0VmxCheckForceFlags(pVCpu, fStepping);
10233 if (rcStrict == VINF_SUCCESS)
10234 {
10235 /* FFs don't get set all the time. */
10236#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
10237 if ( pVmxTransient->fIsNestedGuest
10238 && !CPUMIsGuestInVmxNonRootMode(&pVCpu->cpum.GstCtx))
10239 {
10240 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchNstGstVmexit);
10241 return VINF_VMX_VMEXIT;
10242 }
10243#endif
10244 }
10245 else
10246 return rcStrict;
10247
10248 /*
10249 * Virtualize memory-mapped accesses to the physical APIC (may take locks).
10250 */
10251 /** @todo Doing this from ring-3 after VM setup phase causes a
10252 * VERR_IOM_MMIO_RANGE_NOT_FOUND guru while booting Visa 64 SMP VM. No
10253 * idea why atm. */
10254 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
10255 if ( !pVCpu->hm.s.vmx.u64GstMsrApicBase
10256 && (pVM->hm.s.vmx.Msrs.ProcCtls2.n.allowed1 & VMX_PROC_CTLS2_VIRT_APIC_ACCESS)
10257 && PDMHasApic(pVM))
10258 {
10259 int rc = hmR0VmxMapHCApicAccessPage(pVCpu);
10260 AssertRCReturn(rc, rc);
10261 }
10262
10263#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
10264 /*
10265 * Merge guest VMCS controls with the nested-guest VMCS controls.
10266 *
10267 * Even if we have not executed the guest prior to this (e.g. when resuming from a
10268 * saved state), we should be okay with merging controls as we initialize the
10269 * guest VMCS controls as part of VM setup phase.
10270 */
10271 if ( pVmxTransient->fIsNestedGuest
10272 && !pVCpu->hm.s.vmx.fMergedNstGstCtls)
10273 {
10274 int rc = hmR0VmxMergeVmcsNested(pVCpu);
10275 AssertRCReturn(rc, rc);
10276 pVCpu->hm.s.vmx.fMergedNstGstCtls = true;
10277 }
10278#endif
10279
10280 /*
10281 * Evaluate events to be injected into the guest.
10282 *
10283 * Events in TRPM can be injected without inspecting the guest state.
10284 * If any new events (interrupts/NMI) are pending currently, we try to set up the
10285 * guest to cause a VM-exit the next time they are ready to receive the event.
10286 *
10287 * With nested-guests, evaluating pending events may cause VM-exits.
10288 */
10289 if (TRPMHasTrap(pVCpu))
10290 {
10291 Assert(!pVmxTransient->fIsNestedGuest || !pVCpu->cpum.GstCtx.hwvirt.vmx.fInterceptEvents);
10292 hmR0VmxTrpmTrapToPendingEvent(pVCpu);
10293 }
10294
10295 uint32_t fIntrState;
10296 rcStrict = hmR0VmxEvaluatePendingEvent(pVCpu, pVmxTransient, &fIntrState);
10297
10298#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
10299 /*
10300 * While evaluating pending events if something failed (unlikely) or if we were
10301 * preparing to run a nested-guest but performed a nested-guest VM-exit, we should bail.
10302 */
10303 if (rcStrict != VINF_SUCCESS)
10304 return rcStrict;
10305 if ( pVmxTransient->fIsNestedGuest
10306 && !CPUMIsGuestInVmxNonRootMode(&pVCpu->cpum.GstCtx))
10307 {
10308 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchNstGstVmexit);
10309 return VINF_VMX_VMEXIT;
10310 }
10311#else
10312 Assert(rcStrict == VINF_SUCCESS);
10313#endif
10314
10315 /*
10316 * Event injection may take locks (currently the PGM lock for real-on-v86 case) and thus
10317 * needs to be done with longjmps or interrupts + preemption enabled. Event injection might
10318 * also result in triple-faulting the VM.
10319 *
10320 * With nested-guests, the above does not apply since unrestricted guest execution is a
10321 * requirement. Regardless, we do this here to avoid duplicating code elsewhere.
10322 */
10323 rcStrict = hmR0VmxInjectPendingEvent(pVCpu, pVmxTransient, fIntrState, fStepping);
10324 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
10325 { /* likely */ }
10326 else
10327 {
10328 AssertMsg(rcStrict == VINF_EM_RESET || (rcStrict == VINF_EM_DBG_STEPPED && fStepping),
10329 ("%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
10330 return rcStrict;
10331 }
10332
10333 /*
10334 * A longjump might result in importing CR3 even for VM-exits that don't necessarily
10335 * import CR3 themselves. We will need to update them here, as even as late as the above
10336 * hmR0VmxInjectPendingEvent() call may lazily import guest-CPU state on demand causing
10337 * the below force flags to be set.
10338 */
10339 if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_HM_UPDATE_CR3))
10340 {
10341 Assert(!(ASMAtomicUoReadU64(&pVCpu->cpum.GstCtx.fExtrn) & CPUMCTX_EXTRN_CR3));
10342 int rc2 = PGMUpdateCR3(pVCpu, CPUMGetGuestCR3(pVCpu));
10343 AssertMsgReturn(rc2 == VINF_SUCCESS || rc2 == VINF_PGM_SYNC_CR3,
10344 ("%Rrc\n", rc2), RT_FAILURE_NP(rc2) ? rc2 : VERR_IPE_UNEXPECTED_INFO_STATUS);
10345 Assert(!VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_HM_UPDATE_CR3));
10346 }
10347 if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_HM_UPDATE_PAE_PDPES))
10348 {
10349 PGMGstUpdatePaePdpes(pVCpu, &pVCpu->hm.s.aPdpes[0]);
10350 Assert(!VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_HM_UPDATE_PAE_PDPES));
10351 }
10352
10353#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
10354 /* Paranoia. */
10355 Assert(!pVmxTransient->fIsNestedGuest || CPUMIsGuestInVmxNonRootMode(&pVCpu->cpum.GstCtx));
10356#endif
10357
10358 /*
10359 * No longjmps to ring-3 from this point on!!!
10360 * Asserts() will still longjmp to ring-3 (but won't return), which is intentional, better than a kernel panic.
10361 * This also disables flushing of the R0-logger instance (if any).
10362 */
10363 VMMRZCallRing3Disable(pVCpu);
10364
10365 /*
10366 * Export the guest state bits.
10367 *
10368 * We cannot perform longjmps while loading the guest state because we do not preserve the
10369 * host/guest state (although the VMCS will be preserved) across longjmps which can cause
10370 * CPU migration.
10371 *
10372 * If we are injecting events to a real-on-v86 mode guest, we would have updated RIP and some segment
10373 * registers. Hence, exporting of the guest state needs to be done -after- injection of events.
10374 */
10375 rcStrict = hmR0VmxExportGuestStateOptimal(pVCpu, pVmxTransient);
10376 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
10377 { /* likely */ }
10378 else
10379 {
10380 VMMRZCallRing3Enable(pVCpu);
10381 return rcStrict;
10382 }
10383
10384 /*
10385 * We disable interrupts so that we don't miss any interrupts that would flag preemption
10386 * (IPI/timers etc.) when thread-context hooks aren't used and we've been running with
10387 * preemption disabled for a while. Since this is purely to aid the
10388 * RTThreadPreemptIsPending() code, it doesn't matter that it may temporarily reenable and
10389 * disable interrupt on NT.
10390 *
10391 * We need to check for force-flags that could've possible been altered since we last
10392 * checked them (e.g. by PDMGetInterrupt() leaving the PDM critical section,
10393 * see @bugref{6398}).
10394 *
10395 * We also check a couple of other force-flags as a last opportunity to get the EMT back
10396 * to ring-3 before executing guest code.
10397 */
10398 pVmxTransient->fEFlags = ASMIntDisableFlags();
10399
10400 if ( ( !VM_FF_IS_ANY_SET(pVM, VM_FF_EMT_RENDEZVOUS | VM_FF_TM_VIRTUAL_SYNC)
10401 && !VMCPU_FF_IS_ANY_SET(pVCpu, VMCPU_FF_HM_TO_R3_MASK))
10402 || ( fStepping /* Optimized for the non-stepping case, so a bit of unnecessary work when stepping. */
10403 && !VMCPU_FF_IS_ANY_SET(pVCpu, VMCPU_FF_HM_TO_R3_MASK & ~(VMCPU_FF_TIMER | VMCPU_FF_PDM_CRITSECT))) )
10404 {
10405 if (!RTThreadPreemptIsPending(NIL_RTTHREAD))
10406 {
10407#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
10408 /*
10409 * If we are executing a nested-guest make sure that we should intercept subsequent
10410 * events. The one we are injecting might be part of VM-entry. This is mainly to keep
10411 * the VM-exit instruction emulation happy.
10412 */
10413 if (pVmxTransient->fIsNestedGuest)
10414 pVCpu->cpum.GstCtx.hwvirt.vmx.fInterceptEvents = true;
10415#endif
10416
10417 /*
10418 * We've injected any pending events. This is really the point of no return (to ring-3).
10419 *
10420 * Note! The caller expects to continue with interrupts & longjmps disabled on successful
10421 * returns from this function, so do -not- enable them here.
10422 */
10423 pVCpu->hm.s.Event.fPending = false;
10424 return VINF_SUCCESS;
10425 }
10426
10427 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchPendingHostIrq);
10428 rcStrict = VINF_EM_RAW_INTERRUPT;
10429 }
10430 else
10431 {
10432 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchHmToR3FF);
10433 rcStrict = VINF_EM_RAW_TO_R3;
10434 }
10435
10436 ASMSetFlags(pVmxTransient->fEFlags);
10437 VMMRZCallRing3Enable(pVCpu);
10438
10439 return rcStrict;
10440}
10441
10442
10443/**
10444 * Final preparations before executing guest code using hardware-assisted VMX.
10445 *
10446 * We can no longer get preempted to a different host CPU and there are no returns
10447 * to ring-3. We ignore any errors that may happen from this point (e.g. VMWRITE
10448 * failures), this function is not intended to fail sans unrecoverable hardware
10449 * errors.
10450 *
10451 * @param pVCpu The cross context virtual CPU structure.
10452 * @param pVmxTransient The VMX-transient structure.
10453 *
10454 * @remarks Called with preemption disabled.
10455 * @remarks No-long-jump zone!!!
10456 */
10457static void hmR0VmxPreRunGuestCommitted(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
10458{
10459 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
10460 Assert(VMMR0IsLogFlushDisabled(pVCpu));
10461 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
10462 Assert(!pVCpu->hm.s.Event.fPending);
10463
10464 /*
10465 * Indicate start of guest execution and where poking EMT out of guest-context is recognized.
10466 */
10467 VMCPU_ASSERT_STATE(pVCpu, VMCPUSTATE_STARTED_HM);
10468 VMCPU_SET_STATE(pVCpu, VMCPUSTATE_STARTED_EXEC);
10469
10470 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
10471 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
10472 PHMPHYSCPU pHostCpu = hmR0GetCurrentCpu();
10473 RTCPUID const idCurrentCpu = pHostCpu->idCpu;
10474
10475 if (!CPUMIsGuestFPUStateActive(pVCpu))
10476 {
10477 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatLoadGuestFpuState, x);
10478 if (CPUMR0LoadGuestFPU(pVM, pVCpu) == VINF_CPUM_HOST_CR0_MODIFIED)
10479 pVCpu->hm.s.fCtxChanged |= HM_CHANGED_HOST_CONTEXT;
10480 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatLoadGuestFpuState, x);
10481 STAM_COUNTER_INC(&pVCpu->hm.s.StatLoadGuestFpu);
10482 }
10483
10484 /*
10485 * Re-export the host state bits as we may've been preempted (only happens when
10486 * thread-context hooks are used or when the VM start function changes) or if
10487 * the host CR0 is modified while loading the guest FPU state above.
10488 *
10489 * The 64-on-32 switcher saves the (64-bit) host state into the VMCS and if we
10490 * changed the switcher back to 32-bit, we *must* save the 32-bit host state here,
10491 * see @bugref{8432}.
10492 *
10493 * This may also happen when switching to/from a nested-guest VMCS without leaving
10494 * ring-0.
10495 */
10496 if (pVCpu->hm.s.fCtxChanged & HM_CHANGED_HOST_CONTEXT)
10497 {
10498 hmR0VmxExportHostState(pVCpu);
10499 STAM_COUNTER_INC(&pVCpu->hm.s.StatExportHostState);
10500 }
10501 Assert(!(pVCpu->hm.s.fCtxChanged & HM_CHANGED_HOST_CONTEXT));
10502
10503 /*
10504 * Export the state shared between host and guest (FPU, debug, lazy MSRs).
10505 */
10506 if (pVCpu->hm.s.fCtxChanged & HM_CHANGED_VMX_HOST_GUEST_SHARED_STATE)
10507 hmR0VmxExportSharedState(pVCpu, pVmxTransient);
10508 AssertMsg(!pVCpu->hm.s.fCtxChanged, ("fCtxChanged=%#RX64\n", pVCpu->hm.s.fCtxChanged));
10509
10510 /*
10511 * Store status of the shared guest/host debug state at the time of VM-entry.
10512 */
10513 pVmxTransient->fWasGuestDebugStateActive = CPUMIsGuestDebugStateActive(pVCpu);
10514 pVmxTransient->fWasHyperDebugStateActive = CPUMIsHyperDebugStateActive(pVCpu);
10515
10516 /*
10517 * Always cache the TPR-shadow if the virtual-APIC page exists, thereby skipping
10518 * more than one conditional check. The post-run side of our code shall determine
10519 * if it needs to sync. the virtual APIC TPR with the TPR-shadow.
10520 */
10521 if (pVmcsInfo->pbVirtApic)
10522 pVmxTransient->u8GuestTpr = pVmcsInfo->pbVirtApic[XAPIC_OFF_TPR];
10523
10524 /*
10525 * Update the host MSRs values in the VM-exit MSR-load area.
10526 */
10527 if (!pVCpu->hm.s.vmx.fUpdatedHostAutoMsrs)
10528 {
10529 if (pVmcsInfo->cExitMsrLoad > 0)
10530 hmR0VmxUpdateAutoLoadHostMsrs(pVCpu, pVmcsInfo);
10531 pVCpu->hm.s.vmx.fUpdatedHostAutoMsrs = true;
10532 }
10533
10534 /*
10535 * Evaluate if we need to intercept guest RDTSC/P accesses. Set up the
10536 * VMX-preemption timer based on the next virtual sync clock deadline.
10537 */
10538 if ( !pVmxTransient->fUpdatedTscOffsettingAndPreemptTimer
10539 || idCurrentCpu != pVCpu->hm.s.idLastCpu)
10540 {
10541 hmR0VmxUpdateTscOffsettingAndPreemptTimer(pVCpu, pVmxTransient);
10542 pVmxTransient->fUpdatedTscOffsettingAndPreemptTimer = true;
10543 }
10544
10545 /* Record statistics of how often we use TSC offsetting as opposed to intercepting RDTSC/P. */
10546 bool const fIsRdtscIntercepted = RT_BOOL(pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_RDTSC_EXIT);
10547 if (!fIsRdtscIntercepted)
10548 STAM_COUNTER_INC(&pVCpu->hm.s.StatTscOffset);
10549 else
10550 STAM_COUNTER_INC(&pVCpu->hm.s.StatTscIntercept);
10551
10552 ASMAtomicWriteBool(&pVCpu->hm.s.fCheckedTLBFlush, true); /* Used for TLB flushing, set this across the world switch. */
10553 hmR0VmxFlushTaggedTlb(pHostCpu, pVCpu, pVmcsInfo); /* Invalidate the appropriate guest entries from the TLB. */
10554 Assert(idCurrentCpu == pVCpu->hm.s.idLastCpu);
10555 pVCpu->hm.s.vmx.LastError.idCurrentCpu = idCurrentCpu; /* Record the error reporting info. with the current host CPU. */
10556 pVmcsInfo->idHostCpuState = idCurrentCpu; /* Record the CPU for which the host-state has been exported. */
10557 pVmcsInfo->idHostCpuExec = idCurrentCpu; /* Record the CPU on which we shall execute. */
10558
10559 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatEntry, &pVCpu->hm.s.StatInGC, x);
10560
10561 TMNotifyStartOfExecution(pVM, pVCpu); /* Notify TM to resume its clocks when TSC is tied to execution,
10562 as we're about to start executing the guest. */
10563
10564 /*
10565 * Load the guest TSC_AUX MSR when we are not intercepting RDTSCP.
10566 *
10567 * This is done this late as updating the TSC offsetting/preemption timer above
10568 * figures out if we can skip intercepting RDTSCP by calculating the number of
10569 * host CPU ticks till the next virtual sync deadline (for the dynamic case).
10570 */
10571 if ( (pVmcsInfo->u32ProcCtls2 & VMX_PROC_CTLS2_RDTSCP)
10572 && !fIsRdtscIntercepted)
10573 {
10574 hmR0VmxImportGuestState(pVCpu, pVmcsInfo, CPUMCTX_EXTRN_TSC_AUX);
10575
10576 /* NB: Because we call hmR0VmxAddAutoLoadStoreMsr with fUpdateHostMsr=true,
10577 it's safe even after hmR0VmxUpdateAutoLoadHostMsrs has already been done. */
10578 int rc = hmR0VmxAddAutoLoadStoreMsr(pVCpu, pVmxTransient, MSR_K8_TSC_AUX, CPUMGetGuestTscAux(pVCpu),
10579 true /* fSetReadWrite */, true /* fUpdateHostMsr */);
10580 AssertRC(rc);
10581 Assert(!pVmxTransient->fRemoveTscAuxMsr);
10582 pVmxTransient->fRemoveTscAuxMsr = true;
10583 }
10584
10585#ifdef VBOX_STRICT
10586 Assert(pVCpu->hm.s.vmx.fUpdatedHostAutoMsrs);
10587 hmR0VmxCheckAutoLoadStoreMsrs(pVCpu, pVmcsInfo, pVmxTransient->fIsNestedGuest);
10588 hmR0VmxCheckHostEferMsr(pVCpu, pVmcsInfo);
10589 AssertRC(hmR0VmxCheckVmcsCtls(pVCpu, pVmcsInfo, pVmxTransient->fIsNestedGuest));
10590#endif
10591
10592#ifdef HMVMX_ALWAYS_CHECK_GUEST_STATE
10593 /** @todo r=ramshankar: We can now probably use iemVmxVmentryCheckGuestState here.
10594 * Add a PVMXMSRS parameter to it, so that IEM can look at the host MSRs,
10595 * see @bugref{9180#c54}. */
10596 uint32_t const uInvalidReason = hmR0VmxCheckGuestState(pVCpu, pVmcsInfo);
10597 if (uInvalidReason != VMX_IGS_REASON_NOT_FOUND)
10598 Log4(("hmR0VmxCheckGuestState returned %#x\n", uInvalidReason));
10599#endif
10600}
10601
10602
10603/**
10604 * First C routine invoked after running guest code using hardware-assisted VMX.
10605 *
10606 * @param pVCpu The cross context virtual CPU structure.
10607 * @param pVmxTransient The VMX-transient structure.
10608 * @param rcVMRun Return code of VMLAUNCH/VMRESUME.
10609 *
10610 * @remarks Called with interrupts disabled, and returns with interrupts enabled!
10611 *
10612 * @remarks No-long-jump zone!!! This function will however re-enable longjmps
10613 * unconditionally when it is safe to do so.
10614 */
10615static void hmR0VmxPostRunGuest(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient, int rcVMRun)
10616{
10617 uint64_t const uHostTsc = ASMReadTSC(); /** @todo We can do a lot better here, see @bugref{9180#c38}. */
10618
10619 ASMAtomicWriteBool(&pVCpu->hm.s.fCheckedTLBFlush, false); /* See HMInvalidatePageOnAllVCpus(): used for TLB flushing. */
10620 ASMAtomicIncU32(&pVCpu->hm.s.cWorldSwitchExits); /* Initialized in vmR3CreateUVM(): used for EMT poking. */
10621 pVCpu->hm.s.fCtxChanged = 0; /* Exits/longjmps to ring-3 requires saving the guest state. */
10622 pVmxTransient->fVmcsFieldsRead = 0; /* Transient fields need to be read from the VMCS. */
10623 pVmxTransient->fVectoringPF = false; /* Vectoring page-fault needs to be determined later. */
10624 pVmxTransient->fVectoringDoublePF = false; /* Vectoring double page-fault needs to be determined later. */
10625
10626 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
10627 if (!(pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_RDTSC_EXIT))
10628 {
10629 uint64_t uGstTsc;
10630 if (!pVmxTransient->fIsNestedGuest)
10631 uGstTsc = uHostTsc + pVmcsInfo->u64TscOffset;
10632 else
10633 {
10634 uint64_t const uNstGstTsc = uHostTsc + pVmcsInfo->u64TscOffset;
10635 uGstTsc = CPUMRemoveNestedGuestTscOffset(pVCpu, uNstGstTsc);
10636 }
10637 TMCpuTickSetLastSeen(pVCpu, uGstTsc); /* Update TM with the guest TSC. */
10638 }
10639
10640 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatInGC, &pVCpu->hm.s.StatPreExit, x);
10641 TMNotifyEndOfExecution(pVCpu->CTX_SUFF(pVM), pVCpu); /* Notify TM that the guest is no longer running. */
10642 VMCPU_SET_STATE(pVCpu, VMCPUSTATE_STARTED_HM);
10643
10644 pVCpu->hm.s.vmx.fRestoreHostFlags |= VMX_RESTORE_HOST_REQUIRED; /* Some host state messed up by VMX needs restoring. */
10645 pVmcsInfo->fVmcsState |= VMX_V_VMCS_LAUNCH_STATE_LAUNCHED; /* Use VMRESUME instead of VMLAUNCH in the next run. */
10646#ifdef VBOX_STRICT
10647 hmR0VmxCheckHostEferMsr(pVCpu, pVmcsInfo); /* Verify that the host EFER MSR wasn't modified. */
10648#endif
10649 Assert(!ASMIntAreEnabled());
10650 ASMSetFlags(pVmxTransient->fEFlags); /* Enable interrupts. */
10651 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
10652
10653#ifdef HMVMX_ALWAYS_CLEAN_TRANSIENT
10654 /*
10655 * Clean all the VMCS fields in the transient structure before reading
10656 * anything from the VMCS.
10657 */
10658 pVmxTransient->uExitReason = 0;
10659 pVmxTransient->uExitIntErrorCode = 0;
10660 pVmxTransient->uExitQual = 0;
10661 pVmxTransient->uGuestLinearAddr = 0;
10662 pVmxTransient->uExitIntInfo = 0;
10663 pVmxTransient->cbExitInstr = 0;
10664 pVmxTransient->ExitInstrInfo.u = 0;
10665 pVmxTransient->uEntryIntInfo = 0;
10666 pVmxTransient->uEntryXcptErrorCode = 0;
10667 pVmxTransient->cbEntryInstr = 0;
10668 pVmxTransient->uIdtVectoringInfo = 0;
10669 pVmxTransient->uIdtVectoringErrorCode = 0;
10670#endif
10671
10672 /*
10673 * Save the basic VM-exit reason and check if the VM-entry failed.
10674 * See Intel spec. 24.9.1 "Basic VM-exit Information".
10675 */
10676 uint32_t uExitReason;
10677 int rc = VMXReadVmcs32(VMX_VMCS32_RO_EXIT_REASON, &uExitReason);
10678 AssertRC(rc);
10679 pVmxTransient->uExitReason = VMX_EXIT_REASON_BASIC(uExitReason);
10680 pVmxTransient->fVMEntryFailed = VMX_EXIT_REASON_HAS_ENTRY_FAILED(uExitReason);
10681
10682 /*
10683 * Log the VM-exit before logging anything else as otherwise it might be a
10684 * tad confusing what happens before and after the world-switch.
10685 */
10686 HMVMX_LOG_EXIT(pVCpu, uExitReason);
10687
10688 /*
10689 * Remove the TSC_AUX MSR from the auto-load/store MSR area and reset any MSR
10690 * bitmap permissions, if it was added before VM-entry.
10691 */
10692 if (pVmxTransient->fRemoveTscAuxMsr)
10693 {
10694 hmR0VmxRemoveAutoLoadStoreMsr(pVCpu, pVmxTransient, MSR_K8_TSC_AUX);
10695 pVmxTransient->fRemoveTscAuxMsr = false;
10696 }
10697
10698 /*
10699 * Check if VMLAUNCH/VMRESUME succeeded.
10700 * If this failed, we cause a guru meditation and cease further execution.
10701 *
10702 * However, if we are executing a nested-guest we might fail if we use the
10703 * fast path rather than fully emulating VMLAUNCH/VMRESUME instruction in IEM.
10704 */
10705 if (RT_LIKELY(rcVMRun == VINF_SUCCESS))
10706 {
10707 /*
10708 * Update the VM-exit history array here even if the VM-entry failed due to:
10709 * - Invalid guest state.
10710 * - MSR loading.
10711 * - Machine-check event.
10712 *
10713 * In any of the above cases we will still have a "valid" VM-exit reason
10714 * despite @a fVMEntryFailed being false.
10715 *
10716 * See Intel spec. 26.7 "VM-Entry failures during or after loading guest state".
10717 *
10718 * Note! We don't have CS or RIP at this point. Will probably address that later
10719 * by amending the history entry added here.
10720 */
10721 EMHistoryAddExit(pVCpu, EMEXIT_MAKE_FT(EMEXIT_F_KIND_VMX, pVmxTransient->uExitReason & EMEXIT_F_TYPE_MASK),
10722 UINT64_MAX, uHostTsc);
10723
10724 if (RT_LIKELY(!pVmxTransient->fVMEntryFailed))
10725 {
10726 VMMRZCallRing3Enable(pVCpu);
10727
10728 Assert(!VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_HM_UPDATE_CR3));
10729 Assert(!VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_HM_UPDATE_PAE_PDPES));
10730
10731#ifdef HMVMX_ALWAYS_SAVE_RO_GUEST_STATE
10732 hmR0VmxReadAllRoFieldsVmcs(pVmxTransient);
10733#endif
10734#if defined(HMVMX_ALWAYS_SYNC_FULL_GUEST_STATE) || defined(HMVMX_ALWAYS_SAVE_FULL_GUEST_STATE)
10735 rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, HMVMX_CPUMCTX_EXTRN_ALL);
10736 AssertRC(rc);
10737#elif defined(HMVMX_ALWAYS_SAVE_GUEST_RFLAGS)
10738 rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, HMVMX_CPUMCTX_EXTRN_RFLAGS);
10739 AssertRC(rc);
10740#else
10741 /*
10742 * Import the guest-interruptibility state always as we need it while evaluating
10743 * injecting events on re-entry.
10744 *
10745 * We don't import CR0 (when unrestricted guest execution is unavailable) despite
10746 * checking for real-mode while exporting the state because all bits that cause
10747 * mode changes wrt CR0 are intercepted.
10748 */
10749 rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, CPUMCTX_EXTRN_HM_VMX_INT_STATE);
10750 AssertRC(rc);
10751#endif
10752
10753 /*
10754 * Sync the TPR shadow with our APIC state.
10755 */
10756 if ( !pVmxTransient->fIsNestedGuest
10757 && (pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_USE_TPR_SHADOW))
10758 {
10759 Assert(pVmcsInfo->pbVirtApic);
10760 if (pVmxTransient->u8GuestTpr != pVmcsInfo->pbVirtApic[XAPIC_OFF_TPR])
10761 {
10762 rc = APICSetTpr(pVCpu, pVmcsInfo->pbVirtApic[XAPIC_OFF_TPR]);
10763 AssertRC(rc);
10764 ASMAtomicOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_APIC_TPR);
10765 }
10766 }
10767
10768 Assert(VMMRZCallRing3IsEnabled(pVCpu));
10769 return;
10770 }
10771 }
10772#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
10773 else if (pVmxTransient->fIsNestedGuest)
10774 AssertMsgFailed(("VMLAUNCH/VMRESUME failed but shouldn't happen when VMLAUNCH/VMRESUME was emulated in IEM!\n"));
10775#endif
10776 else
10777 Log4Func(("VM-entry failure: rcVMRun=%Rrc fVMEntryFailed=%RTbool\n", rcVMRun, pVmxTransient->fVMEntryFailed));
10778
10779 VMMRZCallRing3Enable(pVCpu);
10780}
10781
10782
10783/**
10784 * Runs the guest code using hardware-assisted VMX the normal way.
10785 *
10786 * @returns VBox status code.
10787 * @param pVCpu The cross context virtual CPU structure.
10788 * @param pcLoops Pointer to the number of executed loops.
10789 */
10790static VBOXSTRICTRC hmR0VmxRunGuestCodeNormal(PVMCPUCC pVCpu, uint32_t *pcLoops)
10791{
10792 uint32_t const cMaxResumeLoops = pVCpu->CTX_SUFF(pVM)->hm.s.cMaxResumeLoops;
10793 Assert(pcLoops);
10794 Assert(*pcLoops <= cMaxResumeLoops);
10795 Assert(!CPUMIsGuestInVmxNonRootMode(&pVCpu->cpum.GstCtx));
10796
10797#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
10798 /*
10799 * Switch to the guest VMCS as we may have transitioned from executing the nested-guest
10800 * without leaving ring-0. Otherwise, if we came from ring-3 we would have loaded the
10801 * guest VMCS while entering the VMX ring-0 session.
10802 */
10803 if (pVCpu->hm.s.vmx.fSwitchedToNstGstVmcs)
10804 {
10805 int rc = hmR0VmxSwitchToGstOrNstGstVmcs(pVCpu, false /* fSwitchToNstGstVmcs */);
10806 if (RT_SUCCESS(rc))
10807 { /* likely */ }
10808 else
10809 {
10810 LogRelFunc(("Failed to switch to the guest VMCS. rc=%Rrc\n", rc));
10811 return rc;
10812 }
10813 }
10814#endif
10815
10816 VMXTRANSIENT VmxTransient;
10817 RT_ZERO(VmxTransient);
10818 VmxTransient.pVmcsInfo = hmGetVmxActiveVmcsInfo(pVCpu);
10819
10820 /* Paranoia. */
10821 Assert(VmxTransient.pVmcsInfo == &pVCpu->hm.s.vmx.VmcsInfo);
10822
10823 VBOXSTRICTRC rcStrict = VERR_INTERNAL_ERROR_5;
10824 for (;;)
10825 {
10826 Assert(!HMR0SuspendPending());
10827 HMVMX_ASSERT_CPU_SAFE(pVCpu);
10828 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatEntry, x);
10829
10830 /*
10831 * Preparatory work for running nested-guest code, this may force us to
10832 * return to ring-3.
10833 *
10834 * Warning! This bugger disables interrupts on VINF_SUCCESS!
10835 */
10836 rcStrict = hmR0VmxPreRunGuest(pVCpu, &VmxTransient, false /* fStepping */);
10837 if (rcStrict != VINF_SUCCESS)
10838 break;
10839
10840 /* Interrupts are disabled at this point! */
10841 hmR0VmxPreRunGuestCommitted(pVCpu, &VmxTransient);
10842 int rcRun = hmR0VmxRunGuest(pVCpu, &VmxTransient);
10843 hmR0VmxPostRunGuest(pVCpu, &VmxTransient, rcRun);
10844 /* Interrupts are re-enabled at this point! */
10845
10846 /*
10847 * Check for errors with running the VM (VMLAUNCH/VMRESUME).
10848 */
10849 if (RT_SUCCESS(rcRun))
10850 { /* very likely */ }
10851 else
10852 {
10853 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatPreExit, x);
10854 hmR0VmxReportWorldSwitchError(pVCpu, rcRun, &VmxTransient);
10855 return rcRun;
10856 }
10857
10858 /*
10859 * Profile the VM-exit.
10860 */
10861 AssertMsg(VmxTransient.uExitReason <= VMX_EXIT_MAX, ("%#x\n", VmxTransient.uExitReason));
10862 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitAll);
10863 STAM_COUNTER_INC(&pVCpu->hm.s.paStatExitReasonR0[VmxTransient.uExitReason & MASK_EXITREASON_STAT]);
10864 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatPreExit, &pVCpu->hm.s.StatExitHandling, x);
10865 HMVMX_START_EXIT_DISPATCH_PROF();
10866
10867 VBOXVMM_R0_HMVMX_VMEXIT_NOCTX(pVCpu, &pVCpu->cpum.GstCtx, VmxTransient.uExitReason);
10868
10869 /*
10870 * Handle the VM-exit.
10871 */
10872#ifdef HMVMX_USE_FUNCTION_TABLE
10873 rcStrict = g_apfnVMExitHandlers[VmxTransient.uExitReason](pVCpu, &VmxTransient);
10874#else
10875 rcStrict = hmR0VmxHandleExit(pVCpu, &VmxTransient);
10876#endif
10877 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExitHandling, x);
10878 if (rcStrict == VINF_SUCCESS)
10879 {
10880 if (++(*pcLoops) <= cMaxResumeLoops)
10881 continue;
10882 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchMaxResumeLoops);
10883 rcStrict = VINF_EM_RAW_INTERRUPT;
10884 }
10885 break;
10886 }
10887
10888 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatEntry, x);
10889 return rcStrict;
10890}
10891
10892
10893#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
10894/**
10895 * Runs the nested-guest code using hardware-assisted VMX.
10896 *
10897 * @returns VBox status code.
10898 * @param pVCpu The cross context virtual CPU structure.
10899 * @param pcLoops Pointer to the number of executed loops.
10900 *
10901 * @sa hmR0VmxRunGuestCodeNormal.
10902 */
10903static VBOXSTRICTRC hmR0VmxRunGuestCodeNested(PVMCPUCC pVCpu, uint32_t *pcLoops)
10904{
10905 uint32_t const cMaxResumeLoops = pVCpu->CTX_SUFF(pVM)->hm.s.cMaxResumeLoops;
10906 Assert(pcLoops);
10907 Assert(*pcLoops <= cMaxResumeLoops);
10908 Assert(CPUMIsGuestInVmxNonRootMode(&pVCpu->cpum.GstCtx));
10909
10910 /*
10911 * Switch to the nested-guest VMCS as we may have transitioned from executing the
10912 * guest without leaving ring-0. Otherwise, if we came from ring-3 we would have
10913 * loaded the nested-guest VMCS while entering the VMX ring-0 session.
10914 */
10915 if (!pVCpu->hm.s.vmx.fSwitchedToNstGstVmcs)
10916 {
10917 int rc = hmR0VmxSwitchToGstOrNstGstVmcs(pVCpu, true /* fSwitchToNstGstVmcs */);
10918 if (RT_SUCCESS(rc))
10919 { /* likely */ }
10920 else
10921 {
10922 LogRelFunc(("Failed to switch to the nested-guest VMCS. rc=%Rrc\n", rc));
10923 return rc;
10924 }
10925 }
10926
10927 VMXTRANSIENT VmxTransient;
10928 RT_ZERO(VmxTransient);
10929 VmxTransient.pVmcsInfo = hmGetVmxActiveVmcsInfo(pVCpu);
10930 VmxTransient.fIsNestedGuest = true;
10931
10932 /* Paranoia. */
10933 Assert(VmxTransient.pVmcsInfo == &pVCpu->hm.s.vmx.VmcsInfoNstGst);
10934
10935 VBOXSTRICTRC rcStrict = VERR_INTERNAL_ERROR_5;
10936 for (;;)
10937 {
10938 Assert(!HMR0SuspendPending());
10939 HMVMX_ASSERT_CPU_SAFE(pVCpu);
10940 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatEntry, x);
10941
10942 /*
10943 * Preparatory work for running guest code, this may force us to
10944 * return to ring-3.
10945 *
10946 * Warning! This bugger disables interrupts on VINF_SUCCESS!
10947 */
10948 rcStrict = hmR0VmxPreRunGuest(pVCpu, &VmxTransient, false /* fStepping */);
10949 if (rcStrict != VINF_SUCCESS)
10950 break;
10951
10952 /* Interrupts are disabled at this point! */
10953 hmR0VmxPreRunGuestCommitted(pVCpu, &VmxTransient);
10954 int rcRun = hmR0VmxRunGuest(pVCpu, &VmxTransient);
10955 hmR0VmxPostRunGuest(pVCpu, &VmxTransient, rcRun);
10956 /* Interrupts are re-enabled at this point! */
10957
10958 /*
10959 * Check for errors with running the VM (VMLAUNCH/VMRESUME).
10960 */
10961 if (RT_SUCCESS(rcRun))
10962 { /* very likely */ }
10963 else
10964 {
10965 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatPreExit, x);
10966 hmR0VmxReportWorldSwitchError(pVCpu, rcRun, &VmxTransient);
10967 return rcRun;
10968 }
10969
10970 /*
10971 * Profile the VM-exit.
10972 */
10973 AssertMsg(VmxTransient.uExitReason <= VMX_EXIT_MAX, ("%#x\n", VmxTransient.uExitReason));
10974 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitAll);
10975 STAM_COUNTER_INC(&pVCpu->hm.s.StatNestedExitAll);
10976 STAM_COUNTER_INC(&pVCpu->hm.s.paStatNestedExitReasonR0[VmxTransient.uExitReason & MASK_EXITREASON_STAT]);
10977 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatPreExit, &pVCpu->hm.s.StatExitHandling, x);
10978 HMVMX_START_EXIT_DISPATCH_PROF();
10979
10980 VBOXVMM_R0_HMVMX_VMEXIT_NOCTX(pVCpu, &pVCpu->cpum.GstCtx, VmxTransient.uExitReason);
10981
10982 /*
10983 * Handle the VM-exit.
10984 */
10985 rcStrict = hmR0VmxHandleExitNested(pVCpu, &VmxTransient);
10986 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExitHandling, x);
10987 if (rcStrict == VINF_SUCCESS)
10988 {
10989 if (!CPUMIsGuestInVmxNonRootMode(&pVCpu->cpum.GstCtx))
10990 {
10991 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchNstGstVmexit);
10992 rcStrict = VINF_VMX_VMEXIT;
10993 }
10994 else
10995 {
10996 if (++(*pcLoops) <= cMaxResumeLoops)
10997 continue;
10998 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchMaxResumeLoops);
10999 rcStrict = VINF_EM_RAW_INTERRUPT;
11000 }
11001 }
11002 else
11003 Assert(rcStrict != VINF_VMX_VMEXIT);
11004 break;
11005 }
11006
11007 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatEntry, x);
11008 return rcStrict;
11009}
11010#endif /* VBOX_WITH_NESTED_HWVIRT_VMX */
11011
11012
11013/** @name Execution loop for single stepping, DBGF events and expensive Dtrace
11014 * probes.
11015 *
11016 * The following few functions and associated structure contains the bloat
11017 * necessary for providing detailed debug events and dtrace probes as well as
11018 * reliable host side single stepping. This works on the principle of
11019 * "subclassing" the normal execution loop and workers. We replace the loop
11020 * method completely and override selected helpers to add necessary adjustments
11021 * to their core operation.
11022 *
11023 * The goal is to keep the "parent" code lean and mean, so as not to sacrifice
11024 * any performance for debug and analysis features.
11025 *
11026 * @{
11027 */
11028
11029/**
11030 * Transient per-VCPU debug state of VMCS and related info. we save/restore in
11031 * the debug run loop.
11032 */
11033typedef struct VMXRUNDBGSTATE
11034{
11035 /** The RIP we started executing at. This is for detecting that we stepped. */
11036 uint64_t uRipStart;
11037 /** The CS we started executing with. */
11038 uint16_t uCsStart;
11039
11040 /** Whether we've actually modified the 1st execution control field. */
11041 bool fModifiedProcCtls : 1;
11042 /** Whether we've actually modified the 2nd execution control field. */
11043 bool fModifiedProcCtls2 : 1;
11044 /** Whether we've actually modified the exception bitmap. */
11045 bool fModifiedXcptBitmap : 1;
11046
11047 /** We desire the modified the CR0 mask to be cleared. */
11048 bool fClearCr0Mask : 1;
11049 /** We desire the modified the CR4 mask to be cleared. */
11050 bool fClearCr4Mask : 1;
11051 /** Stuff we need in VMX_VMCS32_CTRL_PROC_EXEC. */
11052 uint32_t fCpe1Extra;
11053 /** Stuff we do not want in VMX_VMCS32_CTRL_PROC_EXEC. */
11054 uint32_t fCpe1Unwanted;
11055 /** Stuff we need in VMX_VMCS32_CTRL_PROC_EXEC2. */
11056 uint32_t fCpe2Extra;
11057 /** Extra stuff we need in VMX_VMCS32_CTRL_EXCEPTION_BITMAP. */
11058 uint32_t bmXcptExtra;
11059 /** The sequence number of the Dtrace provider settings the state was
11060 * configured against. */
11061 uint32_t uDtraceSettingsSeqNo;
11062 /** VM-exits to check (one bit per VM-exit). */
11063 uint32_t bmExitsToCheck[3];
11064
11065 /** The initial VMX_VMCS32_CTRL_PROC_EXEC value (helps with restore). */
11066 uint32_t fProcCtlsInitial;
11067 /** The initial VMX_VMCS32_CTRL_PROC_EXEC2 value (helps with restore). */
11068 uint32_t fProcCtls2Initial;
11069 /** The initial VMX_VMCS32_CTRL_EXCEPTION_BITMAP value (helps with restore). */
11070 uint32_t bmXcptInitial;
11071} VMXRUNDBGSTATE;
11072AssertCompileMemberSize(VMXRUNDBGSTATE, bmExitsToCheck, (VMX_EXIT_MAX + 1 + 31) / 32 * 4);
11073typedef VMXRUNDBGSTATE *PVMXRUNDBGSTATE;
11074
11075
11076/**
11077 * Initializes the VMXRUNDBGSTATE structure.
11078 *
11079 * @param pVCpu The cross context virtual CPU structure of the
11080 * calling EMT.
11081 * @param pVmxTransient The VMX-transient structure.
11082 * @param pDbgState The debug state to initialize.
11083 */
11084static void hmR0VmxRunDebugStateInit(PVMCPUCC pVCpu, PCVMXTRANSIENT pVmxTransient, PVMXRUNDBGSTATE pDbgState)
11085{
11086 pDbgState->uRipStart = pVCpu->cpum.GstCtx.rip;
11087 pDbgState->uCsStart = pVCpu->cpum.GstCtx.cs.Sel;
11088
11089 pDbgState->fModifiedProcCtls = false;
11090 pDbgState->fModifiedProcCtls2 = false;
11091 pDbgState->fModifiedXcptBitmap = false;
11092 pDbgState->fClearCr0Mask = false;
11093 pDbgState->fClearCr4Mask = false;
11094 pDbgState->fCpe1Extra = 0;
11095 pDbgState->fCpe1Unwanted = 0;
11096 pDbgState->fCpe2Extra = 0;
11097 pDbgState->bmXcptExtra = 0;
11098 pDbgState->fProcCtlsInitial = pVmxTransient->pVmcsInfo->u32ProcCtls;
11099 pDbgState->fProcCtls2Initial = pVmxTransient->pVmcsInfo->u32ProcCtls2;
11100 pDbgState->bmXcptInitial = pVmxTransient->pVmcsInfo->u32XcptBitmap;
11101}
11102
11103
11104/**
11105 * Updates the VMSC fields with changes requested by @a pDbgState.
11106 *
11107 * This is performed after hmR0VmxPreRunGuestDebugStateUpdate as well
11108 * immediately before executing guest code, i.e. when interrupts are disabled.
11109 * We don't check status codes here as we cannot easily assert or return in the
11110 * latter case.
11111 *
11112 * @param pVCpu The cross context virtual CPU structure.
11113 * @param pVmxTransient The VMX-transient structure.
11114 * @param pDbgState The debug state.
11115 */
11116static void hmR0VmxPreRunGuestDebugStateApply(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient, PVMXRUNDBGSTATE pDbgState)
11117{
11118 /*
11119 * Ensure desired flags in VMCS control fields are set.
11120 * (Ignoring write failure here, as we're committed and it's just debug extras.)
11121 *
11122 * Note! We load the shadow CR0 & CR4 bits when we flag the clearing, so
11123 * there should be no stale data in pCtx at this point.
11124 */
11125 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
11126 if ( (pVmcsInfo->u32ProcCtls & pDbgState->fCpe1Extra) != pDbgState->fCpe1Extra
11127 || (pVmcsInfo->u32ProcCtls & pDbgState->fCpe1Unwanted))
11128 {
11129 pVmcsInfo->u32ProcCtls |= pDbgState->fCpe1Extra;
11130 pVmcsInfo->u32ProcCtls &= ~pDbgState->fCpe1Unwanted;
11131 VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, pVmcsInfo->u32ProcCtls);
11132 Log6Func(("VMX_VMCS32_CTRL_PROC_EXEC: %#RX32\n", pVmcsInfo->u32ProcCtls));
11133 pDbgState->fModifiedProcCtls = true;
11134 }
11135
11136 if ((pVmcsInfo->u32ProcCtls2 & pDbgState->fCpe2Extra) != pDbgState->fCpe2Extra)
11137 {
11138 pVmcsInfo->u32ProcCtls2 |= pDbgState->fCpe2Extra;
11139 VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC2, pVmcsInfo->u32ProcCtls2);
11140 Log6Func(("VMX_VMCS32_CTRL_PROC_EXEC2: %#RX32\n", pVmcsInfo->u32ProcCtls2));
11141 pDbgState->fModifiedProcCtls2 = true;
11142 }
11143
11144 if ((pVmcsInfo->u32XcptBitmap & pDbgState->bmXcptExtra) != pDbgState->bmXcptExtra)
11145 {
11146 pVmcsInfo->u32XcptBitmap |= pDbgState->bmXcptExtra;
11147 VMXWriteVmcs32(VMX_VMCS32_CTRL_EXCEPTION_BITMAP, pVmcsInfo->u32XcptBitmap);
11148 Log6Func(("VMX_VMCS32_CTRL_EXCEPTION_BITMAP: %#RX32\n", pVmcsInfo->u32XcptBitmap));
11149 pDbgState->fModifiedXcptBitmap = true;
11150 }
11151
11152 if (pDbgState->fClearCr0Mask && pVmcsInfo->u64Cr0Mask != 0)
11153 {
11154 pVmcsInfo->u64Cr0Mask = 0;
11155 VMXWriteVmcsNw(VMX_VMCS_CTRL_CR0_MASK, 0);
11156 Log6Func(("VMX_VMCS_CTRL_CR0_MASK: 0\n"));
11157 }
11158
11159 if (pDbgState->fClearCr4Mask && pVmcsInfo->u64Cr4Mask != 0)
11160 {
11161 pVmcsInfo->u64Cr4Mask = 0;
11162 VMXWriteVmcsNw(VMX_VMCS_CTRL_CR4_MASK, 0);
11163 Log6Func(("VMX_VMCS_CTRL_CR4_MASK: 0\n"));
11164 }
11165
11166 NOREF(pVCpu);
11167}
11168
11169
11170/**
11171 * Restores VMCS fields that were changed by hmR0VmxPreRunGuestDebugStateApply for
11172 * re-entry next time around.
11173 *
11174 * @returns Strict VBox status code (i.e. informational status codes too).
11175 * @param pVCpu The cross context virtual CPU structure.
11176 * @param pVmxTransient The VMX-transient structure.
11177 * @param pDbgState The debug state.
11178 * @param rcStrict The return code from executing the guest using single
11179 * stepping.
11180 */
11181static VBOXSTRICTRC hmR0VmxRunDebugStateRevert(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient, PVMXRUNDBGSTATE pDbgState,
11182 VBOXSTRICTRC rcStrict)
11183{
11184 /*
11185 * Restore VM-exit control settings as we may not reenter this function the
11186 * next time around.
11187 */
11188 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
11189
11190 /* We reload the initial value, trigger what we can of recalculations the
11191 next time around. From the looks of things, that's all that's required atm. */
11192 if (pDbgState->fModifiedProcCtls)
11193 {
11194 if (!(pDbgState->fProcCtlsInitial & VMX_PROC_CTLS_MOV_DR_EXIT) && CPUMIsHyperDebugStateActive(pVCpu))
11195 pDbgState->fProcCtlsInitial |= VMX_PROC_CTLS_MOV_DR_EXIT; /* Avoid assertion in hmR0VmxLeave */
11196 int rc2 = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, pDbgState->fProcCtlsInitial);
11197 AssertRC(rc2);
11198 pVmcsInfo->u32ProcCtls = pDbgState->fProcCtlsInitial;
11199 }
11200
11201 /* We're currently the only ones messing with this one, so just restore the
11202 cached value and reload the field. */
11203 if ( pDbgState->fModifiedProcCtls2
11204 && pVmcsInfo->u32ProcCtls2 != pDbgState->fProcCtls2Initial)
11205 {
11206 int rc2 = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC2, pDbgState->fProcCtls2Initial);
11207 AssertRC(rc2);
11208 pVmcsInfo->u32ProcCtls2 = pDbgState->fProcCtls2Initial;
11209 }
11210
11211 /* If we've modified the exception bitmap, we restore it and trigger
11212 reloading and partial recalculation the next time around. */
11213 if (pDbgState->fModifiedXcptBitmap)
11214 pVmcsInfo->u32XcptBitmap = pDbgState->bmXcptInitial;
11215
11216 return rcStrict;
11217}
11218
11219
11220/**
11221 * Configures VM-exit controls for current DBGF and DTrace settings.
11222 *
11223 * This updates @a pDbgState and the VMCS execution control fields to reflect
11224 * the necessary VM-exits demanded by DBGF and DTrace.
11225 *
11226 * @param pVCpu The cross context virtual CPU structure.
11227 * @param pVmxTransient The VMX-transient structure. May update
11228 * fUpdatedTscOffsettingAndPreemptTimer.
11229 * @param pDbgState The debug state.
11230 */
11231static void hmR0VmxPreRunGuestDebugStateUpdate(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient, PVMXRUNDBGSTATE pDbgState)
11232{
11233 /*
11234 * Take down the dtrace serial number so we can spot changes.
11235 */
11236 pDbgState->uDtraceSettingsSeqNo = VBOXVMM_GET_SETTINGS_SEQ_NO();
11237 ASMCompilerBarrier();
11238
11239 /*
11240 * We'll rebuild most of the middle block of data members (holding the
11241 * current settings) as we go along here, so start by clearing it all.
11242 */
11243 pDbgState->bmXcptExtra = 0;
11244 pDbgState->fCpe1Extra = 0;
11245 pDbgState->fCpe1Unwanted = 0;
11246 pDbgState->fCpe2Extra = 0;
11247 for (unsigned i = 0; i < RT_ELEMENTS(pDbgState->bmExitsToCheck); i++)
11248 pDbgState->bmExitsToCheck[i] = 0;
11249
11250 /*
11251 * Software interrupts (INT XXh) - no idea how to trigger these...
11252 */
11253 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
11254 if ( DBGF_IS_EVENT_ENABLED(pVM, DBGFEVENT_INTERRUPT_SOFTWARE)
11255 || VBOXVMM_INT_SOFTWARE_ENABLED())
11256 {
11257 ASMBitSet(pDbgState->bmExitsToCheck, VMX_EXIT_XCPT_OR_NMI);
11258 }
11259
11260 /*
11261 * INT3 breakpoints - triggered by #BP exceptions.
11262 */
11263 if (pVM->dbgf.ro.cEnabledInt3Breakpoints > 0)
11264 pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_BP);
11265
11266 /*
11267 * Exception bitmap and XCPT events+probes.
11268 */
11269 for (int iXcpt = 0; iXcpt < (DBGFEVENT_XCPT_LAST - DBGFEVENT_XCPT_FIRST + 1); iXcpt++)
11270 if (DBGF_IS_EVENT_ENABLED(pVM, (DBGFEVENTTYPE)(DBGFEVENT_XCPT_FIRST + iXcpt)))
11271 pDbgState->bmXcptExtra |= RT_BIT_32(iXcpt);
11272
11273 if (VBOXVMM_XCPT_DE_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_DE);
11274 if (VBOXVMM_XCPT_DB_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_DB);
11275 if (VBOXVMM_XCPT_BP_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_BP);
11276 if (VBOXVMM_XCPT_OF_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_OF);
11277 if (VBOXVMM_XCPT_BR_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_BR);
11278 if (VBOXVMM_XCPT_UD_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_UD);
11279 if (VBOXVMM_XCPT_NM_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_NM);
11280 if (VBOXVMM_XCPT_DF_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_DF);
11281 if (VBOXVMM_XCPT_TS_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_TS);
11282 if (VBOXVMM_XCPT_NP_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_NP);
11283 if (VBOXVMM_XCPT_SS_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_SS);
11284 if (VBOXVMM_XCPT_GP_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_GP);
11285 if (VBOXVMM_XCPT_PF_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_PF);
11286 if (VBOXVMM_XCPT_MF_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_MF);
11287 if (VBOXVMM_XCPT_AC_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_AC);
11288 if (VBOXVMM_XCPT_XF_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_XF);
11289 if (VBOXVMM_XCPT_VE_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_VE);
11290 if (VBOXVMM_XCPT_SX_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_SX);
11291
11292 if (pDbgState->bmXcptExtra)
11293 ASMBitSet(pDbgState->bmExitsToCheck, VMX_EXIT_XCPT_OR_NMI);
11294
11295 /*
11296 * Process events and probes for VM-exits, making sure we get the wanted VM-exits.
11297 *
11298 * Note! This is the reverse of what hmR0VmxHandleExitDtraceEvents does.
11299 * So, when adding/changing/removing please don't forget to update it.
11300 *
11301 * Some of the macros are picking up local variables to save horizontal space,
11302 * (being able to see it in a table is the lesser evil here).
11303 */
11304#define IS_EITHER_ENABLED(a_pVM, a_EventSubName) \
11305 ( DBGF_IS_EVENT_ENABLED(a_pVM, RT_CONCAT(DBGFEVENT_, a_EventSubName)) \
11306 || RT_CONCAT3(VBOXVMM_, a_EventSubName, _ENABLED)() )
11307#define SET_ONLY_XBM_IF_EITHER_EN(a_EventSubName, a_uExit) \
11308 if (IS_EITHER_ENABLED(pVM, a_EventSubName)) \
11309 { AssertCompile((unsigned)(a_uExit) < sizeof(pDbgState->bmExitsToCheck) * 8); \
11310 ASMBitSet((pDbgState)->bmExitsToCheck, a_uExit); \
11311 } else do { } while (0)
11312#define SET_CPE1_XBM_IF_EITHER_EN(a_EventSubName, a_uExit, a_fCtrlProcExec) \
11313 if (IS_EITHER_ENABLED(pVM, a_EventSubName)) \
11314 { \
11315 (pDbgState)->fCpe1Extra |= (a_fCtrlProcExec); \
11316 AssertCompile((unsigned)(a_uExit) < sizeof(pDbgState->bmExitsToCheck) * 8); \
11317 ASMBitSet((pDbgState)->bmExitsToCheck, a_uExit); \
11318 } else do { } while (0)
11319#define SET_CPEU_XBM_IF_EITHER_EN(a_EventSubName, a_uExit, a_fUnwantedCtrlProcExec) \
11320 if (IS_EITHER_ENABLED(pVM, a_EventSubName)) \
11321 { \
11322 (pDbgState)->fCpe1Unwanted |= (a_fUnwantedCtrlProcExec); \
11323 AssertCompile((unsigned)(a_uExit) < sizeof(pDbgState->bmExitsToCheck) * 8); \
11324 ASMBitSet((pDbgState)->bmExitsToCheck, a_uExit); \
11325 } else do { } while (0)
11326#define SET_CPE2_XBM_IF_EITHER_EN(a_EventSubName, a_uExit, a_fCtrlProcExec2) \
11327 if (IS_EITHER_ENABLED(pVM, a_EventSubName)) \
11328 { \
11329 (pDbgState)->fCpe2Extra |= (a_fCtrlProcExec2); \
11330 AssertCompile((unsigned)(a_uExit) < sizeof(pDbgState->bmExitsToCheck) * 8); \
11331 ASMBitSet((pDbgState)->bmExitsToCheck, a_uExit); \
11332 } else do { } while (0)
11333
11334 SET_ONLY_XBM_IF_EITHER_EN(EXIT_TASK_SWITCH, VMX_EXIT_TASK_SWITCH); /* unconditional */
11335 SET_ONLY_XBM_IF_EITHER_EN(EXIT_VMX_EPT_VIOLATION, VMX_EXIT_EPT_VIOLATION); /* unconditional */
11336 SET_ONLY_XBM_IF_EITHER_EN(EXIT_VMX_EPT_MISCONFIG, VMX_EXIT_EPT_MISCONFIG); /* unconditional (unless #VE) */
11337 SET_ONLY_XBM_IF_EITHER_EN(EXIT_VMX_VAPIC_ACCESS, VMX_EXIT_APIC_ACCESS); /* feature dependent, nothing to enable here */
11338 SET_ONLY_XBM_IF_EITHER_EN(EXIT_VMX_VAPIC_WRITE, VMX_EXIT_APIC_WRITE); /* feature dependent, nothing to enable here */
11339
11340 SET_ONLY_XBM_IF_EITHER_EN(INSTR_CPUID, VMX_EXIT_CPUID); /* unconditional */
11341 SET_ONLY_XBM_IF_EITHER_EN( EXIT_CPUID, VMX_EXIT_CPUID);
11342 SET_ONLY_XBM_IF_EITHER_EN(INSTR_GETSEC, VMX_EXIT_GETSEC); /* unconditional */
11343 SET_ONLY_XBM_IF_EITHER_EN( EXIT_GETSEC, VMX_EXIT_GETSEC);
11344 SET_CPE1_XBM_IF_EITHER_EN(INSTR_HALT, VMX_EXIT_HLT, VMX_PROC_CTLS_HLT_EXIT); /* paranoia */
11345 SET_ONLY_XBM_IF_EITHER_EN( EXIT_HALT, VMX_EXIT_HLT);
11346 SET_ONLY_XBM_IF_EITHER_EN(INSTR_INVD, VMX_EXIT_INVD); /* unconditional */
11347 SET_ONLY_XBM_IF_EITHER_EN( EXIT_INVD, VMX_EXIT_INVD);
11348 SET_CPE1_XBM_IF_EITHER_EN(INSTR_INVLPG, VMX_EXIT_INVLPG, VMX_PROC_CTLS_INVLPG_EXIT);
11349 SET_ONLY_XBM_IF_EITHER_EN( EXIT_INVLPG, VMX_EXIT_INVLPG);
11350 SET_CPE1_XBM_IF_EITHER_EN(INSTR_RDPMC, VMX_EXIT_RDPMC, VMX_PROC_CTLS_RDPMC_EXIT);
11351 SET_ONLY_XBM_IF_EITHER_EN( EXIT_RDPMC, VMX_EXIT_RDPMC);
11352 SET_CPE1_XBM_IF_EITHER_EN(INSTR_RDTSC, VMX_EXIT_RDTSC, VMX_PROC_CTLS_RDTSC_EXIT);
11353 SET_ONLY_XBM_IF_EITHER_EN( EXIT_RDTSC, VMX_EXIT_RDTSC);
11354 SET_ONLY_XBM_IF_EITHER_EN(INSTR_RSM, VMX_EXIT_RSM); /* unconditional */
11355 SET_ONLY_XBM_IF_EITHER_EN( EXIT_RSM, VMX_EXIT_RSM);
11356 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMM_CALL, VMX_EXIT_VMCALL); /* unconditional */
11357 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMM_CALL, VMX_EXIT_VMCALL);
11358 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMX_VMCLEAR, VMX_EXIT_VMCLEAR); /* unconditional */
11359 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_VMCLEAR, VMX_EXIT_VMCLEAR);
11360 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMX_VMLAUNCH, VMX_EXIT_VMLAUNCH); /* unconditional */
11361 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_VMLAUNCH, VMX_EXIT_VMLAUNCH);
11362 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMX_VMPTRLD, VMX_EXIT_VMPTRLD); /* unconditional */
11363 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_VMPTRLD, VMX_EXIT_VMPTRLD);
11364 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMX_VMPTRST, VMX_EXIT_VMPTRST); /* unconditional */
11365 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_VMPTRST, VMX_EXIT_VMPTRST);
11366 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMX_VMREAD, VMX_EXIT_VMREAD); /* unconditional */
11367 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_VMREAD, VMX_EXIT_VMREAD);
11368 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMX_VMRESUME, VMX_EXIT_VMRESUME); /* unconditional */
11369 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_VMRESUME, VMX_EXIT_VMRESUME);
11370 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMX_VMWRITE, VMX_EXIT_VMWRITE); /* unconditional */
11371 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_VMWRITE, VMX_EXIT_VMWRITE);
11372 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMX_VMXOFF, VMX_EXIT_VMXOFF); /* unconditional */
11373 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_VMXOFF, VMX_EXIT_VMXOFF);
11374 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMX_VMXON, VMX_EXIT_VMXON); /* unconditional */
11375 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_VMXON, VMX_EXIT_VMXON);
11376
11377 if ( IS_EITHER_ENABLED(pVM, INSTR_CRX_READ)
11378 || IS_EITHER_ENABLED(pVM, INSTR_CRX_WRITE))
11379 {
11380 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, CPUMCTX_EXTRN_CR0 | CPUMCTX_EXTRN_CR4
11381 | CPUMCTX_EXTRN_APIC_TPR);
11382 AssertRC(rc);
11383
11384#if 0 /** @todo fix me */
11385 pDbgState->fClearCr0Mask = true;
11386 pDbgState->fClearCr4Mask = true;
11387#endif
11388 if (IS_EITHER_ENABLED(pVM, INSTR_CRX_READ))
11389 pDbgState->fCpe1Extra |= VMX_PROC_CTLS_CR3_STORE_EXIT | VMX_PROC_CTLS_CR8_STORE_EXIT;
11390 if (IS_EITHER_ENABLED(pVM, INSTR_CRX_WRITE))
11391 pDbgState->fCpe1Extra |= VMX_PROC_CTLS_CR3_LOAD_EXIT | VMX_PROC_CTLS_CR8_LOAD_EXIT;
11392 pDbgState->fCpe1Unwanted |= VMX_PROC_CTLS_USE_TPR_SHADOW; /* risky? */
11393 /* Note! We currently don't use VMX_VMCS32_CTRL_CR3_TARGET_COUNT. It would
11394 require clearing here and in the loop if we start using it. */
11395 ASMBitSet(pDbgState->bmExitsToCheck, VMX_EXIT_MOV_CRX);
11396 }
11397 else
11398 {
11399 if (pDbgState->fClearCr0Mask)
11400 {
11401 pDbgState->fClearCr0Mask = false;
11402 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_CR0);
11403 }
11404 if (pDbgState->fClearCr4Mask)
11405 {
11406 pDbgState->fClearCr4Mask = false;
11407 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_CR4);
11408 }
11409 }
11410 SET_ONLY_XBM_IF_EITHER_EN( EXIT_CRX_READ, VMX_EXIT_MOV_CRX);
11411 SET_ONLY_XBM_IF_EITHER_EN( EXIT_CRX_WRITE, VMX_EXIT_MOV_CRX);
11412
11413 if ( IS_EITHER_ENABLED(pVM, INSTR_DRX_READ)
11414 || IS_EITHER_ENABLED(pVM, INSTR_DRX_WRITE))
11415 {
11416 /** @todo later, need to fix handler as it assumes this won't usually happen. */
11417 ASMBitSet(pDbgState->bmExitsToCheck, VMX_EXIT_MOV_DRX);
11418 }
11419 SET_ONLY_XBM_IF_EITHER_EN( EXIT_DRX_READ, VMX_EXIT_MOV_DRX);
11420 SET_ONLY_XBM_IF_EITHER_EN( EXIT_DRX_WRITE, VMX_EXIT_MOV_DRX);
11421
11422 SET_CPEU_XBM_IF_EITHER_EN(INSTR_RDMSR, VMX_EXIT_RDMSR, VMX_PROC_CTLS_USE_MSR_BITMAPS); /* risky clearing this? */
11423 SET_ONLY_XBM_IF_EITHER_EN( EXIT_RDMSR, VMX_EXIT_RDMSR);
11424 SET_CPEU_XBM_IF_EITHER_EN(INSTR_WRMSR, VMX_EXIT_WRMSR, VMX_PROC_CTLS_USE_MSR_BITMAPS);
11425 SET_ONLY_XBM_IF_EITHER_EN( EXIT_WRMSR, VMX_EXIT_WRMSR);
11426 SET_CPE1_XBM_IF_EITHER_EN(INSTR_MWAIT, VMX_EXIT_MWAIT, VMX_PROC_CTLS_MWAIT_EXIT); /* paranoia */
11427 SET_ONLY_XBM_IF_EITHER_EN( EXIT_MWAIT, VMX_EXIT_MWAIT);
11428 SET_CPE1_XBM_IF_EITHER_EN(INSTR_MONITOR, VMX_EXIT_MONITOR, VMX_PROC_CTLS_MONITOR_EXIT); /* paranoia */
11429 SET_ONLY_XBM_IF_EITHER_EN( EXIT_MONITOR, VMX_EXIT_MONITOR);
11430#if 0 /** @todo too slow, fix handler. */
11431 SET_CPE1_XBM_IF_EITHER_EN(INSTR_PAUSE, VMX_EXIT_PAUSE, VMX_PROC_CTLS_PAUSE_EXIT);
11432#endif
11433 SET_ONLY_XBM_IF_EITHER_EN( EXIT_PAUSE, VMX_EXIT_PAUSE);
11434
11435 if ( IS_EITHER_ENABLED(pVM, INSTR_SGDT)
11436 || IS_EITHER_ENABLED(pVM, INSTR_SIDT)
11437 || IS_EITHER_ENABLED(pVM, INSTR_LGDT)
11438 || IS_EITHER_ENABLED(pVM, INSTR_LIDT))
11439 {
11440 pDbgState->fCpe2Extra |= VMX_PROC_CTLS2_DESC_TABLE_EXIT;
11441 ASMBitSet(pDbgState->bmExitsToCheck, VMX_EXIT_GDTR_IDTR_ACCESS);
11442 }
11443 SET_ONLY_XBM_IF_EITHER_EN( EXIT_SGDT, VMX_EXIT_GDTR_IDTR_ACCESS);
11444 SET_ONLY_XBM_IF_EITHER_EN( EXIT_SIDT, VMX_EXIT_GDTR_IDTR_ACCESS);
11445 SET_ONLY_XBM_IF_EITHER_EN( EXIT_LGDT, VMX_EXIT_GDTR_IDTR_ACCESS);
11446 SET_ONLY_XBM_IF_EITHER_EN( EXIT_LIDT, VMX_EXIT_GDTR_IDTR_ACCESS);
11447
11448 if ( IS_EITHER_ENABLED(pVM, INSTR_SLDT)
11449 || IS_EITHER_ENABLED(pVM, INSTR_STR)
11450 || IS_EITHER_ENABLED(pVM, INSTR_LLDT)
11451 || IS_EITHER_ENABLED(pVM, INSTR_LTR))
11452 {
11453 pDbgState->fCpe2Extra |= VMX_PROC_CTLS2_DESC_TABLE_EXIT;
11454 ASMBitSet(pDbgState->bmExitsToCheck, VMX_EXIT_LDTR_TR_ACCESS);
11455 }
11456 SET_ONLY_XBM_IF_EITHER_EN( EXIT_SLDT, VMX_EXIT_LDTR_TR_ACCESS);
11457 SET_ONLY_XBM_IF_EITHER_EN( EXIT_STR, VMX_EXIT_LDTR_TR_ACCESS);
11458 SET_ONLY_XBM_IF_EITHER_EN( EXIT_LLDT, VMX_EXIT_LDTR_TR_ACCESS);
11459 SET_ONLY_XBM_IF_EITHER_EN( EXIT_LTR, VMX_EXIT_LDTR_TR_ACCESS);
11460
11461 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMX_INVEPT, VMX_EXIT_INVEPT); /* unconditional */
11462 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_INVEPT, VMX_EXIT_INVEPT);
11463 SET_CPE1_XBM_IF_EITHER_EN(INSTR_RDTSCP, VMX_EXIT_RDTSCP, VMX_PROC_CTLS_RDTSC_EXIT);
11464 SET_ONLY_XBM_IF_EITHER_EN( EXIT_RDTSCP, VMX_EXIT_RDTSCP);
11465 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMX_INVVPID, VMX_EXIT_INVVPID); /* unconditional */
11466 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_INVVPID, VMX_EXIT_INVVPID);
11467 SET_CPE2_XBM_IF_EITHER_EN(INSTR_WBINVD, VMX_EXIT_WBINVD, VMX_PROC_CTLS2_WBINVD_EXIT);
11468 SET_ONLY_XBM_IF_EITHER_EN( EXIT_WBINVD, VMX_EXIT_WBINVD);
11469 SET_ONLY_XBM_IF_EITHER_EN(INSTR_XSETBV, VMX_EXIT_XSETBV); /* unconditional */
11470 SET_ONLY_XBM_IF_EITHER_EN( EXIT_XSETBV, VMX_EXIT_XSETBV);
11471 SET_CPE2_XBM_IF_EITHER_EN(INSTR_RDRAND, VMX_EXIT_RDRAND, VMX_PROC_CTLS2_RDRAND_EXIT);
11472 SET_ONLY_XBM_IF_EITHER_EN( EXIT_RDRAND, VMX_EXIT_RDRAND);
11473 SET_CPE1_XBM_IF_EITHER_EN(INSTR_VMX_INVPCID, VMX_EXIT_INVPCID, VMX_PROC_CTLS_INVLPG_EXIT);
11474 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_INVPCID, VMX_EXIT_INVPCID);
11475 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMX_VMFUNC, VMX_EXIT_VMFUNC); /* unconditional for the current setup */
11476 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_VMFUNC, VMX_EXIT_VMFUNC);
11477 SET_CPE2_XBM_IF_EITHER_EN(INSTR_RDSEED, VMX_EXIT_RDSEED, VMX_PROC_CTLS2_RDSEED_EXIT);
11478 SET_ONLY_XBM_IF_EITHER_EN( EXIT_RDSEED, VMX_EXIT_RDSEED);
11479 SET_ONLY_XBM_IF_EITHER_EN(INSTR_XSAVES, VMX_EXIT_XSAVES); /* unconditional (enabled by host, guest cfg) */
11480 SET_ONLY_XBM_IF_EITHER_EN(EXIT_XSAVES, VMX_EXIT_XSAVES);
11481 SET_ONLY_XBM_IF_EITHER_EN(INSTR_XRSTORS, VMX_EXIT_XRSTORS); /* unconditional (enabled by host, guest cfg) */
11482 SET_ONLY_XBM_IF_EITHER_EN( EXIT_XRSTORS, VMX_EXIT_XRSTORS);
11483
11484#undef IS_EITHER_ENABLED
11485#undef SET_ONLY_XBM_IF_EITHER_EN
11486#undef SET_CPE1_XBM_IF_EITHER_EN
11487#undef SET_CPEU_XBM_IF_EITHER_EN
11488#undef SET_CPE2_XBM_IF_EITHER_EN
11489
11490 /*
11491 * Sanitize the control stuff.
11492 */
11493 pDbgState->fCpe2Extra &= pVM->hm.s.vmx.Msrs.ProcCtls2.n.allowed1;
11494 if (pDbgState->fCpe2Extra)
11495 pDbgState->fCpe1Extra |= VMX_PROC_CTLS_USE_SECONDARY_CTLS;
11496 pDbgState->fCpe1Extra &= pVM->hm.s.vmx.Msrs.ProcCtls.n.allowed1;
11497 pDbgState->fCpe1Unwanted &= ~pVM->hm.s.vmx.Msrs.ProcCtls.n.allowed0;
11498 if (pVCpu->hm.s.fDebugWantRdTscExit != RT_BOOL(pDbgState->fCpe1Extra & VMX_PROC_CTLS_RDTSC_EXIT))
11499 {
11500 pVCpu->hm.s.fDebugWantRdTscExit ^= true;
11501 pVmxTransient->fUpdatedTscOffsettingAndPreemptTimer = false;
11502 }
11503
11504 Log6(("HM: debug state: cpe1=%#RX32 cpeu=%#RX32 cpe2=%#RX32%s%s\n",
11505 pDbgState->fCpe1Extra, pDbgState->fCpe1Unwanted, pDbgState->fCpe2Extra,
11506 pDbgState->fClearCr0Mask ? " clr-cr0" : "",
11507 pDbgState->fClearCr4Mask ? " clr-cr4" : ""));
11508}
11509
11510
11511/**
11512 * Fires off DBGF events and dtrace probes for a VM-exit, when it's
11513 * appropriate.
11514 *
11515 * The caller has checked the VM-exit against the
11516 * VMXRUNDBGSTATE::bmExitsToCheck bitmap. The caller has checked for NMIs
11517 * already, so we don't have to do that either.
11518 *
11519 * @returns Strict VBox status code (i.e. informational status codes too).
11520 * @param pVCpu The cross context virtual CPU structure.
11521 * @param pVmxTransient The VMX-transient structure.
11522 * @param uExitReason The VM-exit reason.
11523 *
11524 * @remarks The name of this function is displayed by dtrace, so keep it short
11525 * and to the point. No longer than 33 chars long, please.
11526 */
11527static VBOXSTRICTRC hmR0VmxHandleExitDtraceEvents(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient, uint32_t uExitReason)
11528{
11529 /*
11530 * Translate the event into a DBGF event (enmEvent + uEventArg) and at the
11531 * same time check whether any corresponding Dtrace event is enabled (fDtrace).
11532 *
11533 * Note! This is the reverse operation of what hmR0VmxPreRunGuestDebugStateUpdate
11534 * does. Must add/change/remove both places. Same ordering, please.
11535 *
11536 * Added/removed events must also be reflected in the next section
11537 * where we dispatch dtrace events.
11538 */
11539 bool fDtrace1 = false;
11540 bool fDtrace2 = false;
11541 DBGFEVENTTYPE enmEvent1 = DBGFEVENT_END;
11542 DBGFEVENTTYPE enmEvent2 = DBGFEVENT_END;
11543 uint32_t uEventArg = 0;
11544#define SET_EXIT(a_EventSubName) \
11545 do { \
11546 enmEvent2 = RT_CONCAT(DBGFEVENT_EXIT_, a_EventSubName); \
11547 fDtrace2 = RT_CONCAT3(VBOXVMM_EXIT_, a_EventSubName, _ENABLED)(); \
11548 } while (0)
11549#define SET_BOTH(a_EventSubName) \
11550 do { \
11551 enmEvent1 = RT_CONCAT(DBGFEVENT_INSTR_, a_EventSubName); \
11552 enmEvent2 = RT_CONCAT(DBGFEVENT_EXIT_, a_EventSubName); \
11553 fDtrace1 = RT_CONCAT3(VBOXVMM_INSTR_, a_EventSubName, _ENABLED)(); \
11554 fDtrace2 = RT_CONCAT3(VBOXVMM_EXIT_, a_EventSubName, _ENABLED)(); \
11555 } while (0)
11556 switch (uExitReason)
11557 {
11558 case VMX_EXIT_MTF:
11559 return hmR0VmxExitMtf(pVCpu, pVmxTransient);
11560
11561 case VMX_EXIT_XCPT_OR_NMI:
11562 {
11563 uint8_t const idxVector = VMX_EXIT_INT_INFO_VECTOR(pVmxTransient->uExitIntInfo);
11564 switch (VMX_EXIT_INT_INFO_TYPE(pVmxTransient->uExitIntInfo))
11565 {
11566 case VMX_EXIT_INT_INFO_TYPE_HW_XCPT:
11567 case VMX_EXIT_INT_INFO_TYPE_SW_XCPT:
11568 case VMX_EXIT_INT_INFO_TYPE_PRIV_SW_XCPT:
11569 if (idxVector <= (unsigned)(DBGFEVENT_XCPT_LAST - DBGFEVENT_XCPT_FIRST))
11570 {
11571 if (VMX_EXIT_INT_INFO_IS_ERROR_CODE_VALID(pVmxTransient->uExitIntInfo))
11572 {
11573 hmR0VmxReadExitIntErrorCodeVmcs(pVmxTransient);
11574 uEventArg = pVmxTransient->uExitIntErrorCode;
11575 }
11576 enmEvent1 = (DBGFEVENTTYPE)(DBGFEVENT_XCPT_FIRST + idxVector);
11577 switch (enmEvent1)
11578 {
11579 case DBGFEVENT_XCPT_DE: fDtrace1 = VBOXVMM_XCPT_DE_ENABLED(); break;
11580 case DBGFEVENT_XCPT_DB: fDtrace1 = VBOXVMM_XCPT_DB_ENABLED(); break;
11581 case DBGFEVENT_XCPT_BP: fDtrace1 = VBOXVMM_XCPT_BP_ENABLED(); break;
11582 case DBGFEVENT_XCPT_OF: fDtrace1 = VBOXVMM_XCPT_OF_ENABLED(); break;
11583 case DBGFEVENT_XCPT_BR: fDtrace1 = VBOXVMM_XCPT_BR_ENABLED(); break;
11584 case DBGFEVENT_XCPT_UD: fDtrace1 = VBOXVMM_XCPT_UD_ENABLED(); break;
11585 case DBGFEVENT_XCPT_NM: fDtrace1 = VBOXVMM_XCPT_NM_ENABLED(); break;
11586 case DBGFEVENT_XCPT_DF: fDtrace1 = VBOXVMM_XCPT_DF_ENABLED(); break;
11587 case DBGFEVENT_XCPT_TS: fDtrace1 = VBOXVMM_XCPT_TS_ENABLED(); break;
11588 case DBGFEVENT_XCPT_NP: fDtrace1 = VBOXVMM_XCPT_NP_ENABLED(); break;
11589 case DBGFEVENT_XCPT_SS: fDtrace1 = VBOXVMM_XCPT_SS_ENABLED(); break;
11590 case DBGFEVENT_XCPT_GP: fDtrace1 = VBOXVMM_XCPT_GP_ENABLED(); break;
11591 case DBGFEVENT_XCPT_PF: fDtrace1 = VBOXVMM_XCPT_PF_ENABLED(); break;
11592 case DBGFEVENT_XCPT_MF: fDtrace1 = VBOXVMM_XCPT_MF_ENABLED(); break;
11593 case DBGFEVENT_XCPT_AC: fDtrace1 = VBOXVMM_XCPT_AC_ENABLED(); break;
11594 case DBGFEVENT_XCPT_XF: fDtrace1 = VBOXVMM_XCPT_XF_ENABLED(); break;
11595 case DBGFEVENT_XCPT_VE: fDtrace1 = VBOXVMM_XCPT_VE_ENABLED(); break;
11596 case DBGFEVENT_XCPT_SX: fDtrace1 = VBOXVMM_XCPT_SX_ENABLED(); break;
11597 default: break;
11598 }
11599 }
11600 else
11601 AssertFailed();
11602 break;
11603
11604 case VMX_EXIT_INT_INFO_TYPE_SW_INT:
11605 uEventArg = idxVector;
11606 enmEvent1 = DBGFEVENT_INTERRUPT_SOFTWARE;
11607 fDtrace1 = VBOXVMM_INT_SOFTWARE_ENABLED();
11608 break;
11609 }
11610 break;
11611 }
11612
11613 case VMX_EXIT_TRIPLE_FAULT:
11614 enmEvent1 = DBGFEVENT_TRIPLE_FAULT;
11615 //fDtrace1 = VBOXVMM_EXIT_TRIPLE_FAULT_ENABLED();
11616 break;
11617 case VMX_EXIT_TASK_SWITCH: SET_EXIT(TASK_SWITCH); break;
11618 case VMX_EXIT_EPT_VIOLATION: SET_EXIT(VMX_EPT_VIOLATION); break;
11619 case VMX_EXIT_EPT_MISCONFIG: SET_EXIT(VMX_EPT_MISCONFIG); break;
11620 case VMX_EXIT_APIC_ACCESS: SET_EXIT(VMX_VAPIC_ACCESS); break;
11621 case VMX_EXIT_APIC_WRITE: SET_EXIT(VMX_VAPIC_WRITE); break;
11622
11623 /* Instruction specific VM-exits: */
11624 case VMX_EXIT_CPUID: SET_BOTH(CPUID); break;
11625 case VMX_EXIT_GETSEC: SET_BOTH(GETSEC); break;
11626 case VMX_EXIT_HLT: SET_BOTH(HALT); break;
11627 case VMX_EXIT_INVD: SET_BOTH(INVD); break;
11628 case VMX_EXIT_INVLPG: SET_BOTH(INVLPG); break;
11629 case VMX_EXIT_RDPMC: SET_BOTH(RDPMC); break;
11630 case VMX_EXIT_RDTSC: SET_BOTH(RDTSC); break;
11631 case VMX_EXIT_RSM: SET_BOTH(RSM); break;
11632 case VMX_EXIT_VMCALL: SET_BOTH(VMM_CALL); break;
11633 case VMX_EXIT_VMCLEAR: SET_BOTH(VMX_VMCLEAR); break;
11634 case VMX_EXIT_VMLAUNCH: SET_BOTH(VMX_VMLAUNCH); break;
11635 case VMX_EXIT_VMPTRLD: SET_BOTH(VMX_VMPTRLD); break;
11636 case VMX_EXIT_VMPTRST: SET_BOTH(VMX_VMPTRST); break;
11637 case VMX_EXIT_VMREAD: SET_BOTH(VMX_VMREAD); break;
11638 case VMX_EXIT_VMRESUME: SET_BOTH(VMX_VMRESUME); break;
11639 case VMX_EXIT_VMWRITE: SET_BOTH(VMX_VMWRITE); break;
11640 case VMX_EXIT_VMXOFF: SET_BOTH(VMX_VMXOFF); break;
11641 case VMX_EXIT_VMXON: SET_BOTH(VMX_VMXON); break;
11642 case VMX_EXIT_MOV_CRX:
11643 hmR0VmxReadExitQualVmcs(pVmxTransient);
11644 if (VMX_EXIT_QUAL_CRX_ACCESS(pVmxTransient->uExitQual) == VMX_EXIT_QUAL_CRX_ACCESS_READ)
11645 SET_BOTH(CRX_READ);
11646 else
11647 SET_BOTH(CRX_WRITE);
11648 uEventArg = VMX_EXIT_QUAL_CRX_REGISTER(pVmxTransient->uExitQual);
11649 break;
11650 case VMX_EXIT_MOV_DRX:
11651 hmR0VmxReadExitQualVmcs(pVmxTransient);
11652 if ( VMX_EXIT_QUAL_DRX_DIRECTION(pVmxTransient->uExitQual)
11653 == VMX_EXIT_QUAL_DRX_DIRECTION_READ)
11654 SET_BOTH(DRX_READ);
11655 else
11656 SET_BOTH(DRX_WRITE);
11657 uEventArg = VMX_EXIT_QUAL_DRX_REGISTER(pVmxTransient->uExitQual);
11658 break;
11659 case VMX_EXIT_RDMSR: SET_BOTH(RDMSR); break;
11660 case VMX_EXIT_WRMSR: SET_BOTH(WRMSR); break;
11661 case VMX_EXIT_MWAIT: SET_BOTH(MWAIT); break;
11662 case VMX_EXIT_MONITOR: SET_BOTH(MONITOR); break;
11663 case VMX_EXIT_PAUSE: SET_BOTH(PAUSE); break;
11664 case VMX_EXIT_GDTR_IDTR_ACCESS:
11665 hmR0VmxReadExitInstrInfoVmcs(pVmxTransient);
11666 switch (RT_BF_GET(pVmxTransient->ExitInstrInfo.u, VMX_BF_XDTR_INSINFO_INSTR_ID))
11667 {
11668 case VMX_XDTR_INSINFO_II_SGDT: SET_BOTH(SGDT); break;
11669 case VMX_XDTR_INSINFO_II_SIDT: SET_BOTH(SIDT); break;
11670 case VMX_XDTR_INSINFO_II_LGDT: SET_BOTH(LGDT); break;
11671 case VMX_XDTR_INSINFO_II_LIDT: SET_BOTH(LIDT); break;
11672 }
11673 break;
11674
11675 case VMX_EXIT_LDTR_TR_ACCESS:
11676 hmR0VmxReadExitInstrInfoVmcs(pVmxTransient);
11677 switch (RT_BF_GET(pVmxTransient->ExitInstrInfo.u, VMX_BF_YYTR_INSINFO_INSTR_ID))
11678 {
11679 case VMX_YYTR_INSINFO_II_SLDT: SET_BOTH(SLDT); break;
11680 case VMX_YYTR_INSINFO_II_STR: SET_BOTH(STR); break;
11681 case VMX_YYTR_INSINFO_II_LLDT: SET_BOTH(LLDT); break;
11682 case VMX_YYTR_INSINFO_II_LTR: SET_BOTH(LTR); break;
11683 }
11684 break;
11685
11686 case VMX_EXIT_INVEPT: SET_BOTH(VMX_INVEPT); break;
11687 case VMX_EXIT_RDTSCP: SET_BOTH(RDTSCP); break;
11688 case VMX_EXIT_INVVPID: SET_BOTH(VMX_INVVPID); break;
11689 case VMX_EXIT_WBINVD: SET_BOTH(WBINVD); break;
11690 case VMX_EXIT_XSETBV: SET_BOTH(XSETBV); break;
11691 case VMX_EXIT_RDRAND: SET_BOTH(RDRAND); break;
11692 case VMX_EXIT_INVPCID: SET_BOTH(VMX_INVPCID); break;
11693 case VMX_EXIT_VMFUNC: SET_BOTH(VMX_VMFUNC); break;
11694 case VMX_EXIT_RDSEED: SET_BOTH(RDSEED); break;
11695 case VMX_EXIT_XSAVES: SET_BOTH(XSAVES); break;
11696 case VMX_EXIT_XRSTORS: SET_BOTH(XRSTORS); break;
11697
11698 /* Events that aren't relevant at this point. */
11699 case VMX_EXIT_EXT_INT:
11700 case VMX_EXIT_INT_WINDOW:
11701 case VMX_EXIT_NMI_WINDOW:
11702 case VMX_EXIT_TPR_BELOW_THRESHOLD:
11703 case VMX_EXIT_PREEMPT_TIMER:
11704 case VMX_EXIT_IO_INSTR:
11705 break;
11706
11707 /* Errors and unexpected events. */
11708 case VMX_EXIT_INIT_SIGNAL:
11709 case VMX_EXIT_SIPI:
11710 case VMX_EXIT_IO_SMI:
11711 case VMX_EXIT_SMI:
11712 case VMX_EXIT_ERR_INVALID_GUEST_STATE:
11713 case VMX_EXIT_ERR_MSR_LOAD:
11714 case VMX_EXIT_ERR_MACHINE_CHECK:
11715 case VMX_EXIT_PML_FULL:
11716 case VMX_EXIT_VIRTUALIZED_EOI:
11717 break;
11718
11719 default:
11720 AssertMsgFailed(("Unexpected VM-exit=%#x\n", uExitReason));
11721 break;
11722 }
11723#undef SET_BOTH
11724#undef SET_EXIT
11725
11726 /*
11727 * Dtrace tracepoints go first. We do them here at once so we don't
11728 * have to copy the guest state saving and stuff a few dozen times.
11729 * Down side is that we've got to repeat the switch, though this time
11730 * we use enmEvent since the probes are a subset of what DBGF does.
11731 */
11732 if (fDtrace1 || fDtrace2)
11733 {
11734 hmR0VmxReadExitQualVmcs(pVmxTransient);
11735 hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, HMVMX_CPUMCTX_EXTRN_ALL);
11736 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
11737 switch (enmEvent1)
11738 {
11739 /** @todo consider which extra parameters would be helpful for each probe. */
11740 case DBGFEVENT_END: break;
11741 case DBGFEVENT_XCPT_DE: VBOXVMM_XCPT_DE(pVCpu, pCtx); break;
11742 case DBGFEVENT_XCPT_DB: VBOXVMM_XCPT_DB(pVCpu, pCtx, pCtx->dr[6]); break;
11743 case DBGFEVENT_XCPT_BP: VBOXVMM_XCPT_BP(pVCpu, pCtx); break;
11744 case DBGFEVENT_XCPT_OF: VBOXVMM_XCPT_OF(pVCpu, pCtx); break;
11745 case DBGFEVENT_XCPT_BR: VBOXVMM_XCPT_BR(pVCpu, pCtx); break;
11746 case DBGFEVENT_XCPT_UD: VBOXVMM_XCPT_UD(pVCpu, pCtx); break;
11747 case DBGFEVENT_XCPT_NM: VBOXVMM_XCPT_NM(pVCpu, pCtx); break;
11748 case DBGFEVENT_XCPT_DF: VBOXVMM_XCPT_DF(pVCpu, pCtx); break;
11749 case DBGFEVENT_XCPT_TS: VBOXVMM_XCPT_TS(pVCpu, pCtx, uEventArg); break;
11750 case DBGFEVENT_XCPT_NP: VBOXVMM_XCPT_NP(pVCpu, pCtx, uEventArg); break;
11751 case DBGFEVENT_XCPT_SS: VBOXVMM_XCPT_SS(pVCpu, pCtx, uEventArg); break;
11752 case DBGFEVENT_XCPT_GP: VBOXVMM_XCPT_GP(pVCpu, pCtx, uEventArg); break;
11753 case DBGFEVENT_XCPT_PF: VBOXVMM_XCPT_PF(pVCpu, pCtx, uEventArg, pCtx->cr2); break;
11754 case DBGFEVENT_XCPT_MF: VBOXVMM_XCPT_MF(pVCpu, pCtx); break;
11755 case DBGFEVENT_XCPT_AC: VBOXVMM_XCPT_AC(pVCpu, pCtx); break;
11756 case DBGFEVENT_XCPT_XF: VBOXVMM_XCPT_XF(pVCpu, pCtx); break;
11757 case DBGFEVENT_XCPT_VE: VBOXVMM_XCPT_VE(pVCpu, pCtx); break;
11758 case DBGFEVENT_XCPT_SX: VBOXVMM_XCPT_SX(pVCpu, pCtx, uEventArg); break;
11759 case DBGFEVENT_INTERRUPT_SOFTWARE: VBOXVMM_INT_SOFTWARE(pVCpu, pCtx, (uint8_t)uEventArg); break;
11760 case DBGFEVENT_INSTR_CPUID: VBOXVMM_INSTR_CPUID(pVCpu, pCtx, pCtx->eax, pCtx->ecx); break;
11761 case DBGFEVENT_INSTR_GETSEC: VBOXVMM_INSTR_GETSEC(pVCpu, pCtx); break;
11762 case DBGFEVENT_INSTR_HALT: VBOXVMM_INSTR_HALT(pVCpu, pCtx); break;
11763 case DBGFEVENT_INSTR_INVD: VBOXVMM_INSTR_INVD(pVCpu, pCtx); break;
11764 case DBGFEVENT_INSTR_INVLPG: VBOXVMM_INSTR_INVLPG(pVCpu, pCtx); break;
11765 case DBGFEVENT_INSTR_RDPMC: VBOXVMM_INSTR_RDPMC(pVCpu, pCtx); break;
11766 case DBGFEVENT_INSTR_RDTSC: VBOXVMM_INSTR_RDTSC(pVCpu, pCtx); break;
11767 case DBGFEVENT_INSTR_RSM: VBOXVMM_INSTR_RSM(pVCpu, pCtx); break;
11768 case DBGFEVENT_INSTR_CRX_READ: VBOXVMM_INSTR_CRX_READ(pVCpu, pCtx, (uint8_t)uEventArg); break;
11769 case DBGFEVENT_INSTR_CRX_WRITE: VBOXVMM_INSTR_CRX_WRITE(pVCpu, pCtx, (uint8_t)uEventArg); break;
11770 case DBGFEVENT_INSTR_DRX_READ: VBOXVMM_INSTR_DRX_READ(pVCpu, pCtx, (uint8_t)uEventArg); break;
11771 case DBGFEVENT_INSTR_DRX_WRITE: VBOXVMM_INSTR_DRX_WRITE(pVCpu, pCtx, (uint8_t)uEventArg); break;
11772 case DBGFEVENT_INSTR_RDMSR: VBOXVMM_INSTR_RDMSR(pVCpu, pCtx, pCtx->ecx); break;
11773 case DBGFEVENT_INSTR_WRMSR: VBOXVMM_INSTR_WRMSR(pVCpu, pCtx, pCtx->ecx,
11774 RT_MAKE_U64(pCtx->eax, pCtx->edx)); break;
11775 case DBGFEVENT_INSTR_MWAIT: VBOXVMM_INSTR_MWAIT(pVCpu, pCtx); break;
11776 case DBGFEVENT_INSTR_MONITOR: VBOXVMM_INSTR_MONITOR(pVCpu, pCtx); break;
11777 case DBGFEVENT_INSTR_PAUSE: VBOXVMM_INSTR_PAUSE(pVCpu, pCtx); break;
11778 case DBGFEVENT_INSTR_SGDT: VBOXVMM_INSTR_SGDT(pVCpu, pCtx); break;
11779 case DBGFEVENT_INSTR_SIDT: VBOXVMM_INSTR_SIDT(pVCpu, pCtx); break;
11780 case DBGFEVENT_INSTR_LGDT: VBOXVMM_INSTR_LGDT(pVCpu, pCtx); break;
11781 case DBGFEVENT_INSTR_LIDT: VBOXVMM_INSTR_LIDT(pVCpu, pCtx); break;
11782 case DBGFEVENT_INSTR_SLDT: VBOXVMM_INSTR_SLDT(pVCpu, pCtx); break;
11783 case DBGFEVENT_INSTR_STR: VBOXVMM_INSTR_STR(pVCpu, pCtx); break;
11784 case DBGFEVENT_INSTR_LLDT: VBOXVMM_INSTR_LLDT(pVCpu, pCtx); break;
11785 case DBGFEVENT_INSTR_LTR: VBOXVMM_INSTR_LTR(pVCpu, pCtx); break;
11786 case DBGFEVENT_INSTR_RDTSCP: VBOXVMM_INSTR_RDTSCP(pVCpu, pCtx); break;
11787 case DBGFEVENT_INSTR_WBINVD: VBOXVMM_INSTR_WBINVD(pVCpu, pCtx); break;
11788 case DBGFEVENT_INSTR_XSETBV: VBOXVMM_INSTR_XSETBV(pVCpu, pCtx); break;
11789 case DBGFEVENT_INSTR_RDRAND: VBOXVMM_INSTR_RDRAND(pVCpu, pCtx); break;
11790 case DBGFEVENT_INSTR_RDSEED: VBOXVMM_INSTR_RDSEED(pVCpu, pCtx); break;
11791 case DBGFEVENT_INSTR_XSAVES: VBOXVMM_INSTR_XSAVES(pVCpu, pCtx); break;
11792 case DBGFEVENT_INSTR_XRSTORS: VBOXVMM_INSTR_XRSTORS(pVCpu, pCtx); break;
11793 case DBGFEVENT_INSTR_VMM_CALL: VBOXVMM_INSTR_VMM_CALL(pVCpu, pCtx); break;
11794 case DBGFEVENT_INSTR_VMX_VMCLEAR: VBOXVMM_INSTR_VMX_VMCLEAR(pVCpu, pCtx); break;
11795 case DBGFEVENT_INSTR_VMX_VMLAUNCH: VBOXVMM_INSTR_VMX_VMLAUNCH(pVCpu, pCtx); break;
11796 case DBGFEVENT_INSTR_VMX_VMPTRLD: VBOXVMM_INSTR_VMX_VMPTRLD(pVCpu, pCtx); break;
11797 case DBGFEVENT_INSTR_VMX_VMPTRST: VBOXVMM_INSTR_VMX_VMPTRST(pVCpu, pCtx); break;
11798 case DBGFEVENT_INSTR_VMX_VMREAD: VBOXVMM_INSTR_VMX_VMREAD(pVCpu, pCtx); break;
11799 case DBGFEVENT_INSTR_VMX_VMRESUME: VBOXVMM_INSTR_VMX_VMRESUME(pVCpu, pCtx); break;
11800 case DBGFEVENT_INSTR_VMX_VMWRITE: VBOXVMM_INSTR_VMX_VMWRITE(pVCpu, pCtx); break;
11801 case DBGFEVENT_INSTR_VMX_VMXOFF: VBOXVMM_INSTR_VMX_VMXOFF(pVCpu, pCtx); break;
11802 case DBGFEVENT_INSTR_VMX_VMXON: VBOXVMM_INSTR_VMX_VMXON(pVCpu, pCtx); break;
11803 case DBGFEVENT_INSTR_VMX_INVEPT: VBOXVMM_INSTR_VMX_INVEPT(pVCpu, pCtx); break;
11804 case DBGFEVENT_INSTR_VMX_INVVPID: VBOXVMM_INSTR_VMX_INVVPID(pVCpu, pCtx); break;
11805 case DBGFEVENT_INSTR_VMX_INVPCID: VBOXVMM_INSTR_VMX_INVPCID(pVCpu, pCtx); break;
11806 case DBGFEVENT_INSTR_VMX_VMFUNC: VBOXVMM_INSTR_VMX_VMFUNC(pVCpu, pCtx); break;
11807 default: AssertMsgFailed(("enmEvent1=%d uExitReason=%d\n", enmEvent1, uExitReason)); break;
11808 }
11809 switch (enmEvent2)
11810 {
11811 /** @todo consider which extra parameters would be helpful for each probe. */
11812 case DBGFEVENT_END: break;
11813 case DBGFEVENT_EXIT_TASK_SWITCH: VBOXVMM_EXIT_TASK_SWITCH(pVCpu, pCtx); break;
11814 case DBGFEVENT_EXIT_CPUID: VBOXVMM_EXIT_CPUID(pVCpu, pCtx, pCtx->eax, pCtx->ecx); break;
11815 case DBGFEVENT_EXIT_GETSEC: VBOXVMM_EXIT_GETSEC(pVCpu, pCtx); break;
11816 case DBGFEVENT_EXIT_HALT: VBOXVMM_EXIT_HALT(pVCpu, pCtx); break;
11817 case DBGFEVENT_EXIT_INVD: VBOXVMM_EXIT_INVD(pVCpu, pCtx); break;
11818 case DBGFEVENT_EXIT_INVLPG: VBOXVMM_EXIT_INVLPG(pVCpu, pCtx); break;
11819 case DBGFEVENT_EXIT_RDPMC: VBOXVMM_EXIT_RDPMC(pVCpu, pCtx); break;
11820 case DBGFEVENT_EXIT_RDTSC: VBOXVMM_EXIT_RDTSC(pVCpu, pCtx); break;
11821 case DBGFEVENT_EXIT_RSM: VBOXVMM_EXIT_RSM(pVCpu, pCtx); break;
11822 case DBGFEVENT_EXIT_CRX_READ: VBOXVMM_EXIT_CRX_READ(pVCpu, pCtx, (uint8_t)uEventArg); break;
11823 case DBGFEVENT_EXIT_CRX_WRITE: VBOXVMM_EXIT_CRX_WRITE(pVCpu, pCtx, (uint8_t)uEventArg); break;
11824 case DBGFEVENT_EXIT_DRX_READ: VBOXVMM_EXIT_DRX_READ(pVCpu, pCtx, (uint8_t)uEventArg); break;
11825 case DBGFEVENT_EXIT_DRX_WRITE: VBOXVMM_EXIT_DRX_WRITE(pVCpu, pCtx, (uint8_t)uEventArg); break;
11826 case DBGFEVENT_EXIT_RDMSR: VBOXVMM_EXIT_RDMSR(pVCpu, pCtx, pCtx->ecx); break;
11827 case DBGFEVENT_EXIT_WRMSR: VBOXVMM_EXIT_WRMSR(pVCpu, pCtx, pCtx->ecx,
11828 RT_MAKE_U64(pCtx->eax, pCtx->edx)); break;
11829 case DBGFEVENT_EXIT_MWAIT: VBOXVMM_EXIT_MWAIT(pVCpu, pCtx); break;
11830 case DBGFEVENT_EXIT_MONITOR: VBOXVMM_EXIT_MONITOR(pVCpu, pCtx); break;
11831 case DBGFEVENT_EXIT_PAUSE: VBOXVMM_EXIT_PAUSE(pVCpu, pCtx); break;
11832 case DBGFEVENT_EXIT_SGDT: VBOXVMM_EXIT_SGDT(pVCpu, pCtx); break;
11833 case DBGFEVENT_EXIT_SIDT: VBOXVMM_EXIT_SIDT(pVCpu, pCtx); break;
11834 case DBGFEVENT_EXIT_LGDT: VBOXVMM_EXIT_LGDT(pVCpu, pCtx); break;
11835 case DBGFEVENT_EXIT_LIDT: VBOXVMM_EXIT_LIDT(pVCpu, pCtx); break;
11836 case DBGFEVENT_EXIT_SLDT: VBOXVMM_EXIT_SLDT(pVCpu, pCtx); break;
11837 case DBGFEVENT_EXIT_STR: VBOXVMM_EXIT_STR(pVCpu, pCtx); break;
11838 case DBGFEVENT_EXIT_LLDT: VBOXVMM_EXIT_LLDT(pVCpu, pCtx); break;
11839 case DBGFEVENT_EXIT_LTR: VBOXVMM_EXIT_LTR(pVCpu, pCtx); break;
11840 case DBGFEVENT_EXIT_RDTSCP: VBOXVMM_EXIT_RDTSCP(pVCpu, pCtx); break;
11841 case DBGFEVENT_EXIT_WBINVD: VBOXVMM_EXIT_WBINVD(pVCpu, pCtx); break;
11842 case DBGFEVENT_EXIT_XSETBV: VBOXVMM_EXIT_XSETBV(pVCpu, pCtx); break;
11843 case DBGFEVENT_EXIT_RDRAND: VBOXVMM_EXIT_RDRAND(pVCpu, pCtx); break;
11844 case DBGFEVENT_EXIT_RDSEED: VBOXVMM_EXIT_RDSEED(pVCpu, pCtx); break;
11845 case DBGFEVENT_EXIT_XSAVES: VBOXVMM_EXIT_XSAVES(pVCpu, pCtx); break;
11846 case DBGFEVENT_EXIT_XRSTORS: VBOXVMM_EXIT_XRSTORS(pVCpu, pCtx); break;
11847 case DBGFEVENT_EXIT_VMM_CALL: VBOXVMM_EXIT_VMM_CALL(pVCpu, pCtx); break;
11848 case DBGFEVENT_EXIT_VMX_VMCLEAR: VBOXVMM_EXIT_VMX_VMCLEAR(pVCpu, pCtx); break;
11849 case DBGFEVENT_EXIT_VMX_VMLAUNCH: VBOXVMM_EXIT_VMX_VMLAUNCH(pVCpu, pCtx); break;
11850 case DBGFEVENT_EXIT_VMX_VMPTRLD: VBOXVMM_EXIT_VMX_VMPTRLD(pVCpu, pCtx); break;
11851 case DBGFEVENT_EXIT_VMX_VMPTRST: VBOXVMM_EXIT_VMX_VMPTRST(pVCpu, pCtx); break;
11852 case DBGFEVENT_EXIT_VMX_VMREAD: VBOXVMM_EXIT_VMX_VMREAD(pVCpu, pCtx); break;
11853 case DBGFEVENT_EXIT_VMX_VMRESUME: VBOXVMM_EXIT_VMX_VMRESUME(pVCpu, pCtx); break;
11854 case DBGFEVENT_EXIT_VMX_VMWRITE: VBOXVMM_EXIT_VMX_VMWRITE(pVCpu, pCtx); break;
11855 case DBGFEVENT_EXIT_VMX_VMXOFF: VBOXVMM_EXIT_VMX_VMXOFF(pVCpu, pCtx); break;
11856 case DBGFEVENT_EXIT_VMX_VMXON: VBOXVMM_EXIT_VMX_VMXON(pVCpu, pCtx); break;
11857 case DBGFEVENT_EXIT_VMX_INVEPT: VBOXVMM_EXIT_VMX_INVEPT(pVCpu, pCtx); break;
11858 case DBGFEVENT_EXIT_VMX_INVVPID: VBOXVMM_EXIT_VMX_INVVPID(pVCpu, pCtx); break;
11859 case DBGFEVENT_EXIT_VMX_INVPCID: VBOXVMM_EXIT_VMX_INVPCID(pVCpu, pCtx); break;
11860 case DBGFEVENT_EXIT_VMX_VMFUNC: VBOXVMM_EXIT_VMX_VMFUNC(pVCpu, pCtx); break;
11861 case DBGFEVENT_EXIT_VMX_EPT_MISCONFIG: VBOXVMM_EXIT_VMX_EPT_MISCONFIG(pVCpu, pCtx); break;
11862 case DBGFEVENT_EXIT_VMX_EPT_VIOLATION: VBOXVMM_EXIT_VMX_EPT_VIOLATION(pVCpu, pCtx); break;
11863 case DBGFEVENT_EXIT_VMX_VAPIC_ACCESS: VBOXVMM_EXIT_VMX_VAPIC_ACCESS(pVCpu, pCtx); break;
11864 case DBGFEVENT_EXIT_VMX_VAPIC_WRITE: VBOXVMM_EXIT_VMX_VAPIC_WRITE(pVCpu, pCtx); break;
11865 default: AssertMsgFailed(("enmEvent2=%d uExitReason=%d\n", enmEvent2, uExitReason)); break;
11866 }
11867 }
11868
11869 /*
11870 * Fire of the DBGF event, if enabled (our check here is just a quick one,
11871 * the DBGF call will do a full check).
11872 *
11873 * Note! DBGF sets DBGFEVENT_INTERRUPT_SOFTWARE in the bitmap.
11874 * Note! If we have to events, we prioritize the first, i.e. the instruction
11875 * one, in order to avoid event nesting.
11876 */
11877 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
11878 if ( enmEvent1 != DBGFEVENT_END
11879 && DBGF_IS_EVENT_ENABLED(pVM, enmEvent1))
11880 {
11881 hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, CPUMCTX_EXTRN_CS | CPUMCTX_EXTRN_RIP);
11882 VBOXSTRICTRC rcStrict = DBGFEventGenericWithArgs(pVM, pVCpu, enmEvent1, DBGFEVENTCTX_HM, 1, uEventArg);
11883 if (rcStrict != VINF_SUCCESS)
11884 return rcStrict;
11885 }
11886 else if ( enmEvent2 != DBGFEVENT_END
11887 && DBGF_IS_EVENT_ENABLED(pVM, enmEvent2))
11888 {
11889 hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, CPUMCTX_EXTRN_CS | CPUMCTX_EXTRN_RIP);
11890 VBOXSTRICTRC rcStrict = DBGFEventGenericWithArgs(pVM, pVCpu, enmEvent2, DBGFEVENTCTX_HM, 1, uEventArg);
11891 if (rcStrict != VINF_SUCCESS)
11892 return rcStrict;
11893 }
11894
11895 return VINF_SUCCESS;
11896}
11897
11898
11899/**
11900 * Single-stepping VM-exit filtering.
11901 *
11902 * This is preprocessing the VM-exits and deciding whether we've gotten far
11903 * enough to return VINF_EM_DBG_STEPPED already. If not, normal VM-exit
11904 * handling is performed.
11905 *
11906 * @returns Strict VBox status code (i.e. informational status codes too).
11907 * @param pVCpu The cross context virtual CPU structure of the calling EMT.
11908 * @param pVmxTransient The VMX-transient structure.
11909 * @param pDbgState The debug state.
11910 */
11911DECLINLINE(VBOXSTRICTRC) hmR0VmxRunDebugHandleExit(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient, PVMXRUNDBGSTATE pDbgState)
11912{
11913 /*
11914 * Expensive (saves context) generic dtrace VM-exit probe.
11915 */
11916 uint32_t const uExitReason = pVmxTransient->uExitReason;
11917 if (!VBOXVMM_R0_HMVMX_VMEXIT_ENABLED())
11918 { /* more likely */ }
11919 else
11920 {
11921 hmR0VmxReadExitQualVmcs(pVmxTransient);
11922 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, HMVMX_CPUMCTX_EXTRN_ALL);
11923 AssertRC(rc);
11924 VBOXVMM_R0_HMVMX_VMEXIT(pVCpu, &pVCpu->cpum.GstCtx, pVmxTransient->uExitReason, pVmxTransient->uExitQual);
11925 }
11926
11927 /*
11928 * Check for host NMI, just to get that out of the way.
11929 */
11930 if (uExitReason != VMX_EXIT_XCPT_OR_NMI)
11931 { /* normally likely */ }
11932 else
11933 {
11934 hmR0VmxReadExitIntInfoVmcs(pVmxTransient);
11935 uint32_t const uIntType = VMX_EXIT_INT_INFO_TYPE(pVmxTransient->uExitIntInfo);
11936 if (uIntType == VMX_EXIT_INT_INFO_TYPE_NMI)
11937 return hmR0VmxExitHostNmi(pVCpu, pVmxTransient->pVmcsInfo);
11938 }
11939
11940 /*
11941 * Check for single stepping event if we're stepping.
11942 */
11943 if (pVCpu->hm.s.fSingleInstruction)
11944 {
11945 switch (uExitReason)
11946 {
11947 case VMX_EXIT_MTF:
11948 return hmR0VmxExitMtf(pVCpu, pVmxTransient);
11949
11950 /* Various events: */
11951 case VMX_EXIT_XCPT_OR_NMI:
11952 case VMX_EXIT_EXT_INT:
11953 case VMX_EXIT_TRIPLE_FAULT:
11954 case VMX_EXIT_INT_WINDOW:
11955 case VMX_EXIT_NMI_WINDOW:
11956 case VMX_EXIT_TASK_SWITCH:
11957 case VMX_EXIT_TPR_BELOW_THRESHOLD:
11958 case VMX_EXIT_APIC_ACCESS:
11959 case VMX_EXIT_EPT_VIOLATION:
11960 case VMX_EXIT_EPT_MISCONFIG:
11961 case VMX_EXIT_PREEMPT_TIMER:
11962
11963 /* Instruction specific VM-exits: */
11964 case VMX_EXIT_CPUID:
11965 case VMX_EXIT_GETSEC:
11966 case VMX_EXIT_HLT:
11967 case VMX_EXIT_INVD:
11968 case VMX_EXIT_INVLPG:
11969 case VMX_EXIT_RDPMC:
11970 case VMX_EXIT_RDTSC:
11971 case VMX_EXIT_RSM:
11972 case VMX_EXIT_VMCALL:
11973 case VMX_EXIT_VMCLEAR:
11974 case VMX_EXIT_VMLAUNCH:
11975 case VMX_EXIT_VMPTRLD:
11976 case VMX_EXIT_VMPTRST:
11977 case VMX_EXIT_VMREAD:
11978 case VMX_EXIT_VMRESUME:
11979 case VMX_EXIT_VMWRITE:
11980 case VMX_EXIT_VMXOFF:
11981 case VMX_EXIT_VMXON:
11982 case VMX_EXIT_MOV_CRX:
11983 case VMX_EXIT_MOV_DRX:
11984 case VMX_EXIT_IO_INSTR:
11985 case VMX_EXIT_RDMSR:
11986 case VMX_EXIT_WRMSR:
11987 case VMX_EXIT_MWAIT:
11988 case VMX_EXIT_MONITOR:
11989 case VMX_EXIT_PAUSE:
11990 case VMX_EXIT_GDTR_IDTR_ACCESS:
11991 case VMX_EXIT_LDTR_TR_ACCESS:
11992 case VMX_EXIT_INVEPT:
11993 case VMX_EXIT_RDTSCP:
11994 case VMX_EXIT_INVVPID:
11995 case VMX_EXIT_WBINVD:
11996 case VMX_EXIT_XSETBV:
11997 case VMX_EXIT_RDRAND:
11998 case VMX_EXIT_INVPCID:
11999 case VMX_EXIT_VMFUNC:
12000 case VMX_EXIT_RDSEED:
12001 case VMX_EXIT_XSAVES:
12002 case VMX_EXIT_XRSTORS:
12003 {
12004 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, CPUMCTX_EXTRN_CS | CPUMCTX_EXTRN_RIP);
12005 AssertRCReturn(rc, rc);
12006 if ( pVCpu->cpum.GstCtx.rip != pDbgState->uRipStart
12007 || pVCpu->cpum.GstCtx.cs.Sel != pDbgState->uCsStart)
12008 return VINF_EM_DBG_STEPPED;
12009 break;
12010 }
12011
12012 /* Errors and unexpected events: */
12013 case VMX_EXIT_INIT_SIGNAL:
12014 case VMX_EXIT_SIPI:
12015 case VMX_EXIT_IO_SMI:
12016 case VMX_EXIT_SMI:
12017 case VMX_EXIT_ERR_INVALID_GUEST_STATE:
12018 case VMX_EXIT_ERR_MSR_LOAD:
12019 case VMX_EXIT_ERR_MACHINE_CHECK:
12020 case VMX_EXIT_PML_FULL:
12021 case VMX_EXIT_VIRTUALIZED_EOI:
12022 case VMX_EXIT_APIC_WRITE: /* Some talk about this being fault like, so I guess we must process it? */
12023 break;
12024
12025 default:
12026 AssertMsgFailed(("Unexpected VM-exit=%#x\n", uExitReason));
12027 break;
12028 }
12029 }
12030
12031 /*
12032 * Check for debugger event breakpoints and dtrace probes.
12033 */
12034 if ( uExitReason < RT_ELEMENTS(pDbgState->bmExitsToCheck) * 32U
12035 && ASMBitTest(pDbgState->bmExitsToCheck, uExitReason) )
12036 {
12037 VBOXSTRICTRC rcStrict = hmR0VmxHandleExitDtraceEvents(pVCpu, pVmxTransient, uExitReason);
12038 if (rcStrict != VINF_SUCCESS)
12039 return rcStrict;
12040 }
12041
12042 /*
12043 * Normal processing.
12044 */
12045#ifdef HMVMX_USE_FUNCTION_TABLE
12046 return g_apfnVMExitHandlers[uExitReason](pVCpu, pVmxTransient);
12047#else
12048 return hmR0VmxHandleExit(pVCpu, pVmxTransient, uExitReason);
12049#endif
12050}
12051
12052
12053/**
12054 * Single steps guest code using hardware-assisted VMX.
12055 *
12056 * This is -not- the same as the guest single-stepping itself (say using EFLAGS.TF)
12057 * but single-stepping through the hypervisor debugger.
12058 *
12059 * @returns Strict VBox status code (i.e. informational status codes too).
12060 * @param pVCpu The cross context virtual CPU structure.
12061 * @param pcLoops Pointer to the number of executed loops.
12062 *
12063 * @note Mostly the same as hmR0VmxRunGuestCodeNormal().
12064 */
12065static VBOXSTRICTRC hmR0VmxRunGuestCodeDebug(PVMCPUCC pVCpu, uint32_t *pcLoops)
12066{
12067 uint32_t const cMaxResumeLoops = pVCpu->CTX_SUFF(pVM)->hm.s.cMaxResumeLoops;
12068 Assert(pcLoops);
12069 Assert(*pcLoops <= cMaxResumeLoops);
12070
12071 VMXTRANSIENT VmxTransient;
12072 RT_ZERO(VmxTransient);
12073 VmxTransient.pVmcsInfo = hmGetVmxActiveVmcsInfo(pVCpu);
12074
12075 /* Set HMCPU indicators. */
12076 bool const fSavedSingleInstruction = pVCpu->hm.s.fSingleInstruction;
12077 pVCpu->hm.s.fSingleInstruction = pVCpu->hm.s.fSingleInstruction || DBGFIsStepping(pVCpu);
12078 pVCpu->hm.s.fDebugWantRdTscExit = false;
12079 pVCpu->hm.s.fUsingDebugLoop = true;
12080
12081 /* State we keep to help modify and later restore the VMCS fields we alter, and for detecting steps. */
12082 VMXRUNDBGSTATE DbgState;
12083 hmR0VmxRunDebugStateInit(pVCpu, &VmxTransient, &DbgState);
12084 hmR0VmxPreRunGuestDebugStateUpdate(pVCpu, &VmxTransient, &DbgState);
12085
12086 /*
12087 * The loop.
12088 */
12089 VBOXSTRICTRC rcStrict = VERR_INTERNAL_ERROR_5;
12090 for (;;)
12091 {
12092 Assert(!HMR0SuspendPending());
12093 HMVMX_ASSERT_CPU_SAFE(pVCpu);
12094 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatEntry, x);
12095 bool fStepping = pVCpu->hm.s.fSingleInstruction;
12096
12097 /* Set up VM-execution controls the next two can respond to. */
12098 hmR0VmxPreRunGuestDebugStateApply(pVCpu, &VmxTransient, &DbgState);
12099
12100 /*
12101 * Preparatory work for running guest code, this may force us to
12102 * return to ring-3.
12103 *
12104 * Warning! This bugger disables interrupts on VINF_SUCCESS!
12105 */
12106 rcStrict = hmR0VmxPreRunGuest(pVCpu, &VmxTransient, fStepping);
12107 if (rcStrict != VINF_SUCCESS)
12108 break;
12109
12110 /* Interrupts are disabled at this point! */
12111 hmR0VmxPreRunGuestCommitted(pVCpu, &VmxTransient);
12112
12113 /* Override any obnoxious code in the above two calls. */
12114 hmR0VmxPreRunGuestDebugStateApply(pVCpu, &VmxTransient, &DbgState);
12115
12116 /*
12117 * Finally execute the guest.
12118 */
12119 int rcRun = hmR0VmxRunGuest(pVCpu, &VmxTransient);
12120
12121 hmR0VmxPostRunGuest(pVCpu, &VmxTransient, rcRun);
12122 /* Interrupts are re-enabled at this point! */
12123
12124 /* Check for errors with running the VM (VMLAUNCH/VMRESUME). */
12125 if (RT_SUCCESS(rcRun))
12126 { /* very likely */ }
12127 else
12128 {
12129 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatPreExit, x);
12130 hmR0VmxReportWorldSwitchError(pVCpu, rcRun, &VmxTransient);
12131 return rcRun;
12132 }
12133
12134 /* Profile the VM-exit. */
12135 AssertMsg(VmxTransient.uExitReason <= VMX_EXIT_MAX, ("%#x\n", VmxTransient.uExitReason));
12136 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitAll);
12137 STAM_COUNTER_INC(&pVCpu->hm.s.paStatExitReasonR0[VmxTransient.uExitReason & MASK_EXITREASON_STAT]);
12138 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatPreExit, &pVCpu->hm.s.StatExitHandling, x);
12139 HMVMX_START_EXIT_DISPATCH_PROF();
12140
12141 VBOXVMM_R0_HMVMX_VMEXIT_NOCTX(pVCpu, &pVCpu->cpum.GstCtx, VmxTransient.uExitReason);
12142
12143 /*
12144 * Handle the VM-exit - we quit earlier on certain VM-exits, see hmR0VmxHandleExitDebug().
12145 */
12146 rcStrict = hmR0VmxRunDebugHandleExit(pVCpu, &VmxTransient, &DbgState);
12147 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExitHandling, x);
12148 if (rcStrict != VINF_SUCCESS)
12149 break;
12150 if (++(*pcLoops) > cMaxResumeLoops)
12151 {
12152 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchMaxResumeLoops);
12153 rcStrict = VINF_EM_RAW_INTERRUPT;
12154 break;
12155 }
12156
12157 /*
12158 * Stepping: Did the RIP change, if so, consider it a single step.
12159 * Otherwise, make sure one of the TFs gets set.
12160 */
12161 if (fStepping)
12162 {
12163 int rc = hmR0VmxImportGuestState(pVCpu, VmxTransient.pVmcsInfo, CPUMCTX_EXTRN_CS | CPUMCTX_EXTRN_RIP);
12164 AssertRC(rc);
12165 if ( pVCpu->cpum.GstCtx.rip != DbgState.uRipStart
12166 || pVCpu->cpum.GstCtx.cs.Sel != DbgState.uCsStart)
12167 {
12168 rcStrict = VINF_EM_DBG_STEPPED;
12169 break;
12170 }
12171 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_DR7);
12172 }
12173
12174 /*
12175 * Update when dtrace settings changes (DBGF kicks us, so no need to check).
12176 */
12177 if (VBOXVMM_GET_SETTINGS_SEQ_NO() != DbgState.uDtraceSettingsSeqNo)
12178 hmR0VmxPreRunGuestDebugStateUpdate(pVCpu, &VmxTransient, &DbgState);
12179 }
12180
12181 /*
12182 * Clear the X86_EFL_TF if necessary.
12183 */
12184 if (pVCpu->hm.s.fClearTrapFlag)
12185 {
12186 int rc = hmR0VmxImportGuestState(pVCpu, VmxTransient.pVmcsInfo, CPUMCTX_EXTRN_RFLAGS);
12187 AssertRC(rc);
12188 pVCpu->hm.s.fClearTrapFlag = false;
12189 pVCpu->cpum.GstCtx.eflags.Bits.u1TF = 0;
12190 }
12191 /** @todo there seems to be issues with the resume flag when the monitor trap
12192 * flag is pending without being used. Seen early in bios init when
12193 * accessing APIC page in protected mode. */
12194
12195 /*
12196 * Restore VM-exit control settings as we may not re-enter this function the
12197 * next time around.
12198 */
12199 rcStrict = hmR0VmxRunDebugStateRevert(pVCpu, &VmxTransient, &DbgState, rcStrict);
12200
12201 /* Restore HMCPU indicators. */
12202 pVCpu->hm.s.fUsingDebugLoop = false;
12203 pVCpu->hm.s.fDebugWantRdTscExit = false;
12204 pVCpu->hm.s.fSingleInstruction = fSavedSingleInstruction;
12205
12206 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatEntry, x);
12207 return rcStrict;
12208}
12209
12210
12211/** @} */
12212
12213
12214/**
12215 * Checks if any expensive dtrace probes are enabled and we should go to the
12216 * debug loop.
12217 *
12218 * @returns true if we should use debug loop, false if not.
12219 */
12220static bool hmR0VmxAnyExpensiveProbesEnabled(void)
12221{
12222 /* It's probably faster to OR the raw 32-bit counter variables together.
12223 Since the variables are in an array and the probes are next to one
12224 another (more or less), we have good locality. So, better read
12225 eight-nine cache lines ever time and only have one conditional, than
12226 128+ conditionals, right? */
12227 return ( VBOXVMM_R0_HMVMX_VMEXIT_ENABLED_RAW() /* expensive too due to context */
12228 | VBOXVMM_XCPT_DE_ENABLED_RAW()
12229 | VBOXVMM_XCPT_DB_ENABLED_RAW()
12230 | VBOXVMM_XCPT_BP_ENABLED_RAW()
12231 | VBOXVMM_XCPT_OF_ENABLED_RAW()
12232 | VBOXVMM_XCPT_BR_ENABLED_RAW()
12233 | VBOXVMM_XCPT_UD_ENABLED_RAW()
12234 | VBOXVMM_XCPT_NM_ENABLED_RAW()
12235 | VBOXVMM_XCPT_DF_ENABLED_RAW()
12236 | VBOXVMM_XCPT_TS_ENABLED_RAW()
12237 | VBOXVMM_XCPT_NP_ENABLED_RAW()
12238 | VBOXVMM_XCPT_SS_ENABLED_RAW()
12239 | VBOXVMM_XCPT_GP_ENABLED_RAW()
12240 | VBOXVMM_XCPT_PF_ENABLED_RAW()
12241 | VBOXVMM_XCPT_MF_ENABLED_RAW()
12242 | VBOXVMM_XCPT_AC_ENABLED_RAW()
12243 | VBOXVMM_XCPT_XF_ENABLED_RAW()
12244 | VBOXVMM_XCPT_VE_ENABLED_RAW()
12245 | VBOXVMM_XCPT_SX_ENABLED_RAW()
12246 | VBOXVMM_INT_SOFTWARE_ENABLED_RAW()
12247 | VBOXVMM_INT_HARDWARE_ENABLED_RAW()
12248 ) != 0
12249 || ( VBOXVMM_INSTR_HALT_ENABLED_RAW()
12250 | VBOXVMM_INSTR_MWAIT_ENABLED_RAW()
12251 | VBOXVMM_INSTR_MONITOR_ENABLED_RAW()
12252 | VBOXVMM_INSTR_CPUID_ENABLED_RAW()
12253 | VBOXVMM_INSTR_INVD_ENABLED_RAW()
12254 | VBOXVMM_INSTR_WBINVD_ENABLED_RAW()
12255 | VBOXVMM_INSTR_INVLPG_ENABLED_RAW()
12256 | VBOXVMM_INSTR_RDTSC_ENABLED_RAW()
12257 | VBOXVMM_INSTR_RDTSCP_ENABLED_RAW()
12258 | VBOXVMM_INSTR_RDPMC_ENABLED_RAW()
12259 | VBOXVMM_INSTR_RDMSR_ENABLED_RAW()
12260 | VBOXVMM_INSTR_WRMSR_ENABLED_RAW()
12261 | VBOXVMM_INSTR_CRX_READ_ENABLED_RAW()
12262 | VBOXVMM_INSTR_CRX_WRITE_ENABLED_RAW()
12263 | VBOXVMM_INSTR_DRX_READ_ENABLED_RAW()
12264 | VBOXVMM_INSTR_DRX_WRITE_ENABLED_RAW()
12265 | VBOXVMM_INSTR_PAUSE_ENABLED_RAW()
12266 | VBOXVMM_INSTR_XSETBV_ENABLED_RAW()
12267 | VBOXVMM_INSTR_SIDT_ENABLED_RAW()
12268 | VBOXVMM_INSTR_LIDT_ENABLED_RAW()
12269 | VBOXVMM_INSTR_SGDT_ENABLED_RAW()
12270 | VBOXVMM_INSTR_LGDT_ENABLED_RAW()
12271 | VBOXVMM_INSTR_SLDT_ENABLED_RAW()
12272 | VBOXVMM_INSTR_LLDT_ENABLED_RAW()
12273 | VBOXVMM_INSTR_STR_ENABLED_RAW()
12274 | VBOXVMM_INSTR_LTR_ENABLED_RAW()
12275 | VBOXVMM_INSTR_GETSEC_ENABLED_RAW()
12276 | VBOXVMM_INSTR_RSM_ENABLED_RAW()
12277 | VBOXVMM_INSTR_RDRAND_ENABLED_RAW()
12278 | VBOXVMM_INSTR_RDSEED_ENABLED_RAW()
12279 | VBOXVMM_INSTR_XSAVES_ENABLED_RAW()
12280 | VBOXVMM_INSTR_XRSTORS_ENABLED_RAW()
12281 | VBOXVMM_INSTR_VMM_CALL_ENABLED_RAW()
12282 | VBOXVMM_INSTR_VMX_VMCLEAR_ENABLED_RAW()
12283 | VBOXVMM_INSTR_VMX_VMLAUNCH_ENABLED_RAW()
12284 | VBOXVMM_INSTR_VMX_VMPTRLD_ENABLED_RAW()
12285 | VBOXVMM_INSTR_VMX_VMPTRST_ENABLED_RAW()
12286 | VBOXVMM_INSTR_VMX_VMREAD_ENABLED_RAW()
12287 | VBOXVMM_INSTR_VMX_VMRESUME_ENABLED_RAW()
12288 | VBOXVMM_INSTR_VMX_VMWRITE_ENABLED_RAW()
12289 | VBOXVMM_INSTR_VMX_VMXOFF_ENABLED_RAW()
12290 | VBOXVMM_INSTR_VMX_VMXON_ENABLED_RAW()
12291 | VBOXVMM_INSTR_VMX_VMFUNC_ENABLED_RAW()
12292 | VBOXVMM_INSTR_VMX_INVEPT_ENABLED_RAW()
12293 | VBOXVMM_INSTR_VMX_INVVPID_ENABLED_RAW()
12294 | VBOXVMM_INSTR_VMX_INVPCID_ENABLED_RAW()
12295 ) != 0
12296 || ( VBOXVMM_EXIT_TASK_SWITCH_ENABLED_RAW()
12297 | VBOXVMM_EXIT_HALT_ENABLED_RAW()
12298 | VBOXVMM_EXIT_MWAIT_ENABLED_RAW()
12299 | VBOXVMM_EXIT_MONITOR_ENABLED_RAW()
12300 | VBOXVMM_EXIT_CPUID_ENABLED_RAW()
12301 | VBOXVMM_EXIT_INVD_ENABLED_RAW()
12302 | VBOXVMM_EXIT_WBINVD_ENABLED_RAW()
12303 | VBOXVMM_EXIT_INVLPG_ENABLED_RAW()
12304 | VBOXVMM_EXIT_RDTSC_ENABLED_RAW()
12305 | VBOXVMM_EXIT_RDTSCP_ENABLED_RAW()
12306 | VBOXVMM_EXIT_RDPMC_ENABLED_RAW()
12307 | VBOXVMM_EXIT_RDMSR_ENABLED_RAW()
12308 | VBOXVMM_EXIT_WRMSR_ENABLED_RAW()
12309 | VBOXVMM_EXIT_CRX_READ_ENABLED_RAW()
12310 | VBOXVMM_EXIT_CRX_WRITE_ENABLED_RAW()
12311 | VBOXVMM_EXIT_DRX_READ_ENABLED_RAW()
12312 | VBOXVMM_EXIT_DRX_WRITE_ENABLED_RAW()
12313 | VBOXVMM_EXIT_PAUSE_ENABLED_RAW()
12314 | VBOXVMM_EXIT_XSETBV_ENABLED_RAW()
12315 | VBOXVMM_EXIT_SIDT_ENABLED_RAW()
12316 | VBOXVMM_EXIT_LIDT_ENABLED_RAW()
12317 | VBOXVMM_EXIT_SGDT_ENABLED_RAW()
12318 | VBOXVMM_EXIT_LGDT_ENABLED_RAW()
12319 | VBOXVMM_EXIT_SLDT_ENABLED_RAW()
12320 | VBOXVMM_EXIT_LLDT_ENABLED_RAW()
12321 | VBOXVMM_EXIT_STR_ENABLED_RAW()
12322 | VBOXVMM_EXIT_LTR_ENABLED_RAW()
12323 | VBOXVMM_EXIT_GETSEC_ENABLED_RAW()
12324 | VBOXVMM_EXIT_RSM_ENABLED_RAW()
12325 | VBOXVMM_EXIT_RDRAND_ENABLED_RAW()
12326 | VBOXVMM_EXIT_RDSEED_ENABLED_RAW()
12327 | VBOXVMM_EXIT_XSAVES_ENABLED_RAW()
12328 | VBOXVMM_EXIT_XRSTORS_ENABLED_RAW()
12329 | VBOXVMM_EXIT_VMM_CALL_ENABLED_RAW()
12330 | VBOXVMM_EXIT_VMX_VMCLEAR_ENABLED_RAW()
12331 | VBOXVMM_EXIT_VMX_VMLAUNCH_ENABLED_RAW()
12332 | VBOXVMM_EXIT_VMX_VMPTRLD_ENABLED_RAW()
12333 | VBOXVMM_EXIT_VMX_VMPTRST_ENABLED_RAW()
12334 | VBOXVMM_EXIT_VMX_VMREAD_ENABLED_RAW()
12335 | VBOXVMM_EXIT_VMX_VMRESUME_ENABLED_RAW()
12336 | VBOXVMM_EXIT_VMX_VMWRITE_ENABLED_RAW()
12337 | VBOXVMM_EXIT_VMX_VMXOFF_ENABLED_RAW()
12338 | VBOXVMM_EXIT_VMX_VMXON_ENABLED_RAW()
12339 | VBOXVMM_EXIT_VMX_VMFUNC_ENABLED_RAW()
12340 | VBOXVMM_EXIT_VMX_INVEPT_ENABLED_RAW()
12341 | VBOXVMM_EXIT_VMX_INVVPID_ENABLED_RAW()
12342 | VBOXVMM_EXIT_VMX_INVPCID_ENABLED_RAW()
12343 | VBOXVMM_EXIT_VMX_EPT_VIOLATION_ENABLED_RAW()
12344 | VBOXVMM_EXIT_VMX_EPT_MISCONFIG_ENABLED_RAW()
12345 | VBOXVMM_EXIT_VMX_VAPIC_ACCESS_ENABLED_RAW()
12346 | VBOXVMM_EXIT_VMX_VAPIC_WRITE_ENABLED_RAW()
12347 ) != 0;
12348}
12349
12350
12351/**
12352 * Runs the guest using hardware-assisted VMX.
12353 *
12354 * @returns Strict VBox status code (i.e. informational status codes too).
12355 * @param pVCpu The cross context virtual CPU structure.
12356 */
12357VMMR0DECL(VBOXSTRICTRC) VMXR0RunGuestCode(PVMCPUCC pVCpu)
12358{
12359 AssertPtr(pVCpu);
12360 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
12361 Assert(VMMRZCallRing3IsEnabled(pVCpu));
12362 Assert(!ASMAtomicUoReadU64(&pCtx->fExtrn));
12363 HMVMX_ASSERT_PREEMPT_SAFE(pVCpu);
12364
12365 VMMRZCallRing3SetNotification(pVCpu, hmR0VmxCallRing3Callback, pCtx);
12366
12367 VBOXSTRICTRC rcStrict;
12368 uint32_t cLoops = 0;
12369 for (;;)
12370 {
12371#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
12372 bool const fInNestedGuestMode = CPUMIsGuestInVmxNonRootMode(pCtx);
12373#else
12374 bool const fInNestedGuestMode = false;
12375#endif
12376 if (!fInNestedGuestMode)
12377 {
12378 if ( !pVCpu->hm.s.fUseDebugLoop
12379 && (!VBOXVMM_ANY_PROBES_ENABLED() || !hmR0VmxAnyExpensiveProbesEnabled())
12380 && !DBGFIsStepping(pVCpu)
12381 && !pVCpu->CTX_SUFF(pVM)->dbgf.ro.cEnabledInt3Breakpoints)
12382 rcStrict = hmR0VmxRunGuestCodeNormal(pVCpu, &cLoops);
12383 else
12384 rcStrict = hmR0VmxRunGuestCodeDebug(pVCpu, &cLoops);
12385 }
12386#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
12387 else
12388 rcStrict = hmR0VmxRunGuestCodeNested(pVCpu, &cLoops);
12389
12390 if (rcStrict == VINF_VMX_VMLAUNCH_VMRESUME)
12391 {
12392 Assert(CPUMIsGuestInVmxNonRootMode(pCtx));
12393 continue;
12394 }
12395 if (rcStrict == VINF_VMX_VMEXIT)
12396 {
12397 Assert(!CPUMIsGuestInVmxNonRootMode(pCtx));
12398 continue;
12399 }
12400#endif
12401 break;
12402 }
12403
12404 int const rcLoop = VBOXSTRICTRC_VAL(rcStrict);
12405 switch (rcLoop)
12406 {
12407 case VERR_EM_INTERPRETER: rcStrict = VINF_EM_RAW_EMULATE_INSTR; break;
12408 case VINF_EM_RESET: rcStrict = VINF_EM_TRIPLE_FAULT; break;
12409 }
12410
12411 int rc2 = hmR0VmxExitToRing3(pVCpu, rcStrict);
12412 if (RT_FAILURE(rc2))
12413 {
12414 pVCpu->hm.s.u32HMError = (uint32_t)VBOXSTRICTRC_VAL(rcStrict);
12415 rcStrict = rc2;
12416 }
12417 Assert(!ASMAtomicUoReadU64(&pCtx->fExtrn));
12418 Assert(!VMMRZCallRing3IsNotificationSet(pVCpu));
12419 return rcStrict;
12420}
12421
12422
12423#ifndef HMVMX_USE_FUNCTION_TABLE
12424/**
12425 * Handles a guest VM-exit from hardware-assisted VMX execution.
12426 *
12427 * @returns Strict VBox status code (i.e. informational status codes too).
12428 * @param pVCpu The cross context virtual CPU structure.
12429 * @param pVmxTransient The VMX-transient structure.
12430 */
12431DECLINLINE(VBOXSTRICTRC) hmR0VmxHandleExit(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
12432{
12433#ifdef DEBUG_ramshankar
12434# define VMEXIT_CALL_RET(a_fSave, a_CallExpr) \
12435 do { \
12436 if (a_fSave != 0) \
12437 hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, HMVMX_CPUMCTX_EXTRN_ALL); \
12438 VBOXSTRICTRC rcStrict = a_CallExpr; \
12439 if (a_fSave != 0) \
12440 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_ALL_GUEST); \
12441 return rcStrict; \
12442 } while (0)
12443#else
12444# define VMEXIT_CALL_RET(a_fSave, a_CallExpr) return a_CallExpr
12445#endif
12446 uint32_t const uExitReason = pVmxTransient->uExitReason;
12447 switch (uExitReason)
12448 {
12449 case VMX_EXIT_EPT_MISCONFIG: VMEXIT_CALL_RET(0, hmR0VmxExitEptMisconfig(pVCpu, pVmxTransient));
12450 case VMX_EXIT_EPT_VIOLATION: VMEXIT_CALL_RET(0, hmR0VmxExitEptViolation(pVCpu, pVmxTransient));
12451 case VMX_EXIT_IO_INSTR: VMEXIT_CALL_RET(0, hmR0VmxExitIoInstr(pVCpu, pVmxTransient));
12452 case VMX_EXIT_CPUID: VMEXIT_CALL_RET(0, hmR0VmxExitCpuid(pVCpu, pVmxTransient));
12453 case VMX_EXIT_RDTSC: VMEXIT_CALL_RET(0, hmR0VmxExitRdtsc(pVCpu, pVmxTransient));
12454 case VMX_EXIT_RDTSCP: VMEXIT_CALL_RET(0, hmR0VmxExitRdtscp(pVCpu, pVmxTransient));
12455 case VMX_EXIT_APIC_ACCESS: VMEXIT_CALL_RET(0, hmR0VmxExitApicAccess(pVCpu, pVmxTransient));
12456 case VMX_EXIT_XCPT_OR_NMI: VMEXIT_CALL_RET(0, hmR0VmxExitXcptOrNmi(pVCpu, pVmxTransient));
12457 case VMX_EXIT_MOV_CRX: VMEXIT_CALL_RET(0, hmR0VmxExitMovCRx(pVCpu, pVmxTransient));
12458 case VMX_EXIT_EXT_INT: VMEXIT_CALL_RET(0, hmR0VmxExitExtInt(pVCpu, pVmxTransient));
12459 case VMX_EXIT_INT_WINDOW: VMEXIT_CALL_RET(0, hmR0VmxExitIntWindow(pVCpu, pVmxTransient));
12460 case VMX_EXIT_TPR_BELOW_THRESHOLD: VMEXIT_CALL_RET(0, hmR0VmxExitTprBelowThreshold(pVCpu, pVmxTransient));
12461 case VMX_EXIT_MWAIT: VMEXIT_CALL_RET(0, hmR0VmxExitMwait(pVCpu, pVmxTransient));
12462 case VMX_EXIT_MONITOR: VMEXIT_CALL_RET(0, hmR0VmxExitMonitor(pVCpu, pVmxTransient));
12463 case VMX_EXIT_TASK_SWITCH: VMEXIT_CALL_RET(0, hmR0VmxExitTaskSwitch(pVCpu, pVmxTransient));
12464 case VMX_EXIT_PREEMPT_TIMER: VMEXIT_CALL_RET(0, hmR0VmxExitPreemptTimer(pVCpu, pVmxTransient));
12465 case VMX_EXIT_RDMSR: VMEXIT_CALL_RET(0, hmR0VmxExitRdmsr(pVCpu, pVmxTransient));
12466 case VMX_EXIT_WRMSR: VMEXIT_CALL_RET(0, hmR0VmxExitWrmsr(pVCpu, pVmxTransient));
12467 case VMX_EXIT_VMCALL: VMEXIT_CALL_RET(0, hmR0VmxExitVmcall(pVCpu, pVmxTransient));
12468 case VMX_EXIT_MOV_DRX: VMEXIT_CALL_RET(0, hmR0VmxExitMovDRx(pVCpu, pVmxTransient));
12469 case VMX_EXIT_HLT: VMEXIT_CALL_RET(0, hmR0VmxExitHlt(pVCpu, pVmxTransient));
12470 case VMX_EXIT_INVD: VMEXIT_CALL_RET(0, hmR0VmxExitInvd(pVCpu, pVmxTransient));
12471 case VMX_EXIT_INVLPG: VMEXIT_CALL_RET(0, hmR0VmxExitInvlpg(pVCpu, pVmxTransient));
12472 case VMX_EXIT_MTF: VMEXIT_CALL_RET(0, hmR0VmxExitMtf(pVCpu, pVmxTransient));
12473 case VMX_EXIT_PAUSE: VMEXIT_CALL_RET(0, hmR0VmxExitPause(pVCpu, pVmxTransient));
12474 case VMX_EXIT_WBINVD: VMEXIT_CALL_RET(0, hmR0VmxExitWbinvd(pVCpu, pVmxTransient));
12475 case VMX_EXIT_XSETBV: VMEXIT_CALL_RET(0, hmR0VmxExitXsetbv(pVCpu, pVmxTransient));
12476 case VMX_EXIT_INVPCID: VMEXIT_CALL_RET(0, hmR0VmxExitInvpcid(pVCpu, pVmxTransient));
12477 case VMX_EXIT_GETSEC: VMEXIT_CALL_RET(0, hmR0VmxExitGetsec(pVCpu, pVmxTransient));
12478 case VMX_EXIT_RDPMC: VMEXIT_CALL_RET(0, hmR0VmxExitRdpmc(pVCpu, pVmxTransient));
12479#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
12480 case VMX_EXIT_VMCLEAR: VMEXIT_CALL_RET(0, hmR0VmxExitVmclear(pVCpu, pVmxTransient));
12481 case VMX_EXIT_VMLAUNCH: VMEXIT_CALL_RET(0, hmR0VmxExitVmlaunch(pVCpu, pVmxTransient));
12482 case VMX_EXIT_VMPTRLD: VMEXIT_CALL_RET(0, hmR0VmxExitVmptrld(pVCpu, pVmxTransient));
12483 case VMX_EXIT_VMPTRST: VMEXIT_CALL_RET(0, hmR0VmxExitVmptrst(pVCpu, pVmxTransient));
12484 case VMX_EXIT_VMREAD: VMEXIT_CALL_RET(0, hmR0VmxExitVmread(pVCpu, pVmxTransient));
12485 case VMX_EXIT_VMRESUME: VMEXIT_CALL_RET(0, hmR0VmxExitVmwrite(pVCpu, pVmxTransient));
12486 case VMX_EXIT_VMWRITE: VMEXIT_CALL_RET(0, hmR0VmxExitVmresume(pVCpu, pVmxTransient));
12487 case VMX_EXIT_VMXOFF: VMEXIT_CALL_RET(0, hmR0VmxExitVmxoff(pVCpu, pVmxTransient));
12488 case VMX_EXIT_VMXON: VMEXIT_CALL_RET(0, hmR0VmxExitVmxon(pVCpu, pVmxTransient));
12489 case VMX_EXIT_INVVPID: VMEXIT_CALL_RET(0, hmR0VmxExitInvvpid(pVCpu, pVmxTransient));
12490 case VMX_EXIT_INVEPT: VMEXIT_CALL_RET(0, hmR0VmxExitSetPendingXcptUD(pVCpu, pVmxTransient));
12491#else
12492 case VMX_EXIT_VMCLEAR:
12493 case VMX_EXIT_VMLAUNCH:
12494 case VMX_EXIT_VMPTRLD:
12495 case VMX_EXIT_VMPTRST:
12496 case VMX_EXIT_VMREAD:
12497 case VMX_EXIT_VMRESUME:
12498 case VMX_EXIT_VMWRITE:
12499 case VMX_EXIT_VMXOFF:
12500 case VMX_EXIT_VMXON:
12501 case VMX_EXIT_INVVPID:
12502 case VMX_EXIT_INVEPT:
12503 return hmR0VmxExitSetPendingXcptUD(pVCpu, pVmxTransient);
12504#endif
12505
12506 case VMX_EXIT_TRIPLE_FAULT: return hmR0VmxExitTripleFault(pVCpu, pVmxTransient);
12507 case VMX_EXIT_NMI_WINDOW: return hmR0VmxExitNmiWindow(pVCpu, pVmxTransient);
12508 case VMX_EXIT_ERR_INVALID_GUEST_STATE: return hmR0VmxExitErrInvalidGuestState(pVCpu, pVmxTransient);
12509
12510 case VMX_EXIT_INIT_SIGNAL:
12511 case VMX_EXIT_SIPI:
12512 case VMX_EXIT_IO_SMI:
12513 case VMX_EXIT_SMI:
12514 case VMX_EXIT_ERR_MSR_LOAD:
12515 case VMX_EXIT_ERR_MACHINE_CHECK:
12516 case VMX_EXIT_PML_FULL:
12517 case VMX_EXIT_VIRTUALIZED_EOI:
12518 case VMX_EXIT_GDTR_IDTR_ACCESS:
12519 case VMX_EXIT_LDTR_TR_ACCESS:
12520 case VMX_EXIT_APIC_WRITE:
12521 case VMX_EXIT_RDRAND:
12522 case VMX_EXIT_RSM:
12523 case VMX_EXIT_VMFUNC:
12524 case VMX_EXIT_ENCLS:
12525 case VMX_EXIT_RDSEED:
12526 case VMX_EXIT_XSAVES:
12527 case VMX_EXIT_XRSTORS:
12528 case VMX_EXIT_UMWAIT:
12529 case VMX_EXIT_TPAUSE:
12530 default:
12531 return hmR0VmxExitErrUnexpected(pVCpu, pVmxTransient);
12532 }
12533#undef VMEXIT_CALL_RET
12534}
12535#endif /* !HMVMX_USE_FUNCTION_TABLE */
12536
12537
12538#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
12539/**
12540 * Handles a nested-guest VM-exit from hardware-assisted VMX execution.
12541 *
12542 * @returns Strict VBox status code (i.e. informational status codes too).
12543 * @param pVCpu The cross context virtual CPU structure.
12544 * @param pVmxTransient The VMX-transient structure.
12545 */
12546DECLINLINE(VBOXSTRICTRC) hmR0VmxHandleExitNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
12547{
12548 /** @todo NSTVMX: Remove after debugging page-fault issue. */
12549#ifdef DEBUG_ramshankar
12550 hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, HMVMX_CPUMCTX_EXTRN_ALL);
12551 Log4Func(("cs:rip=%#04x:%#RX64 rsp=%#RX64 eflags=%#RX32 cr3=%#RX64\n", pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip,
12552 pVCpu->cpum.GstCtx.rsp, pVCpu->cpum.GstCtx.eflags.u32, pVCpu->cpum.GstCtx.cr3));
12553#endif
12554
12555 uint32_t const uExitReason = pVmxTransient->uExitReason;
12556 switch (uExitReason)
12557 {
12558 case VMX_EXIT_EPT_MISCONFIG: return hmR0VmxExitEptMisconfig(pVCpu, pVmxTransient);
12559 case VMX_EXIT_EPT_VIOLATION: return hmR0VmxExitEptViolation(pVCpu, pVmxTransient);
12560 case VMX_EXIT_XCPT_OR_NMI: return hmR0VmxExitXcptOrNmiNested(pVCpu, pVmxTransient);
12561 case VMX_EXIT_IO_INSTR: return hmR0VmxExitIoInstrNested(pVCpu, pVmxTransient);
12562 case VMX_EXIT_HLT: return hmR0VmxExitHltNested(pVCpu, pVmxTransient);
12563
12564 /*
12565 * We shouldn't direct host physical interrupts to the nested-guest.
12566 */
12567 case VMX_EXIT_EXT_INT:
12568 return hmR0VmxExitExtInt(pVCpu, pVmxTransient);
12569
12570 /*
12571 * Instructions that cause VM-exits unconditionally or the condition is
12572 * always is taken solely from the guest hypervisor (meaning if the VM-exit
12573 * happens, it's guaranteed to be a nested-guest VM-exit).
12574 *
12575 * - Provides VM-exit instruction length ONLY.
12576 */
12577 case VMX_EXIT_CPUID: /* Unconditional. */
12578 case VMX_EXIT_VMCALL:
12579 case VMX_EXIT_GETSEC:
12580 case VMX_EXIT_INVD:
12581 case VMX_EXIT_XSETBV:
12582 case VMX_EXIT_VMLAUNCH:
12583 case VMX_EXIT_VMRESUME:
12584 case VMX_EXIT_VMXOFF:
12585 case VMX_EXIT_ENCLS: /* Condition specified solely by guest hypervisor. */
12586 case VMX_EXIT_VMFUNC:
12587 return hmR0VmxExitInstrNested(pVCpu, pVmxTransient);
12588
12589 /*
12590 * Instructions that cause VM-exits unconditionally or the condition is
12591 * always is taken solely from the guest hypervisor (meaning if the VM-exit
12592 * happens, it's guaranteed to be a nested-guest VM-exit).
12593 *
12594 * - Provides VM-exit instruction length.
12595 * - Provides VM-exit information.
12596 * - Optionally provides Exit qualification.
12597 *
12598 * Since Exit qualification is 0 for all VM-exits where it is not
12599 * applicable, reading and passing it to the guest should produce
12600 * defined behavior.
12601 *
12602 * See Intel spec. 27.2.1 "Basic VM-Exit Information".
12603 */
12604 case VMX_EXIT_INVEPT: /* Unconditional. */
12605 case VMX_EXIT_INVVPID:
12606 case VMX_EXIT_VMCLEAR:
12607 case VMX_EXIT_VMPTRLD:
12608 case VMX_EXIT_VMPTRST:
12609 case VMX_EXIT_VMXON:
12610 case VMX_EXIT_GDTR_IDTR_ACCESS: /* Condition specified solely by guest hypervisor. */
12611 case VMX_EXIT_LDTR_TR_ACCESS:
12612 case VMX_EXIT_RDRAND:
12613 case VMX_EXIT_RDSEED:
12614 case VMX_EXIT_XSAVES:
12615 case VMX_EXIT_XRSTORS:
12616 case VMX_EXIT_UMWAIT:
12617 case VMX_EXIT_TPAUSE:
12618 return hmR0VmxExitInstrWithInfoNested(pVCpu, pVmxTransient);
12619
12620 case VMX_EXIT_RDTSC: return hmR0VmxExitRdtscNested(pVCpu, pVmxTransient);
12621 case VMX_EXIT_RDTSCP: return hmR0VmxExitRdtscpNested(pVCpu, pVmxTransient);
12622 case VMX_EXIT_RDMSR: return hmR0VmxExitRdmsrNested(pVCpu, pVmxTransient);
12623 case VMX_EXIT_WRMSR: return hmR0VmxExitWrmsrNested(pVCpu, pVmxTransient);
12624 case VMX_EXIT_INVLPG: return hmR0VmxExitInvlpgNested(pVCpu, pVmxTransient);
12625 case VMX_EXIT_INVPCID: return hmR0VmxExitInvpcidNested(pVCpu, pVmxTransient);
12626 case VMX_EXIT_TASK_SWITCH: return hmR0VmxExitTaskSwitchNested(pVCpu, pVmxTransient);
12627 case VMX_EXIT_WBINVD: return hmR0VmxExitWbinvdNested(pVCpu, pVmxTransient);
12628 case VMX_EXIT_MTF: return hmR0VmxExitMtfNested(pVCpu, pVmxTransient);
12629 case VMX_EXIT_APIC_ACCESS: return hmR0VmxExitApicAccessNested(pVCpu, pVmxTransient);
12630 case VMX_EXIT_APIC_WRITE: return hmR0VmxExitApicWriteNested(pVCpu, pVmxTransient);
12631 case VMX_EXIT_VIRTUALIZED_EOI: return hmR0VmxExitVirtEoiNested(pVCpu, pVmxTransient);
12632 case VMX_EXIT_MOV_CRX: return hmR0VmxExitMovCRxNested(pVCpu, pVmxTransient);
12633 case VMX_EXIT_INT_WINDOW: return hmR0VmxExitIntWindowNested(pVCpu, pVmxTransient);
12634 case VMX_EXIT_NMI_WINDOW: return hmR0VmxExitNmiWindowNested(pVCpu, pVmxTransient);
12635 case VMX_EXIT_TPR_BELOW_THRESHOLD: return hmR0VmxExitTprBelowThresholdNested(pVCpu, pVmxTransient);
12636 case VMX_EXIT_MWAIT: return hmR0VmxExitMwaitNested(pVCpu, pVmxTransient);
12637 case VMX_EXIT_MONITOR: return hmR0VmxExitMonitorNested(pVCpu, pVmxTransient);
12638 case VMX_EXIT_PAUSE: return hmR0VmxExitPauseNested(pVCpu, pVmxTransient);
12639
12640 case VMX_EXIT_PREEMPT_TIMER:
12641 {
12642 /** @todo NSTVMX: Preempt timer. */
12643 return hmR0VmxExitPreemptTimer(pVCpu, pVmxTransient);
12644 }
12645
12646 case VMX_EXIT_MOV_DRX: return hmR0VmxExitMovDRxNested(pVCpu, pVmxTransient);
12647 case VMX_EXIT_RDPMC: return hmR0VmxExitRdpmcNested(pVCpu, pVmxTransient);
12648
12649 case VMX_EXIT_VMREAD:
12650 case VMX_EXIT_VMWRITE: return hmR0VmxExitVmreadVmwriteNested(pVCpu, pVmxTransient);
12651
12652 case VMX_EXIT_TRIPLE_FAULT: return hmR0VmxExitTripleFaultNested(pVCpu, pVmxTransient);
12653 case VMX_EXIT_ERR_INVALID_GUEST_STATE: return hmR0VmxExitErrInvalidGuestStateNested(pVCpu, pVmxTransient);
12654
12655 case VMX_EXIT_INIT_SIGNAL:
12656 case VMX_EXIT_SIPI:
12657 case VMX_EXIT_IO_SMI:
12658 case VMX_EXIT_SMI:
12659 case VMX_EXIT_ERR_MSR_LOAD:
12660 case VMX_EXIT_ERR_MACHINE_CHECK:
12661 case VMX_EXIT_PML_FULL:
12662 case VMX_EXIT_RSM:
12663 default:
12664 return hmR0VmxExitErrUnexpected(pVCpu, pVmxTransient);
12665 }
12666}
12667#endif /* VBOX_WITH_NESTED_HWVIRT_VMX */
12668
12669
12670/** @name VM-exit helpers.
12671 * @{
12672 */
12673/* -=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= */
12674/* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= VM-exit helpers -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- */
12675/* -=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= */
12676
12677/** Macro for VM-exits called unexpectedly. */
12678#define HMVMX_UNEXPECTED_EXIT_RET(a_pVCpu, a_HmError) \
12679 do { \
12680 (a_pVCpu)->hm.s.u32HMError = (a_HmError); \
12681 return VERR_VMX_UNEXPECTED_EXIT; \
12682 } while (0)
12683
12684#ifdef VBOX_STRICT
12685/* Is there some generic IPRT define for this that are not in Runtime/internal/\* ?? */
12686# define HMVMX_ASSERT_PREEMPT_CPUID_VAR() \
12687 RTCPUID const idAssertCpu = RTThreadPreemptIsEnabled(NIL_RTTHREAD) ? NIL_RTCPUID : RTMpCpuId()
12688
12689# define HMVMX_ASSERT_PREEMPT_CPUID() \
12690 do { \
12691 RTCPUID const idAssertCpuNow = RTThreadPreemptIsEnabled(NIL_RTTHREAD) ? NIL_RTCPUID : RTMpCpuId(); \
12692 AssertMsg(idAssertCpu == idAssertCpuNow, ("VMX %#x, %#x\n", idAssertCpu, idAssertCpuNow)); \
12693 } while (0)
12694
12695# define HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(a_pVCpu, a_pVmxTransient) \
12696 do { \
12697 AssertPtr((a_pVCpu)); \
12698 AssertPtr((a_pVmxTransient)); \
12699 Assert((a_pVmxTransient)->fVMEntryFailed == false); \
12700 Assert((a_pVmxTransient)->pVmcsInfo); \
12701 Assert(ASMIntAreEnabled()); \
12702 HMVMX_ASSERT_PREEMPT_SAFE(a_pVCpu); \
12703 HMVMX_ASSERT_PREEMPT_CPUID_VAR(); \
12704 Log4Func(("vcpu[%RU32]\n", (a_pVCpu)->idCpu)); \
12705 HMVMX_ASSERT_PREEMPT_SAFE(a_pVCpu); \
12706 if (VMMR0IsLogFlushDisabled((a_pVCpu))) \
12707 HMVMX_ASSERT_PREEMPT_CPUID(); \
12708 HMVMX_STOP_EXIT_DISPATCH_PROF(); \
12709 } while (0)
12710
12711# define HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(a_pVCpu, a_pVmxTransient) \
12712 do { \
12713 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(a_pVCpu, a_pVmxTransient); \
12714 Assert((a_pVmxTransient)->fIsNestedGuest); \
12715 } while (0)
12716
12717# define HMVMX_VALIDATE_EXIT_XCPT_HANDLER_PARAMS(a_pVCpu, a_pVmxTransient) \
12718 do { \
12719 Log4Func(("\n")); \
12720 } while (0)
12721#else
12722# define HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(a_pVCpu, a_pVmxTransient) \
12723 do { \
12724 HMVMX_STOP_EXIT_DISPATCH_PROF(); \
12725 NOREF((a_pVCpu)); NOREF((a_pVmxTransient)); \
12726 } while (0)
12727
12728# define HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(a_pVCpu, a_pVmxTransient) \
12729 do { HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(a_pVCpu, a_pVmxTransient); } while (0)
12730
12731# define HMVMX_VALIDATE_EXIT_XCPT_HANDLER_PARAMS(a_pVCpu, a_pVmxTransient) do { } while (0)
12732#endif
12733
12734#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
12735/** Macro that does the necessary privilege checks and intercepted VM-exits for
12736 * guests that attempted to execute a VMX instruction. */
12737# define HMVMX_CHECK_EXIT_DUE_TO_VMX_INSTR(a_pVCpu, a_uExitReason) \
12738 do \
12739 { \
12740 VBOXSTRICTRC rcStrictTmp = hmR0VmxCheckExitDueToVmxInstr((a_pVCpu), (a_uExitReason)); \
12741 if (rcStrictTmp == VINF_SUCCESS) \
12742 { /* likely */ } \
12743 else if (rcStrictTmp == VINF_HM_PENDING_XCPT) \
12744 { \
12745 Assert((a_pVCpu)->hm.s.Event.fPending); \
12746 Log4Func(("Privilege checks failed -> %#x\n", VMX_ENTRY_INT_INFO_VECTOR((a_pVCpu)->hm.s.Event.u64IntInfo))); \
12747 return VINF_SUCCESS; \
12748 } \
12749 else \
12750 { \
12751 int rcTmp = VBOXSTRICTRC_VAL(rcStrictTmp); \
12752 AssertMsgFailedReturn(("Unexpected failure. rc=%Rrc", rcTmp), rcTmp); \
12753 } \
12754 } while (0)
12755
12756/** Macro that decodes a memory operand for an VM-exit caused by an instruction. */
12757# define HMVMX_DECODE_MEM_OPERAND(a_pVCpu, a_uExitInstrInfo, a_uExitQual, a_enmMemAccess, a_pGCPtrEffAddr) \
12758 do \
12759 { \
12760 VBOXSTRICTRC rcStrictTmp = hmR0VmxDecodeMemOperand((a_pVCpu), (a_uExitInstrInfo), (a_uExitQual), (a_enmMemAccess), \
12761 (a_pGCPtrEffAddr)); \
12762 if (rcStrictTmp == VINF_SUCCESS) \
12763 { /* likely */ } \
12764 else if (rcStrictTmp == VINF_HM_PENDING_XCPT) \
12765 { \
12766 uint8_t const uXcptTmp = VMX_ENTRY_INT_INFO_VECTOR((a_pVCpu)->hm.s.Event.u64IntInfo); \
12767 Log4Func(("Memory operand decoding failed, raising xcpt %#x\n", uXcptTmp)); \
12768 NOREF(uXcptTmp); \
12769 return VINF_SUCCESS; \
12770 } \
12771 else \
12772 { \
12773 Log4Func(("hmR0VmxDecodeMemOperand failed. rc=%Rrc\n", VBOXSTRICTRC_VAL(rcStrictTmp))); \
12774 return rcStrictTmp; \
12775 } \
12776 } while (0)
12777#endif /* VBOX_WITH_NESTED_HWVIRT_VMX */
12778
12779
12780/**
12781 * Advances the guest RIP by the specified number of bytes.
12782 *
12783 * @param pVCpu The cross context virtual CPU structure.
12784 * @param cbInstr Number of bytes to advance the RIP by.
12785 *
12786 * @remarks No-long-jump zone!!!
12787 */
12788DECLINLINE(void) hmR0VmxAdvanceGuestRipBy(PVMCPUCC pVCpu, uint32_t cbInstr)
12789{
12790 /* Advance the RIP. */
12791 pVCpu->cpum.GstCtx.rip += cbInstr;
12792 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP);
12793
12794 /* Update interrupt inhibition. */
12795 if ( VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS)
12796 && pVCpu->cpum.GstCtx.rip != EMGetInhibitInterruptsPC(pVCpu))
12797 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS);
12798}
12799
12800
12801/**
12802 * Advances the guest RIP after reading it from the VMCS.
12803 *
12804 * @returns VBox status code, no informational status codes.
12805 * @param pVCpu The cross context virtual CPU structure.
12806 * @param pVmxTransient The VMX-transient structure.
12807 *
12808 * @remarks No-long-jump zone!!!
12809 */
12810static int hmR0VmxAdvanceGuestRip(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
12811{
12812 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
12813 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, CPUMCTX_EXTRN_RIP | CPUMCTX_EXTRN_RFLAGS);
12814 AssertRCReturn(rc, rc);
12815
12816 hmR0VmxAdvanceGuestRipBy(pVCpu, pVmxTransient->cbExitInstr);
12817 return VINF_SUCCESS;
12818}
12819
12820
12821/**
12822 * Handle a condition that occurred while delivering an event through the guest or
12823 * nested-guest IDT.
12824 *
12825 * @returns Strict VBox status code (i.e. informational status codes too).
12826 * @retval VINF_SUCCESS if we should continue handling the VM-exit.
12827 * @retval VINF_HM_DOUBLE_FAULT if a \#DF condition was detected and we ought
12828 * to continue execution of the guest which will delivery the \#DF.
12829 * @retval VINF_EM_RESET if we detected a triple-fault condition.
12830 * @retval VERR_EM_GUEST_CPU_HANG if we detected a guest CPU hang.
12831 *
12832 * @param pVCpu The cross context virtual CPU structure.
12833 * @param pVmxTransient The VMX-transient structure.
12834 *
12835 * @remarks Requires all fields in HMVMX_READ_XCPT_INFO to be read from the VMCS.
12836 * Additionally, HMVMX_READ_EXIT_QUALIFICATION is required if the VM-exit
12837 * is due to an EPT violation, PML full or SPP-related event.
12838 *
12839 * @remarks No-long-jump zone!!!
12840 */
12841static VBOXSTRICTRC hmR0VmxCheckExitDueToEventDelivery(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
12842{
12843 Assert(!pVCpu->hm.s.Event.fPending);
12844 HMVMX_ASSERT_READ(pVmxTransient, HMVMX_READ_XCPT_INFO);
12845 if ( pVmxTransient->uExitReason == VMX_EXIT_EPT_VIOLATION
12846 || pVmxTransient->uExitReason == VMX_EXIT_PML_FULL
12847 || pVmxTransient->uExitReason == VMX_EXIT_SPP_EVENT)
12848 HMVMX_ASSERT_READ(pVmxTransient, HMVMX_READ_EXIT_QUALIFICATION);
12849
12850 VBOXSTRICTRC rcStrict = VINF_SUCCESS;
12851 PCVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
12852 uint32_t const uIdtVectorInfo = pVmxTransient->uIdtVectoringInfo;
12853 uint32_t const uExitIntInfo = pVmxTransient->uExitIntInfo;
12854 if (VMX_IDT_VECTORING_INFO_IS_VALID(uIdtVectorInfo))
12855 {
12856 uint32_t const uIdtVector = VMX_IDT_VECTORING_INFO_VECTOR(uIdtVectorInfo);
12857 uint32_t const uIdtVectorType = VMX_IDT_VECTORING_INFO_TYPE(uIdtVectorInfo);
12858
12859 /*
12860 * If the event was a software interrupt (generated with INT n) or a software exception
12861 * (generated by INT3/INTO) or a privileged software exception (generated by INT1), we
12862 * can handle the VM-exit and continue guest execution which will re-execute the
12863 * instruction rather than re-injecting the exception, as that can cause premature
12864 * trips to ring-3 before injection and involve TRPM which currently has no way of
12865 * storing that these exceptions were caused by these instructions (ICEBP's #DB poses
12866 * the problem).
12867 */
12868 IEMXCPTRAISE enmRaise;
12869 IEMXCPTRAISEINFO fRaiseInfo;
12870 if ( uIdtVectorType == VMX_IDT_VECTORING_INFO_TYPE_SW_INT
12871 || uIdtVectorType == VMX_IDT_VECTORING_INFO_TYPE_SW_XCPT
12872 || uIdtVectorType == VMX_IDT_VECTORING_INFO_TYPE_PRIV_SW_XCPT)
12873 {
12874 enmRaise = IEMXCPTRAISE_REEXEC_INSTR;
12875 fRaiseInfo = IEMXCPTRAISEINFO_NONE;
12876 }
12877 else if (VMX_EXIT_INT_INFO_IS_VALID(uExitIntInfo))
12878 {
12879 uint32_t const uExitVectorType = VMX_EXIT_INT_INFO_TYPE(uExitIntInfo);
12880 uint8_t const uExitVector = VMX_EXIT_INT_INFO_VECTOR(uExitIntInfo);
12881 Assert(uExitVectorType == VMX_EXIT_INT_INFO_TYPE_HW_XCPT);
12882
12883 uint32_t const fIdtVectorFlags = hmR0VmxGetIemXcptFlags(uIdtVector, uIdtVectorType);
12884 uint32_t const fExitVectorFlags = hmR0VmxGetIemXcptFlags(uExitVector, uExitVectorType);
12885
12886 enmRaise = IEMEvaluateRecursiveXcpt(pVCpu, fIdtVectorFlags, uIdtVector, fExitVectorFlags, uExitVector, &fRaiseInfo);
12887
12888 /* Determine a vectoring #PF condition, see comment in hmR0VmxExitXcptPF(). */
12889 if (fRaiseInfo & (IEMXCPTRAISEINFO_EXT_INT_PF | IEMXCPTRAISEINFO_NMI_PF))
12890 {
12891 pVmxTransient->fVectoringPF = true;
12892 enmRaise = IEMXCPTRAISE_PREV_EVENT;
12893 }
12894 }
12895 else
12896 {
12897 /*
12898 * If an exception or hardware interrupt delivery caused an EPT violation/misconfig or APIC access
12899 * VM-exit, then the VM-exit interruption-information will not be valid and we end up here.
12900 * It is sufficient to reflect the original event to the guest after handling the VM-exit.
12901 */
12902 Assert( uIdtVectorType == VMX_IDT_VECTORING_INFO_TYPE_HW_XCPT
12903 || uIdtVectorType == VMX_IDT_VECTORING_INFO_TYPE_NMI
12904 || uIdtVectorType == VMX_IDT_VECTORING_INFO_TYPE_EXT_INT);
12905 enmRaise = IEMXCPTRAISE_PREV_EVENT;
12906 fRaiseInfo = IEMXCPTRAISEINFO_NONE;
12907 }
12908
12909 /*
12910 * On CPUs that support Virtual NMIs, if this VM-exit (be it an exception or EPT violation/misconfig
12911 * etc.) occurred while delivering the NMI, we need to clear the block-by-NMI field in the guest
12912 * interruptibility-state before re-delivering the NMI after handling the VM-exit. Otherwise the
12913 * subsequent VM-entry would fail, see @bugref{7445}.
12914 *
12915 * See Intel spec. 30.7.1.2 "Resuming Guest Software after Handling an Exception".
12916 */
12917 if ( uIdtVectorType == VMX_IDT_VECTORING_INFO_TYPE_NMI
12918 && enmRaise == IEMXCPTRAISE_PREV_EVENT
12919 && (pVmcsInfo->u32PinCtls & VMX_PIN_CTLS_VIRT_NMI)
12920 && CPUMIsGuestNmiBlocking(pVCpu))
12921 {
12922 CPUMSetGuestNmiBlocking(pVCpu, false);
12923 }
12924
12925 switch (enmRaise)
12926 {
12927 case IEMXCPTRAISE_CURRENT_XCPT:
12928 {
12929 Log4Func(("IDT: Pending secondary Xcpt: idtinfo=%#RX64 exitinfo=%#RX64\n", uIdtVectorInfo, uExitIntInfo));
12930 Assert(rcStrict == VINF_SUCCESS);
12931 break;
12932 }
12933
12934 case IEMXCPTRAISE_PREV_EVENT:
12935 {
12936 uint32_t u32ErrCode;
12937 if (VMX_IDT_VECTORING_INFO_IS_ERROR_CODE_VALID(uIdtVectorInfo))
12938 u32ErrCode = pVmxTransient->uIdtVectoringErrorCode;
12939 else
12940 u32ErrCode = 0;
12941
12942 /* If uExitVector is #PF, CR2 value will be updated from the VMCS if it's a guest #PF, see hmR0VmxExitXcptPF(). */
12943 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectReflect);
12944 hmR0VmxSetPendingEvent(pVCpu, VMX_ENTRY_INT_INFO_FROM_EXIT_IDT_INFO(uIdtVectorInfo), 0 /* cbInstr */,
12945 u32ErrCode, pVCpu->cpum.GstCtx.cr2);
12946
12947 Log4Func(("IDT: Pending vectoring event %#RX64 Err=%#RX32\n", pVCpu->hm.s.Event.u64IntInfo,
12948 pVCpu->hm.s.Event.u32ErrCode));
12949 Assert(rcStrict == VINF_SUCCESS);
12950 break;
12951 }
12952
12953 case IEMXCPTRAISE_REEXEC_INSTR:
12954 Assert(rcStrict == VINF_SUCCESS);
12955 break;
12956
12957 case IEMXCPTRAISE_DOUBLE_FAULT:
12958 {
12959 /*
12960 * Determing a vectoring double #PF condition. Used later, when PGM evaluates the
12961 * second #PF as a guest #PF (and not a shadow #PF) and needs to be converted into a #DF.
12962 */
12963 if (fRaiseInfo & IEMXCPTRAISEINFO_PF_PF)
12964 {
12965 pVmxTransient->fVectoringDoublePF = true;
12966 Log4Func(("IDT: Vectoring double #PF %#RX64 cr2=%#RX64\n", pVCpu->hm.s.Event.u64IntInfo,
12967 pVCpu->cpum.GstCtx.cr2));
12968 rcStrict = VINF_SUCCESS;
12969 }
12970 else
12971 {
12972 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectConvertDF);
12973 hmR0VmxSetPendingXcptDF(pVCpu);
12974 Log4Func(("IDT: Pending vectoring #DF %#RX64 uIdtVector=%#x uExitVector=%#x\n", pVCpu->hm.s.Event.u64IntInfo,
12975 uIdtVector, VMX_EXIT_INT_INFO_VECTOR(uExitIntInfo)));
12976 rcStrict = VINF_HM_DOUBLE_FAULT;
12977 }
12978 break;
12979 }
12980
12981 case IEMXCPTRAISE_TRIPLE_FAULT:
12982 {
12983 Log4Func(("IDT: Pending vectoring triple-fault uIdt=%#x uExit=%#x\n", uIdtVector,
12984 VMX_EXIT_INT_INFO_VECTOR(uExitIntInfo)));
12985 rcStrict = VINF_EM_RESET;
12986 break;
12987 }
12988
12989 case IEMXCPTRAISE_CPU_HANG:
12990 {
12991 Log4Func(("IDT: Bad guest! Entering CPU hang. fRaiseInfo=%#x\n", fRaiseInfo));
12992 rcStrict = VERR_EM_GUEST_CPU_HANG;
12993 break;
12994 }
12995
12996 default:
12997 {
12998 AssertMsgFailed(("IDT: vcpu[%RU32] Unexpected/invalid value! enmRaise=%#x\n", pVCpu->idCpu, enmRaise));
12999 rcStrict = VERR_VMX_IPE_2;
13000 break;
13001 }
13002 }
13003 }
13004 else if ( (pVmcsInfo->u32PinCtls & VMX_PIN_CTLS_VIRT_NMI)
13005 && !CPUMIsGuestNmiBlocking(pVCpu))
13006 {
13007 if ( VMX_EXIT_INT_INFO_IS_VALID(uExitIntInfo)
13008 && VMX_EXIT_INT_INFO_VECTOR(uExitIntInfo) != X86_XCPT_DF
13009 && VMX_EXIT_INT_INFO_IS_NMI_UNBLOCK_IRET(uExitIntInfo))
13010 {
13011 /*
13012 * Execution of IRET caused a fault when NMI blocking was in effect (i.e we're in
13013 * the guest or nested-guest NMI handler). We need to set the block-by-NMI field so
13014 * that NMIs remain blocked until the IRET execution is completed.
13015 *
13016 * See Intel spec. 31.7.1.2 "Resuming Guest Software After Handling An Exception".
13017 */
13018 CPUMSetGuestNmiBlocking(pVCpu, true);
13019 Log4Func(("Set NMI blocking. uExitReason=%u\n", pVmxTransient->uExitReason));
13020 }
13021 else if ( pVmxTransient->uExitReason == VMX_EXIT_EPT_VIOLATION
13022 || pVmxTransient->uExitReason == VMX_EXIT_PML_FULL
13023 || pVmxTransient->uExitReason == VMX_EXIT_SPP_EVENT)
13024 {
13025 /*
13026 * Execution of IRET caused an EPT violation, page-modification log-full event or
13027 * SPP-related event VM-exit when NMI blocking was in effect (i.e. we're in the
13028 * guest or nested-guest NMI handler). We need to set the block-by-NMI field so
13029 * that NMIs remain blocked until the IRET execution is completed.
13030 *
13031 * See Intel spec. 27.2.3 "Information about NMI unblocking due to IRET"
13032 */
13033 if (VMX_EXIT_QUAL_EPT_IS_NMI_UNBLOCK_IRET(pVmxTransient->uExitQual))
13034 {
13035 CPUMSetGuestNmiBlocking(pVCpu, true);
13036 Log4Func(("Set NMI blocking. uExitReason=%u\n", pVmxTransient->uExitReason));
13037 }
13038 }
13039 }
13040
13041 Assert( rcStrict == VINF_SUCCESS || rcStrict == VINF_HM_DOUBLE_FAULT
13042 || rcStrict == VINF_EM_RESET || rcStrict == VERR_EM_GUEST_CPU_HANG);
13043 return rcStrict;
13044}
13045
13046
13047#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
13048/**
13049 * Perform the relevant VMX instruction checks for VM-exits that occurred due to the
13050 * guest attempting to execute a VMX instruction.
13051 *
13052 * @returns Strict VBox status code (i.e. informational status codes too).
13053 * @retval VINF_SUCCESS if we should continue handling the VM-exit.
13054 * @retval VINF_HM_PENDING_XCPT if an exception was raised.
13055 *
13056 * @param pVCpu The cross context virtual CPU structure.
13057 * @param uExitReason The VM-exit reason.
13058 *
13059 * @todo NSTVMX: Document other error codes when VM-exit is implemented.
13060 * @remarks No-long-jump zone!!!
13061 */
13062static VBOXSTRICTRC hmR0VmxCheckExitDueToVmxInstr(PVMCPUCC pVCpu, uint32_t uExitReason)
13063{
13064 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_CR0 | CPUMCTX_EXTRN_RFLAGS | CPUMCTX_EXTRN_SS
13065 | CPUMCTX_EXTRN_CS | CPUMCTX_EXTRN_EFER);
13066
13067 /*
13068 * The physical CPU would have already checked the CPU mode/code segment.
13069 * We shall just assert here for paranoia.
13070 * See Intel spec. 25.1.1 "Relative Priority of Faults and VM Exits".
13071 */
13072 Assert(!CPUMIsGuestInRealOrV86ModeEx(&pVCpu->cpum.GstCtx));
13073 Assert( !CPUMIsGuestInLongModeEx(&pVCpu->cpum.GstCtx)
13074 || CPUMIsGuestIn64BitCodeEx(&pVCpu->cpum.GstCtx));
13075
13076 if (uExitReason == VMX_EXIT_VMXON)
13077 {
13078 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_CR4);
13079
13080 /*
13081 * We check CR4.VMXE because it is required to be always set while in VMX operation
13082 * by physical CPUs and our CR4 read-shadow is only consulted when executing specific
13083 * instructions (CLTS, LMSW, MOV CR, and SMSW) and thus doesn't affect CPU operation
13084 * otherwise (i.e. physical CPU won't automatically #UD if Cr4Shadow.VMXE is 0).
13085 */
13086 if (!CPUMIsGuestVmxEnabled(&pVCpu->cpum.GstCtx))
13087 {
13088 Log4Func(("CR4.VMXE is not set -> #UD\n"));
13089 hmR0VmxSetPendingXcptUD(pVCpu);
13090 return VINF_HM_PENDING_XCPT;
13091 }
13092 }
13093 else if (!CPUMIsGuestInVmxRootMode(&pVCpu->cpum.GstCtx))
13094 {
13095 /*
13096 * The guest has not entered VMX operation but attempted to execute a VMX instruction
13097 * (other than VMXON), we need to raise a #UD.
13098 */
13099 Log4Func(("Not in VMX root mode -> #UD\n"));
13100 hmR0VmxSetPendingXcptUD(pVCpu);
13101 return VINF_HM_PENDING_XCPT;
13102 }
13103
13104 /* All other checks (including VM-exit intercepts) are handled by IEM instruction emulation. */
13105 return VINF_SUCCESS;
13106}
13107
13108
13109/**
13110 * Decodes the memory operand of an instruction that caused a VM-exit.
13111 *
13112 * The Exit qualification field provides the displacement field for memory
13113 * operand instructions, if any.
13114 *
13115 * @returns Strict VBox status code (i.e. informational status codes too).
13116 * @retval VINF_SUCCESS if the operand was successfully decoded.
13117 * @retval VINF_HM_PENDING_XCPT if an exception was raised while decoding the
13118 * operand.
13119 * @param pVCpu The cross context virtual CPU structure.
13120 * @param uExitInstrInfo The VM-exit instruction information field.
13121 * @param enmMemAccess The memory operand's access type (read or write).
13122 * @param GCPtrDisp The instruction displacement field, if any. For
13123 * RIP-relative addressing pass RIP + displacement here.
13124 * @param pGCPtrMem Where to store the effective destination memory address.
13125 *
13126 * @remarks Warning! This function ASSUMES the instruction cannot be used in real or
13127 * virtual-8086 mode hence skips those checks while verifying if the
13128 * segment is valid.
13129 */
13130static VBOXSTRICTRC hmR0VmxDecodeMemOperand(PVMCPUCC pVCpu, uint32_t uExitInstrInfo, RTGCPTR GCPtrDisp, VMXMEMACCESS enmMemAccess,
13131 PRTGCPTR pGCPtrMem)
13132{
13133 Assert(pGCPtrMem);
13134 Assert(!CPUMIsGuestInRealOrV86Mode(pVCpu));
13135 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_RIP | CPUMCTX_EXTRN_RSP | CPUMCTX_EXTRN_SREG_MASK | CPUMCTX_EXTRN_EFER
13136 | CPUMCTX_EXTRN_CR0);
13137
13138 static uint64_t const s_auAddrSizeMasks[] = { UINT64_C(0xffff), UINT64_C(0xffffffff), UINT64_C(0xffffffffffffffff) };
13139 static uint64_t const s_auAccessSizeMasks[] = { sizeof(uint16_t), sizeof(uint32_t), sizeof(uint64_t) };
13140 AssertCompile(RT_ELEMENTS(s_auAccessSizeMasks) == RT_ELEMENTS(s_auAddrSizeMasks));
13141
13142 VMXEXITINSTRINFO ExitInstrInfo;
13143 ExitInstrInfo.u = uExitInstrInfo;
13144 uint8_t const uAddrSize = ExitInstrInfo.All.u3AddrSize;
13145 uint8_t const iSegReg = ExitInstrInfo.All.iSegReg;
13146 bool const fIdxRegValid = !ExitInstrInfo.All.fIdxRegInvalid;
13147 uint8_t const iIdxReg = ExitInstrInfo.All.iIdxReg;
13148 uint8_t const uScale = ExitInstrInfo.All.u2Scaling;
13149 bool const fBaseRegValid = !ExitInstrInfo.All.fBaseRegInvalid;
13150 uint8_t const iBaseReg = ExitInstrInfo.All.iBaseReg;
13151 bool const fIsMemOperand = !ExitInstrInfo.All.fIsRegOperand;
13152 bool const fIsLongMode = CPUMIsGuestInLongModeEx(&pVCpu->cpum.GstCtx);
13153
13154 /*
13155 * Validate instruction information.
13156 * This shouldn't happen on real hardware but useful while testing our nested hardware-virtualization code.
13157 */
13158 AssertLogRelMsgReturn(uAddrSize < RT_ELEMENTS(s_auAddrSizeMasks),
13159 ("Invalid address size. ExitInstrInfo=%#RX32\n", ExitInstrInfo.u), VERR_VMX_IPE_1);
13160 AssertLogRelMsgReturn(iSegReg < X86_SREG_COUNT,
13161 ("Invalid segment register. ExitInstrInfo=%#RX32\n", ExitInstrInfo.u), VERR_VMX_IPE_2);
13162 AssertLogRelMsgReturn(fIsMemOperand,
13163 ("Expected memory operand. ExitInstrInfo=%#RX32\n", ExitInstrInfo.u), VERR_VMX_IPE_3);
13164
13165 /*
13166 * Compute the complete effective address.
13167 *
13168 * See AMD instruction spec. 1.4.2 "SIB Byte Format"
13169 * See AMD spec. 4.5.2 "Segment Registers".
13170 */
13171 RTGCPTR GCPtrMem = GCPtrDisp;
13172 if (fBaseRegValid)
13173 GCPtrMem += pVCpu->cpum.GstCtx.aGRegs[iBaseReg].u64;
13174 if (fIdxRegValid)
13175 GCPtrMem += pVCpu->cpum.GstCtx.aGRegs[iIdxReg].u64 << uScale;
13176
13177 RTGCPTR const GCPtrOff = GCPtrMem;
13178 if ( !fIsLongMode
13179 || iSegReg >= X86_SREG_FS)
13180 GCPtrMem += pVCpu->cpum.GstCtx.aSRegs[iSegReg].u64Base;
13181 GCPtrMem &= s_auAddrSizeMasks[uAddrSize];
13182
13183 /*
13184 * Validate effective address.
13185 * See AMD spec. 4.5.3 "Segment Registers in 64-Bit Mode".
13186 */
13187 uint8_t const cbAccess = s_auAccessSizeMasks[uAddrSize];
13188 Assert(cbAccess > 0);
13189 if (fIsLongMode)
13190 {
13191 if (X86_IS_CANONICAL(GCPtrMem))
13192 {
13193 *pGCPtrMem = GCPtrMem;
13194 return VINF_SUCCESS;
13195 }
13196
13197 /** @todo r=ramshankar: We should probably raise \#SS or \#GP. See AMD spec. 4.12.2
13198 * "Data Limit Checks in 64-bit Mode". */
13199 Log4Func(("Long mode effective address is not canonical GCPtrMem=%#RX64\n", GCPtrMem));
13200 hmR0VmxSetPendingXcptGP(pVCpu, 0);
13201 return VINF_HM_PENDING_XCPT;
13202 }
13203
13204 /*
13205 * This is a watered down version of iemMemApplySegment().
13206 * Parts that are not applicable for VMX instructions like real-or-v8086 mode
13207 * and segment CPL/DPL checks are skipped.
13208 */
13209 RTGCPTR32 const GCPtrFirst32 = (RTGCPTR32)GCPtrOff;
13210 RTGCPTR32 const GCPtrLast32 = GCPtrFirst32 + cbAccess - 1;
13211 PCCPUMSELREG pSel = &pVCpu->cpum.GstCtx.aSRegs[iSegReg];
13212
13213 /* Check if the segment is present and usable. */
13214 if ( pSel->Attr.n.u1Present
13215 && !pSel->Attr.n.u1Unusable)
13216 {
13217 Assert(pSel->Attr.n.u1DescType);
13218 if (!(pSel->Attr.n.u4Type & X86_SEL_TYPE_CODE))
13219 {
13220 /* Check permissions for the data segment. */
13221 if ( enmMemAccess == VMXMEMACCESS_WRITE
13222 && !(pSel->Attr.n.u4Type & X86_SEL_TYPE_WRITE))
13223 {
13224 Log4Func(("Data segment access invalid. iSegReg=%#x Attr=%#RX32\n", iSegReg, pSel->Attr.u));
13225 hmR0VmxSetPendingXcptGP(pVCpu, iSegReg);
13226 return VINF_HM_PENDING_XCPT;
13227 }
13228
13229 /* Check limits if it's a normal data segment. */
13230 if (!(pSel->Attr.n.u4Type & X86_SEL_TYPE_DOWN))
13231 {
13232 if ( GCPtrFirst32 > pSel->u32Limit
13233 || GCPtrLast32 > pSel->u32Limit)
13234 {
13235 Log4Func(("Data segment limit exceeded. "
13236 "iSegReg=%#x GCPtrFirst32=%#RX32 GCPtrLast32=%#RX32 u32Limit=%#RX32\n", iSegReg, GCPtrFirst32,
13237 GCPtrLast32, pSel->u32Limit));
13238 if (iSegReg == X86_SREG_SS)
13239 hmR0VmxSetPendingXcptSS(pVCpu, 0);
13240 else
13241 hmR0VmxSetPendingXcptGP(pVCpu, 0);
13242 return VINF_HM_PENDING_XCPT;
13243 }
13244 }
13245 else
13246 {
13247 /* Check limits if it's an expand-down data segment.
13248 Note! The upper boundary is defined by the B bit, not the G bit! */
13249 if ( GCPtrFirst32 < pSel->u32Limit + UINT32_C(1)
13250 || GCPtrLast32 > (pSel->Attr.n.u1DefBig ? UINT32_MAX : UINT32_C(0xffff)))
13251 {
13252 Log4Func(("Expand-down data segment limit exceeded. "
13253 "iSegReg=%#x GCPtrFirst32=%#RX32 GCPtrLast32=%#RX32 u32Limit=%#RX32\n", iSegReg, GCPtrFirst32,
13254 GCPtrLast32, pSel->u32Limit));
13255 if (iSegReg == X86_SREG_SS)
13256 hmR0VmxSetPendingXcptSS(pVCpu, 0);
13257 else
13258 hmR0VmxSetPendingXcptGP(pVCpu, 0);
13259 return VINF_HM_PENDING_XCPT;
13260 }
13261 }
13262 }
13263 else
13264 {
13265 /* Check permissions for the code segment. */
13266 if ( enmMemAccess == VMXMEMACCESS_WRITE
13267 || ( enmMemAccess == VMXMEMACCESS_READ
13268 && !(pSel->Attr.n.u4Type & X86_SEL_TYPE_READ)))
13269 {
13270 Log4Func(("Code segment access invalid. Attr=%#RX32\n", pSel->Attr.u));
13271 Assert(!CPUMIsGuestInRealOrV86ModeEx(&pVCpu->cpum.GstCtx));
13272 hmR0VmxSetPendingXcptGP(pVCpu, 0);
13273 return VINF_HM_PENDING_XCPT;
13274 }
13275
13276 /* Check limits for the code segment (normal/expand-down not applicable for code segments). */
13277 if ( GCPtrFirst32 > pSel->u32Limit
13278 || GCPtrLast32 > pSel->u32Limit)
13279 {
13280 Log4Func(("Code segment limit exceeded. GCPtrFirst32=%#RX32 GCPtrLast32=%#RX32 u32Limit=%#RX32\n",
13281 GCPtrFirst32, GCPtrLast32, pSel->u32Limit));
13282 if (iSegReg == X86_SREG_SS)
13283 hmR0VmxSetPendingXcptSS(pVCpu, 0);
13284 else
13285 hmR0VmxSetPendingXcptGP(pVCpu, 0);
13286 return VINF_HM_PENDING_XCPT;
13287 }
13288 }
13289 }
13290 else
13291 {
13292 Log4Func(("Not present or unusable segment. iSegReg=%#x Attr=%#RX32\n", iSegReg, pSel->Attr.u));
13293 hmR0VmxSetPendingXcptGP(pVCpu, 0);
13294 return VINF_HM_PENDING_XCPT;
13295 }
13296
13297 *pGCPtrMem = GCPtrMem;
13298 return VINF_SUCCESS;
13299}
13300#endif /* VBOX_WITH_NESTED_HWVIRT_VMX */
13301
13302
13303/**
13304 * VM-exit helper for LMSW.
13305 */
13306static VBOXSTRICTRC hmR0VmxExitLmsw(PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo, uint8_t cbInstr, uint16_t uMsw, RTGCPTR GCPtrEffDst)
13307{
13308 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, IEM_CPUMCTX_EXTRN_MUST_MASK);
13309 AssertRCReturn(rc, rc);
13310
13311 VBOXSTRICTRC rcStrict = IEMExecDecodedLmsw(pVCpu, cbInstr, uMsw, GCPtrEffDst);
13312 AssertMsg( rcStrict == VINF_SUCCESS
13313 || rcStrict == VINF_IEM_RAISED_XCPT, ("%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
13314
13315 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS | HM_CHANGED_GUEST_CR0);
13316 if (rcStrict == VINF_IEM_RAISED_XCPT)
13317 {
13318 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
13319 rcStrict = VINF_SUCCESS;
13320 }
13321
13322 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitLmsw);
13323 Log4Func(("rcStrict=%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
13324 return rcStrict;
13325}
13326
13327
13328/**
13329 * VM-exit helper for CLTS.
13330 */
13331static VBOXSTRICTRC hmR0VmxExitClts(PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo, uint8_t cbInstr)
13332{
13333 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, IEM_CPUMCTX_EXTRN_MUST_MASK);
13334 AssertRCReturn(rc, rc);
13335
13336 VBOXSTRICTRC rcStrict = IEMExecDecodedClts(pVCpu, cbInstr);
13337 AssertMsg( rcStrict == VINF_SUCCESS
13338 || rcStrict == VINF_IEM_RAISED_XCPT, ("%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
13339
13340 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS | HM_CHANGED_GUEST_CR0);
13341 if (rcStrict == VINF_IEM_RAISED_XCPT)
13342 {
13343 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
13344 rcStrict = VINF_SUCCESS;
13345 }
13346
13347 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitClts);
13348 Log4Func(("rcStrict=%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
13349 return rcStrict;
13350}
13351
13352
13353/**
13354 * VM-exit helper for MOV from CRx (CRx read).
13355 */
13356static VBOXSTRICTRC hmR0VmxExitMovFromCrX(PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo, uint8_t cbInstr, uint8_t iGReg, uint8_t iCrReg)
13357{
13358 Assert(iCrReg < 16);
13359 Assert(iGReg < RT_ELEMENTS(pVCpu->cpum.GstCtx.aGRegs));
13360
13361 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, IEM_CPUMCTX_EXTRN_MUST_MASK);
13362 AssertRCReturn(rc, rc);
13363
13364 VBOXSTRICTRC rcStrict = IEMExecDecodedMovCRxRead(pVCpu, cbInstr, iGReg, iCrReg);
13365 AssertMsg( rcStrict == VINF_SUCCESS
13366 || rcStrict == VINF_IEM_RAISED_XCPT, ("%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
13367
13368 if (iGReg == X86_GREG_xSP)
13369 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS | HM_CHANGED_GUEST_RSP);
13370 else
13371 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS);
13372#ifdef VBOX_WITH_STATISTICS
13373 switch (iCrReg)
13374 {
13375 case 0: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCR0Read); break;
13376 case 2: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCR2Read); break;
13377 case 3: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCR3Read); break;
13378 case 4: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCR4Read); break;
13379 case 8: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCR8Read); break;
13380 }
13381#endif
13382 Log4Func(("CR%d Read access rcStrict=%Rrc\n", iCrReg, VBOXSTRICTRC_VAL(rcStrict)));
13383 return rcStrict;
13384}
13385
13386
13387/**
13388 * VM-exit helper for MOV to CRx (CRx write).
13389 */
13390static VBOXSTRICTRC hmR0VmxExitMovToCrX(PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo, uint8_t cbInstr, uint8_t iGReg, uint8_t iCrReg)
13391{
13392 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, IEM_CPUMCTX_EXTRN_MUST_MASK);
13393 AssertRCReturn(rc, rc);
13394
13395 VBOXSTRICTRC rcStrict = IEMExecDecodedMovCRxWrite(pVCpu, cbInstr, iCrReg, iGReg);
13396 AssertMsg( rcStrict == VINF_SUCCESS
13397 || rcStrict == VINF_IEM_RAISED_XCPT
13398 || rcStrict == VINF_PGM_SYNC_CR3, ("%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
13399
13400 switch (iCrReg)
13401 {
13402 case 0:
13403 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS | HM_CHANGED_GUEST_CR0);
13404 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCR0Write);
13405 Log4Func(("CR0 write. rcStrict=%Rrc CR0=%#RX64\n", VBOXSTRICTRC_VAL(rcStrict), pVCpu->cpum.GstCtx.cr0));
13406 break;
13407
13408 case 2:
13409 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCR2Write);
13410 /* Nothing to do here, CR2 it's not part of the VMCS. */
13411 break;
13412
13413 case 3:
13414 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS | HM_CHANGED_GUEST_CR3);
13415 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCR3Write);
13416 Log4Func(("CR3 write. rcStrict=%Rrc CR3=%#RX64\n", VBOXSTRICTRC_VAL(rcStrict), pVCpu->cpum.GstCtx.cr3));
13417 break;
13418
13419 case 4:
13420 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS | HM_CHANGED_GUEST_CR4);
13421 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCR4Write);
13422 Log4Func(("CR4 write. rc=%Rrc CR4=%#RX64 fLoadSaveGuestXcr0=%u\n", VBOXSTRICTRC_VAL(rcStrict),
13423 pVCpu->cpum.GstCtx.cr4, pVCpu->hm.s.fLoadSaveGuestXcr0));
13424 break;
13425
13426 case 8:
13427 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged,
13428 HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS | HM_CHANGED_GUEST_APIC_TPR);
13429 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCR8Write);
13430 break;
13431
13432 default:
13433 AssertMsgFailed(("Invalid CRx register %#x\n", iCrReg));
13434 break;
13435 }
13436
13437 if (rcStrict == VINF_IEM_RAISED_XCPT)
13438 {
13439 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
13440 rcStrict = VINF_SUCCESS;
13441 }
13442 return rcStrict;
13443}
13444
13445
13446/**
13447 * VM-exit exception handler for \#PF (Page-fault exception).
13448 *
13449 * @remarks Requires all fields in HMVMX_READ_XCPT_INFO to be read from the VMCS.
13450 */
13451static VBOXSTRICTRC hmR0VmxExitXcptPF(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
13452{
13453 HMVMX_VALIDATE_EXIT_XCPT_HANDLER_PARAMS(pVCpu, pVmxTransient);
13454 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
13455 hmR0VmxReadExitQualVmcs(pVmxTransient);
13456
13457 if (!pVM->hm.s.fNestedPaging)
13458 { /* likely */ }
13459 else
13460 {
13461#if !defined(HMVMX_ALWAYS_TRAP_ALL_XCPTS) && !defined(HMVMX_ALWAYS_TRAP_PF)
13462 Assert(pVmxTransient->fIsNestedGuest || pVCpu->hm.s.fUsingDebugLoop);
13463#endif
13464 pVCpu->hm.s.Event.fPending = false; /* In case it's a contributory or vectoring #PF. */
13465 if (!pVmxTransient->fVectoringDoublePF)
13466 {
13467 hmR0VmxSetPendingEvent(pVCpu, VMX_ENTRY_INT_INFO_FROM_EXIT_INT_INFO(pVmxTransient->uExitIntInfo), 0 /* cbInstr */,
13468 pVmxTransient->uExitIntErrorCode, pVmxTransient->uExitQual);
13469 }
13470 else
13471 {
13472 /* A guest page-fault occurred during delivery of a page-fault. Inject #DF. */
13473 Assert(!pVmxTransient->fIsNestedGuest);
13474 hmR0VmxSetPendingXcptDF(pVCpu);
13475 Log4Func(("Pending #DF due to vectoring #PF w/ NestedPaging\n"));
13476 }
13477 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestPF);
13478 return VINF_SUCCESS;
13479 }
13480
13481 Assert(!pVmxTransient->fIsNestedGuest);
13482
13483 /* If it's a vectoring #PF, emulate injecting the original event injection as PGMTrap0eHandler() is incapable
13484 of differentiating between instruction emulation and event injection that caused a #PF. See @bugref{6607}. */
13485 if (pVmxTransient->fVectoringPF)
13486 {
13487 Assert(pVCpu->hm.s.Event.fPending);
13488 return VINF_EM_RAW_INJECT_TRPM_EVENT;
13489 }
13490
13491 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
13492 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, HMVMX_CPUMCTX_EXTRN_ALL);
13493 AssertRCReturn(rc, rc);
13494
13495 Log4Func(("#PF: cs:rip=%#04x:%#RX64 err_code=%#RX32 exit_qual=%#RX64 cr3=%#RX64\n", pCtx->cs.Sel, pCtx->rip,
13496 pVmxTransient->uExitIntErrorCode, pVmxTransient->uExitQual, pCtx->cr3));
13497
13498 TRPMAssertXcptPF(pVCpu, pVmxTransient->uExitQual, (RTGCUINT)pVmxTransient->uExitIntErrorCode);
13499 rc = PGMTrap0eHandler(pVCpu, pVmxTransient->uExitIntErrorCode, CPUMCTX2CORE(pCtx), (RTGCPTR)pVmxTransient->uExitQual);
13500
13501 Log4Func(("#PF: rc=%Rrc\n", rc));
13502 if (rc == VINF_SUCCESS)
13503 {
13504 /*
13505 * This is typically a shadow page table sync or a MMIO instruction. But we may have
13506 * emulated something like LTR or a far jump. Any part of the CPU context may have changed.
13507 */
13508 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_ALL_GUEST);
13509 TRPMResetTrap(pVCpu);
13510 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitShadowPF);
13511 return rc;
13512 }
13513
13514 if (rc == VINF_EM_RAW_GUEST_TRAP)
13515 {
13516 if (!pVmxTransient->fVectoringDoublePF)
13517 {
13518 /* It's a guest page fault and needs to be reflected to the guest. */
13519 uint32_t uGstErrorCode = TRPMGetErrorCode(pVCpu);
13520 TRPMResetTrap(pVCpu);
13521 pVCpu->hm.s.Event.fPending = false; /* In case it's a contributory #PF. */
13522 hmR0VmxSetPendingEvent(pVCpu, VMX_ENTRY_INT_INFO_FROM_EXIT_INT_INFO(pVmxTransient->uExitIntInfo), 0 /* cbInstr */,
13523 uGstErrorCode, pVmxTransient->uExitQual);
13524 }
13525 else
13526 {
13527 /* A guest page-fault occurred during delivery of a page-fault. Inject #DF. */
13528 TRPMResetTrap(pVCpu);
13529 pVCpu->hm.s.Event.fPending = false; /* Clear pending #PF to replace it with #DF. */
13530 hmR0VmxSetPendingXcptDF(pVCpu);
13531 Log4Func(("#PF: Pending #DF due to vectoring #PF\n"));
13532 }
13533
13534 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestPF);
13535 return VINF_SUCCESS;
13536 }
13537
13538 TRPMResetTrap(pVCpu);
13539 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitShadowPFEM);
13540 return rc;
13541}
13542
13543
13544/**
13545 * VM-exit exception handler for \#MF (Math Fault: floating point exception).
13546 *
13547 * @remarks Requires all fields in HMVMX_READ_XCPT_INFO to be read from the VMCS.
13548 */
13549static VBOXSTRICTRC hmR0VmxExitXcptMF(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
13550{
13551 HMVMX_VALIDATE_EXIT_XCPT_HANDLER_PARAMS(pVCpu, pVmxTransient);
13552 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestMF);
13553
13554 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, CPUMCTX_EXTRN_CR0);
13555 AssertRCReturn(rc, rc);
13556
13557 if (!(pVCpu->cpum.GstCtx.cr0 & X86_CR0_NE))
13558 {
13559 /* Convert a #MF into a FERR -> IRQ 13. See @bugref{6117}. */
13560 rc = PDMIsaSetIrq(pVCpu->CTX_SUFF(pVM), 13, 1, 0 /* uTagSrc */);
13561
13562 /** @todo r=ramshankar: The Intel spec. does -not- specify that this VM-exit
13563 * provides VM-exit instruction length. If this causes problem later,
13564 * disassemble the instruction like it's done on AMD-V. */
13565 int rc2 = hmR0VmxAdvanceGuestRip(pVCpu, pVmxTransient);
13566 AssertRCReturn(rc2, rc2);
13567 return rc;
13568 }
13569
13570 hmR0VmxSetPendingEvent(pVCpu, VMX_ENTRY_INT_INFO_FROM_EXIT_INT_INFO(pVmxTransient->uExitIntInfo), pVmxTransient->cbExitInstr,
13571 pVmxTransient->uExitIntErrorCode, 0 /* GCPtrFaultAddress */);
13572 return VINF_SUCCESS;
13573}
13574
13575
13576/**
13577 * VM-exit exception handler for \#BP (Breakpoint exception).
13578 *
13579 * @remarks Requires all fields in HMVMX_READ_XCPT_INFO to be read from the VMCS.
13580 */
13581static VBOXSTRICTRC hmR0VmxExitXcptBP(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
13582{
13583 HMVMX_VALIDATE_EXIT_XCPT_HANDLER_PARAMS(pVCpu, pVmxTransient);
13584 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestBP);
13585
13586 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, HMVMX_CPUMCTX_EXTRN_ALL);
13587 AssertRCReturn(rc, rc);
13588
13589 if (!pVmxTransient->fIsNestedGuest)
13590 rc = DBGFRZTrap03Handler(pVCpu->CTX_SUFF(pVM), pVCpu, CPUMCTX2CORE(&pVCpu->cpum.GstCtx));
13591 else
13592 rc = VINF_EM_RAW_GUEST_TRAP;
13593
13594 if (rc == VINF_EM_RAW_GUEST_TRAP)
13595 {
13596 hmR0VmxSetPendingEvent(pVCpu, VMX_ENTRY_INT_INFO_FROM_EXIT_INT_INFO(pVmxTransient->uExitIntInfo),
13597 pVmxTransient->cbExitInstr, pVmxTransient->uExitIntErrorCode, 0 /* GCPtrFaultAddress */);
13598 rc = VINF_SUCCESS;
13599 }
13600
13601 Assert(rc == VINF_SUCCESS || rc == VINF_EM_DBG_BREAKPOINT);
13602 return rc;
13603}
13604
13605
13606/**
13607 * VM-exit exception handler for \#AC (Alignment-check exception).
13608 *
13609 * @remarks Requires all fields in HMVMX_READ_XCPT_INFO to be read from the VMCS.
13610 */
13611static VBOXSTRICTRC hmR0VmxExitXcptAC(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
13612{
13613 HMVMX_VALIDATE_EXIT_XCPT_HANDLER_PARAMS(pVCpu, pVmxTransient);
13614 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestAC);
13615
13616 /* Re-inject it. We'll detect any nesting before getting here. */
13617 hmR0VmxSetPendingEvent(pVCpu, VMX_ENTRY_INT_INFO_FROM_EXIT_INT_INFO(pVmxTransient->uExitIntInfo),
13618 pVmxTransient->cbExitInstr, pVmxTransient->uExitIntErrorCode, 0 /* GCPtrFaultAddress */);
13619 return VINF_SUCCESS;
13620}
13621
13622
13623/**
13624 * VM-exit exception handler for \#DB (Debug exception).
13625 *
13626 * @remarks Requires all fields in HMVMX_READ_XCPT_INFO to be read from the VMCS.
13627 */
13628static VBOXSTRICTRC hmR0VmxExitXcptDB(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
13629{
13630 HMVMX_VALIDATE_EXIT_XCPT_HANDLER_PARAMS(pVCpu, pVmxTransient);
13631 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestDB);
13632
13633 /*
13634 * Get the DR6-like values from the Exit qualification and pass it to DBGF for processing.
13635 */
13636 hmR0VmxReadExitQualVmcs(pVmxTransient);
13637
13638 /* Refer Intel spec. Table 27-1. "Exit Qualifications for debug exceptions" for the format. */
13639 uint64_t const uDR6 = X86_DR6_INIT_VAL
13640 | (pVmxTransient->uExitQual & ( X86_DR6_B0 | X86_DR6_B1 | X86_DR6_B2 | X86_DR6_B3
13641 | X86_DR6_BD | X86_DR6_BS));
13642
13643 int rc;
13644 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
13645 if (!pVmxTransient->fIsNestedGuest)
13646 rc = DBGFRZTrap01Handler(pVCpu->CTX_SUFF(pVM), pVCpu, CPUMCTX2CORE(pCtx), uDR6, pVCpu->hm.s.fSingleInstruction);
13647 else
13648 rc = VINF_EM_RAW_GUEST_TRAP;
13649 Log6Func(("rc=%Rrc\n", rc));
13650 if (rc == VINF_EM_RAW_GUEST_TRAP)
13651 {
13652 /*
13653 * The exception was for the guest. Update DR6, DR7.GD and
13654 * IA32_DEBUGCTL.LBR before forwarding it.
13655 * See Intel spec. 27.1 "Architectural State before a VM-Exit".
13656 */
13657 VMMRZCallRing3Disable(pVCpu);
13658 HM_DISABLE_PREEMPT(pVCpu);
13659
13660 pCtx->dr[6] &= ~X86_DR6_B_MASK;
13661 pCtx->dr[6] |= uDR6;
13662 if (CPUMIsGuestDebugStateActive(pVCpu))
13663 ASMSetDR6(pCtx->dr[6]);
13664
13665 HM_RESTORE_PREEMPT();
13666 VMMRZCallRing3Enable(pVCpu);
13667
13668 rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, CPUMCTX_EXTRN_DR7);
13669 AssertRCReturn(rc, rc);
13670
13671 /* X86_DR7_GD will be cleared if DRx accesses should be trapped inside the guest. */
13672 pCtx->dr[7] &= ~(uint64_t)X86_DR7_GD;
13673
13674 /* Paranoia. */
13675 pCtx->dr[7] &= ~(uint64_t)X86_DR7_RAZ_MASK;
13676 pCtx->dr[7] |= X86_DR7_RA1_MASK;
13677
13678 rc = VMXWriteVmcsNw(VMX_VMCS_GUEST_DR7, pCtx->dr[7]);
13679 AssertRC(rc);
13680
13681 /*
13682 * Raise #DB in the guest.
13683 *
13684 * It is important to reflect exactly what the VM-exit gave us (preserving the
13685 * interruption-type) rather than use hmR0VmxSetPendingXcptDB() as the #DB could've
13686 * been raised while executing ICEBP (INT1) and not the regular #DB. Thus it may
13687 * trigger different handling in the CPU (like skipping DPL checks), see @bugref{6398}.
13688 *
13689 * Intel re-documented ICEBP/INT1 on May 2018 previously documented as part of
13690 * Intel 386, see Intel spec. 24.8.3 "VM-Entry Controls for Event Injection".
13691 */
13692 hmR0VmxSetPendingEvent(pVCpu, VMX_ENTRY_INT_INFO_FROM_EXIT_INT_INFO(pVmxTransient->uExitIntInfo),
13693 pVmxTransient->cbExitInstr, pVmxTransient->uExitIntErrorCode, 0 /* GCPtrFaultAddress */);
13694 return VINF_SUCCESS;
13695 }
13696
13697 /*
13698 * Not a guest trap, must be a hypervisor related debug event then.
13699 * Update DR6 in case someone is interested in it.
13700 */
13701 AssertMsg(rc == VINF_EM_DBG_STEPPED || rc == VINF_EM_DBG_BREAKPOINT, ("%Rrc\n", rc));
13702 AssertReturn(pVmxTransient->fWasHyperDebugStateActive, VERR_HM_IPE_5);
13703 CPUMSetHyperDR6(pVCpu, uDR6);
13704
13705 return rc;
13706}
13707
13708
13709/**
13710 * Hacks its way around the lovely mesa driver's backdoor accesses.
13711 *
13712 * @sa hmR0SvmHandleMesaDrvGp.
13713 */
13714static int hmR0VmxHandleMesaDrvGp(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient, PCPUMCTX pCtx)
13715{
13716 LogFunc(("cs:rip=%#04x:%#RX64 rcx=%#RX64 rbx=%#RX64\n", pCtx->cs.Sel, pCtx->rip, pCtx->rcx, pCtx->rbx));
13717 RT_NOREF(pCtx);
13718
13719 /* For now we'll just skip the instruction. */
13720 return hmR0VmxAdvanceGuestRip(pVCpu, pVmxTransient);
13721}
13722
13723
13724/**
13725 * Checks if the \#GP'ing instruction is the mesa driver doing it's lovely
13726 * backdoor logging w/o checking what it is running inside.
13727 *
13728 * This recognizes an "IN EAX,DX" instruction executed in flat ring-3, with the
13729 * backdoor port and magic numbers loaded in registers.
13730 *
13731 * @returns true if it is, false if it isn't.
13732 * @sa hmR0SvmIsMesaDrvGp.
13733 */
13734DECLINLINE(bool) hmR0VmxIsMesaDrvGp(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient, PCPUMCTX pCtx)
13735{
13736 /* 0xed: IN eAX,dx */
13737 uint8_t abInstr[1];
13738 if (pVmxTransient->cbExitInstr != sizeof(abInstr))
13739 return false;
13740
13741 /* Check that it is #GP(0). */
13742 if (pVmxTransient->uExitIntErrorCode != 0)
13743 return false;
13744
13745 /* Check magic and port. */
13746 Assert(!(pCtx->fExtrn & (CPUMCTX_EXTRN_RAX | CPUMCTX_EXTRN_RDX | CPUMCTX_EXTRN_RCX)));
13747 /*Log(("hmR0VmxIsMesaDrvGp: rax=%RX64 rdx=%RX64\n", pCtx->rax, pCtx->rdx));*/
13748 if (pCtx->rax != UINT32_C(0x564d5868))
13749 return false;
13750 if (pCtx->dx != UINT32_C(0x5658))
13751 return false;
13752
13753 /* Flat ring-3 CS. */
13754 AssertCompile(HMVMX_CPUMCTX_EXTRN_ALL & CPUMCTX_EXTRN_CS);
13755 Assert(!(pCtx->fExtrn & CPUMCTX_EXTRN_CS));
13756 /*Log(("hmR0VmxIsMesaDrvGp: cs.Attr.n.u2Dpl=%d base=%Rx64\n", pCtx->cs.Attr.n.u2Dpl, pCtx->cs.u64Base));*/
13757 if (pCtx->cs.Attr.n.u2Dpl != 3)
13758 return false;
13759 if (pCtx->cs.u64Base != 0)
13760 return false;
13761
13762 /* Check opcode. */
13763 AssertCompile(HMVMX_CPUMCTX_EXTRN_ALL & CPUMCTX_EXTRN_RIP);
13764 Assert(!(pCtx->fExtrn & CPUMCTX_EXTRN_RIP));
13765 int rc = PGMPhysSimpleReadGCPtr(pVCpu, abInstr, pCtx->rip, sizeof(abInstr));
13766 /*Log(("hmR0VmxIsMesaDrvGp: PGMPhysSimpleReadGCPtr -> %Rrc %#x\n", rc, abInstr[0]));*/
13767 if (RT_FAILURE(rc))
13768 return false;
13769 if (abInstr[0] != 0xed)
13770 return false;
13771
13772 return true;
13773}
13774
13775
13776/**
13777 * VM-exit exception handler for \#GP (General-protection exception).
13778 *
13779 * @remarks Requires all fields in HMVMX_READ_XCPT_INFO to be read from the VMCS.
13780 */
13781static VBOXSTRICTRC hmR0VmxExitXcptGP(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
13782{
13783 HMVMX_VALIDATE_EXIT_XCPT_HANDLER_PARAMS(pVCpu, pVmxTransient);
13784 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestGP);
13785
13786 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
13787 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
13788 if (pVmcsInfo->RealMode.fRealOnV86Active)
13789 { /* likely */ }
13790 else
13791 {
13792#ifndef HMVMX_ALWAYS_TRAP_ALL_XCPTS
13793 Assert(pVCpu->hm.s.fUsingDebugLoop || pVCpu->hm.s.fTrapXcptGpForLovelyMesaDrv || pVmxTransient->fIsNestedGuest);
13794#endif
13795 /*
13796 * If the guest is not in real-mode or we have unrestricted guest execution support, or if we are
13797 * executing a nested-guest, reflect #GP to the guest or nested-guest.
13798 */
13799 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, HMVMX_CPUMCTX_EXTRN_ALL);
13800 AssertRCReturn(rc, rc);
13801 Log4Func(("Gst: cs:rip=%#04x:%#RX64 ErrorCode=%#x cr0=%#RX64 cpl=%u tr=%#04x\n", pCtx->cs.Sel, pCtx->rip,
13802 pVmxTransient->uExitIntErrorCode, pCtx->cr0, CPUMGetGuestCPL(pVCpu), pCtx->tr.Sel));
13803
13804 if ( pVmxTransient->fIsNestedGuest
13805 || !pVCpu->hm.s.fTrapXcptGpForLovelyMesaDrv
13806 || !hmR0VmxIsMesaDrvGp(pVCpu, pVmxTransient, pCtx))
13807 hmR0VmxSetPendingEvent(pVCpu, VMX_ENTRY_INT_INFO_FROM_EXIT_INT_INFO(pVmxTransient->uExitIntInfo),
13808 pVmxTransient->cbExitInstr, pVmxTransient->uExitIntErrorCode, 0 /* GCPtrFaultAddress */);
13809 else
13810 rc = hmR0VmxHandleMesaDrvGp(pVCpu, pVmxTransient, pCtx);
13811 return rc;
13812 }
13813
13814 Assert(CPUMIsGuestInRealModeEx(pCtx));
13815 Assert(!pVCpu->CTX_SUFF(pVM)->hm.s.vmx.fUnrestrictedGuest);
13816 Assert(!pVmxTransient->fIsNestedGuest);
13817
13818 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, HMVMX_CPUMCTX_EXTRN_ALL);
13819 AssertRCReturn(rc, rc);
13820
13821 VBOXSTRICTRC rcStrict = IEMExecOne(pVCpu);
13822 if (rcStrict == VINF_SUCCESS)
13823 {
13824 if (!CPUMIsGuestInRealModeEx(pCtx))
13825 {
13826 /*
13827 * The guest is no longer in real-mode, check if we can continue executing the
13828 * guest using hardware-assisted VMX. Otherwise, fall back to emulation.
13829 */
13830 pVmcsInfo->RealMode.fRealOnV86Active = false;
13831 if (HMCanExecuteVmxGuest(pVCpu->pVMR0, pVCpu, pCtx))
13832 {
13833 Log4Func(("Mode changed but guest still suitable for executing using hardware-assisted VMX\n"));
13834 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_ALL_GUEST);
13835 }
13836 else
13837 {
13838 Log4Func(("Mode changed -> VINF_EM_RESCHEDULE\n"));
13839 rcStrict = VINF_EM_RESCHEDULE;
13840 }
13841 }
13842 else
13843 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_ALL_GUEST);
13844 }
13845 else if (rcStrict == VINF_IEM_RAISED_XCPT)
13846 {
13847 rcStrict = VINF_SUCCESS;
13848 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
13849 }
13850 return VBOXSTRICTRC_VAL(rcStrict);
13851}
13852
13853
13854/**
13855 * VM-exit exception handler wrapper for all other exceptions that are not handled
13856 * by a specific handler.
13857 *
13858 * This simply re-injects the exception back into the VM without any special
13859 * processing.
13860 *
13861 * @remarks Requires all fields in HMVMX_READ_XCPT_INFO to be read from the VMCS.
13862 */
13863static VBOXSTRICTRC hmR0VmxExitXcptOthers(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
13864{
13865 HMVMX_VALIDATE_EXIT_XCPT_HANDLER_PARAMS(pVCpu, pVmxTransient);
13866
13867#ifndef HMVMX_ALWAYS_TRAP_ALL_XCPTS
13868 PCVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
13869 AssertMsg(pVCpu->hm.s.fUsingDebugLoop || pVmcsInfo->RealMode.fRealOnV86Active || pVmxTransient->fIsNestedGuest,
13870 ("uVector=%#x u32XcptBitmap=%#X32\n",
13871 VMX_EXIT_INT_INFO_VECTOR(pVmxTransient->uExitIntInfo), pVmcsInfo->u32XcptBitmap));
13872 NOREF(pVmcsInfo);
13873#endif
13874
13875 /*
13876 * Re-inject the exception into the guest. This cannot be a double-fault condition which
13877 * would have been handled while checking exits due to event delivery.
13878 */
13879 uint8_t const uVector = VMX_EXIT_INT_INFO_VECTOR(pVmxTransient->uExitIntInfo);
13880
13881#ifdef HMVMX_ALWAYS_TRAP_ALL_XCPTS
13882 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, CPUMCTX_EXTRN_CS | CPUMCTX_EXTRN_RIP);
13883 AssertRCReturn(rc, rc);
13884 Log4Func(("Reinjecting Xcpt. uVector=%#x cs:rip=%#04x:%#RX64\n", uVector, pCtx->cs.Sel, pCtx->rip));
13885#endif
13886
13887#ifdef VBOX_WITH_STATISTICS
13888 switch (uVector)
13889 {
13890 case X86_XCPT_DE: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestDE); break;
13891 case X86_XCPT_DB: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestDB); break;
13892 case X86_XCPT_BP: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestBP); break;
13893 case X86_XCPT_OF: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestOF); break;
13894 case X86_XCPT_BR: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestBR); break;
13895 case X86_XCPT_UD: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestUD); break;
13896 case X86_XCPT_NM: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestOF); break;
13897 case X86_XCPT_DF: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestDF); break;
13898 case X86_XCPT_TS: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestTS); break;
13899 case X86_XCPT_NP: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestNP); break;
13900 case X86_XCPT_SS: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestSS); break;
13901 case X86_XCPT_GP: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestGP); break;
13902 case X86_XCPT_PF: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestPF); break;
13903 case X86_XCPT_MF: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestMF); break;
13904 case X86_XCPT_AC: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestAC); break;
13905 case X86_XCPT_XF: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestXF); break;
13906 default:
13907 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestXcpUnk);
13908 break;
13909 }
13910#endif
13911
13912 /* We should never call this function for a page-fault, we'd need to pass on the fault address below otherwise. */
13913 Assert(!VMX_EXIT_INT_INFO_IS_XCPT_PF(pVmxTransient->uExitIntInfo));
13914 NOREF(uVector);
13915
13916 /* Re-inject the original exception into the guest. */
13917 hmR0VmxSetPendingEvent(pVCpu, VMX_ENTRY_INT_INFO_FROM_EXIT_INT_INFO(pVmxTransient->uExitIntInfo),
13918 pVmxTransient->cbExitInstr, pVmxTransient->uExitIntErrorCode, 0 /* GCPtrFaultAddress */);
13919 return VINF_SUCCESS;
13920}
13921
13922
13923/**
13924 * VM-exit exception handler for all exceptions (except NMIs!).
13925 *
13926 * @remarks This may be called for both guests and nested-guests. Take care to not
13927 * make assumptions and avoid doing anything that is not relevant when
13928 * executing a nested-guest (e.g., Mesa driver hacks).
13929 */
13930static VBOXSTRICTRC hmR0VmxExitXcpt(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
13931{
13932 HMVMX_ASSERT_READ(pVmxTransient, HMVMX_READ_XCPT_INFO);
13933
13934 /*
13935 * If this VM-exit occurred while delivering an event through the guest IDT, take
13936 * action based on the return code and additional hints (e.g. for page-faults)
13937 * that will be updated in the VMX transient structure.
13938 */
13939 VBOXSTRICTRC rcStrict = hmR0VmxCheckExitDueToEventDelivery(pVCpu, pVmxTransient);
13940 if (rcStrict == VINF_SUCCESS)
13941 {
13942 /*
13943 * If an exception caused a VM-exit due to delivery of an event, the original
13944 * event may have to be re-injected into the guest. We shall reinject it and
13945 * continue guest execution. However, page-fault is a complicated case and
13946 * needs additional processing done in hmR0VmxExitXcptPF().
13947 */
13948 Assert(VMX_EXIT_INT_INFO_IS_VALID(pVmxTransient->uExitIntInfo));
13949 uint8_t const uVector = VMX_EXIT_INT_INFO_VECTOR(pVmxTransient->uExitIntInfo);
13950 if ( !pVCpu->hm.s.Event.fPending
13951 || uVector == X86_XCPT_PF)
13952 {
13953 switch (uVector)
13954 {
13955 case X86_XCPT_PF: return hmR0VmxExitXcptPF(pVCpu, pVmxTransient);
13956 case X86_XCPT_GP: return hmR0VmxExitXcptGP(pVCpu, pVmxTransient);
13957 case X86_XCPT_MF: return hmR0VmxExitXcptMF(pVCpu, pVmxTransient);
13958 case X86_XCPT_DB: return hmR0VmxExitXcptDB(pVCpu, pVmxTransient);
13959 case X86_XCPT_BP: return hmR0VmxExitXcptBP(pVCpu, pVmxTransient);
13960 case X86_XCPT_AC: return hmR0VmxExitXcptAC(pVCpu, pVmxTransient);
13961 default:
13962 return hmR0VmxExitXcptOthers(pVCpu, pVmxTransient);
13963 }
13964 }
13965 /* else: inject pending event before resuming guest execution. */
13966 }
13967 else if (rcStrict == VINF_HM_DOUBLE_FAULT)
13968 {
13969 Assert(pVCpu->hm.s.Event.fPending);
13970 rcStrict = VINF_SUCCESS;
13971 }
13972
13973 return rcStrict;
13974}
13975/** @} */
13976
13977
13978/** @name VM-exit handlers.
13979 * @{
13980 */
13981/* -=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= */
13982/* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- VM-exit handlers -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- */
13983/* -=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= */
13984
13985/**
13986 * VM-exit handler for external interrupts (VMX_EXIT_EXT_INT).
13987 */
13988HMVMX_EXIT_DECL hmR0VmxExitExtInt(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
13989{
13990 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
13991 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitExtInt);
13992 /* Windows hosts (32-bit and 64-bit) have DPC latency issues. See @bugref{6853}. */
13993 if (VMMR0ThreadCtxHookIsEnabled(pVCpu))
13994 return VINF_SUCCESS;
13995 return VINF_EM_RAW_INTERRUPT;
13996}
13997
13998
13999/**
14000 * VM-exit handler for exceptions or NMIs (VMX_EXIT_XCPT_OR_NMI). Conditional
14001 * VM-exit.
14002 */
14003HMVMX_EXIT_DECL hmR0VmxExitXcptOrNmi(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14004{
14005 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14006 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatExitXcptNmi, y3);
14007
14008 hmR0VmxReadExitIntInfoVmcs(pVmxTransient);
14009
14010 uint32_t const uExitIntType = VMX_EXIT_INT_INFO_TYPE(pVmxTransient->uExitIntInfo);
14011 uint8_t const uVector = VMX_EXIT_INT_INFO_VECTOR(pVmxTransient->uExitIntInfo);
14012 Assert(VMX_EXIT_INT_INFO_IS_VALID(pVmxTransient->uExitIntInfo));
14013
14014 PCVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
14015 Assert( !(pVmcsInfo->u32ExitCtls & VMX_EXIT_CTLS_ACK_EXT_INT)
14016 && uExitIntType != VMX_EXIT_INT_INFO_TYPE_EXT_INT);
14017 NOREF(pVmcsInfo);
14018
14019 VBOXSTRICTRC rcStrict;
14020 switch (uExitIntType)
14021 {
14022 /*
14023 * Host physical NMIs:
14024 * This cannot be a guest NMI as the only way for the guest to receive an NMI is if we
14025 * injected it ourselves and anything we inject is not going to cause a VM-exit directly
14026 * for the event being injected[1]. Go ahead and dispatch the NMI to the host[2].
14027 *
14028 * See Intel spec. 27.2.3 "Information for VM Exits During Event Delivery".
14029 * See Intel spec. 27.5.5 "Updating Non-Register State".
14030 */
14031 case VMX_EXIT_INT_INFO_TYPE_NMI:
14032 {
14033 rcStrict = hmR0VmxExitHostNmi(pVCpu, pVmcsInfo);
14034 break;
14035 }
14036
14037 /*
14038 * Privileged software exceptions (#DB from ICEBP),
14039 * Software exceptions (#BP and #OF),
14040 * Hardware exceptions:
14041 * Process the required exceptions and resume guest execution if possible.
14042 */
14043 case VMX_EXIT_INT_INFO_TYPE_PRIV_SW_XCPT:
14044 Assert(uVector == X86_XCPT_DB);
14045 RT_FALL_THRU();
14046 case VMX_EXIT_INT_INFO_TYPE_SW_XCPT:
14047 Assert(uVector == X86_XCPT_BP || uVector == X86_XCPT_OF || uExitIntType == VMX_EXIT_INT_INFO_TYPE_PRIV_SW_XCPT);
14048 RT_FALL_THRU();
14049 case VMX_EXIT_INT_INFO_TYPE_HW_XCPT:
14050 {
14051 NOREF(uVector);
14052 hmR0VmxReadExitIntErrorCodeVmcs(pVmxTransient);
14053 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
14054 hmR0VmxReadIdtVectoringInfoVmcs(pVmxTransient);
14055 hmR0VmxReadIdtVectoringErrorCodeVmcs(pVmxTransient);
14056
14057 rcStrict = hmR0VmxExitXcpt(pVCpu, pVmxTransient);
14058 break;
14059 }
14060
14061 default:
14062 {
14063 pVCpu->hm.s.u32HMError = pVmxTransient->uExitIntInfo;
14064 rcStrict = VERR_VMX_UNEXPECTED_INTERRUPTION_EXIT_TYPE;
14065 AssertMsgFailed(("Invalid/unexpected VM-exit interruption info %#x\n", pVmxTransient->uExitIntInfo));
14066 break;
14067 }
14068 }
14069
14070 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExitXcptNmi, y3);
14071 return rcStrict;
14072}
14073
14074
14075/**
14076 * VM-exit handler for interrupt-window exiting (VMX_EXIT_INT_WINDOW).
14077 */
14078HMVMX_EXIT_NSRC_DECL hmR0VmxExitIntWindow(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14079{
14080 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14081
14082 /* Indicate that we no longer need to VM-exit when the guest is ready to receive interrupts, it is now ready. */
14083 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
14084 hmR0VmxClearIntWindowExitVmcs(pVmcsInfo);
14085
14086 /* Evaluate and deliver pending events and resume guest execution. */
14087 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIntWindow);
14088 return VINF_SUCCESS;
14089}
14090
14091
14092/**
14093 * VM-exit handler for NMI-window exiting (VMX_EXIT_NMI_WINDOW).
14094 */
14095HMVMX_EXIT_NSRC_DECL hmR0VmxExitNmiWindow(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14096{
14097 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14098
14099 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
14100 if (RT_UNLIKELY(!(pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_NMI_WINDOW_EXIT))) /** @todo NSTVMX: Turn this into an assertion. */
14101 {
14102 AssertMsgFailed(("Unexpected NMI-window exit.\n"));
14103 HMVMX_UNEXPECTED_EXIT_RET(pVCpu, pVmxTransient->uExitReason);
14104 }
14105
14106 Assert(!CPUMIsGuestNmiBlocking(pVCpu));
14107
14108 /*
14109 * If block-by-STI is set when we get this VM-exit, it means the CPU doesn't block NMIs following STI.
14110 * It is therefore safe to unblock STI and deliver the NMI ourselves. See @bugref{7445}.
14111 */
14112 uint32_t fIntrState;
14113 int rc = VMXReadVmcs32(VMX_VMCS32_GUEST_INT_STATE, &fIntrState);
14114 AssertRC(rc);
14115 Assert(!(fIntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_MOVSS));
14116 if (fIntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_STI)
14117 {
14118 if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS))
14119 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS);
14120
14121 fIntrState &= ~VMX_VMCS_GUEST_INT_STATE_BLOCK_STI;
14122 rc = VMXWriteVmcs32(VMX_VMCS32_GUEST_INT_STATE, fIntrState);
14123 AssertRC(rc);
14124 }
14125
14126 /* Indicate that we no longer need to VM-exit when the guest is ready to receive NMIs, it is now ready */
14127 hmR0VmxClearNmiWindowExitVmcs(pVmcsInfo);
14128
14129 /* Evaluate and deliver pending events and resume guest execution. */
14130 return VINF_SUCCESS;
14131}
14132
14133
14134/**
14135 * VM-exit handler for WBINVD (VMX_EXIT_WBINVD). Conditional VM-exit.
14136 */
14137HMVMX_EXIT_NSRC_DECL hmR0VmxExitWbinvd(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14138{
14139 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14140 return hmR0VmxAdvanceGuestRip(pVCpu, pVmxTransient);
14141}
14142
14143
14144/**
14145 * VM-exit handler for INVD (VMX_EXIT_INVD). Unconditional VM-exit.
14146 */
14147HMVMX_EXIT_NSRC_DECL hmR0VmxExitInvd(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14148{
14149 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14150 return hmR0VmxAdvanceGuestRip(pVCpu, pVmxTransient);
14151}
14152
14153
14154/**
14155 * VM-exit handler for CPUID (VMX_EXIT_CPUID). Unconditional VM-exit.
14156 */
14157HMVMX_EXIT_DECL hmR0VmxExitCpuid(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14158{
14159 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14160
14161 /*
14162 * Get the state we need and update the exit history entry.
14163 */
14164 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
14165 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
14166
14167 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, IEM_CPUMCTX_EXTRN_EXEC_DECODED_NO_MEM_MASK);
14168 AssertRCReturn(rc, rc);
14169
14170 VBOXSTRICTRC rcStrict;
14171 PCEMEXITREC pExitRec = EMHistoryUpdateFlagsAndTypeAndPC(pVCpu,
14172 EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM | EMEXIT_F_HM, EMEXITTYPE_CPUID),
14173 pVCpu->cpum.GstCtx.rip + pVCpu->cpum.GstCtx.cs.u64Base);
14174 if (!pExitRec)
14175 {
14176 /*
14177 * Regular CPUID instruction execution.
14178 */
14179 rcStrict = IEMExecDecodedCpuid(pVCpu, pVmxTransient->cbExitInstr);
14180 if (rcStrict == VINF_SUCCESS)
14181 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS);
14182 else if (rcStrict == VINF_IEM_RAISED_XCPT)
14183 {
14184 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
14185 rcStrict = VINF_SUCCESS;
14186 }
14187 }
14188 else
14189 {
14190 /*
14191 * Frequent exit or something needing probing. Get state and call EMHistoryExec.
14192 */
14193 int rc2 = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, HMVMX_CPUMCTX_EXTRN_ALL);
14194 AssertRCReturn(rc2, rc2);
14195
14196 Log4(("CpuIdExit/%u: %04x:%08RX64: %#x/%#x -> EMHistoryExec\n",
14197 pVCpu->idCpu, pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip, pVCpu->cpum.GstCtx.eax, pVCpu->cpum.GstCtx.ecx));
14198
14199 rcStrict = EMHistoryExec(pVCpu, pExitRec, 0);
14200 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_ALL_GUEST);
14201
14202 Log4(("CpuIdExit/%u: %04x:%08RX64: EMHistoryExec -> %Rrc + %04x:%08RX64\n",
14203 pVCpu->idCpu, pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip,
14204 VBOXSTRICTRC_VAL(rcStrict), pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip));
14205 }
14206 return rcStrict;
14207}
14208
14209
14210/**
14211 * VM-exit handler for GETSEC (VMX_EXIT_GETSEC). Unconditional VM-exit.
14212 */
14213HMVMX_EXIT_DECL hmR0VmxExitGetsec(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14214{
14215 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14216
14217 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
14218 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, CPUMCTX_EXTRN_CR4);
14219 AssertRCReturn(rc, rc);
14220
14221 if (pVCpu->cpum.GstCtx.cr4 & X86_CR4_SMXE)
14222 return VINF_EM_RAW_EMULATE_INSTR;
14223
14224 AssertMsgFailed(("hmR0VmxExitGetsec: Unexpected VM-exit when CR4.SMXE is 0.\n"));
14225 HMVMX_UNEXPECTED_EXIT_RET(pVCpu, pVmxTransient->uExitReason);
14226}
14227
14228
14229/**
14230 * VM-exit handler for RDTSC (VMX_EXIT_RDTSC). Conditional VM-exit.
14231 */
14232HMVMX_EXIT_DECL hmR0VmxExitRdtsc(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14233{
14234 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14235
14236 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
14237 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
14238 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, IEM_CPUMCTX_EXTRN_MUST_MASK);
14239 AssertRCReturn(rc, rc);
14240
14241 VBOXSTRICTRC rcStrict = IEMExecDecodedRdtsc(pVCpu, pVmxTransient->cbExitInstr);
14242 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
14243 {
14244 /* If we get a spurious VM-exit when TSC offsetting is enabled,
14245 we must reset offsetting on VM-entry. See @bugref{6634}. */
14246 if (pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_USE_TSC_OFFSETTING)
14247 pVmxTransient->fUpdatedTscOffsettingAndPreemptTimer = false;
14248 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS);
14249 }
14250 else if (rcStrict == VINF_IEM_RAISED_XCPT)
14251 {
14252 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
14253 rcStrict = VINF_SUCCESS;
14254 }
14255 return rcStrict;
14256}
14257
14258
14259/**
14260 * VM-exit handler for RDTSCP (VMX_EXIT_RDTSCP). Conditional VM-exit.
14261 */
14262HMVMX_EXIT_DECL hmR0VmxExitRdtscp(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14263{
14264 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14265
14266 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
14267 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
14268 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, IEM_CPUMCTX_EXTRN_MUST_MASK | CPUMCTX_EXTRN_TSC_AUX);
14269 AssertRCReturn(rc, rc);
14270
14271 VBOXSTRICTRC rcStrict = IEMExecDecodedRdtscp(pVCpu, pVmxTransient->cbExitInstr);
14272 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
14273 {
14274 /* If we get a spurious VM-exit when TSC offsetting is enabled,
14275 we must reset offsetting on VM-reentry. See @bugref{6634}. */
14276 if (pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_USE_TSC_OFFSETTING)
14277 pVmxTransient->fUpdatedTscOffsettingAndPreemptTimer = false;
14278 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS);
14279 }
14280 else if (rcStrict == VINF_IEM_RAISED_XCPT)
14281 {
14282 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
14283 rcStrict = VINF_SUCCESS;
14284 }
14285 return rcStrict;
14286}
14287
14288
14289/**
14290 * VM-exit handler for RDPMC (VMX_EXIT_RDPMC). Conditional VM-exit.
14291 */
14292HMVMX_EXIT_DECL hmR0VmxExitRdpmc(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14293{
14294 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14295
14296 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
14297 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, CPUMCTX_EXTRN_CR4 | CPUMCTX_EXTRN_CR0
14298 | CPUMCTX_EXTRN_RFLAGS | CPUMCTX_EXTRN_SS);
14299 AssertRCReturn(rc, rc);
14300
14301 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
14302 rc = EMInterpretRdpmc(pVCpu->CTX_SUFF(pVM), pVCpu, CPUMCTX2CORE(pCtx));
14303 if (RT_LIKELY(rc == VINF_SUCCESS))
14304 {
14305 rc = hmR0VmxAdvanceGuestRip(pVCpu, pVmxTransient);
14306 Assert(pVmxTransient->cbExitInstr == 2);
14307 }
14308 else
14309 {
14310 AssertMsgFailed(("hmR0VmxExitRdpmc: EMInterpretRdpmc failed with %Rrc\n", rc));
14311 rc = VERR_EM_INTERPRETER;
14312 }
14313 return rc;
14314}
14315
14316
14317/**
14318 * VM-exit handler for VMCALL (VMX_EXIT_VMCALL). Unconditional VM-exit.
14319 */
14320HMVMX_EXIT_DECL hmR0VmxExitVmcall(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14321{
14322 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14323
14324 VBOXSTRICTRC rcStrict = VERR_VMX_IPE_3;
14325 if (EMAreHypercallInstructionsEnabled(pVCpu))
14326 {
14327 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
14328 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, CPUMCTX_EXTRN_RIP | CPUMCTX_EXTRN_RFLAGS | CPUMCTX_EXTRN_CR0
14329 | CPUMCTX_EXTRN_SS | CPUMCTX_EXTRN_CS | CPUMCTX_EXTRN_EFER);
14330 AssertRCReturn(rc, rc);
14331
14332 /* Perform the hypercall. */
14333 rcStrict = GIMHypercall(pVCpu, &pVCpu->cpum.GstCtx);
14334 if (rcStrict == VINF_SUCCESS)
14335 {
14336 rc = hmR0VmxAdvanceGuestRip(pVCpu, pVmxTransient);
14337 AssertRCReturn(rc, rc);
14338 }
14339 else
14340 Assert( rcStrict == VINF_GIM_R3_HYPERCALL
14341 || rcStrict == VINF_GIM_HYPERCALL_CONTINUING
14342 || RT_FAILURE(rcStrict));
14343
14344 /* If the hypercall changes anything other than guest's general-purpose registers,
14345 we would need to reload the guest changed bits here before VM-entry. */
14346 }
14347 else
14348 Log4Func(("Hypercalls not enabled\n"));
14349
14350 /* If hypercalls are disabled or the hypercall failed for some reason, raise #UD and continue. */
14351 if (RT_FAILURE(rcStrict))
14352 {
14353 hmR0VmxSetPendingXcptUD(pVCpu);
14354 rcStrict = VINF_SUCCESS;
14355 }
14356
14357 return rcStrict;
14358}
14359
14360
14361/**
14362 * VM-exit handler for INVLPG (VMX_EXIT_INVLPG). Conditional VM-exit.
14363 */
14364HMVMX_EXIT_DECL hmR0VmxExitInvlpg(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14365{
14366 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14367 Assert(!pVCpu->CTX_SUFF(pVM)->hm.s.fNestedPaging || pVCpu->hm.s.fUsingDebugLoop);
14368
14369 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
14370 hmR0VmxReadExitQualVmcs(pVmxTransient);
14371 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
14372 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, IEM_CPUMCTX_EXTRN_EXEC_DECODED_MEM_MASK);
14373 AssertRCReturn(rc, rc);
14374
14375 VBOXSTRICTRC rcStrict = IEMExecDecodedInvlpg(pVCpu, pVmxTransient->cbExitInstr, pVmxTransient->uExitQual);
14376
14377 if (rcStrict == VINF_SUCCESS || rcStrict == VINF_PGM_SYNC_CR3)
14378 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS);
14379 else if (rcStrict == VINF_IEM_RAISED_XCPT)
14380 {
14381 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
14382 rcStrict = VINF_SUCCESS;
14383 }
14384 else
14385 AssertMsgFailed(("Unexpected IEMExecDecodedInvlpg(%#RX64) status: %Rrc\n", pVmxTransient->uExitQual,
14386 VBOXSTRICTRC_VAL(rcStrict)));
14387 return rcStrict;
14388}
14389
14390
14391/**
14392 * VM-exit handler for MONITOR (VMX_EXIT_MONITOR). Conditional VM-exit.
14393 */
14394HMVMX_EXIT_DECL hmR0VmxExitMonitor(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14395{
14396 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14397
14398 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
14399 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
14400 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, IEM_CPUMCTX_EXTRN_EXEC_DECODED_MEM_MASK | CPUMCTX_EXTRN_DS);
14401 AssertRCReturn(rc, rc);
14402
14403 VBOXSTRICTRC rcStrict = IEMExecDecodedMonitor(pVCpu, pVmxTransient->cbExitInstr);
14404 if (rcStrict == VINF_SUCCESS)
14405 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS);
14406 else if (rcStrict == VINF_IEM_RAISED_XCPT)
14407 {
14408 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
14409 rcStrict = VINF_SUCCESS;
14410 }
14411
14412 return rcStrict;
14413}
14414
14415
14416/**
14417 * VM-exit handler for MWAIT (VMX_EXIT_MWAIT). Conditional VM-exit.
14418 */
14419HMVMX_EXIT_DECL hmR0VmxExitMwait(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14420{
14421 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14422
14423 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
14424 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
14425 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, IEM_CPUMCTX_EXTRN_EXEC_DECODED_NO_MEM_MASK);
14426 AssertRCReturn(rc, rc);
14427
14428 VBOXSTRICTRC rcStrict = IEMExecDecodedMwait(pVCpu, pVmxTransient->cbExitInstr);
14429 if (RT_SUCCESS(rcStrict))
14430 {
14431 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS);
14432 if (EMMonitorWaitShouldContinue(pVCpu, &pVCpu->cpum.GstCtx))
14433 rcStrict = VINF_SUCCESS;
14434 }
14435
14436 return rcStrict;
14437}
14438
14439
14440/**
14441 * VM-exit handler for triple faults (VMX_EXIT_TRIPLE_FAULT). Unconditional
14442 * VM-exit.
14443 */
14444HMVMX_EXIT_DECL hmR0VmxExitTripleFault(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14445{
14446 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14447 return VINF_EM_RESET;
14448}
14449
14450
14451/**
14452 * VM-exit handler for HLT (VMX_EXIT_HLT). Conditional VM-exit.
14453 */
14454HMVMX_EXIT_DECL hmR0VmxExitHlt(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14455{
14456 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14457
14458 int rc = hmR0VmxAdvanceGuestRip(pVCpu, pVmxTransient);
14459 AssertRCReturn(rc, rc);
14460
14461 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_RFLAGS); /* Advancing the RIP above should've imported eflags. */
14462 if (EMShouldContinueAfterHalt(pVCpu, &pVCpu->cpum.GstCtx)) /* Requires eflags. */
14463 rc = VINF_SUCCESS;
14464 else
14465 rc = VINF_EM_HALT;
14466
14467 if (rc != VINF_SUCCESS)
14468 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchHltToR3);
14469 return rc;
14470}
14471
14472
14473/**
14474 * VM-exit handler for instructions that result in a \#UD exception delivered to
14475 * the guest.
14476 */
14477HMVMX_EXIT_NSRC_DECL hmR0VmxExitSetPendingXcptUD(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14478{
14479 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14480 hmR0VmxSetPendingXcptUD(pVCpu);
14481 return VINF_SUCCESS;
14482}
14483
14484
14485/**
14486 * VM-exit handler for expiry of the VMX-preemption timer.
14487 */
14488HMVMX_EXIT_DECL hmR0VmxExitPreemptTimer(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14489{
14490 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14491
14492 /* If the VMX-preemption timer has expired, reinitialize the preemption timer on next VM-entry. */
14493 pVmxTransient->fUpdatedTscOffsettingAndPreemptTimer = false;
14494
14495 /* If there are any timer events pending, fall back to ring-3, otherwise resume guest execution. */
14496 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
14497 bool fTimersPending = TMTimerPollBool(pVM, pVCpu);
14498 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitPreemptTimer);
14499 return fTimersPending ? VINF_EM_RAW_TIMER_PENDING : VINF_SUCCESS;
14500}
14501
14502
14503/**
14504 * VM-exit handler for XSETBV (VMX_EXIT_XSETBV). Unconditional VM-exit.
14505 */
14506HMVMX_EXIT_DECL hmR0VmxExitXsetbv(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14507{
14508 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14509
14510 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
14511 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
14512 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, IEM_CPUMCTX_EXTRN_MUST_MASK | CPUMCTX_EXTRN_CR4);
14513 AssertRCReturn(rc, rc);
14514
14515 VBOXSTRICTRC rcStrict = IEMExecDecodedXsetbv(pVCpu, pVmxTransient->cbExitInstr);
14516 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, rcStrict != VINF_IEM_RAISED_XCPT ? HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS
14517 : HM_CHANGED_RAISED_XCPT_MASK);
14518
14519 PCCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
14520 pVCpu->hm.s.fLoadSaveGuestXcr0 = (pCtx->cr4 & X86_CR4_OSXSAVE) && pCtx->aXcr[0] != ASMGetXcr0();
14521
14522 return rcStrict;
14523}
14524
14525
14526/**
14527 * VM-exit handler for INVPCID (VMX_EXIT_INVPCID). Conditional VM-exit.
14528 */
14529HMVMX_EXIT_DECL hmR0VmxExitInvpcid(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14530{
14531 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14532 /** @todo Use VM-exit instruction information. */
14533 return VERR_EM_INTERPRETER;
14534}
14535
14536
14537/**
14538 * VM-exit handler for invalid-guest-state (VMX_EXIT_ERR_INVALID_GUEST_STATE). Error
14539 * VM-exit.
14540 */
14541HMVMX_EXIT_NSRC_DECL hmR0VmxExitErrInvalidGuestState(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14542{
14543 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
14544 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, HMVMX_CPUMCTX_EXTRN_ALL);
14545 AssertRCReturn(rc, rc);
14546
14547 rc = hmR0VmxCheckVmcsCtls(pVCpu, pVmcsInfo, pVmxTransient->fIsNestedGuest);
14548 if (RT_FAILURE(rc))
14549 return rc;
14550
14551 uint32_t const uInvalidReason = hmR0VmxCheckGuestState(pVCpu, pVmcsInfo);
14552 NOREF(uInvalidReason);
14553
14554#ifdef VBOX_STRICT
14555 uint32_t fIntrState;
14556 uint64_t u64Val;
14557 hmR0VmxReadEntryIntInfoVmcs(pVmxTransient);
14558 hmR0VmxReadEntryXcptErrorCodeVmcs(pVmxTransient);
14559 hmR0VmxReadEntryInstrLenVmcs(pVmxTransient);
14560
14561 Log4(("uInvalidReason %u\n", uInvalidReason));
14562 Log4(("VMX_VMCS32_CTRL_ENTRY_INTERRUPTION_INFO %#RX32\n", pVmxTransient->uEntryIntInfo));
14563 Log4(("VMX_VMCS32_CTRL_ENTRY_EXCEPTION_ERRCODE %#RX32\n", pVmxTransient->uEntryXcptErrorCode));
14564 Log4(("VMX_VMCS32_CTRL_ENTRY_INSTR_LENGTH %#RX32\n", pVmxTransient->cbEntryInstr));
14565
14566 rc = VMXReadVmcs32(VMX_VMCS32_GUEST_INT_STATE, &fIntrState); AssertRC(rc);
14567 Log4(("VMX_VMCS32_GUEST_INT_STATE %#RX32\n", fIntrState));
14568 rc = VMXReadVmcsNw(VMX_VMCS_GUEST_CR0, &u64Val); AssertRC(rc);
14569 Log4(("VMX_VMCS_GUEST_CR0 %#RX64\n", u64Val));
14570 rc = VMXReadVmcsNw(VMX_VMCS_CTRL_CR0_MASK, &u64Val); AssertRC(rc);
14571 Log4(("VMX_VMCS_CTRL_CR0_MASK %#RX64\n", u64Val));
14572 rc = VMXReadVmcsNw(VMX_VMCS_CTRL_CR0_READ_SHADOW, &u64Val); AssertRC(rc);
14573 Log4(("VMX_VMCS_CTRL_CR4_READ_SHADOW %#RX64\n", u64Val));
14574 rc = VMXReadVmcsNw(VMX_VMCS_CTRL_CR4_MASK, &u64Val); AssertRC(rc);
14575 Log4(("VMX_VMCS_CTRL_CR4_MASK %#RX64\n", u64Val));
14576 rc = VMXReadVmcsNw(VMX_VMCS_CTRL_CR4_READ_SHADOW, &u64Val); AssertRC(rc);
14577 Log4(("VMX_VMCS_CTRL_CR4_READ_SHADOW %#RX64\n", u64Val));
14578 if (pVCpu->CTX_SUFF(pVM)->hm.s.fNestedPaging)
14579 {
14580 rc = VMXReadVmcs64(VMX_VMCS64_CTRL_EPTP_FULL, &u64Val); AssertRC(rc);
14581 Log4(("VMX_VMCS64_CTRL_EPTP_FULL %#RX64\n", u64Val));
14582 }
14583 hmR0DumpRegs(pVCpu, HM_DUMP_REG_FLAGS_ALL);
14584#endif
14585
14586 return VERR_VMX_INVALID_GUEST_STATE;
14587}
14588
14589/**
14590 * VM-exit handler for all undefined/unexpected reasons. Should never happen.
14591 */
14592HMVMX_EXIT_NSRC_DECL hmR0VmxExitErrUnexpected(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14593{
14594 /*
14595 * Cummulative notes of all recognized but unexpected VM-exits.
14596 *
14597 * 1. This does -not- cover scenarios like like a page-fault VM-exit occurring when
14598 * nested-paging is used.
14599 *
14600 * 2. Any instruction that causes a VM-exit unconditionally (for e.g. VMXON) must be
14601 * emulated or a #UD must be raised in the guest. Therefore, we should -not- be using
14602 * this function (and thereby stop VM execution) for handling such instructions.
14603 *
14604 *
14605 * VMX_EXIT_INIT_SIGNAL:
14606 * INIT signals are blocked in VMX root operation by VMXON and by SMI in SMM.
14607 * It is -NOT- blocked in VMX non-root operation so we can, in theory, still get these
14608 * VM-exits. However, we should not receive INIT signals VM-exit while executing a VM.
14609 *
14610 * See Intel spec. 33.14.1 Default Treatment of SMI Delivery"
14611 * See Intel spec. 29.3 "VMX Instructions" for "VMXON".
14612 * See Intel spec. "23.8 Restrictions on VMX operation".
14613 *
14614 * VMX_EXIT_SIPI:
14615 * SIPI exits can only occur in VMX non-root operation when the "wait-for-SIPI" guest
14616 * activity state is used. We don't make use of it as our guests don't have direct
14617 * access to the host local APIC.
14618 *
14619 * See Intel spec. 25.3 "Other Causes of VM-exits".
14620 *
14621 * VMX_EXIT_IO_SMI:
14622 * VMX_EXIT_SMI:
14623 * This can only happen if we support dual-monitor treatment of SMI, which can be
14624 * activated by executing VMCALL in VMX root operation. Only an STM (SMM transfer
14625 * monitor) would get this VM-exit when we (the executive monitor) execute a VMCALL in
14626 * VMX root mode or receive an SMI. If we get here, something funny is going on.
14627 *
14628 * See Intel spec. 33.15.6 "Activating the Dual-Monitor Treatment"
14629 * See Intel spec. 25.3 "Other Causes of VM-Exits"
14630 *
14631 * VMX_EXIT_ERR_MSR_LOAD:
14632 * Failures while loading MSRs are part of the VM-entry MSR-load area are unexpected
14633 * and typically indicates a bug in the hypervisor code. We thus cannot not resume
14634 * execution.
14635 *
14636 * See Intel spec. 26.7 "VM-Entry Failures During Or After Loading Guest State".
14637 *
14638 * VMX_EXIT_ERR_MACHINE_CHECK:
14639 * Machine check exceptions indicates a fatal/unrecoverable hardware condition
14640 * including but not limited to system bus, ECC, parity, cache and TLB errors. A
14641 * #MC exception abort class exception is raised. We thus cannot assume a
14642 * reasonable chance of continuing any sort of execution and we bail.
14643 *
14644 * See Intel spec. 15.1 "Machine-check Architecture".
14645 * See Intel spec. 27.1 "Architectural State Before A VM Exit".
14646 *
14647 * VMX_EXIT_PML_FULL:
14648 * VMX_EXIT_VIRTUALIZED_EOI:
14649 * VMX_EXIT_APIC_WRITE:
14650 * We do not currently support any of these features and thus they are all unexpected
14651 * VM-exits.
14652 *
14653 * VMX_EXIT_GDTR_IDTR_ACCESS:
14654 * VMX_EXIT_LDTR_TR_ACCESS:
14655 * VMX_EXIT_RDRAND:
14656 * VMX_EXIT_RSM:
14657 * VMX_EXIT_VMFUNC:
14658 * VMX_EXIT_ENCLS:
14659 * VMX_EXIT_RDSEED:
14660 * VMX_EXIT_XSAVES:
14661 * VMX_EXIT_XRSTORS:
14662 * VMX_EXIT_UMWAIT:
14663 * VMX_EXIT_TPAUSE:
14664 * These VM-exits are -not- caused unconditionally by execution of the corresponding
14665 * instruction. Any VM-exit for these instructions indicate a hardware problem,
14666 * unsupported CPU modes (like SMM) or potentially corrupt VMCS controls.
14667 *
14668 * See Intel spec. 25.1.3 "Instructions That Cause VM Exits Conditionally".
14669 */
14670 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14671 AssertMsgFailed(("Unexpected VM-exit %u\n", pVmxTransient->uExitReason));
14672 HMVMX_UNEXPECTED_EXIT_RET(pVCpu, pVmxTransient->uExitReason);
14673}
14674
14675
14676/**
14677 * VM-exit handler for RDMSR (VMX_EXIT_RDMSR).
14678 */
14679HMVMX_EXIT_DECL hmR0VmxExitRdmsr(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14680{
14681 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14682
14683 /** @todo Optimize this: We currently drag in in the whole MSR state
14684 * (CPUMCTX_EXTRN_ALL_MSRS) here. We should optimize this to only get
14685 * MSRs required. That would require changes to IEM and possibly CPUM too.
14686 * (Should probably do it lazy fashion from CPUMAllMsrs.cpp). */
14687 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
14688 uint32_t const idMsr = pVCpu->cpum.GstCtx.ecx;
14689 uint64_t fImport = IEM_CPUMCTX_EXTRN_EXEC_DECODED_NO_MEM_MASK | CPUMCTX_EXTRN_ALL_MSRS;
14690 switch (idMsr)
14691 {
14692 case MSR_K8_FS_BASE: fImport |= CPUMCTX_EXTRN_FS; break;
14693 case MSR_K8_GS_BASE: fImport |= CPUMCTX_EXTRN_GS; break;
14694 }
14695
14696 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
14697 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, fImport);
14698 AssertRCReturn(rc, rc);
14699
14700 Log4Func(("ecx=%#RX32\n", idMsr));
14701
14702#ifdef VBOX_STRICT
14703 Assert(!pVmxTransient->fIsNestedGuest);
14704 if (pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_USE_MSR_BITMAPS)
14705 {
14706 if ( hmR0VmxIsAutoLoadGuestMsr(pVmcsInfo, idMsr)
14707 && idMsr != MSR_K6_EFER)
14708 {
14709 AssertMsgFailed(("Unexpected RDMSR for an MSR in the auto-load/store area in the VMCS. ecx=%#RX32\n", idMsr));
14710 HMVMX_UNEXPECTED_EXIT_RET(pVCpu, idMsr);
14711 }
14712 if (hmR0VmxIsLazyGuestMsr(pVCpu, idMsr))
14713 {
14714 Assert(pVmcsInfo->pvMsrBitmap);
14715 uint32_t fMsrpm = CPUMGetVmxMsrPermission(pVmcsInfo->pvMsrBitmap, idMsr);
14716 if (fMsrpm & VMXMSRPM_ALLOW_RD)
14717 {
14718 AssertMsgFailed(("Unexpected RDMSR for a passthru lazy-restore MSR. ecx=%#RX32\n", idMsr));
14719 HMVMX_UNEXPECTED_EXIT_RET(pVCpu, idMsr);
14720 }
14721 }
14722 }
14723#endif
14724
14725 VBOXSTRICTRC rcStrict = IEMExecDecodedRdmsr(pVCpu, pVmxTransient->cbExitInstr);
14726 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitRdmsr);
14727 if (rcStrict == VINF_SUCCESS)
14728 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS
14729 | HM_CHANGED_GUEST_RAX | HM_CHANGED_GUEST_RDX);
14730 else if (rcStrict == VINF_IEM_RAISED_XCPT)
14731 {
14732 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
14733 rcStrict = VINF_SUCCESS;
14734 }
14735 else
14736 AssertMsg(rcStrict == VINF_CPUM_R3_MSR_READ, ("Unexpected IEMExecDecodedRdmsr rc (%Rrc)\n", VBOXSTRICTRC_VAL(rcStrict)));
14737
14738 return rcStrict;
14739}
14740
14741
14742/**
14743 * VM-exit handler for WRMSR (VMX_EXIT_WRMSR).
14744 */
14745HMVMX_EXIT_DECL hmR0VmxExitWrmsr(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14746{
14747 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14748
14749 /** @todo Optimize this: We currently drag in in the whole MSR state
14750 * (CPUMCTX_EXTRN_ALL_MSRS) here. We should optimize this to only get
14751 * MSRs required. That would require changes to IEM and possibly CPUM too.
14752 * (Should probably do it lazy fashion from CPUMAllMsrs.cpp). */
14753 uint32_t const idMsr = pVCpu->cpum.GstCtx.ecx;
14754 uint64_t fImport = IEM_CPUMCTX_EXTRN_EXEC_DECODED_NO_MEM_MASK | CPUMCTX_EXTRN_ALL_MSRS;
14755
14756 /*
14757 * The FS and GS base MSRs are not part of the above all-MSRs mask.
14758 * Although we don't need to fetch the base as it will be overwritten shortly, while
14759 * loading guest-state we would also load the entire segment register including limit
14760 * and attributes and thus we need to load them here.
14761 */
14762 switch (idMsr)
14763 {
14764 case MSR_K8_FS_BASE: fImport |= CPUMCTX_EXTRN_FS; break;
14765 case MSR_K8_GS_BASE: fImport |= CPUMCTX_EXTRN_GS; break;
14766 }
14767
14768 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
14769 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
14770 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, fImport);
14771 AssertRCReturn(rc, rc);
14772
14773 Log4Func(("ecx=%#RX32 edx:eax=%#RX32:%#RX32\n", idMsr, pVCpu->cpum.GstCtx.edx, pVCpu->cpum.GstCtx.eax));
14774
14775 VBOXSTRICTRC rcStrict = IEMExecDecodedWrmsr(pVCpu, pVmxTransient->cbExitInstr);
14776 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitWrmsr);
14777
14778 if (rcStrict == VINF_SUCCESS)
14779 {
14780 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS);
14781
14782 /* If this is an X2APIC WRMSR access, update the APIC state as well. */
14783 if ( idMsr == MSR_IA32_APICBASE
14784 || ( idMsr >= MSR_IA32_X2APIC_START
14785 && idMsr <= MSR_IA32_X2APIC_END))
14786 {
14787 /*
14788 * We've already saved the APIC related guest-state (TPR) in post-run phase.
14789 * When full APIC register virtualization is implemented we'll have to make
14790 * sure APIC state is saved from the VMCS before IEM changes it.
14791 */
14792 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_APIC_TPR);
14793 }
14794 else if (idMsr == MSR_IA32_TSC) /* Windows 7 does this during bootup. See @bugref{6398}. */
14795 pVmxTransient->fUpdatedTscOffsettingAndPreemptTimer = false;
14796 else if (idMsr == MSR_K6_EFER)
14797 {
14798 /*
14799 * If the guest touches the EFER MSR we need to update the VM-Entry and VM-Exit controls
14800 * as well, even if it is -not- touching bits that cause paging mode changes (LMA/LME).
14801 * We care about the other bits as well, SCE and NXE. See @bugref{7368}.
14802 */
14803 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_EFER_MSR | HM_CHANGED_VMX_ENTRY_EXIT_CTLS);
14804 }
14805
14806 /* Update MSRs that are part of the VMCS and auto-load/store area when MSR-bitmaps are not used. */
14807 if (!(pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_USE_MSR_BITMAPS))
14808 {
14809 switch (idMsr)
14810 {
14811 case MSR_IA32_SYSENTER_CS: ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_SYSENTER_CS_MSR); break;
14812 case MSR_IA32_SYSENTER_EIP: ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_SYSENTER_EIP_MSR); break;
14813 case MSR_IA32_SYSENTER_ESP: ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_SYSENTER_ESP_MSR); break;
14814 case MSR_K8_FS_BASE: ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_FS); break;
14815 case MSR_K8_GS_BASE: ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_GS); break;
14816 case MSR_K6_EFER: /* Nothing to do, already handled above. */ break;
14817 default:
14818 {
14819 if (hmR0VmxIsLazyGuestMsr(pVCpu, idMsr))
14820 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_VMX_GUEST_LAZY_MSRS);
14821 else if (hmR0VmxIsAutoLoadGuestMsr(pVmcsInfo, idMsr))
14822 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_VMX_GUEST_AUTO_MSRS);
14823 break;
14824 }
14825 }
14826 }
14827#ifdef VBOX_STRICT
14828 else
14829 {
14830 /* Paranoia. Validate that MSRs in the MSR-bitmaps with write-passthru are not intercepted. */
14831 switch (idMsr)
14832 {
14833 case MSR_IA32_SYSENTER_CS:
14834 case MSR_IA32_SYSENTER_EIP:
14835 case MSR_IA32_SYSENTER_ESP:
14836 case MSR_K8_FS_BASE:
14837 case MSR_K8_GS_BASE:
14838 {
14839 AssertMsgFailed(("Unexpected WRMSR for an MSR in the VMCS. ecx=%#RX32\n", idMsr));
14840 HMVMX_UNEXPECTED_EXIT_RET(pVCpu, idMsr);
14841 }
14842
14843 /* Writes to MSRs in auto-load/store area/swapped MSRs, shouldn't cause VM-exits with MSR-bitmaps. */
14844 default:
14845 {
14846 if (hmR0VmxIsAutoLoadGuestMsr(pVmcsInfo, idMsr))
14847 {
14848 /* EFER MSR writes are always intercepted. */
14849 if (idMsr != MSR_K6_EFER)
14850 {
14851 AssertMsgFailed(("Unexpected WRMSR for an MSR in the auto-load/store area in the VMCS. ecx=%#RX32\n",
14852 idMsr));
14853 HMVMX_UNEXPECTED_EXIT_RET(pVCpu, idMsr);
14854 }
14855 }
14856
14857 if (hmR0VmxIsLazyGuestMsr(pVCpu, idMsr))
14858 {
14859 Assert(pVmcsInfo->pvMsrBitmap);
14860 uint32_t fMsrpm = CPUMGetVmxMsrPermission(pVmcsInfo->pvMsrBitmap, idMsr);
14861 if (fMsrpm & VMXMSRPM_ALLOW_WR)
14862 {
14863 AssertMsgFailed(("Unexpected WRMSR for passthru, lazy-restore MSR. ecx=%#RX32\n", idMsr));
14864 HMVMX_UNEXPECTED_EXIT_RET(pVCpu, idMsr);
14865 }
14866 }
14867 break;
14868 }
14869 }
14870 }
14871#endif /* VBOX_STRICT */
14872 }
14873 else if (rcStrict == VINF_IEM_RAISED_XCPT)
14874 {
14875 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
14876 rcStrict = VINF_SUCCESS;
14877 }
14878 else
14879 AssertMsg(rcStrict == VINF_CPUM_R3_MSR_WRITE, ("Unexpected IEMExecDecodedWrmsr rc (%Rrc)\n", VBOXSTRICTRC_VAL(rcStrict)));
14880
14881 return rcStrict;
14882}
14883
14884
14885/**
14886 * VM-exit handler for PAUSE (VMX_EXIT_PAUSE). Conditional VM-exit.
14887 */
14888HMVMX_EXIT_DECL hmR0VmxExitPause(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14889{
14890 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14891
14892 /** @todo The guest has likely hit a contended spinlock. We might want to
14893 * poke a schedule different guest VCPU. */
14894 int rc = hmR0VmxAdvanceGuestRip(pVCpu, pVmxTransient);
14895 if (RT_SUCCESS(rc))
14896 return VINF_EM_RAW_INTERRUPT;
14897
14898 AssertMsgFailed(("hmR0VmxExitPause: Failed to increment RIP. rc=%Rrc\n", rc));
14899 return rc;
14900}
14901
14902
14903/**
14904 * VM-exit handler for when the TPR value is lowered below the specified
14905 * threshold (VMX_EXIT_TPR_BELOW_THRESHOLD). Conditional VM-exit.
14906 */
14907HMVMX_EXIT_NSRC_DECL hmR0VmxExitTprBelowThreshold(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14908{
14909 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14910 Assert(pVmxTransient->pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_USE_TPR_SHADOW);
14911
14912 /*
14913 * The TPR shadow would've been synced with the APIC TPR in the post-run phase.
14914 * We'll re-evaluate pending interrupts and inject them before the next VM
14915 * entry so we can just continue execution here.
14916 */
14917 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitTprBelowThreshold);
14918 return VINF_SUCCESS;
14919}
14920
14921
14922/**
14923 * VM-exit handler for control-register accesses (VMX_EXIT_MOV_CRX). Conditional
14924 * VM-exit.
14925 *
14926 * @retval VINF_SUCCESS when guest execution can continue.
14927 * @retval VINF_PGM_SYNC_CR3 CR3 sync is required, back to ring-3.
14928 * @retval VERR_EM_RESCHEDULE_REM when we need to return to ring-3 due to
14929 * incompatible guest state for VMX execution (real-on-v86 case).
14930 */
14931HMVMX_EXIT_DECL hmR0VmxExitMovCRx(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14932{
14933 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14934 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatExitMovCRx, y2);
14935
14936 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
14937 hmR0VmxReadExitQualVmcs(pVmxTransient);
14938 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
14939
14940 VBOXSTRICTRC rcStrict;
14941 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
14942 uint64_t const uExitQual = pVmxTransient->uExitQual;
14943 uint32_t const uAccessType = VMX_EXIT_QUAL_CRX_ACCESS(uExitQual);
14944 switch (uAccessType)
14945 {
14946 /*
14947 * MOV to CRx.
14948 */
14949 case VMX_EXIT_QUAL_CRX_ACCESS_WRITE:
14950 {
14951 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, IEM_CPUMCTX_EXTRN_MUST_MASK);
14952 AssertRCReturn(rc, rc);
14953
14954 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_CR0);
14955 uint32_t const uOldCr0 = pVCpu->cpum.GstCtx.cr0;
14956 uint8_t const iGReg = VMX_EXIT_QUAL_CRX_GENREG(uExitQual);
14957 uint8_t const iCrReg = VMX_EXIT_QUAL_CRX_REGISTER(uExitQual);
14958
14959 /*
14960 * MOV to CR3 only cause a VM-exit when one or more of the following are true:
14961 * - When nested paging isn't used.
14962 * - If the guest doesn't have paging enabled (intercept CR3 to update shadow page tables).
14963 * - We are executing in the VM debug loop.
14964 */
14965 Assert( iCrReg != 3
14966 || !pVM->hm.s.fNestedPaging
14967 || !CPUMIsGuestPagingEnabledEx(&pVCpu->cpum.GstCtx)
14968 || pVCpu->hm.s.fUsingDebugLoop);
14969
14970 /* MOV to CR8 writes only cause VM-exits when TPR shadow is not used. */
14971 Assert( iCrReg != 8
14972 || !(pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_USE_TPR_SHADOW));
14973
14974 rcStrict = hmR0VmxExitMovToCrX(pVCpu, pVmcsInfo, pVmxTransient->cbExitInstr, iGReg, iCrReg);
14975 AssertMsg( rcStrict == VINF_SUCCESS
14976 || rcStrict == VINF_PGM_SYNC_CR3, ("%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
14977
14978 /*
14979 * This is a kludge for handling switches back to real mode when we try to use
14980 * V86 mode to run real mode code directly. Problem is that V86 mode cannot
14981 * deal with special selector values, so we have to return to ring-3 and run
14982 * there till the selector values are V86 mode compatible.
14983 *
14984 * Note! Using VINF_EM_RESCHEDULE_REM here rather than VINF_EM_RESCHEDULE since the
14985 * latter is an alias for VINF_IEM_RAISED_XCPT which is asserted at the end of
14986 * this function.
14987 */
14988 if ( iCrReg == 0
14989 && rcStrict == VINF_SUCCESS
14990 && !pVM->hm.s.vmx.fUnrestrictedGuest
14991 && CPUMIsGuestInRealModeEx(&pVCpu->cpum.GstCtx)
14992 && (uOldCr0 & X86_CR0_PE)
14993 && !(pVCpu->cpum.GstCtx.cr0 & X86_CR0_PE))
14994 {
14995 /** @todo Check selectors rather than returning all the time. */
14996 Assert(!pVmxTransient->fIsNestedGuest);
14997 Log4Func(("CR0 write, back to real mode -> VINF_EM_RESCHEDULE_REM\n"));
14998 rcStrict = VINF_EM_RESCHEDULE_REM;
14999 }
15000 break;
15001 }
15002
15003 /*
15004 * MOV from CRx.
15005 */
15006 case VMX_EXIT_QUAL_CRX_ACCESS_READ:
15007 {
15008 uint8_t const iGReg = VMX_EXIT_QUAL_CRX_GENREG(uExitQual);
15009 uint8_t const iCrReg = VMX_EXIT_QUAL_CRX_REGISTER(uExitQual);
15010
15011 /*
15012 * MOV from CR3 only cause a VM-exit when one or more of the following are true:
15013 * - When nested paging isn't used.
15014 * - If the guest doesn't have paging enabled (pass guest's CR3 rather than our identity mapped CR3).
15015 * - We are executing in the VM debug loop.
15016 */
15017 Assert( iCrReg != 3
15018 || !pVM->hm.s.fNestedPaging
15019 || !CPUMIsGuestPagingEnabledEx(&pVCpu->cpum.GstCtx)
15020 || pVCpu->hm.s.fUsingDebugLoop);
15021
15022 /* MOV from CR8 reads only cause a VM-exit when the TPR shadow feature isn't enabled. */
15023 Assert( iCrReg != 8
15024 || !(pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_USE_TPR_SHADOW));
15025
15026 rcStrict = hmR0VmxExitMovFromCrX(pVCpu, pVmcsInfo, pVmxTransient->cbExitInstr, iGReg, iCrReg);
15027 break;
15028 }
15029
15030 /*
15031 * CLTS (Clear Task-Switch Flag in CR0).
15032 */
15033 case VMX_EXIT_QUAL_CRX_ACCESS_CLTS:
15034 {
15035 rcStrict = hmR0VmxExitClts(pVCpu, pVmcsInfo, pVmxTransient->cbExitInstr);
15036 break;
15037 }
15038
15039 /*
15040 * LMSW (Load Machine-Status Word into CR0).
15041 * LMSW cannot clear CR0.PE, so no fRealOnV86Active kludge needed here.
15042 */
15043 case VMX_EXIT_QUAL_CRX_ACCESS_LMSW:
15044 {
15045 RTGCPTR GCPtrEffDst;
15046 uint8_t const cbInstr = pVmxTransient->cbExitInstr;
15047 uint16_t const uMsw = VMX_EXIT_QUAL_CRX_LMSW_DATA(uExitQual);
15048 bool const fMemOperand = VMX_EXIT_QUAL_CRX_LMSW_OP_MEM(uExitQual);
15049 if (fMemOperand)
15050 {
15051 hmR0VmxReadGuestLinearAddrVmcs(pVmxTransient);
15052 GCPtrEffDst = pVmxTransient->uGuestLinearAddr;
15053 }
15054 else
15055 GCPtrEffDst = NIL_RTGCPTR;
15056 rcStrict = hmR0VmxExitLmsw(pVCpu, pVmcsInfo, cbInstr, uMsw, GCPtrEffDst);
15057 break;
15058 }
15059
15060 default:
15061 {
15062 AssertMsgFailed(("Unrecognized Mov CRX access type %#x\n", uAccessType));
15063 HMVMX_UNEXPECTED_EXIT_RET(pVCpu, uAccessType);
15064 }
15065 }
15066
15067 Assert((pVCpu->hm.s.fCtxChanged & (HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS))
15068 == (HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS));
15069 Assert(rcStrict != VINF_IEM_RAISED_XCPT);
15070
15071 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExitMovCRx, y2);
15072 NOREF(pVM);
15073 return rcStrict;
15074}
15075
15076
15077/**
15078 * VM-exit handler for I/O instructions (VMX_EXIT_IO_INSTR). Conditional
15079 * VM-exit.
15080 */
15081HMVMX_EXIT_DECL hmR0VmxExitIoInstr(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
15082{
15083 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
15084 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatExitIO, y1);
15085
15086 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
15087 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
15088 hmR0VmxReadExitQualVmcs(pVmxTransient);
15089 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
15090 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, IEM_CPUMCTX_EXTRN_MUST_MASK | CPUMCTX_EXTRN_SREG_MASK
15091 | CPUMCTX_EXTRN_EFER);
15092 /* EFER MSR also required for longmode checks in EMInterpretDisasCurrent(), but it's always up-to-date. */
15093 AssertRCReturn(rc, rc);
15094
15095 /* Refer Intel spec. 27-5. "Exit Qualifications for I/O Instructions" for the format. */
15096 uint32_t const uIOPort = VMX_EXIT_QUAL_IO_PORT(pVmxTransient->uExitQual);
15097 uint8_t const uIOSize = VMX_EXIT_QUAL_IO_SIZE(pVmxTransient->uExitQual);
15098 bool const fIOWrite = (VMX_EXIT_QUAL_IO_DIRECTION(pVmxTransient->uExitQual) == VMX_EXIT_QUAL_IO_DIRECTION_OUT);
15099 bool const fIOString = VMX_EXIT_QUAL_IO_IS_STRING(pVmxTransient->uExitQual);
15100 bool const fGstStepping = RT_BOOL(pCtx->eflags.Bits.u1TF);
15101 bool const fDbgStepping = pVCpu->hm.s.fSingleInstruction;
15102 AssertReturn(uIOSize <= 3 && uIOSize != 2, VERR_VMX_IPE_1);
15103
15104 /*
15105 * Update exit history to see if this exit can be optimized.
15106 */
15107 VBOXSTRICTRC rcStrict;
15108 PCEMEXITREC pExitRec = NULL;
15109 if ( !fGstStepping
15110 && !fDbgStepping)
15111 pExitRec = EMHistoryUpdateFlagsAndTypeAndPC(pVCpu,
15112 !fIOString
15113 ? !fIOWrite
15114 ? EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM | EMEXIT_F_HM, EMEXITTYPE_IO_PORT_READ)
15115 : EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM | EMEXIT_F_HM, EMEXITTYPE_IO_PORT_WRITE)
15116 : !fIOWrite
15117 ? EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM | EMEXIT_F_HM, EMEXITTYPE_IO_PORT_STR_READ)
15118 : EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM | EMEXIT_F_HM, EMEXITTYPE_IO_PORT_STR_WRITE),
15119 pVCpu->cpum.GstCtx.rip + pVCpu->cpum.GstCtx.cs.u64Base);
15120 if (!pExitRec)
15121 {
15122 static uint32_t const s_aIOSizes[4] = { 1, 2, 0, 4 }; /* Size of the I/O accesses in bytes. */
15123 static uint32_t const s_aIOOpAnd[4] = { 0xff, 0xffff, 0, 0xffffffff }; /* AND masks for saving result in AL/AX/EAX. */
15124
15125 uint32_t const cbValue = s_aIOSizes[uIOSize];
15126 uint32_t const cbInstr = pVmxTransient->cbExitInstr;
15127 bool fUpdateRipAlready = false; /* ugly hack, should be temporary. */
15128 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
15129 if (fIOString)
15130 {
15131 /*
15132 * INS/OUTS - I/O String instruction.
15133 *
15134 * Use instruction-information if available, otherwise fall back on
15135 * interpreting the instruction.
15136 */
15137 Log4Func(("cs:rip=%#04x:%#RX64 %#06x/%u %c str\n", pCtx->cs.Sel, pCtx->rip, uIOPort, cbValue, fIOWrite ? 'w' : 'r'));
15138 AssertReturn(pCtx->dx == uIOPort, VERR_VMX_IPE_2);
15139 bool const fInsOutsInfo = RT_BF_GET(pVM->hm.s.vmx.Msrs.u64Basic, VMX_BF_BASIC_VMCS_INS_OUTS);
15140 if (fInsOutsInfo)
15141 {
15142 hmR0VmxReadExitInstrInfoVmcs(pVmxTransient);
15143 AssertReturn(pVmxTransient->ExitInstrInfo.StrIo.u3AddrSize <= 2, VERR_VMX_IPE_3);
15144 AssertCompile(IEMMODE_16BIT == 0 && IEMMODE_32BIT == 1 && IEMMODE_64BIT == 2);
15145 IEMMODE const enmAddrMode = (IEMMODE)pVmxTransient->ExitInstrInfo.StrIo.u3AddrSize;
15146 bool const fRep = VMX_EXIT_QUAL_IO_IS_REP(pVmxTransient->uExitQual);
15147 if (fIOWrite)
15148 rcStrict = IEMExecStringIoWrite(pVCpu, cbValue, enmAddrMode, fRep, cbInstr,
15149 pVmxTransient->ExitInstrInfo.StrIo.iSegReg, true /*fIoChecked*/);
15150 else
15151 {
15152 /*
15153 * The segment prefix for INS cannot be overridden and is always ES. We can safely assume X86_SREG_ES.
15154 * Hence "iSegReg" field is undefined in the instruction-information field in VT-x for INS.
15155 * See Intel Instruction spec. for "INS".
15156 * See Intel spec. Table 27-8 "Format of the VM-Exit Instruction-Information Field as Used for INS and OUTS".
15157 */
15158 rcStrict = IEMExecStringIoRead(pVCpu, cbValue, enmAddrMode, fRep, cbInstr, true /*fIoChecked*/);
15159 }
15160 }
15161 else
15162 rcStrict = IEMExecOne(pVCpu);
15163
15164 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP);
15165 fUpdateRipAlready = true;
15166 }
15167 else
15168 {
15169 /*
15170 * IN/OUT - I/O instruction.
15171 */
15172 Log4Func(("cs:rip=%04x:%08RX64 %#06x/%u %c\n", pCtx->cs.Sel, pCtx->rip, uIOPort, cbValue, fIOWrite ? 'w' : 'r'));
15173 uint32_t const uAndVal = s_aIOOpAnd[uIOSize];
15174 Assert(!VMX_EXIT_QUAL_IO_IS_REP(pVmxTransient->uExitQual));
15175 if (fIOWrite)
15176 {
15177 rcStrict = IOMIOPortWrite(pVM, pVCpu, uIOPort, pCtx->eax & uAndVal, cbValue);
15178 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIOWrite);
15179 if ( rcStrict == VINF_IOM_R3_IOPORT_WRITE
15180 && !pCtx->eflags.Bits.u1TF)
15181 rcStrict = EMRZSetPendingIoPortWrite(pVCpu, uIOPort, cbInstr, cbValue, pCtx->eax & uAndVal);
15182 }
15183 else
15184 {
15185 uint32_t u32Result = 0;
15186 rcStrict = IOMIOPortRead(pVM, pVCpu, uIOPort, &u32Result, cbValue);
15187 if (IOM_SUCCESS(rcStrict))
15188 {
15189 /* Save result of I/O IN instr. in AL/AX/EAX. */
15190 pCtx->eax = (pCtx->eax & ~uAndVal) | (u32Result & uAndVal);
15191 }
15192 if ( rcStrict == VINF_IOM_R3_IOPORT_READ
15193 && !pCtx->eflags.Bits.u1TF)
15194 rcStrict = EMRZSetPendingIoPortRead(pVCpu, uIOPort, cbInstr, cbValue);
15195 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIORead);
15196 }
15197 }
15198
15199 if (IOM_SUCCESS(rcStrict))
15200 {
15201 if (!fUpdateRipAlready)
15202 {
15203 hmR0VmxAdvanceGuestRipBy(pVCpu, cbInstr);
15204 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP);
15205 }
15206
15207 /*
15208 * INS/OUTS with REP prefix updates RFLAGS, can be observed with triple-fault guru
15209 * while booting Fedora 17 64-bit guest.
15210 *
15211 * See Intel Instruction reference for REP/REPE/REPZ/REPNE/REPNZ.
15212 */
15213 if (fIOString)
15214 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RFLAGS);
15215
15216 /*
15217 * If any I/O breakpoints are armed, we need to check if one triggered
15218 * and take appropriate action.
15219 * Note that the I/O breakpoint type is undefined if CR4.DE is 0.
15220 */
15221 rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, CPUMCTX_EXTRN_DR7);
15222 AssertRCReturn(rc, rc);
15223
15224 /** @todo Optimize away the DBGFBpIsHwIoArmed call by having DBGF tell the
15225 * execution engines about whether hyper BPs and such are pending. */
15226 uint32_t const uDr7 = pCtx->dr[7];
15227 if (RT_UNLIKELY( ( (uDr7 & X86_DR7_ENABLED_MASK)
15228 && X86_DR7_ANY_RW_IO(uDr7)
15229 && (pCtx->cr4 & X86_CR4_DE))
15230 || DBGFBpIsHwIoArmed(pVM)))
15231 {
15232 STAM_COUNTER_INC(&pVCpu->hm.s.StatDRxIoCheck);
15233
15234 /* We're playing with the host CPU state here, make sure we don't preempt or longjmp. */
15235 VMMRZCallRing3Disable(pVCpu);
15236 HM_DISABLE_PREEMPT(pVCpu);
15237
15238 bool fIsGuestDbgActive = CPUMR0DebugStateMaybeSaveGuest(pVCpu, true /* fDr6 */);
15239
15240 VBOXSTRICTRC rcStrict2 = DBGFBpCheckIo(pVM, pVCpu, pCtx, uIOPort, cbValue);
15241 if (rcStrict2 == VINF_EM_RAW_GUEST_TRAP)
15242 {
15243 /* Raise #DB. */
15244 if (fIsGuestDbgActive)
15245 ASMSetDR6(pCtx->dr[6]);
15246 if (pCtx->dr[7] != uDr7)
15247 pVCpu->hm.s.fCtxChanged |= HM_CHANGED_GUEST_DR7;
15248
15249 hmR0VmxSetPendingXcptDB(pVCpu);
15250 }
15251 /* rcStrict is VINF_SUCCESS, VINF_IOM_R3_IOPORT_COMMIT_WRITE, or in [VINF_EM_FIRST..VINF_EM_LAST],
15252 however we can ditch VINF_IOM_R3_IOPORT_COMMIT_WRITE as it has VMCPU_FF_IOM as backup. */
15253 else if ( rcStrict2 != VINF_SUCCESS
15254 && (rcStrict == VINF_SUCCESS || rcStrict2 < rcStrict))
15255 rcStrict = rcStrict2;
15256 AssertCompile(VINF_EM_LAST < VINF_IOM_R3_IOPORT_COMMIT_WRITE);
15257
15258 HM_RESTORE_PREEMPT();
15259 VMMRZCallRing3Enable(pVCpu);
15260 }
15261 }
15262
15263#ifdef VBOX_STRICT
15264 if ( rcStrict == VINF_IOM_R3_IOPORT_READ
15265 || rcStrict == VINF_EM_PENDING_R3_IOPORT_READ)
15266 Assert(!fIOWrite);
15267 else if ( rcStrict == VINF_IOM_R3_IOPORT_WRITE
15268 || rcStrict == VINF_IOM_R3_IOPORT_COMMIT_WRITE
15269 || rcStrict == VINF_EM_PENDING_R3_IOPORT_WRITE)
15270 Assert(fIOWrite);
15271 else
15272 {
15273# if 0 /** @todo r=bird: This is missing a bunch of VINF_EM_FIRST..VINF_EM_LAST
15274 * statuses, that the VMM device and some others may return. See
15275 * IOM_SUCCESS() for guidance. */
15276 AssertMsg( RT_FAILURE(rcStrict)
15277 || rcStrict == VINF_SUCCESS
15278 || rcStrict == VINF_EM_RAW_EMULATE_INSTR
15279 || rcStrict == VINF_EM_DBG_BREAKPOINT
15280 || rcStrict == VINF_EM_RAW_GUEST_TRAP
15281 || rcStrict == VINF_EM_RAW_TO_R3
15282 || rcStrict == VINF_TRPM_XCPT_DISPATCHED, ("%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
15283# endif
15284 }
15285#endif
15286 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExitIO, y1);
15287 }
15288 else
15289 {
15290 /*
15291 * Frequent exit or something needing probing. Get state and call EMHistoryExec.
15292 */
15293 int rc2 = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, HMVMX_CPUMCTX_EXTRN_ALL);
15294 AssertRCReturn(rc2, rc2);
15295 STAM_COUNTER_INC(!fIOString ? fIOWrite ? &pVCpu->hm.s.StatExitIOWrite : &pVCpu->hm.s.StatExitIORead
15296 : fIOWrite ? &pVCpu->hm.s.StatExitIOStringWrite : &pVCpu->hm.s.StatExitIOStringRead);
15297 Log4(("IOExit/%u: %04x:%08RX64: %s%s%s %#x LB %u -> EMHistoryExec\n",
15298 pVCpu->idCpu, pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip,
15299 VMX_EXIT_QUAL_IO_IS_REP(pVmxTransient->uExitQual) ? "REP " : "",
15300 fIOWrite ? "OUT" : "IN", fIOString ? "S" : "", uIOPort, uIOSize));
15301
15302 rcStrict = EMHistoryExec(pVCpu, pExitRec, 0);
15303 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_ALL_GUEST);
15304
15305 Log4(("IOExit/%u: %04x:%08RX64: EMHistoryExec -> %Rrc + %04x:%08RX64\n",
15306 pVCpu->idCpu, pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip,
15307 VBOXSTRICTRC_VAL(rcStrict), pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip));
15308 }
15309 return rcStrict;
15310}
15311
15312
15313/**
15314 * VM-exit handler for task switches (VMX_EXIT_TASK_SWITCH). Unconditional
15315 * VM-exit.
15316 */
15317HMVMX_EXIT_DECL hmR0VmxExitTaskSwitch(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
15318{
15319 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
15320
15321 /* Check if this task-switch occurred while delivery an event through the guest IDT. */
15322 hmR0VmxReadExitQualVmcs(pVmxTransient);
15323 if (VMX_EXIT_QUAL_TASK_SWITCH_TYPE(pVmxTransient->uExitQual) == VMX_EXIT_QUAL_TASK_SWITCH_TYPE_IDT)
15324 {
15325 hmR0VmxReadIdtVectoringInfoVmcs(pVmxTransient);
15326 if (VMX_IDT_VECTORING_INFO_IS_VALID(pVmxTransient->uIdtVectoringInfo))
15327 {
15328 uint32_t uErrCode;
15329 if (VMX_IDT_VECTORING_INFO_IS_ERROR_CODE_VALID(pVmxTransient->uIdtVectoringInfo))
15330 {
15331 hmR0VmxReadIdtVectoringErrorCodeVmcs(pVmxTransient);
15332 uErrCode = pVmxTransient->uIdtVectoringErrorCode;
15333 }
15334 else
15335 uErrCode = 0;
15336
15337 RTGCUINTPTR GCPtrFaultAddress;
15338 if (VMX_IDT_VECTORING_INFO_IS_XCPT_PF(pVmxTransient->uIdtVectoringInfo))
15339 GCPtrFaultAddress = pVCpu->cpum.GstCtx.cr2;
15340 else
15341 GCPtrFaultAddress = 0;
15342
15343 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
15344
15345 hmR0VmxSetPendingEvent(pVCpu, VMX_ENTRY_INT_INFO_FROM_EXIT_IDT_INFO(pVmxTransient->uIdtVectoringInfo),
15346 pVmxTransient->cbExitInstr, uErrCode, GCPtrFaultAddress);
15347
15348 Log4Func(("Pending event. uIntType=%#x uVector=%#x\n", VMX_IDT_VECTORING_INFO_TYPE(pVmxTransient->uIdtVectoringInfo),
15349 VMX_IDT_VECTORING_INFO_VECTOR(pVmxTransient->uIdtVectoringInfo)));
15350 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitTaskSwitch);
15351 return VINF_EM_RAW_INJECT_TRPM_EVENT;
15352 }
15353 }
15354
15355 /* Fall back to the interpreter to emulate the task-switch. */
15356 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitTaskSwitch);
15357 return VERR_EM_INTERPRETER;
15358}
15359
15360
15361/**
15362 * VM-exit handler for monitor-trap-flag (VMX_EXIT_MTF). Conditional VM-exit.
15363 */
15364HMVMX_EXIT_DECL hmR0VmxExitMtf(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
15365{
15366 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
15367
15368 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
15369 pVmcsInfo->u32ProcCtls &= ~VMX_PROC_CTLS_MONITOR_TRAP_FLAG;
15370 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, pVmcsInfo->u32ProcCtls);
15371 AssertRC(rc);
15372 return VINF_EM_DBG_STEPPED;
15373}
15374
15375
15376/**
15377 * VM-exit handler for APIC access (VMX_EXIT_APIC_ACCESS). Conditional VM-exit.
15378 */
15379HMVMX_EXIT_DECL hmR0VmxExitApicAccess(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
15380{
15381 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
15382 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitApicAccess);
15383
15384 hmR0VmxReadExitIntInfoVmcs(pVmxTransient);
15385 hmR0VmxReadExitIntErrorCodeVmcs(pVmxTransient);
15386 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
15387 hmR0VmxReadIdtVectoringInfoVmcs(pVmxTransient);
15388 hmR0VmxReadIdtVectoringErrorCodeVmcs(pVmxTransient);
15389
15390 /*
15391 * If this VM-exit occurred while delivering an event through the guest IDT, handle it accordingly.
15392 */
15393 VBOXSTRICTRC rcStrict = hmR0VmxCheckExitDueToEventDelivery(pVCpu, pVmxTransient);
15394 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
15395 {
15396 /* For some crazy guest, if an event delivery causes an APIC-access VM-exit, go to instruction emulation. */
15397 if (RT_UNLIKELY(pVCpu->hm.s.Event.fPending))
15398 {
15399 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectInterpret);
15400 return VINF_EM_RAW_INJECT_TRPM_EVENT;
15401 }
15402 }
15403 else
15404 {
15405 Assert(rcStrict != VINF_HM_DOUBLE_FAULT);
15406 return rcStrict;
15407 }
15408
15409 /* IOMMIOPhysHandler() below may call into IEM, save the necessary state. */
15410 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
15411 hmR0VmxReadExitQualVmcs(pVmxTransient);
15412 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, IEM_CPUMCTX_EXTRN_MUST_MASK);
15413 AssertRCReturn(rc, rc);
15414
15415 /* See Intel spec. 27-6 "Exit Qualifications for APIC-access VM-exits from Linear Accesses & Guest-Phyiscal Addresses" */
15416 uint32_t const uAccessType = VMX_EXIT_QUAL_APIC_ACCESS_TYPE(pVmxTransient->uExitQual);
15417 switch (uAccessType)
15418 {
15419 case VMX_APIC_ACCESS_TYPE_LINEAR_WRITE:
15420 case VMX_APIC_ACCESS_TYPE_LINEAR_READ:
15421 {
15422 AssertMsg( !(pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_USE_TPR_SHADOW)
15423 || VMX_EXIT_QUAL_APIC_ACCESS_OFFSET(pVmxTransient->uExitQual) != XAPIC_OFF_TPR,
15424 ("hmR0VmxExitApicAccess: can't access TPR offset while using TPR shadowing.\n"));
15425
15426 RTGCPHYS GCPhys = pVCpu->hm.s.vmx.u64GstMsrApicBase; /* Always up-to-date, as it is not part of the VMCS. */
15427 GCPhys &= PAGE_BASE_GC_MASK;
15428 GCPhys += VMX_EXIT_QUAL_APIC_ACCESS_OFFSET(pVmxTransient->uExitQual);
15429 Log4Func(("Linear access uAccessType=%#x GCPhys=%#RGp Off=%#x\n", uAccessType, GCPhys,
15430 VMX_EXIT_QUAL_APIC_ACCESS_OFFSET(pVmxTransient->uExitQual)));
15431
15432 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
15433 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
15434 rcStrict = IOMMMIOPhysHandler(pVM, pVCpu,
15435 uAccessType == VMX_APIC_ACCESS_TYPE_LINEAR_READ ? 0 : X86_TRAP_PF_RW,
15436 CPUMCTX2CORE(pCtx), GCPhys);
15437 Log4Func(("IOMMMIOPhysHandler returned %Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
15438 if ( rcStrict == VINF_SUCCESS
15439 || rcStrict == VERR_PAGE_TABLE_NOT_PRESENT
15440 || rcStrict == VERR_PAGE_NOT_PRESENT)
15441 {
15442 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RSP | HM_CHANGED_GUEST_RFLAGS
15443 | HM_CHANGED_GUEST_APIC_TPR);
15444 rcStrict = VINF_SUCCESS;
15445 }
15446 break;
15447 }
15448
15449 default:
15450 {
15451 Log4Func(("uAccessType=%#x\n", uAccessType));
15452 rcStrict = VINF_EM_RAW_EMULATE_INSTR;
15453 break;
15454 }
15455 }
15456
15457 if (rcStrict != VINF_SUCCESS)
15458 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchApicAccessToR3);
15459 return rcStrict;
15460}
15461
15462
15463/**
15464 * VM-exit handler for debug-register accesses (VMX_EXIT_MOV_DRX). Conditional
15465 * VM-exit.
15466 */
15467HMVMX_EXIT_DECL hmR0VmxExitMovDRx(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
15468{
15469 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
15470 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
15471
15472 /* We might get this VM-exit if the nested-guest is not intercepting MOV DRx accesses. */
15473 if (!pVmxTransient->fIsNestedGuest)
15474 {
15475 /* We should -not- get this VM-exit if the guest's debug registers were active. */
15476 if (pVmxTransient->fWasGuestDebugStateActive)
15477 {
15478 AssertMsgFailed(("Unexpected MOV DRx exit\n"));
15479 HMVMX_UNEXPECTED_EXIT_RET(pVCpu, pVmxTransient->uExitReason);
15480 }
15481
15482 if ( !pVCpu->hm.s.fSingleInstruction
15483 && !pVmxTransient->fWasHyperDebugStateActive)
15484 {
15485 Assert(!DBGFIsStepping(pVCpu));
15486 Assert(pVmcsInfo->u32XcptBitmap & RT_BIT(X86_XCPT_DB));
15487
15488 /* Don't intercept MOV DRx any more. */
15489 pVmcsInfo->u32ProcCtls &= ~VMX_PROC_CTLS_MOV_DR_EXIT;
15490 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, pVmcsInfo->u32ProcCtls);
15491 AssertRC(rc);
15492
15493 /* We're playing with the host CPU state here, make sure we can't preempt or longjmp. */
15494 VMMRZCallRing3Disable(pVCpu);
15495 HM_DISABLE_PREEMPT(pVCpu);
15496
15497 /* Save the host & load the guest debug state, restart execution of the MOV DRx instruction. */
15498 CPUMR0LoadGuestDebugState(pVCpu, true /* include DR6 */);
15499 Assert(CPUMIsGuestDebugStateActive(pVCpu));
15500
15501 HM_RESTORE_PREEMPT();
15502 VMMRZCallRing3Enable(pVCpu);
15503
15504#ifdef VBOX_WITH_STATISTICS
15505 hmR0VmxReadExitQualVmcs(pVmxTransient);
15506 if (VMX_EXIT_QUAL_DRX_DIRECTION(pVmxTransient->uExitQual) == VMX_EXIT_QUAL_DRX_DIRECTION_WRITE)
15507 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitDRxWrite);
15508 else
15509 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitDRxRead);
15510#endif
15511 STAM_COUNTER_INC(&pVCpu->hm.s.StatDRxContextSwitch);
15512 return VINF_SUCCESS;
15513 }
15514 }
15515
15516 /*
15517 * EMInterpretDRx[Write|Read]() calls CPUMIsGuestIn64BitCode() which requires EFER MSR, CS.
15518 * The EFER MSR is always up-to-date.
15519 * Update the segment registers and DR7 from the CPU.
15520 */
15521 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
15522 hmR0VmxReadExitQualVmcs(pVmxTransient);
15523 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, CPUMCTX_EXTRN_SREG_MASK | CPUMCTX_EXTRN_DR7);
15524 AssertRCReturn(rc, rc);
15525 Log4Func(("cs:rip=%#04x:%#RX64\n", pCtx->cs.Sel, pCtx->rip));
15526
15527 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
15528 if (VMX_EXIT_QUAL_DRX_DIRECTION(pVmxTransient->uExitQual) == VMX_EXIT_QUAL_DRX_DIRECTION_WRITE)
15529 {
15530 rc = EMInterpretDRxWrite(pVM, pVCpu, CPUMCTX2CORE(pCtx),
15531 VMX_EXIT_QUAL_DRX_REGISTER(pVmxTransient->uExitQual),
15532 VMX_EXIT_QUAL_DRX_GENREG(pVmxTransient->uExitQual));
15533 if (RT_SUCCESS(rc))
15534 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_DR7);
15535 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitDRxWrite);
15536 }
15537 else
15538 {
15539 rc = EMInterpretDRxRead(pVM, pVCpu, CPUMCTX2CORE(pCtx),
15540 VMX_EXIT_QUAL_DRX_GENREG(pVmxTransient->uExitQual),
15541 VMX_EXIT_QUAL_DRX_REGISTER(pVmxTransient->uExitQual));
15542 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitDRxRead);
15543 }
15544
15545 Assert(rc == VINF_SUCCESS || rc == VERR_EM_INTERPRETER);
15546 if (RT_SUCCESS(rc))
15547 {
15548 int rc2 = hmR0VmxAdvanceGuestRip(pVCpu, pVmxTransient);
15549 AssertRCReturn(rc2, rc2);
15550 return VINF_SUCCESS;
15551 }
15552 return rc;
15553}
15554
15555
15556/**
15557 * VM-exit handler for EPT misconfiguration (VMX_EXIT_EPT_MISCONFIG).
15558 * Conditional VM-exit.
15559 */
15560HMVMX_EXIT_DECL hmR0VmxExitEptMisconfig(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
15561{
15562 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
15563 Assert(pVCpu->CTX_SUFF(pVM)->hm.s.fNestedPaging);
15564
15565 hmR0VmxReadExitIntInfoVmcs(pVmxTransient);
15566 hmR0VmxReadExitIntErrorCodeVmcs(pVmxTransient);
15567 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
15568 hmR0VmxReadIdtVectoringInfoVmcs(pVmxTransient);
15569 hmR0VmxReadIdtVectoringErrorCodeVmcs(pVmxTransient);
15570
15571 /*
15572 * If this VM-exit occurred while delivering an event through the guest IDT, handle it accordingly.
15573 */
15574 VBOXSTRICTRC rcStrict = hmR0VmxCheckExitDueToEventDelivery(pVCpu, pVmxTransient);
15575 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
15576 {
15577 /*
15578 * In the unlikely case where delivering an event causes an EPT misconfig (MMIO), go back to
15579 * instruction emulation to inject the original event. Otherwise, injecting the original event
15580 * using hardware-assisted VMX would would trigger the same EPT misconfig VM-exit again.
15581 */
15582 if (!pVCpu->hm.s.Event.fPending)
15583 { /* likely */ }
15584 else
15585 {
15586 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectInterpret);
15587#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
15588 /** @todo NSTVMX: Think about how this should be handled. */
15589 if (pVmxTransient->fIsNestedGuest)
15590 return VERR_VMX_IPE_3;
15591#endif
15592 return VINF_EM_RAW_INJECT_TRPM_EVENT;
15593 }
15594 }
15595 else
15596 {
15597 Assert(rcStrict != VINF_HM_DOUBLE_FAULT);
15598 return rcStrict;
15599 }
15600
15601 /*
15602 * Get sufficent state and update the exit history entry.
15603 */
15604 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
15605 hmR0VmxReadGuestPhysicalAddrVmcs(pVmxTransient);
15606 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, IEM_CPUMCTX_EXTRN_MUST_MASK);
15607 AssertRCReturn(rc, rc);
15608
15609 RTGCPHYS const GCPhys = pVmxTransient->uGuestPhysicalAddr;
15610 PCEMEXITREC pExitRec = EMHistoryUpdateFlagsAndTypeAndPC(pVCpu,
15611 EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM | EMEXIT_F_HM, EMEXITTYPE_MMIO),
15612 pVCpu->cpum.GstCtx.rip + pVCpu->cpum.GstCtx.cs.u64Base);
15613 if (!pExitRec)
15614 {
15615 /*
15616 * If we succeed, resume guest execution.
15617 * If we fail in interpreting the instruction because we couldn't get the guest physical address
15618 * of the page containing the instruction via the guest's page tables (we would invalidate the guest page
15619 * in the host TLB), resume execution which would cause a guest page fault to let the guest handle this
15620 * weird case. See @bugref{6043}.
15621 */
15622 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
15623 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
15624 rcStrict = PGMR0Trap0eHandlerNPMisconfig(pVM, pVCpu, PGMMODE_EPT, CPUMCTX2CORE(pCtx), GCPhys, UINT32_MAX);
15625 Log4Func(("At %#RGp RIP=%#RX64 rc=%Rrc\n", GCPhys, pCtx->rip, VBOXSTRICTRC_VAL(rcStrict)));
15626 if ( rcStrict == VINF_SUCCESS
15627 || rcStrict == VERR_PAGE_TABLE_NOT_PRESENT
15628 || rcStrict == VERR_PAGE_NOT_PRESENT)
15629 {
15630 /* Successfully handled MMIO operation. */
15631 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RSP | HM_CHANGED_GUEST_RFLAGS
15632 | HM_CHANGED_GUEST_APIC_TPR);
15633 rcStrict = VINF_SUCCESS;
15634 }
15635 }
15636 else
15637 {
15638 /*
15639 * Frequent exit or something needing probing. Call EMHistoryExec.
15640 */
15641 Log4(("EptMisscfgExit/%u: %04x:%08RX64: %RGp -> EMHistoryExec\n",
15642 pVCpu->idCpu, pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip, GCPhys));
15643
15644 rcStrict = EMHistoryExec(pVCpu, pExitRec, 0);
15645 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_ALL_GUEST);
15646
15647 Log4(("EptMisscfgExit/%u: %04x:%08RX64: EMHistoryExec -> %Rrc + %04x:%08RX64\n",
15648 pVCpu->idCpu, pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip,
15649 VBOXSTRICTRC_VAL(rcStrict), pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip));
15650 }
15651 return rcStrict;
15652}
15653
15654
15655/**
15656 * VM-exit handler for EPT violation (VMX_EXIT_EPT_VIOLATION). Conditional
15657 * VM-exit.
15658 */
15659HMVMX_EXIT_DECL hmR0VmxExitEptViolation(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
15660{
15661 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
15662 Assert(pVCpu->CTX_SUFF(pVM)->hm.s.fNestedPaging);
15663
15664 hmR0VmxReadExitQualVmcs(pVmxTransient);
15665 hmR0VmxReadExitIntInfoVmcs(pVmxTransient);
15666 hmR0VmxReadExitIntErrorCodeVmcs(pVmxTransient);
15667 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
15668 hmR0VmxReadIdtVectoringInfoVmcs(pVmxTransient);
15669 hmR0VmxReadIdtVectoringErrorCodeVmcs(pVmxTransient);
15670
15671 /*
15672 * If this VM-exit occurred while delivering an event through the guest IDT, handle it accordingly.
15673 */
15674 VBOXSTRICTRC rcStrict = hmR0VmxCheckExitDueToEventDelivery(pVCpu, pVmxTransient);
15675 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
15676 {
15677 /*
15678 * If delivery of an event causes an EPT violation (true nested #PF and not MMIO),
15679 * we shall resolve the nested #PF and re-inject the original event.
15680 */
15681 if (pVCpu->hm.s.Event.fPending)
15682 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectReflectNPF);
15683 }
15684 else
15685 {
15686 Assert(rcStrict != VINF_HM_DOUBLE_FAULT);
15687 return rcStrict;
15688 }
15689
15690 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
15691 hmR0VmxReadGuestPhysicalAddrVmcs(pVmxTransient);
15692 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, IEM_CPUMCTX_EXTRN_MUST_MASK);
15693 AssertRCReturn(rc, rc);
15694
15695 RTGCPHYS const GCPhys = pVmxTransient->uGuestPhysicalAddr;
15696 uint64_t const uExitQual = pVmxTransient->uExitQual;
15697 AssertMsg(((pVmxTransient->uExitQual >> 7) & 3) != 2, ("%#RX64", uExitQual));
15698
15699 RTGCUINT uErrorCode = 0;
15700 if (uExitQual & VMX_EXIT_QUAL_EPT_INSTR_FETCH)
15701 uErrorCode |= X86_TRAP_PF_ID;
15702 if (uExitQual & VMX_EXIT_QUAL_EPT_DATA_WRITE)
15703 uErrorCode |= X86_TRAP_PF_RW;
15704 if (uExitQual & VMX_EXIT_QUAL_EPT_ENTRY_PRESENT)
15705 uErrorCode |= X86_TRAP_PF_P;
15706
15707 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
15708 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
15709 Log4Func(("at %#RX64 (%#RX64 errcode=%#x) cs:rip=%#04x:%#RX64\n", GCPhys, uExitQual, uErrorCode, pCtx->cs.Sel, pCtx->rip));
15710
15711 /*
15712 * Handle the pagefault trap for the nested shadow table.
15713 */
15714 TRPMAssertXcptPF(pVCpu, GCPhys, uErrorCode);
15715 rcStrict = PGMR0Trap0eHandlerNestedPaging(pVM, pVCpu, PGMMODE_EPT, uErrorCode, CPUMCTX2CORE(pCtx), GCPhys);
15716 TRPMResetTrap(pVCpu);
15717
15718 /* Same case as PGMR0Trap0eHandlerNPMisconfig(). See comment above, @bugref{6043}. */
15719 if ( rcStrict == VINF_SUCCESS
15720 || rcStrict == VERR_PAGE_TABLE_NOT_PRESENT
15721 || rcStrict == VERR_PAGE_NOT_PRESENT)
15722 {
15723 /* Successfully synced our nested page tables. */
15724 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitReasonNpf);
15725 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RSP | HM_CHANGED_GUEST_RFLAGS);
15726 return VINF_SUCCESS;
15727 }
15728
15729 Log4Func(("EPT return to ring-3 rcStrict2=%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
15730 return rcStrict;
15731}
15732
15733
15734#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
15735/**
15736 * VM-exit handler for VMCLEAR (VMX_EXIT_VMCLEAR). Unconditional VM-exit.
15737 */
15738HMVMX_EXIT_DECL hmR0VmxExitVmclear(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
15739{
15740 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
15741
15742 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
15743 hmR0VmxReadExitInstrInfoVmcs(pVmxTransient);
15744 hmR0VmxReadExitQualVmcs(pVmxTransient);
15745 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, CPUMCTX_EXTRN_RSP | CPUMCTX_EXTRN_SREG_MASK
15746 | CPUMCTX_EXTRN_HWVIRT
15747 | IEM_CPUMCTX_EXTRN_EXEC_DECODED_MEM_MASK);
15748 AssertRCReturn(rc, rc);
15749
15750 HMVMX_CHECK_EXIT_DUE_TO_VMX_INSTR(pVCpu, pVmxTransient->uExitReason);
15751
15752 VMXVEXITINFO ExitInfo;
15753 RT_ZERO(ExitInfo);
15754 ExitInfo.uReason = pVmxTransient->uExitReason;
15755 ExitInfo.u64Qual = pVmxTransient->uExitQual;
15756 ExitInfo.InstrInfo.u = pVmxTransient->ExitInstrInfo.u;
15757 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
15758 HMVMX_DECODE_MEM_OPERAND(pVCpu, ExitInfo.InstrInfo.u, ExitInfo.u64Qual, VMXMEMACCESS_READ, &ExitInfo.GCPtrEffAddr);
15759
15760 VBOXSTRICTRC rcStrict = IEMExecDecodedVmclear(pVCpu, &ExitInfo);
15761 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
15762 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS | HM_CHANGED_GUEST_HWVIRT);
15763 else if (rcStrict == VINF_IEM_RAISED_XCPT)
15764 {
15765 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
15766 rcStrict = VINF_SUCCESS;
15767 }
15768 return rcStrict;
15769}
15770
15771
15772/**
15773 * VM-exit handler for VMLAUNCH (VMX_EXIT_VMLAUNCH). Unconditional VM-exit.
15774 */
15775HMVMX_EXIT_DECL hmR0VmxExitVmlaunch(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
15776{
15777 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
15778
15779 /* Import the entire VMCS state for now as we would be switching VMCS on successful VMLAUNCH,
15780 otherwise we could import just IEM_CPUMCTX_EXTRN_VMX_VMENTRY_MASK. */
15781 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
15782 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, HMVMX_CPUMCTX_EXTRN_ALL);
15783 AssertRCReturn(rc, rc);
15784
15785 HMVMX_CHECK_EXIT_DUE_TO_VMX_INSTR(pVCpu, pVmxTransient->uExitReason);
15786
15787 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatExitVmentry, z);
15788 VBOXSTRICTRC rcStrict = IEMExecDecodedVmlaunchVmresume(pVCpu, pVmxTransient->cbExitInstr, VMXINSTRID_VMLAUNCH);
15789 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExitVmentry, z);
15790 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
15791 {
15792 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_ALL_GUEST);
15793 if (CPUMIsGuestInVmxNonRootMode(&pVCpu->cpum.GstCtx))
15794 rcStrict = VINF_VMX_VMLAUNCH_VMRESUME;
15795 }
15796 Assert(rcStrict != VINF_IEM_RAISED_XCPT);
15797 return rcStrict;
15798}
15799
15800
15801/**
15802 * VM-exit handler for VMPTRLD (VMX_EXIT_VMPTRLD). Unconditional VM-exit.
15803 */
15804HMVMX_EXIT_DECL hmR0VmxExitVmptrld(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
15805{
15806 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
15807
15808 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
15809 hmR0VmxReadExitInstrInfoVmcs(pVmxTransient);
15810 hmR0VmxReadExitQualVmcs(pVmxTransient);
15811 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, CPUMCTX_EXTRN_RSP | CPUMCTX_EXTRN_SREG_MASK
15812 | CPUMCTX_EXTRN_HWVIRT
15813 | IEM_CPUMCTX_EXTRN_EXEC_DECODED_MEM_MASK);
15814 AssertRCReturn(rc, rc);
15815
15816 HMVMX_CHECK_EXIT_DUE_TO_VMX_INSTR(pVCpu, pVmxTransient->uExitReason);
15817
15818 VMXVEXITINFO ExitInfo;
15819 RT_ZERO(ExitInfo);
15820 ExitInfo.uReason = pVmxTransient->uExitReason;
15821 ExitInfo.u64Qual = pVmxTransient->uExitQual;
15822 ExitInfo.InstrInfo.u = pVmxTransient->ExitInstrInfo.u;
15823 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
15824 HMVMX_DECODE_MEM_OPERAND(pVCpu, ExitInfo.InstrInfo.u, ExitInfo.u64Qual, VMXMEMACCESS_READ, &ExitInfo.GCPtrEffAddr);
15825
15826 VBOXSTRICTRC rcStrict = IEMExecDecodedVmptrld(pVCpu, &ExitInfo);
15827 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
15828 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS | HM_CHANGED_GUEST_HWVIRT);
15829 else if (rcStrict == VINF_IEM_RAISED_XCPT)
15830 {
15831 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
15832 rcStrict = VINF_SUCCESS;
15833 }
15834 return rcStrict;
15835}
15836
15837
15838/**
15839 * VM-exit handler for VMPTRST (VMX_EXIT_VMPTRST). Unconditional VM-exit.
15840 */
15841HMVMX_EXIT_DECL hmR0VmxExitVmptrst(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
15842{
15843 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
15844
15845 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
15846 hmR0VmxReadExitInstrInfoVmcs(pVmxTransient);
15847 hmR0VmxReadExitQualVmcs(pVmxTransient);
15848 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, CPUMCTX_EXTRN_RSP | CPUMCTX_EXTRN_SREG_MASK
15849 | CPUMCTX_EXTRN_HWVIRT
15850 | IEM_CPUMCTX_EXTRN_EXEC_DECODED_MEM_MASK);
15851 AssertRCReturn(rc, rc);
15852
15853 HMVMX_CHECK_EXIT_DUE_TO_VMX_INSTR(pVCpu, pVmxTransient->uExitReason);
15854
15855 VMXVEXITINFO ExitInfo;
15856 RT_ZERO(ExitInfo);
15857 ExitInfo.uReason = pVmxTransient->uExitReason;
15858 ExitInfo.u64Qual = pVmxTransient->uExitQual;
15859 ExitInfo.InstrInfo.u = pVmxTransient->ExitInstrInfo.u;
15860 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
15861 HMVMX_DECODE_MEM_OPERAND(pVCpu, ExitInfo.InstrInfo.u, ExitInfo.u64Qual, VMXMEMACCESS_WRITE, &ExitInfo.GCPtrEffAddr);
15862
15863 VBOXSTRICTRC rcStrict = IEMExecDecodedVmptrst(pVCpu, &ExitInfo);
15864 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
15865 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS);
15866 else if (rcStrict == VINF_IEM_RAISED_XCPT)
15867 {
15868 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
15869 rcStrict = VINF_SUCCESS;
15870 }
15871 return rcStrict;
15872}
15873
15874
15875/**
15876 * VM-exit handler for VMREAD (VMX_EXIT_VMREAD). Conditional VM-exit.
15877 */
15878HMVMX_EXIT_DECL hmR0VmxExitVmread(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
15879{
15880 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
15881
15882 /*
15883 * Strictly speaking we should not get VMREAD VM-exits for shadow VMCS fields and
15884 * thus might not need to import the shadow VMCS state, it's safer just in case
15885 * code elsewhere dares look at unsynced VMCS fields.
15886 */
15887 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
15888 hmR0VmxReadExitInstrInfoVmcs(pVmxTransient);
15889 hmR0VmxReadExitQualVmcs(pVmxTransient);
15890 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, CPUMCTX_EXTRN_RSP | CPUMCTX_EXTRN_SREG_MASK
15891 | CPUMCTX_EXTRN_HWVIRT
15892 | IEM_CPUMCTX_EXTRN_EXEC_DECODED_MEM_MASK);
15893 AssertRCReturn(rc, rc);
15894
15895 HMVMX_CHECK_EXIT_DUE_TO_VMX_INSTR(pVCpu, pVmxTransient->uExitReason);
15896
15897 VMXVEXITINFO ExitInfo;
15898 RT_ZERO(ExitInfo);
15899 ExitInfo.uReason = pVmxTransient->uExitReason;
15900 ExitInfo.u64Qual = pVmxTransient->uExitQual;
15901 ExitInfo.InstrInfo.u = pVmxTransient->ExitInstrInfo.u;
15902 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
15903 if (!ExitInfo.InstrInfo.VmreadVmwrite.fIsRegOperand)
15904 HMVMX_DECODE_MEM_OPERAND(pVCpu, ExitInfo.InstrInfo.u, ExitInfo.u64Qual, VMXMEMACCESS_WRITE, &ExitInfo.GCPtrEffAddr);
15905
15906 VBOXSTRICTRC rcStrict = IEMExecDecodedVmread(pVCpu, &ExitInfo);
15907 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
15908 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS);
15909 else if (rcStrict == VINF_IEM_RAISED_XCPT)
15910 {
15911 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
15912 rcStrict = VINF_SUCCESS;
15913 }
15914 return rcStrict;
15915}
15916
15917
15918/**
15919 * VM-exit handler for VMRESUME (VMX_EXIT_VMRESUME). Unconditional VM-exit.
15920 */
15921HMVMX_EXIT_DECL hmR0VmxExitVmresume(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
15922{
15923 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
15924
15925 /* Import the entire VMCS state for now as we would be switching VMCS on successful VMRESUME,
15926 otherwise we could import just IEM_CPUMCTX_EXTRN_VMX_VMENTRY_MASK. */
15927 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
15928 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, HMVMX_CPUMCTX_EXTRN_ALL);
15929 AssertRCReturn(rc, rc);
15930
15931 HMVMX_CHECK_EXIT_DUE_TO_VMX_INSTR(pVCpu, pVmxTransient->uExitReason);
15932
15933 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatExitVmentry, z);
15934 VBOXSTRICTRC rcStrict = IEMExecDecodedVmlaunchVmresume(pVCpu, pVmxTransient->cbExitInstr, VMXINSTRID_VMRESUME);
15935 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExitVmentry, z);
15936 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
15937 {
15938 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_ALL_GUEST);
15939 if (CPUMIsGuestInVmxNonRootMode(&pVCpu->cpum.GstCtx))
15940 rcStrict = VINF_VMX_VMLAUNCH_VMRESUME;
15941 }
15942 Assert(rcStrict != VINF_IEM_RAISED_XCPT);
15943 return rcStrict;
15944}
15945
15946
15947/**
15948 * VM-exit handler for VMWRITE (VMX_EXIT_VMWRITE). Conditional VM-exit.
15949 */
15950HMVMX_EXIT_DECL hmR0VmxExitVmwrite(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
15951{
15952 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
15953
15954 /*
15955 * Although we should not get VMWRITE VM-exits for shadow VMCS fields, since our HM hook
15956 * gets invoked when IEM's VMWRITE instruction emulation modifies the current VMCS and it
15957 * flags re-loading the entire shadow VMCS, we should save the entire shadow VMCS here.
15958 */
15959 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
15960 hmR0VmxReadExitInstrInfoVmcs(pVmxTransient);
15961 hmR0VmxReadExitQualVmcs(pVmxTransient);
15962 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, CPUMCTX_EXTRN_RSP | CPUMCTX_EXTRN_SREG_MASK
15963 | CPUMCTX_EXTRN_HWVIRT
15964 | IEM_CPUMCTX_EXTRN_EXEC_DECODED_MEM_MASK);
15965 AssertRCReturn(rc, rc);
15966
15967 HMVMX_CHECK_EXIT_DUE_TO_VMX_INSTR(pVCpu, pVmxTransient->uExitReason);
15968
15969 VMXVEXITINFO ExitInfo;
15970 RT_ZERO(ExitInfo);
15971 ExitInfo.uReason = pVmxTransient->uExitReason;
15972 ExitInfo.u64Qual = pVmxTransient->uExitQual;
15973 ExitInfo.InstrInfo.u = pVmxTransient->ExitInstrInfo.u;
15974 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
15975 if (!ExitInfo.InstrInfo.VmreadVmwrite.fIsRegOperand)
15976 HMVMX_DECODE_MEM_OPERAND(pVCpu, ExitInfo.InstrInfo.u, ExitInfo.u64Qual, VMXMEMACCESS_READ, &ExitInfo.GCPtrEffAddr);
15977
15978 VBOXSTRICTRC rcStrict = IEMExecDecodedVmwrite(pVCpu, &ExitInfo);
15979 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
15980 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS | HM_CHANGED_GUEST_HWVIRT);
15981 else if (rcStrict == VINF_IEM_RAISED_XCPT)
15982 {
15983 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
15984 rcStrict = VINF_SUCCESS;
15985 }
15986 return rcStrict;
15987}
15988
15989
15990/**
15991 * VM-exit handler for VMXOFF (VMX_EXIT_VMXOFF). Unconditional VM-exit.
15992 */
15993HMVMX_EXIT_DECL hmR0VmxExitVmxoff(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
15994{
15995 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
15996
15997 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
15998 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, CPUMCTX_EXTRN_CR4
15999 | CPUMCTX_EXTRN_HWVIRT
16000 | IEM_CPUMCTX_EXTRN_EXEC_DECODED_NO_MEM_MASK);
16001 AssertRCReturn(rc, rc);
16002
16003 HMVMX_CHECK_EXIT_DUE_TO_VMX_INSTR(pVCpu, pVmxTransient->uExitReason);
16004
16005 VBOXSTRICTRC rcStrict = IEMExecDecodedVmxoff(pVCpu, pVmxTransient->cbExitInstr);
16006 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
16007 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_HWVIRT);
16008 else if (rcStrict == VINF_IEM_RAISED_XCPT)
16009 {
16010 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
16011 rcStrict = VINF_SUCCESS;
16012 }
16013 return rcStrict;
16014}
16015
16016
16017/**
16018 * VM-exit handler for VMXON (VMX_EXIT_VMXON). Unconditional VM-exit.
16019 */
16020HMVMX_EXIT_DECL hmR0VmxExitVmxon(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16021{
16022 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16023
16024 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16025 hmR0VmxReadExitInstrInfoVmcs(pVmxTransient);
16026 hmR0VmxReadExitQualVmcs(pVmxTransient);
16027 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, CPUMCTX_EXTRN_RSP | CPUMCTX_EXTRN_SREG_MASK
16028 | CPUMCTX_EXTRN_HWVIRT
16029 | IEM_CPUMCTX_EXTRN_EXEC_DECODED_MEM_MASK);
16030 AssertRCReturn(rc, rc);
16031
16032 HMVMX_CHECK_EXIT_DUE_TO_VMX_INSTR(pVCpu, pVmxTransient->uExitReason);
16033
16034 VMXVEXITINFO ExitInfo;
16035 RT_ZERO(ExitInfo);
16036 ExitInfo.uReason = pVmxTransient->uExitReason;
16037 ExitInfo.u64Qual = pVmxTransient->uExitQual;
16038 ExitInfo.InstrInfo.u = pVmxTransient->ExitInstrInfo.u;
16039 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
16040 HMVMX_DECODE_MEM_OPERAND(pVCpu, ExitInfo.InstrInfo.u, ExitInfo.u64Qual, VMXMEMACCESS_READ, &ExitInfo.GCPtrEffAddr);
16041
16042 VBOXSTRICTRC rcStrict = IEMExecDecodedVmxon(pVCpu, &ExitInfo);
16043 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
16044 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS | HM_CHANGED_GUEST_HWVIRT);
16045 else if (rcStrict == VINF_IEM_RAISED_XCPT)
16046 {
16047 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
16048 rcStrict = VINF_SUCCESS;
16049 }
16050 return rcStrict;
16051}
16052
16053
16054/**
16055 * VM-exit handler for INVVPID (VMX_EXIT_INVVPID). Unconditional VM-exit.
16056 */
16057HMVMX_EXIT_DECL hmR0VmxExitInvvpid(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16058{
16059 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16060
16061 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16062 hmR0VmxReadExitInstrInfoVmcs(pVmxTransient);
16063 hmR0VmxReadExitQualVmcs(pVmxTransient);
16064 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, CPUMCTX_EXTRN_RSP | CPUMCTX_EXTRN_SREG_MASK
16065 | IEM_CPUMCTX_EXTRN_EXEC_DECODED_MEM_MASK);
16066 AssertRCReturn(rc, rc);
16067
16068 HMVMX_CHECK_EXIT_DUE_TO_VMX_INSTR(pVCpu, pVmxTransient->uExitReason);
16069
16070 VMXVEXITINFO ExitInfo;
16071 RT_ZERO(ExitInfo);
16072 ExitInfo.uReason = pVmxTransient->uExitReason;
16073 ExitInfo.u64Qual = pVmxTransient->uExitQual;
16074 ExitInfo.InstrInfo.u = pVmxTransient->ExitInstrInfo.u;
16075 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
16076 HMVMX_DECODE_MEM_OPERAND(pVCpu, ExitInfo.InstrInfo.u, ExitInfo.u64Qual, VMXMEMACCESS_READ, &ExitInfo.GCPtrEffAddr);
16077
16078 VBOXSTRICTRC rcStrict = IEMExecDecodedInvvpid(pVCpu, &ExitInfo);
16079 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
16080 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS);
16081 else if (rcStrict == VINF_IEM_RAISED_XCPT)
16082 {
16083 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
16084 rcStrict = VINF_SUCCESS;
16085 }
16086 return rcStrict;
16087}
16088#endif /* VBOX_WITH_NESTED_HWVIRT_VMX */
16089/** @} */
16090
16091
16092#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
16093/** @name Nested-guest VM-exit handlers.
16094 * @{
16095 */
16096/* -=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= */
16097/* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- Nested-guest VM-exit handlers -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= */
16098/* -=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= */
16099
16100/**
16101 * Nested-guest VM-exit handler for exceptions or NMIs (VMX_EXIT_XCPT_OR_NMI).
16102 * Conditional VM-exit.
16103 */
16104HMVMX_EXIT_DECL hmR0VmxExitXcptOrNmiNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16105{
16106 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16107
16108 hmR0VmxReadExitIntInfoVmcs(pVmxTransient);
16109
16110 uint64_t const uExitIntInfo = pVmxTransient->uExitIntInfo;
16111 uint32_t const uExitIntType = VMX_EXIT_INT_INFO_TYPE(uExitIntInfo);
16112 Assert(VMX_EXIT_INT_INFO_IS_VALID(uExitIntInfo));
16113
16114 switch (uExitIntType)
16115 {
16116 /*
16117 * Physical NMIs:
16118 * We shouldn't direct host physical NMIs to the nested-guest. Dispatch it to the host.
16119 */
16120 case VMX_EXIT_INT_INFO_TYPE_NMI:
16121 return hmR0VmxExitHostNmi(pVCpu, pVmxTransient->pVmcsInfo);
16122
16123 /*
16124 * Hardware exceptions,
16125 * Software exceptions,
16126 * Privileged software exceptions:
16127 * Figure out if the exception must be delivered to the guest or the nested-guest.
16128 */
16129 case VMX_EXIT_INT_INFO_TYPE_SW_XCPT:
16130 case VMX_EXIT_INT_INFO_TYPE_PRIV_SW_XCPT:
16131 case VMX_EXIT_INT_INFO_TYPE_HW_XCPT:
16132 {
16133 hmR0VmxReadExitIntErrorCodeVmcs(pVmxTransient);
16134 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16135 hmR0VmxReadIdtVectoringInfoVmcs(pVmxTransient);
16136 hmR0VmxReadIdtVectoringErrorCodeVmcs(pVmxTransient);
16137
16138 PCCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
16139 bool const fIntercept = CPUMIsGuestVmxXcptInterceptSet(pVCpu, pCtx, VMX_EXIT_INT_INFO_VECTOR(uExitIntInfo),
16140 pVmxTransient->uExitIntErrorCode);
16141 if (fIntercept)
16142 {
16143 /* Exit qualification is required for debug and page-fault exceptions. */
16144 hmR0VmxReadExitQualVmcs(pVmxTransient);
16145
16146 /*
16147 * For VM-exits due to software exceptions (those generated by INT3 or INTO) and privileged
16148 * software exceptions (those generated by INT1/ICEBP) we need to supply the VM-exit instruction
16149 * length. However, if delivery of a software interrupt, software exception or privileged
16150 * software exception causes a VM-exit, that too provides the VM-exit instruction length.
16151 */
16152 VMXVEXITINFO ExitInfo;
16153 RT_ZERO(ExitInfo);
16154 ExitInfo.uReason = pVmxTransient->uExitReason;
16155 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
16156 ExitInfo.u64Qual = pVmxTransient->uExitQual;
16157
16158 VMXVEXITEVENTINFO ExitEventInfo;
16159 RT_ZERO(ExitEventInfo);
16160 ExitEventInfo.uExitIntInfo = pVmxTransient->uExitIntInfo;
16161 ExitEventInfo.uExitIntErrCode = pVmxTransient->uExitIntErrorCode;
16162 ExitEventInfo.uIdtVectoringInfo = pVmxTransient->uIdtVectoringInfo;
16163 ExitEventInfo.uIdtVectoringErrCode = pVmxTransient->uIdtVectoringErrorCode;
16164
16165#ifdef DEBUG_ramshankar
16166 hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, HMVMX_CPUMCTX_EXTRN_ALL);
16167 Log4Func(("exit_int_info=%#RX32 err_code=%#RX32 exit_qual=%#RX64\n", pVmxTransient->uExitIntInfo,
16168 pVmxTransient->uExitIntErrorCode, pVmxTransient->uExitQual));
16169 if (VMX_IDT_VECTORING_INFO_IS_VALID(pVmxTransient->uIdtVectoringInfo))
16170 {
16171 Log4Func(("idt_info=%#RX32 idt_errcode=%#RX32 cr2=%#RX64\n", pVmxTransient->uIdtVectoringInfo,
16172 pVmxTransient->uIdtVectoringErrorCode, pCtx->cr2));
16173 }
16174#endif
16175 return IEMExecVmxVmexitXcpt(pVCpu, &ExitInfo, &ExitEventInfo);
16176 }
16177
16178 /* Nested paging is currently a requirement, otherwise we would need to handle shadow #PFs in hmR0VmxExitXcptPF. */
16179 Assert(pVCpu->CTX_SUFF(pVM)->hm.s.fNestedPaging);
16180 return hmR0VmxExitXcpt(pVCpu, pVmxTransient);
16181 }
16182
16183 /*
16184 * Software interrupts:
16185 * VM-exits cannot be caused by software interrupts.
16186 *
16187 * External interrupts:
16188 * This should only happen when "acknowledge external interrupts on VM-exit"
16189 * control is set. However, we never set this when executing a guest or
16190 * nested-guest. For nested-guests it is emulated while injecting interrupts into
16191 * the guest.
16192 */
16193 case VMX_EXIT_INT_INFO_TYPE_SW_INT:
16194 case VMX_EXIT_INT_INFO_TYPE_EXT_INT:
16195 default:
16196 {
16197 pVCpu->hm.s.u32HMError = pVmxTransient->uExitIntInfo;
16198 return VERR_VMX_UNEXPECTED_INTERRUPTION_EXIT_TYPE;
16199 }
16200 }
16201}
16202
16203
16204/**
16205 * Nested-guest VM-exit handler for triple faults (VMX_EXIT_TRIPLE_FAULT).
16206 * Unconditional VM-exit.
16207 */
16208HMVMX_EXIT_DECL hmR0VmxExitTripleFaultNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16209{
16210 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16211 return IEMExecVmxVmexitTripleFault(pVCpu);
16212}
16213
16214
16215/**
16216 * Nested-guest VM-exit handler for interrupt-window exiting (VMX_EXIT_INT_WINDOW).
16217 */
16218HMVMX_EXIT_NSRC_DECL hmR0VmxExitIntWindowNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16219{
16220 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16221
16222 if (CPUMIsGuestVmxProcCtlsSet(pVCpu, &pVCpu->cpum.GstCtx, VMX_PROC_CTLS_INT_WINDOW_EXIT))
16223 return IEMExecVmxVmexit(pVCpu, pVmxTransient->uExitReason, 0 /* uExitQual */);
16224 return hmR0VmxExitIntWindow(pVCpu, pVmxTransient);
16225}
16226
16227
16228/**
16229 * Nested-guest VM-exit handler for NMI-window exiting (VMX_EXIT_NMI_WINDOW).
16230 */
16231HMVMX_EXIT_NSRC_DECL hmR0VmxExitNmiWindowNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16232{
16233 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16234
16235 if (CPUMIsGuestVmxProcCtlsSet(pVCpu, &pVCpu->cpum.GstCtx, VMX_PROC_CTLS_NMI_WINDOW_EXIT))
16236 return IEMExecVmxVmexit(pVCpu, pVmxTransient->uExitReason, 0 /* uExitQual */);
16237 return hmR0VmxExitIntWindow(pVCpu, pVmxTransient);
16238}
16239
16240
16241/**
16242 * Nested-guest VM-exit handler for task switches (VMX_EXIT_TASK_SWITCH).
16243 * Unconditional VM-exit.
16244 */
16245HMVMX_EXIT_DECL hmR0VmxExitTaskSwitchNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16246{
16247 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16248
16249 hmR0VmxReadExitQualVmcs(pVmxTransient);
16250 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16251 hmR0VmxReadIdtVectoringInfoVmcs(pVmxTransient);
16252 hmR0VmxReadIdtVectoringErrorCodeVmcs(pVmxTransient);
16253
16254 VMXVEXITINFO ExitInfo;
16255 RT_ZERO(ExitInfo);
16256 ExitInfo.uReason = pVmxTransient->uExitReason;
16257 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
16258 ExitInfo.u64Qual = pVmxTransient->uExitQual;
16259
16260 VMXVEXITEVENTINFO ExitEventInfo;
16261 RT_ZERO(ExitEventInfo);
16262 ExitEventInfo.uIdtVectoringInfo = pVmxTransient->uIdtVectoringInfo;
16263 ExitEventInfo.uIdtVectoringErrCode = pVmxTransient->uIdtVectoringErrorCode;
16264 return IEMExecVmxVmexitTaskSwitch(pVCpu, &ExitInfo, &ExitEventInfo);
16265}
16266
16267
16268/**
16269 * Nested-guest VM-exit handler for HLT (VMX_EXIT_HLT). Conditional VM-exit.
16270 */
16271HMVMX_EXIT_DECL hmR0VmxExitHltNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16272{
16273 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16274
16275 if (CPUMIsGuestVmxProcCtlsSet(pVCpu, &pVCpu->cpum.GstCtx, VMX_PROC_CTLS_HLT_EXIT))
16276 {
16277 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16278 return IEMExecVmxVmexitInstr(pVCpu, pVmxTransient->uExitReason, pVmxTransient->cbExitInstr);
16279 }
16280 return hmR0VmxExitHlt(pVCpu, pVmxTransient);
16281}
16282
16283
16284/**
16285 * Nested-guest VM-exit handler for INVLPG (VMX_EXIT_INVLPG). Conditional VM-exit.
16286 */
16287HMVMX_EXIT_DECL hmR0VmxExitInvlpgNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16288{
16289 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16290
16291 if (CPUMIsGuestVmxProcCtlsSet(pVCpu, &pVCpu->cpum.GstCtx, VMX_PROC_CTLS_INVLPG_EXIT))
16292 {
16293 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16294 hmR0VmxReadExitQualVmcs(pVmxTransient);
16295
16296 VMXVEXITINFO ExitInfo;
16297 RT_ZERO(ExitInfo);
16298 ExitInfo.uReason = pVmxTransient->uExitReason;
16299 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
16300 ExitInfo.u64Qual = pVmxTransient->uExitQual;
16301 return IEMExecVmxVmexitInstrWithInfo(pVCpu, &ExitInfo);
16302 }
16303 return hmR0VmxExitInvlpg(pVCpu, pVmxTransient);
16304}
16305
16306
16307/**
16308 * Nested-guest VM-exit handler for RDPMC (VMX_EXIT_RDPMC). Conditional VM-exit.
16309 */
16310HMVMX_EXIT_DECL hmR0VmxExitRdpmcNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16311{
16312 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16313
16314 if (CPUMIsGuestVmxProcCtlsSet(pVCpu, &pVCpu->cpum.GstCtx, VMX_PROC_CTLS_RDPMC_EXIT))
16315 {
16316 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16317 return IEMExecVmxVmexitInstr(pVCpu, pVmxTransient->uExitReason, pVmxTransient->cbExitInstr);
16318 }
16319 return hmR0VmxExitRdpmc(pVCpu, pVmxTransient);
16320}
16321
16322
16323/**
16324 * Nested-guest VM-exit handler for VMREAD (VMX_EXIT_VMREAD) and VMWRITE
16325 * (VMX_EXIT_VMWRITE). Conditional VM-exit.
16326 */
16327HMVMX_EXIT_DECL hmR0VmxExitVmreadVmwriteNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16328{
16329 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16330
16331 Assert( pVmxTransient->uExitReason == VMX_EXIT_VMREAD
16332 || pVmxTransient->uExitReason == VMX_EXIT_VMWRITE);
16333
16334 hmR0VmxReadExitInstrInfoVmcs(pVmxTransient);
16335
16336 uint8_t const iGReg = pVmxTransient->ExitInstrInfo.VmreadVmwrite.iReg2;
16337 Assert(iGReg < RT_ELEMENTS(pVCpu->cpum.GstCtx.aGRegs));
16338 uint64_t u64VmcsField = pVCpu->cpum.GstCtx.aGRegs[iGReg].u64;
16339
16340 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_EFER);
16341 if (!CPUMIsGuestInLongModeEx(&pVCpu->cpum.GstCtx))
16342 u64VmcsField &= UINT64_C(0xffffffff);
16343
16344 if (CPUMIsGuestVmxVmreadVmwriteInterceptSet(pVCpu, pVmxTransient->uExitReason, u64VmcsField))
16345 {
16346 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16347 hmR0VmxReadExitQualVmcs(pVmxTransient);
16348
16349 VMXVEXITINFO ExitInfo;
16350 RT_ZERO(ExitInfo);
16351 ExitInfo.uReason = pVmxTransient->uExitReason;
16352 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
16353 ExitInfo.u64Qual = pVmxTransient->uExitQual;
16354 ExitInfo.InstrInfo = pVmxTransient->ExitInstrInfo;
16355 return IEMExecVmxVmexitInstrWithInfo(pVCpu, &ExitInfo);
16356 }
16357
16358 if (pVmxTransient->uExitReason == VMX_EXIT_VMREAD)
16359 return hmR0VmxExitVmread(pVCpu, pVmxTransient);
16360 return hmR0VmxExitVmwrite(pVCpu, pVmxTransient);
16361}
16362
16363
16364/**
16365 * Nested-guest VM-exit handler for RDTSC (VMX_EXIT_RDTSC). Conditional VM-exit.
16366 */
16367HMVMX_EXIT_DECL hmR0VmxExitRdtscNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16368{
16369 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16370
16371 if (CPUMIsGuestVmxProcCtlsSet(pVCpu, &pVCpu->cpum.GstCtx, VMX_PROC_CTLS_RDTSC_EXIT))
16372 {
16373 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16374 return IEMExecVmxVmexitInstr(pVCpu, pVmxTransient->uExitReason, pVmxTransient->cbExitInstr);
16375 }
16376
16377 return hmR0VmxExitRdtsc(pVCpu, pVmxTransient);
16378}
16379
16380
16381/**
16382 * Nested-guest VM-exit handler for control-register accesses (VMX_EXIT_MOV_CRX).
16383 * Conditional VM-exit.
16384 */
16385HMVMX_EXIT_DECL hmR0VmxExitMovCRxNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16386{
16387 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16388
16389 hmR0VmxReadExitQualVmcs(pVmxTransient);
16390 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16391
16392 VBOXSTRICTRC rcStrict;
16393 uint32_t const uAccessType = VMX_EXIT_QUAL_CRX_ACCESS(pVmxTransient->uExitQual);
16394 switch (uAccessType)
16395 {
16396 case VMX_EXIT_QUAL_CRX_ACCESS_WRITE:
16397 {
16398 uint8_t const iCrReg = VMX_EXIT_QUAL_CRX_REGISTER(pVmxTransient->uExitQual);
16399 uint8_t const iGReg = VMX_EXIT_QUAL_CRX_GENREG(pVmxTransient->uExitQual);
16400 Assert(iGReg < RT_ELEMENTS(pVCpu->cpum.GstCtx.aGRegs));
16401 uint64_t const uNewCrX = pVCpu->cpum.GstCtx.aGRegs[iGReg].u64;
16402
16403 bool fIntercept;
16404 switch (iCrReg)
16405 {
16406 case 0:
16407 case 4:
16408 fIntercept = CPUMIsGuestVmxMovToCr0Cr4InterceptSet(pVCpu, &pVCpu->cpum.GstCtx, iCrReg, uNewCrX);
16409 break;
16410
16411 case 3:
16412 fIntercept = CPUMIsGuestVmxMovToCr3InterceptSet(pVCpu, uNewCrX);
16413 break;
16414
16415 case 8:
16416 fIntercept = CPUMIsGuestVmxProcCtlsSet(pVCpu, &pVCpu->cpum.GstCtx, VMX_PROC_CTLS_CR8_LOAD_EXIT);
16417 break;
16418
16419 default:
16420 fIntercept = false;
16421 break;
16422 }
16423 if (fIntercept)
16424 {
16425 VMXVEXITINFO ExitInfo;
16426 RT_ZERO(ExitInfo);
16427 ExitInfo.uReason = pVmxTransient->uExitReason;
16428 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
16429 ExitInfo.u64Qual = pVmxTransient->uExitQual;
16430 rcStrict = IEMExecVmxVmexitInstrWithInfo(pVCpu, &ExitInfo);
16431 }
16432 else
16433 rcStrict = hmR0VmxExitMovToCrX(pVCpu, pVmxTransient->pVmcsInfo, pVmxTransient->cbExitInstr, iGReg, iCrReg);
16434 break;
16435 }
16436
16437 case VMX_EXIT_QUAL_CRX_ACCESS_READ:
16438 {
16439 /*
16440 * CR0/CR4 reads do not cause VM-exits, the read-shadow is used (subject to masking).
16441 * CR2 reads do not cause a VM-exit.
16442 * CR3 reads cause a VM-exit depending on the "CR3 store exiting" control.
16443 * CR8 reads cause a VM-exit depending on the "CR8 store exiting" control.
16444 */
16445 uint8_t const iCrReg = VMX_EXIT_QUAL_CRX_REGISTER(pVmxTransient->uExitQual);
16446 if ( iCrReg == 3
16447 || iCrReg == 8)
16448 {
16449 static const uint32_t s_auCrXReadIntercepts[] = { 0, 0, 0, VMX_PROC_CTLS_CR3_STORE_EXIT, 0,
16450 0, 0, 0, VMX_PROC_CTLS_CR8_STORE_EXIT };
16451 uint32_t const uIntercept = s_auCrXReadIntercepts[iCrReg];
16452 if (CPUMIsGuestVmxProcCtlsSet(pVCpu, &pVCpu->cpum.GstCtx, uIntercept))
16453 {
16454 VMXVEXITINFO ExitInfo;
16455 RT_ZERO(ExitInfo);
16456 ExitInfo.uReason = pVmxTransient->uExitReason;
16457 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
16458 ExitInfo.u64Qual = pVmxTransient->uExitQual;
16459 rcStrict = IEMExecVmxVmexitInstrWithInfo(pVCpu, &ExitInfo);
16460 }
16461 else
16462 {
16463 uint8_t const iGReg = VMX_EXIT_QUAL_CRX_GENREG(pVmxTransient->uExitQual);
16464 rcStrict = hmR0VmxExitMovFromCrX(pVCpu, pVmxTransient->pVmcsInfo, pVmxTransient->cbExitInstr, iGReg, iCrReg);
16465 }
16466 }
16467 else
16468 {
16469 AssertMsgFailed(("MOV from CR%d VM-exit must not happen\n", iCrReg));
16470 HMVMX_UNEXPECTED_EXIT_RET(pVCpu, iCrReg);
16471 }
16472 break;
16473 }
16474
16475 case VMX_EXIT_QUAL_CRX_ACCESS_CLTS:
16476 {
16477 PCVMXVVMCS pVmcsNstGst = pVCpu->cpum.GstCtx.hwvirt.vmx.CTX_SUFF(pVmcs);
16478 Assert(pVmcsNstGst);
16479 uint64_t const uGstHostMask = pVmcsNstGst->u64Cr0Mask.u;
16480 uint64_t const uReadShadow = pVmcsNstGst->u64Cr0ReadShadow.u;
16481 if ( (uGstHostMask & X86_CR0_TS)
16482 && (uReadShadow & X86_CR0_TS))
16483 {
16484 VMXVEXITINFO ExitInfo;
16485 RT_ZERO(ExitInfo);
16486 ExitInfo.uReason = pVmxTransient->uExitReason;
16487 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
16488 ExitInfo.u64Qual = pVmxTransient->uExitQual;
16489 rcStrict = IEMExecVmxVmexitInstrWithInfo(pVCpu, &ExitInfo);
16490 }
16491 else
16492 rcStrict = hmR0VmxExitClts(pVCpu, pVmxTransient->pVmcsInfo, pVmxTransient->cbExitInstr);
16493 break;
16494 }
16495
16496 case VMX_EXIT_QUAL_CRX_ACCESS_LMSW: /* LMSW (Load Machine-Status Word into CR0) */
16497 {
16498 RTGCPTR GCPtrEffDst;
16499 uint16_t const uNewMsw = VMX_EXIT_QUAL_CRX_LMSW_DATA(pVmxTransient->uExitQual);
16500 bool const fMemOperand = VMX_EXIT_QUAL_CRX_LMSW_OP_MEM(pVmxTransient->uExitQual);
16501 if (fMemOperand)
16502 {
16503 hmR0VmxReadGuestLinearAddrVmcs(pVmxTransient);
16504 GCPtrEffDst = pVmxTransient->uGuestLinearAddr;
16505 }
16506 else
16507 GCPtrEffDst = NIL_RTGCPTR;
16508
16509 if (CPUMIsGuestVmxLmswInterceptSet(pVCpu, &pVCpu->cpum.GstCtx, uNewMsw))
16510 {
16511 VMXVEXITINFO ExitInfo;
16512 RT_ZERO(ExitInfo);
16513 ExitInfo.uReason = pVmxTransient->uExitReason;
16514 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
16515 ExitInfo.u64GuestLinearAddr = GCPtrEffDst;
16516 ExitInfo.u64Qual = pVmxTransient->uExitQual;
16517 rcStrict = IEMExecVmxVmexitInstrWithInfo(pVCpu, &ExitInfo);
16518 }
16519 else
16520 rcStrict = hmR0VmxExitLmsw(pVCpu, pVmxTransient->pVmcsInfo, pVmxTransient->cbExitInstr, uNewMsw, GCPtrEffDst);
16521 break;
16522 }
16523
16524 default:
16525 {
16526 AssertMsgFailed(("Unrecognized Mov CRX access type %#x\n", uAccessType));
16527 HMVMX_UNEXPECTED_EXIT_RET(pVCpu, uAccessType);
16528 }
16529 }
16530
16531 if (rcStrict == VINF_IEM_RAISED_XCPT)
16532 {
16533 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
16534 rcStrict = VINF_SUCCESS;
16535 }
16536 return rcStrict;
16537}
16538
16539
16540/**
16541 * Nested-guest VM-exit handler for debug-register accesses (VMX_EXIT_MOV_DRX).
16542 * Conditional VM-exit.
16543 */
16544HMVMX_EXIT_DECL hmR0VmxExitMovDRxNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16545{
16546 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16547
16548 if (CPUMIsGuestVmxProcCtlsSet(pVCpu, &pVCpu->cpum.GstCtx, VMX_PROC_CTLS_MOV_DR_EXIT))
16549 {
16550 hmR0VmxReadExitQualVmcs(pVmxTransient);
16551 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16552
16553 VMXVEXITINFO ExitInfo;
16554 RT_ZERO(ExitInfo);
16555 ExitInfo.uReason = pVmxTransient->uExitReason;
16556 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
16557 ExitInfo.u64Qual = pVmxTransient->uExitQual;
16558 return IEMExecVmxVmexitInstrWithInfo(pVCpu, &ExitInfo);
16559 }
16560 return hmR0VmxExitMovDRx(pVCpu, pVmxTransient);
16561}
16562
16563
16564/**
16565 * Nested-guest VM-exit handler for I/O instructions (VMX_EXIT_IO_INSTR).
16566 * Conditional VM-exit.
16567 */
16568HMVMX_EXIT_DECL hmR0VmxExitIoInstrNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16569{
16570 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16571
16572 hmR0VmxReadExitQualVmcs(pVmxTransient);
16573
16574 uint32_t const uIOPort = VMX_EXIT_QUAL_IO_PORT(pVmxTransient->uExitQual);
16575 uint8_t const uIOSize = VMX_EXIT_QUAL_IO_SIZE(pVmxTransient->uExitQual);
16576 AssertReturn(uIOSize <= 3 && uIOSize != 2, VERR_VMX_IPE_1);
16577
16578 static uint32_t const s_aIOSizes[4] = { 1, 2, 0, 4 }; /* Size of the I/O accesses in bytes. */
16579 uint8_t const cbAccess = s_aIOSizes[uIOSize];
16580 if (CPUMIsGuestVmxIoInterceptSet(pVCpu, uIOPort, cbAccess))
16581 {
16582 /*
16583 * IN/OUT instruction:
16584 * - Provides VM-exit instruction length.
16585 *
16586 * INS/OUTS instruction:
16587 * - Provides VM-exit instruction length.
16588 * - Provides Guest-linear address.
16589 * - Optionally provides VM-exit instruction info (depends on CPU feature).
16590 */
16591 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
16592 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16593
16594 /* Make sure we don't use stale/uninitialized VMX-transient info. below. */
16595 pVmxTransient->ExitInstrInfo.u = 0;
16596 pVmxTransient->uGuestLinearAddr = 0;
16597
16598 bool const fVmxInsOutsInfo = pVM->cpum.ro.GuestFeatures.fVmxInsOutInfo;
16599 bool const fIOString = VMX_EXIT_QUAL_IO_IS_STRING(pVmxTransient->uExitQual);
16600 if (fIOString)
16601 {
16602 hmR0VmxReadGuestLinearAddrVmcs(pVmxTransient);
16603 if (fVmxInsOutsInfo)
16604 {
16605 Assert(RT_BF_GET(pVM->hm.s.vmx.Msrs.u64Basic, VMX_BF_BASIC_VMCS_INS_OUTS)); /* Paranoia. */
16606 hmR0VmxReadExitInstrInfoVmcs(pVmxTransient);
16607 }
16608 }
16609
16610 VMXVEXITINFO ExitInfo;
16611 RT_ZERO(ExitInfo);
16612 ExitInfo.uReason = pVmxTransient->uExitReason;
16613 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
16614 ExitInfo.u64Qual = pVmxTransient->uExitQual;
16615 ExitInfo.InstrInfo = pVmxTransient->ExitInstrInfo;
16616 ExitInfo.u64GuestLinearAddr = pVmxTransient->uGuestLinearAddr;
16617 return IEMExecVmxVmexitInstrWithInfo(pVCpu, &ExitInfo);
16618 }
16619 return hmR0VmxExitIoInstr(pVCpu, pVmxTransient);
16620}
16621
16622
16623/**
16624 * Nested-guest VM-exit handler for RDMSR (VMX_EXIT_RDMSR).
16625 */
16626HMVMX_EXIT_DECL hmR0VmxExitRdmsrNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16627{
16628 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16629
16630 uint32_t fMsrpm;
16631 if (CPUMIsGuestVmxProcCtlsSet(pVCpu, &pVCpu->cpum.GstCtx, VMX_PROC_CTLS_USE_MSR_BITMAPS))
16632 fMsrpm = CPUMGetVmxMsrPermission(pVCpu->cpum.GstCtx.hwvirt.vmx.CTX_SUFF(pvMsrBitmap), pVCpu->cpum.GstCtx.ecx);
16633 else
16634 fMsrpm = VMXMSRPM_EXIT_RD;
16635
16636 if (fMsrpm & VMXMSRPM_EXIT_RD)
16637 {
16638 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16639 return IEMExecVmxVmexitInstr(pVCpu, pVmxTransient->uExitReason, pVmxTransient->cbExitInstr);
16640 }
16641 return hmR0VmxExitRdmsr(pVCpu, pVmxTransient);
16642}
16643
16644
16645/**
16646 * Nested-guest VM-exit handler for WRMSR (VMX_EXIT_WRMSR).
16647 */
16648HMVMX_EXIT_DECL hmR0VmxExitWrmsrNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16649{
16650 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16651
16652 uint32_t fMsrpm;
16653 if (CPUMIsGuestVmxProcCtlsSet(pVCpu, &pVCpu->cpum.GstCtx, VMX_PROC_CTLS_USE_MSR_BITMAPS))
16654 fMsrpm = CPUMGetVmxMsrPermission(pVCpu->cpum.GstCtx.hwvirt.vmx.CTX_SUFF(pvMsrBitmap), pVCpu->cpum.GstCtx.ecx);
16655 else
16656 fMsrpm = VMXMSRPM_EXIT_WR;
16657
16658 if (fMsrpm & VMXMSRPM_EXIT_WR)
16659 {
16660 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16661 return IEMExecVmxVmexitInstr(pVCpu, pVmxTransient->uExitReason, pVmxTransient->cbExitInstr);
16662 }
16663 return hmR0VmxExitWrmsr(pVCpu, pVmxTransient);
16664}
16665
16666
16667/**
16668 * Nested-guest VM-exit handler for MWAIT (VMX_EXIT_MWAIT). Conditional VM-exit.
16669 */
16670HMVMX_EXIT_DECL hmR0VmxExitMwaitNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16671{
16672 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16673
16674 if (CPUMIsGuestVmxProcCtlsSet(pVCpu, &pVCpu->cpum.GstCtx, VMX_PROC_CTLS_MWAIT_EXIT))
16675 {
16676 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16677 return IEMExecVmxVmexitInstr(pVCpu, pVmxTransient->uExitReason, pVmxTransient->cbExitInstr);
16678 }
16679 return hmR0VmxExitMwait(pVCpu, pVmxTransient);
16680}
16681
16682
16683/**
16684 * Nested-guest VM-exit handler for monitor-trap-flag (VMX_EXIT_MTF). Conditional
16685 * VM-exit.
16686 */
16687HMVMX_EXIT_DECL hmR0VmxExitMtfNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16688{
16689 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16690
16691 /** @todo NSTVMX: Should consider debugging nested-guests using VM debugger. */
16692 hmR0VmxReadGuestPendingDbgXctps(pVmxTransient);
16693 VMXVEXITINFO ExitInfo;
16694 RT_ZERO(ExitInfo);
16695 ExitInfo.uReason = pVmxTransient->uExitReason;
16696 ExitInfo.u64GuestPendingDbgXcpts = pVmxTransient->uGuestPendingDbgXcpts;
16697 return IEMExecVmxVmexitTrapLike(pVCpu, &ExitInfo);
16698}
16699
16700
16701/**
16702 * Nested-guest VM-exit handler for MONITOR (VMX_EXIT_MONITOR). Conditional VM-exit.
16703 */
16704HMVMX_EXIT_DECL hmR0VmxExitMonitorNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16705{
16706 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16707
16708 if (CPUMIsGuestVmxProcCtlsSet(pVCpu, &pVCpu->cpum.GstCtx, VMX_PROC_CTLS_MONITOR_EXIT))
16709 {
16710 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16711 return IEMExecVmxVmexitInstr(pVCpu, pVmxTransient->uExitReason, pVmxTransient->cbExitInstr);
16712 }
16713 return hmR0VmxExitMonitor(pVCpu, pVmxTransient);
16714}
16715
16716
16717/**
16718 * Nested-guest VM-exit handler for PAUSE (VMX_EXIT_PAUSE). Conditional VM-exit.
16719 */
16720HMVMX_EXIT_DECL hmR0VmxExitPauseNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16721{
16722 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16723
16724 /** @todo NSTVMX: Think about this more. Does the outer guest need to intercept
16725 * PAUSE when executing a nested-guest? If it does not, we would not need
16726 * to check for the intercepts here. Just call VM-exit... */
16727
16728 /* The CPU would have already performed the necessary CPL checks for PAUSE-loop exiting. */
16729 if ( CPUMIsGuestVmxProcCtlsSet(pVCpu, &pVCpu->cpum.GstCtx, VMX_PROC_CTLS_PAUSE_EXIT)
16730 || CPUMIsGuestVmxProcCtls2Set(pVCpu, &pVCpu->cpum.GstCtx, VMX_PROC_CTLS2_PAUSE_LOOP_EXIT))
16731 {
16732 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16733 return IEMExecVmxVmexitInstr(pVCpu, pVmxTransient->uExitReason, pVmxTransient->cbExitInstr);
16734 }
16735 return hmR0VmxExitPause(pVCpu, pVmxTransient);
16736}
16737
16738
16739/**
16740 * Nested-guest VM-exit handler for when the TPR value is lowered below the
16741 * specified threshold (VMX_EXIT_TPR_BELOW_THRESHOLD). Conditional VM-exit.
16742 */
16743HMVMX_EXIT_NSRC_DECL hmR0VmxExitTprBelowThresholdNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16744{
16745 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16746
16747 if (CPUMIsGuestVmxProcCtlsSet(pVCpu, &pVCpu->cpum.GstCtx, VMX_PROC_CTLS_USE_TPR_SHADOW))
16748 {
16749 hmR0VmxReadGuestPendingDbgXctps(pVmxTransient);
16750 VMXVEXITINFO ExitInfo;
16751 RT_ZERO(ExitInfo);
16752 ExitInfo.uReason = pVmxTransient->uExitReason;
16753 ExitInfo.u64GuestPendingDbgXcpts = pVmxTransient->uGuestPendingDbgXcpts;
16754 return IEMExecVmxVmexitTrapLike(pVCpu, &ExitInfo);
16755 }
16756 return hmR0VmxExitTprBelowThreshold(pVCpu, pVmxTransient);
16757}
16758
16759
16760/**
16761 * Nested-guest VM-exit handler for APIC access (VMX_EXIT_APIC_ACCESS). Conditional
16762 * VM-exit.
16763 */
16764HMVMX_EXIT_DECL hmR0VmxExitApicAccessNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16765{
16766 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16767
16768 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16769 hmR0VmxReadIdtVectoringInfoVmcs(pVmxTransient);
16770 hmR0VmxReadIdtVectoringErrorCodeVmcs(pVmxTransient);
16771 hmR0VmxReadExitQualVmcs(pVmxTransient);
16772
16773 Assert(CPUMIsGuestVmxProcCtls2Set(pVCpu, &pVCpu->cpum.GstCtx, VMX_PROC_CTLS2_VIRT_APIC_ACCESS));
16774
16775 Log4Func(("at offset %#x type=%u\n", VMX_EXIT_QUAL_APIC_ACCESS_OFFSET(pVmxTransient->uExitQual),
16776 VMX_EXIT_QUAL_APIC_ACCESS_TYPE(pVmxTransient->uExitQual)));
16777
16778 VMXVEXITINFO ExitInfo;
16779 RT_ZERO(ExitInfo);
16780 ExitInfo.uReason = pVmxTransient->uExitReason;
16781 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
16782 ExitInfo.u64Qual = pVmxTransient->uExitQual;
16783
16784 VMXVEXITEVENTINFO ExitEventInfo;
16785 RT_ZERO(ExitEventInfo);
16786 ExitEventInfo.uIdtVectoringInfo = pVmxTransient->uIdtVectoringInfo;
16787 ExitEventInfo.uIdtVectoringErrCode = pVmxTransient->uIdtVectoringErrorCode;
16788 return IEMExecVmxVmexitApicAccess(pVCpu, &ExitInfo, &ExitEventInfo);
16789}
16790
16791
16792/**
16793 * Nested-guest VM-exit handler for APIC write emulation (VMX_EXIT_APIC_WRITE).
16794 * Conditional VM-exit.
16795 */
16796HMVMX_EXIT_DECL hmR0VmxExitApicWriteNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16797{
16798 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16799
16800 Assert(CPUMIsGuestVmxProcCtls2Set(pVCpu, &pVCpu->cpum.GstCtx, VMX_PROC_CTLS2_APIC_REG_VIRT));
16801 hmR0VmxReadExitQualVmcs(pVmxTransient);
16802 return IEMExecVmxVmexit(pVCpu, pVmxTransient->uExitReason, pVmxTransient->uExitQual);
16803}
16804
16805
16806/**
16807 * Nested-guest VM-exit handler for virtualized EOI (VMX_EXIT_VIRTUALIZED_EOI).
16808 * Conditional VM-exit.
16809 */
16810HMVMX_EXIT_DECL hmR0VmxExitVirtEoiNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16811{
16812 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16813
16814 Assert(CPUMIsGuestVmxProcCtls2Set(pVCpu, &pVCpu->cpum.GstCtx, VMX_PROC_CTLS2_VIRT_INT_DELIVERY));
16815 hmR0VmxReadExitQualVmcs(pVmxTransient);
16816 return IEMExecVmxVmexit(pVCpu, pVmxTransient->uExitReason, pVmxTransient->uExitQual);
16817}
16818
16819
16820/**
16821 * Nested-guest VM-exit handler for RDTSCP (VMX_EXIT_RDTSCP). Conditional VM-exit.
16822 */
16823HMVMX_EXIT_DECL hmR0VmxExitRdtscpNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16824{
16825 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16826
16827 if (CPUMIsGuestVmxProcCtlsSet(pVCpu, &pVCpu->cpum.GstCtx, VMX_PROC_CTLS_RDTSC_EXIT))
16828 {
16829 Assert(CPUMIsGuestVmxProcCtls2Set(pVCpu, &pVCpu->cpum.GstCtx, VMX_PROC_CTLS2_RDTSCP));
16830 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16831 return IEMExecVmxVmexitInstr(pVCpu, pVmxTransient->uExitReason, pVmxTransient->cbExitInstr);
16832 }
16833 return hmR0VmxExitRdtscp(pVCpu, pVmxTransient);
16834}
16835
16836
16837/**
16838 * Nested-guest VM-exit handler for WBINVD (VMX_EXIT_WBINVD). Conditional VM-exit.
16839 */
16840HMVMX_EXIT_NSRC_DECL hmR0VmxExitWbinvdNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16841{
16842 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16843
16844 if (CPUMIsGuestVmxProcCtls2Set(pVCpu, &pVCpu->cpum.GstCtx, VMX_PROC_CTLS2_WBINVD_EXIT))
16845 {
16846 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16847 return IEMExecVmxVmexitInstr(pVCpu, pVmxTransient->uExitReason, pVmxTransient->cbExitInstr);
16848 }
16849 return hmR0VmxExitWbinvd(pVCpu, pVmxTransient);
16850}
16851
16852
16853/**
16854 * Nested-guest VM-exit handler for INVPCID (VMX_EXIT_INVPCID). Conditional VM-exit.
16855 */
16856HMVMX_EXIT_DECL hmR0VmxExitInvpcidNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16857{
16858 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16859
16860 if (CPUMIsGuestVmxProcCtlsSet(pVCpu, &pVCpu->cpum.GstCtx, VMX_PROC_CTLS_INVLPG_EXIT))
16861 {
16862 Assert(CPUMIsGuestVmxProcCtls2Set(pVCpu, &pVCpu->cpum.GstCtx, VMX_PROC_CTLS2_INVPCID));
16863 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16864 hmR0VmxReadExitQualVmcs(pVmxTransient);
16865 hmR0VmxReadExitInstrInfoVmcs(pVmxTransient);
16866
16867 VMXVEXITINFO ExitInfo;
16868 RT_ZERO(ExitInfo);
16869 ExitInfo.uReason = pVmxTransient->uExitReason;
16870 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
16871 ExitInfo.u64Qual = pVmxTransient->uExitQual;
16872 ExitInfo.InstrInfo = pVmxTransient->ExitInstrInfo;
16873 return IEMExecVmxVmexitInstrWithInfo(pVCpu, &ExitInfo);
16874 }
16875 return hmR0VmxExitInvpcid(pVCpu, pVmxTransient);
16876}
16877
16878
16879/**
16880 * Nested-guest VM-exit handler for invalid-guest state
16881 * (VMX_EXIT_ERR_INVALID_GUEST_STATE). Error VM-exit.
16882 */
16883HMVMX_EXIT_DECL hmR0VmxExitErrInvalidGuestStateNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16884{
16885 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16886
16887 /*
16888 * Currently this should never happen because we fully emulate VMLAUNCH/VMRESUME in IEM.
16889 * So if it does happen, it indicates a bug possibly in the hardware-assisted VMX code.
16890 * Handle it like it's in an invalid guest state of the outer guest.
16891 *
16892 * When the fast path is implemented, this should be changed to cause the corresponding
16893 * nested-guest VM-exit.
16894 */
16895 return hmR0VmxExitErrInvalidGuestState(pVCpu, pVmxTransient);
16896}
16897
16898
16899/**
16900 * Nested-guest VM-exit handler for instructions that cause VM-exits uncondtionally
16901 * and only provide the instruction length.
16902 *
16903 * Unconditional VM-exit.
16904 */
16905HMVMX_EXIT_DECL hmR0VmxExitInstrNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16906{
16907 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16908
16909#ifdef VBOX_STRICT
16910 PCCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
16911 switch (pVmxTransient->uExitReason)
16912 {
16913 case VMX_EXIT_ENCLS:
16914 Assert(CPUMIsGuestVmxProcCtls2Set(pVCpu, pCtx, VMX_PROC_CTLS2_ENCLS_EXIT));
16915 break;
16916
16917 case VMX_EXIT_VMFUNC:
16918 Assert(CPUMIsGuestVmxProcCtls2Set(pVCpu, pCtx, VMX_PROC_CTLS2_VMFUNC));
16919 break;
16920 }
16921#endif
16922
16923 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16924 return IEMExecVmxVmexitInstr(pVCpu, pVmxTransient->uExitReason, pVmxTransient->cbExitInstr);
16925}
16926
16927
16928/**
16929 * Nested-guest VM-exit handler for instructions that provide instruction length as
16930 * well as more information.
16931 *
16932 * Unconditional VM-exit.
16933 */
16934HMVMX_EXIT_DECL hmR0VmxExitInstrWithInfoNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16935{
16936 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16937
16938#ifdef VBOX_STRICT
16939 PCCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
16940 switch (pVmxTransient->uExitReason)
16941 {
16942 case VMX_EXIT_GDTR_IDTR_ACCESS:
16943 case VMX_EXIT_LDTR_TR_ACCESS:
16944 Assert(CPUMIsGuestVmxProcCtls2Set(pVCpu, pCtx, VMX_PROC_CTLS2_DESC_TABLE_EXIT));
16945 break;
16946
16947 case VMX_EXIT_RDRAND:
16948 Assert(CPUMIsGuestVmxProcCtls2Set(pVCpu, pCtx, VMX_PROC_CTLS2_RDRAND_EXIT));
16949 break;
16950
16951 case VMX_EXIT_RDSEED:
16952 Assert(CPUMIsGuestVmxProcCtls2Set(pVCpu, pCtx, VMX_PROC_CTLS2_RDSEED_EXIT));
16953 break;
16954
16955 case VMX_EXIT_XSAVES:
16956 case VMX_EXIT_XRSTORS:
16957 /** @todo NSTVMX: Verify XSS-bitmap. */
16958 Assert(CPUMIsGuestVmxProcCtls2Set(pVCpu, pCtx, VMX_PROC_CTLS2_XSAVES_XRSTORS));
16959 break;
16960
16961 case VMX_EXIT_UMWAIT:
16962 case VMX_EXIT_TPAUSE:
16963 Assert(CPUMIsGuestVmxProcCtlsSet(pVCpu, pCtx, VMX_PROC_CTLS_RDTSC_EXIT));
16964 Assert(CPUMIsGuestVmxProcCtls2Set(pVCpu, pCtx, VMX_PROC_CTLS2_USER_WAIT_PAUSE));
16965 break;
16966 }
16967#endif
16968
16969 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16970 hmR0VmxReadExitQualVmcs(pVmxTransient);
16971 hmR0VmxReadExitInstrInfoVmcs(pVmxTransient);
16972
16973 VMXVEXITINFO ExitInfo;
16974 RT_ZERO(ExitInfo);
16975 ExitInfo.uReason = pVmxTransient->uExitReason;
16976 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
16977 ExitInfo.u64Qual = pVmxTransient->uExitQual;
16978 ExitInfo.InstrInfo = pVmxTransient->ExitInstrInfo;
16979 return IEMExecVmxVmexitInstrWithInfo(pVCpu, &ExitInfo);
16980}
16981
16982/** @} */
16983#endif /* VBOX_WITH_NESTED_HWVIRT_VMX */
16984
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