VirtualBox

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

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

VMM/HM: bugref:9546 Fix registering of the longjmp callback to be soon after enabling VT-x/AMD-V on the CPU. This gives us proper behavior when ring-0 assertions happen prior to VMXR0RunGuestCode/SVMR0RunGuestCode so we can relinquish hardware resources on the way out.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 702.4 KB
Line 
1/* $Id: HMVMXR0.cpp 80587 2019-09-04 17:44:20Z 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 -> VMXR0CallRing3Callback()
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 VMXR0CallRing3Callback() 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 VMXR0CallRing3Callback() 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) and deregistering the longjmp-to-ring-3 callback. */
8013 int rc = HMR0LeaveCpu(pVCpu);
8014 HM_RESTORE_PREEMPT();
8015 return rc;
8016}
8017
8018
8019/**
8020 * Does the necessary state syncing before doing a longjmp to ring-3.
8021 *
8022 * @returns VBox status code.
8023 * @param pVCpu The cross context virtual CPU structure.
8024 *
8025 * @remarks No-long-jmp zone!!!
8026 */
8027DECLINLINE(int) hmR0VmxLongJmpToRing3(PVMCPUCC pVCpu)
8028{
8029 return hmR0VmxLeaveSession(pVCpu);
8030}
8031
8032
8033/**
8034 * Take necessary actions before going back to ring-3.
8035 *
8036 * An action requires us to go back to ring-3. This function does the necessary
8037 * steps before we can safely return to ring-3. This is not the same as longjmps
8038 * to ring-3, this is voluntary and prepares the guest so it may continue
8039 * executing outside HM (recompiler/IEM).
8040 *
8041 * @returns VBox status code.
8042 * @param pVCpu The cross context virtual CPU structure.
8043 * @param rcExit The reason for exiting to ring-3. Can be
8044 * VINF_VMM_UNKNOWN_RING3_CALL.
8045 */
8046static int hmR0VmxExitToRing3(PVMCPUCC pVCpu, VBOXSTRICTRC rcExit)
8047{
8048 HMVMX_ASSERT_PREEMPT_SAFE(pVCpu);
8049
8050 PVMXVMCSINFO pVmcsInfo = hmGetVmxActiveVmcsInfo(pVCpu);
8051 if (RT_UNLIKELY(rcExit == VERR_VMX_INVALID_VMCS_PTR))
8052 {
8053 VMXGetCurrentVmcs(&pVCpu->hm.s.vmx.LastError.HCPhysCurrentVmcs);
8054 pVCpu->hm.s.vmx.LastError.u32VmcsRev = *(uint32_t *)pVmcsInfo->pvVmcs;
8055 pVCpu->hm.s.vmx.LastError.idEnteredCpu = pVCpu->hm.s.idEnteredCpu;
8056 /* LastError.idCurrentCpu was updated in hmR0VmxPreRunGuestCommitted(). */
8057 }
8058
8059 /* Please, no longjumps here (any logging shouldn't flush jump back to ring-3). NO LOGGING BEFORE THIS POINT! */
8060 VMMRZCallRing3Disable(pVCpu);
8061 Log4Func(("rcExit=%d\n", VBOXSTRICTRC_VAL(rcExit)));
8062
8063 /*
8064 * Convert any pending HM events back to TRPM due to premature exits to ring-3.
8065 * We need to do this only on returns to ring-3 and not for longjmps to ring3.
8066 *
8067 * This is because execution may continue from ring-3 and we would need to inject
8068 * the event from there (hence place it back in TRPM).
8069 */
8070 if (pVCpu->hm.s.Event.fPending)
8071 {
8072 hmR0VmxPendingEventToTrpmTrap(pVCpu);
8073 Assert(!pVCpu->hm.s.Event.fPending);
8074
8075 /* Clear the events from the VMCS. */
8076 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_ENTRY_INTERRUPTION_INFO, 0);
8077 AssertRC(rc);
8078 }
8079#ifdef VBOX_STRICT
8080 else
8081 {
8082 /*
8083 * Ensure we don't accidentally clear a pending HM event without clearing the VMCS.
8084 * This can be pretty hard to debug otherwise, interrupts might get injected twice
8085 * occasionally, see @bugref{9180#c42}.
8086 *
8087 * However, if the VM-entry failed, any VM entry-interruption info. field would
8088 * be left unmodified as the event would not have been injected to the guest. In
8089 * such cases, don't assert, we're not going to continue guest execution anyway.
8090 */
8091 uint32_t uExitReason;
8092 uint32_t uEntryIntInfo;
8093 int rc = VMXReadVmcs32(VMX_VMCS32_RO_EXIT_REASON, &uExitReason);
8094 rc |= VMXReadVmcs32(VMX_VMCS32_CTRL_ENTRY_INTERRUPTION_INFO, &uEntryIntInfo);
8095 AssertRC(rc);
8096 Assert(VMX_EXIT_REASON_HAS_ENTRY_FAILED(uExitReason) || !VMX_ENTRY_INT_INFO_IS_VALID(uEntryIntInfo));
8097 }
8098#endif
8099
8100 /*
8101 * Clear the interrupt-window and NMI-window VMCS controls as we could have got
8102 * a VM-exit with higher priority than interrupt-window or NMI-window VM-exits
8103 * (e.g. TPR below threshold).
8104 */
8105 if (!CPUMIsGuestInVmxNonRootMode(&pVCpu->cpum.GstCtx))
8106 {
8107 hmR0VmxClearIntWindowExitVmcs(pVmcsInfo);
8108 hmR0VmxClearNmiWindowExitVmcs(pVmcsInfo);
8109 }
8110
8111 /* If we're emulating an instruction, we shouldn't have any TRPM traps pending
8112 and if we're injecting an event we should have a TRPM trap pending. */
8113 AssertMsg(rcExit != VINF_EM_RAW_INJECT_TRPM_EVENT || TRPMHasTrap(pVCpu), ("%Rrc\n", VBOXSTRICTRC_VAL(rcExit)));
8114#ifndef DEBUG_bird /* Triggered after firing an NMI against NT4SP1, possibly a triple fault in progress. */
8115 AssertMsg(rcExit != VINF_EM_RAW_EMULATE_INSTR || !TRPMHasTrap(pVCpu), ("%Rrc\n", VBOXSTRICTRC_VAL(rcExit)));
8116#endif
8117
8118 /* Save guest state and restore host state bits. */
8119 int rc = hmR0VmxLeaveSession(pVCpu);
8120 AssertRCReturn(rc, rc);
8121 STAM_COUNTER_DEC(&pVCpu->hm.s.StatSwitchLongJmpToR3);
8122
8123 /* Thread-context hooks are unregistered at this point!!! */
8124 /* Ring-3 callback notifications 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 VMMRZCallRing3Enable(pVCpu);
8153 return rc;
8154}
8155
8156
8157/**
8158 * VMMRZCallRing3() callback wrapper which saves the guest state before we
8159 * longjump to ring-3 and possibly get preempted.
8160 *
8161 * @returns VBox status code.
8162 * @param pVCpu The cross context virtual CPU structure.
8163 * @param enmOperation The operation causing the ring-3 longjump.
8164 */
8165VMMR0DECL(int) VMXR0CallRing3Callback(PVMCPUCC pVCpu, VMMCALLRING3 enmOperation)
8166{
8167 if (enmOperation == VMMCALLRING3_VM_R0_ASSERTION)
8168 {
8169 /*
8170 * !!! IMPORTANT !!!
8171 * If you modify code here, check whether hmR0VmxLeave() and hmR0VmxLeaveSession() needs to be updated too.
8172 * This is a stripped down version which gets out ASAP, trying to not trigger any further assertions.
8173 */
8174 VMMRZCallRing3RemoveNotification(pVCpu);
8175 VMMRZCallRing3Disable(pVCpu);
8176 HM_DISABLE_PREEMPT(pVCpu);
8177
8178 PVMXVMCSINFO pVmcsInfo = hmGetVmxActiveVmcsInfo(pVCpu);
8179 hmR0VmxImportGuestState(pVCpu, pVmcsInfo, HMVMX_CPUMCTX_EXTRN_ALL);
8180 CPUMR0FpuStateMaybeSaveGuestAndRestoreHost(pVCpu);
8181 CPUMR0DebugStateMaybeSaveGuestAndRestoreHost(pVCpu, true /* save DR6 */);
8182
8183 /* Restore host-state bits that VT-x only restores partially. */
8184 if ( (pVCpu->hm.s.vmx.fRestoreHostFlags & VMX_RESTORE_HOST_REQUIRED)
8185 && (pVCpu->hm.s.vmx.fRestoreHostFlags & ~VMX_RESTORE_HOST_REQUIRED))
8186 VMXRestoreHostState(pVCpu->hm.s.vmx.fRestoreHostFlags, &pVCpu->hm.s.vmx.RestoreHost);
8187 pVCpu->hm.s.vmx.fRestoreHostFlags = 0;
8188
8189 /* Restore the lazy host MSRs as we're leaving VT-x context. */
8190 if (pVCpu->hm.s.vmx.fLazyMsrs & VMX_LAZY_MSRS_LOADED_GUEST)
8191 hmR0VmxLazyRestoreHostMsrs(pVCpu);
8192
8193 /* Update auto-load/store host MSRs values when we re-enter VT-x (as we could be on a different CPU). */
8194 pVCpu->hm.s.vmx.fUpdatedHostAutoMsrs = false;
8195 VMCPU_CMPXCHG_STATE(pVCpu, VMCPUSTATE_STARTED_HM, VMCPUSTATE_STARTED_EXEC);
8196
8197 /* Clear the current VMCS data back to memory (shadow VMCS if any would have been
8198 cleared as part of importing the guest state above. */
8199 hmR0VmxClearVmcs(pVmcsInfo);
8200
8201 /** @todo eliminate the need for calling VMMR0ThreadCtxHookDisable here! */
8202 VMMR0ThreadCtxHookDisable(pVCpu);
8203
8204 /* Leave HM context. This takes care of local init (term). */
8205 HMR0LeaveCpu(pVCpu);
8206 HM_RESTORE_PREEMPT();
8207 return VINF_SUCCESS;
8208 }
8209
8210 Assert(pVCpu);
8211 Assert(VMMRZCallRing3IsEnabled(pVCpu));
8212 HMVMX_ASSERT_PREEMPT_SAFE(pVCpu);
8213
8214 VMMRZCallRing3Disable(pVCpu);
8215 Assert(VMMR0IsLogFlushDisabled(pVCpu));
8216
8217 Log4Func(("-> hmR0VmxLongJmpToRing3 enmOperation=%d\n", enmOperation));
8218
8219 int rc = hmR0VmxLongJmpToRing3(pVCpu);
8220 AssertRCReturn(rc, rc);
8221
8222 VMMRZCallRing3Enable(pVCpu);
8223 return VINF_SUCCESS;
8224}
8225
8226
8227/**
8228 * Pushes a 2-byte value onto the real-mode (in virtual-8086 mode) guest's
8229 * stack.
8230 *
8231 * @returns Strict VBox status code (i.e. informational status codes too).
8232 * @retval VINF_EM_RESET if pushing a value to the stack caused a triple-fault.
8233 * @param pVCpu The cross context virtual CPU structure.
8234 * @param uValue The value to push to the guest stack.
8235 */
8236static VBOXSTRICTRC hmR0VmxRealModeGuestStackPush(PVMCPUCC pVCpu, uint16_t uValue)
8237{
8238 /*
8239 * The stack limit is 0xffff in real-on-virtual 8086 mode. Real-mode with weird stack limits cannot be run in
8240 * virtual 8086 mode in VT-x. See Intel spec. 26.3.1.2 "Checks on Guest Segment Registers".
8241 * See Intel Instruction reference for PUSH and Intel spec. 22.33.1 "Segment Wraparound".
8242 */
8243 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
8244 if (pCtx->sp == 1)
8245 return VINF_EM_RESET;
8246 pCtx->sp -= sizeof(uint16_t); /* May wrap around which is expected behaviour. */
8247 int rc = PGMPhysSimpleWriteGCPhys(pVCpu->CTX_SUFF(pVM), pCtx->ss.u64Base + pCtx->sp, &uValue, sizeof(uint16_t));
8248 AssertRC(rc);
8249 return rc;
8250}
8251
8252
8253/**
8254 * Injects an event into the guest upon VM-entry by updating the relevant fields
8255 * in the VM-entry area in the VMCS.
8256 *
8257 * @returns Strict VBox status code (i.e. informational status codes too).
8258 * @retval VINF_SUCCESS if the event is successfully injected into the VMCS.
8259 * @retval VINF_EM_RESET if event injection resulted in a triple-fault.
8260 *
8261 * @param pVCpu The cross context virtual CPU structure.
8262 * @param pVmxTransient The VMX-transient structure.
8263 * @param pEvent The event being injected.
8264 * @param pfIntrState Pointer to the VT-x guest-interruptibility-state. This
8265 * will be updated if necessary. This cannot not be NULL.
8266 * @param fStepping Whether we're single-stepping guest execution and should
8267 * return VINF_EM_DBG_STEPPED if the event is injected
8268 * directly (registers modified by us, not by hardware on
8269 * VM-entry).
8270 */
8271static VBOXSTRICTRC hmR0VmxInjectEventVmcs(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient, PCHMEVENT pEvent, bool fStepping,
8272 uint32_t *pfIntrState)
8273{
8274 /* Intel spec. 24.8.3 "VM-Entry Controls for Event Injection" specifies the interruption-information field to be 32-bits. */
8275 AssertMsg(!RT_HI_U32(pEvent->u64IntInfo), ("%#RX64\n", pEvent->u64IntInfo));
8276 Assert(pfIntrState);
8277
8278 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
8279 uint32_t u32IntInfo = pEvent->u64IntInfo;
8280 uint32_t const u32ErrCode = pEvent->u32ErrCode;
8281 uint32_t const cbInstr = pEvent->cbInstr;
8282 RTGCUINTPTR const GCPtrFault = pEvent->GCPtrFaultAddress;
8283 uint8_t const uVector = VMX_ENTRY_INT_INFO_VECTOR(u32IntInfo);
8284 uint32_t const uIntType = VMX_ENTRY_INT_INFO_TYPE(u32IntInfo);
8285
8286#ifdef VBOX_STRICT
8287 /*
8288 * Validate the error-code-valid bit for hardware exceptions.
8289 * No error codes for exceptions in real-mode.
8290 *
8291 * See Intel spec. 20.1.4 "Interrupt and Exception Handling"
8292 */
8293 if ( uIntType == VMX_EXIT_INT_INFO_TYPE_HW_XCPT
8294 && !CPUMIsGuestInRealModeEx(pCtx))
8295 {
8296 switch (uVector)
8297 {
8298 case X86_XCPT_PF:
8299 case X86_XCPT_DF:
8300 case X86_XCPT_TS:
8301 case X86_XCPT_NP:
8302 case X86_XCPT_SS:
8303 case X86_XCPT_GP:
8304 case X86_XCPT_AC:
8305 AssertMsg(VMX_ENTRY_INT_INFO_IS_ERROR_CODE_VALID(u32IntInfo),
8306 ("Error-code-valid bit not set for exception that has an error code uVector=%#x\n", uVector));
8307 RT_FALL_THRU();
8308 default:
8309 break;
8310 }
8311 }
8312
8313 /* Cannot inject an NMI when block-by-MOV SS is in effect. */
8314 Assert( uIntType != VMX_EXIT_INT_INFO_TYPE_NMI
8315 || !(*pfIntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_MOVSS));
8316#endif
8317
8318 STAM_COUNTER_INC(&pVCpu->hm.s.paStatInjectedIrqsR0[uVector & MASK_INJECT_IRQ_STAT]);
8319
8320 /*
8321 * Hardware interrupts & exceptions cannot be delivered through the software interrupt
8322 * redirection bitmap to the real mode task in virtual-8086 mode. We must jump to the
8323 * interrupt handler in the (real-mode) guest.
8324 *
8325 * See Intel spec. 20.3 "Interrupt and Exception handling in Virtual-8086 Mode".
8326 * See Intel spec. 20.1.4 "Interrupt and Exception Handling" for real-mode interrupt handling.
8327 */
8328 if (CPUMIsGuestInRealModeEx(pCtx)) /* CR0.PE bit changes are always intercepted, so it's up to date. */
8329 {
8330 if (pVCpu->CTX_SUFF(pVM)->hm.s.vmx.fUnrestrictedGuest)
8331 {
8332 /*
8333 * For CPUs with unrestricted guest execution enabled and with the guest
8334 * in real-mode, we must not set the deliver-error-code bit.
8335 *
8336 * See Intel spec. 26.2.1.3 "VM-Entry Control Fields".
8337 */
8338 u32IntInfo &= ~VMX_ENTRY_INT_INFO_ERROR_CODE_VALID;
8339 }
8340 else
8341 {
8342 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
8343 Assert(PDMVmmDevHeapIsEnabled(pVM));
8344 Assert(pVM->hm.s.vmx.pRealModeTSS);
8345 Assert(!CPUMIsGuestInVmxNonRootMode(&pVCpu->cpum.GstCtx));
8346
8347 /* We require RIP, RSP, RFLAGS, CS, IDTR, import them. */
8348 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
8349 int rc2 = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, CPUMCTX_EXTRN_SREG_MASK | CPUMCTX_EXTRN_TABLE_MASK
8350 | CPUMCTX_EXTRN_RIP | CPUMCTX_EXTRN_RSP | CPUMCTX_EXTRN_RFLAGS);
8351 AssertRCReturn(rc2, rc2);
8352
8353 /* Check if the interrupt handler is present in the IVT (real-mode IDT). IDT limit is (4N - 1). */
8354 size_t const cbIdtEntry = sizeof(X86IDTR16);
8355 if (uVector * cbIdtEntry + (cbIdtEntry - 1) > pCtx->idtr.cbIdt)
8356 {
8357 /* If we are trying to inject a #DF with no valid IDT entry, return a triple-fault. */
8358 if (uVector == X86_XCPT_DF)
8359 return VINF_EM_RESET;
8360
8361 /* If we're injecting a #GP with no valid IDT entry, inject a double-fault.
8362 No error codes for exceptions in real-mode. */
8363 if (uVector == X86_XCPT_GP)
8364 {
8365 uint32_t const uXcptDfInfo = RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_VECTOR, X86_XCPT_DF)
8366 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_TYPE, VMX_ENTRY_INT_INFO_TYPE_HW_XCPT)
8367 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_ERR_CODE_VALID, 0)
8368 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_VALID, 1);
8369 HMEVENT EventXcptDf;
8370 RT_ZERO(EventXcptDf);
8371 EventXcptDf.u64IntInfo = uXcptDfInfo;
8372 return hmR0VmxInjectEventVmcs(pVCpu, pVmxTransient, &EventXcptDf, fStepping, pfIntrState);
8373 }
8374
8375 /*
8376 * If we're injecting an event with no valid IDT entry, inject a #GP.
8377 * No error codes for exceptions in real-mode.
8378 *
8379 * See Intel spec. 20.1.4 "Interrupt and Exception Handling"
8380 */
8381 uint32_t const uXcptGpInfo = RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_VECTOR, X86_XCPT_GP)
8382 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_TYPE, VMX_ENTRY_INT_INFO_TYPE_HW_XCPT)
8383 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_ERR_CODE_VALID, 0)
8384 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_VALID, 1);
8385 HMEVENT EventXcptGp;
8386 RT_ZERO(EventXcptGp);
8387 EventXcptGp.u64IntInfo = uXcptGpInfo;
8388 return hmR0VmxInjectEventVmcs(pVCpu, pVmxTransient, &EventXcptGp, fStepping, pfIntrState);
8389 }
8390
8391 /* Software exceptions (#BP and #OF exceptions thrown as a result of INT3 or INTO) */
8392 uint16_t uGuestIp = pCtx->ip;
8393 if (uIntType == VMX_ENTRY_INT_INFO_TYPE_SW_XCPT)
8394 {
8395 Assert(uVector == X86_XCPT_BP || uVector == X86_XCPT_OF);
8396 /* #BP and #OF are both benign traps, we need to resume the next instruction. */
8397 uGuestIp = pCtx->ip + (uint16_t)cbInstr;
8398 }
8399 else if (uIntType == VMX_ENTRY_INT_INFO_TYPE_SW_INT)
8400 uGuestIp = pCtx->ip + (uint16_t)cbInstr;
8401
8402 /* Get the code segment selector and offset from the IDT entry for the interrupt handler. */
8403 X86IDTR16 IdtEntry;
8404 RTGCPHYS const GCPhysIdtEntry = (RTGCPHYS)pCtx->idtr.pIdt + uVector * cbIdtEntry;
8405 rc2 = PGMPhysSimpleReadGCPhys(pVM, &IdtEntry, GCPhysIdtEntry, cbIdtEntry);
8406 AssertRCReturn(rc2, rc2);
8407
8408 /* Construct the stack frame for the interrupt/exception handler. */
8409 VBOXSTRICTRC rcStrict;
8410 rcStrict = hmR0VmxRealModeGuestStackPush(pVCpu, pCtx->eflags.u32);
8411 if (rcStrict == VINF_SUCCESS)
8412 {
8413 rcStrict = hmR0VmxRealModeGuestStackPush(pVCpu, pCtx->cs.Sel);
8414 if (rcStrict == VINF_SUCCESS)
8415 rcStrict = hmR0VmxRealModeGuestStackPush(pVCpu, uGuestIp);
8416 }
8417
8418 /* Clear the required eflag bits and jump to the interrupt/exception handler. */
8419 if (rcStrict == VINF_SUCCESS)
8420 {
8421 pCtx->eflags.u32 &= ~(X86_EFL_IF | X86_EFL_TF | X86_EFL_RF | X86_EFL_AC);
8422 pCtx->rip = IdtEntry.offSel;
8423 pCtx->cs.Sel = IdtEntry.uSel;
8424 pCtx->cs.ValidSel = IdtEntry.uSel;
8425 pCtx->cs.u64Base = IdtEntry.uSel << cbIdtEntry;
8426 if ( uIntType == VMX_ENTRY_INT_INFO_TYPE_HW_XCPT
8427 && uVector == X86_XCPT_PF)
8428 pCtx->cr2 = GCPtrFault;
8429
8430 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_CS | HM_CHANGED_GUEST_CR2
8431 | HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS
8432 | HM_CHANGED_GUEST_RSP);
8433
8434 /*
8435 * If we delivered a hardware exception (other than an NMI) and if there was
8436 * block-by-STI in effect, we should clear it.
8437 */
8438 if (*pfIntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_STI)
8439 {
8440 Assert( uIntType != VMX_ENTRY_INT_INFO_TYPE_NMI
8441 && uIntType != VMX_ENTRY_INT_INFO_TYPE_EXT_INT);
8442 Log4Func(("Clearing inhibition due to STI\n"));
8443 *pfIntrState &= ~VMX_VMCS_GUEST_INT_STATE_BLOCK_STI;
8444 }
8445
8446 Log4(("Injected real-mode: u32IntInfo=%#x u32ErrCode=%#x cbInstr=%#x Eflags=%#x CS:EIP=%04x:%04x\n",
8447 u32IntInfo, u32ErrCode, cbInstr, pCtx->eflags.u, pCtx->cs.Sel, pCtx->eip));
8448
8449 /*
8450 * The event has been truly dispatched to the guest. Mark it as no longer pending so
8451 * we don't attempt to undo it if we are returning to ring-3 before executing guest code.
8452 */
8453 pVCpu->hm.s.Event.fPending = false;
8454
8455 /*
8456 * If we eventually support nested-guest execution without unrestricted guest execution,
8457 * we should set fInterceptEvents here.
8458 */
8459 Assert(!pVmxTransient->fIsNestedGuest);
8460
8461 /* If we're stepping and we've changed cs:rip above, bail out of the VMX R0 execution loop. */
8462 if (fStepping)
8463 rcStrict = VINF_EM_DBG_STEPPED;
8464 }
8465 AssertMsg(rcStrict == VINF_SUCCESS || rcStrict == VINF_EM_RESET || (rcStrict == VINF_EM_DBG_STEPPED && fStepping),
8466 ("%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
8467 return rcStrict;
8468 }
8469 }
8470
8471 /*
8472 * Validate.
8473 */
8474 Assert(VMX_ENTRY_INT_INFO_IS_VALID(u32IntInfo)); /* Bit 31 (Valid bit) must be set by caller. */
8475 Assert(!(u32IntInfo & VMX_BF_ENTRY_INT_INFO_RSVD_12_30_MASK)); /* Bits 30:12 MBZ. */
8476
8477 /*
8478 * Inject the event into the VMCS.
8479 */
8480 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_ENTRY_INTERRUPTION_INFO, u32IntInfo);
8481 if (VMX_ENTRY_INT_INFO_IS_ERROR_CODE_VALID(u32IntInfo))
8482 rc |= VMXWriteVmcs32(VMX_VMCS32_CTRL_ENTRY_EXCEPTION_ERRCODE, u32ErrCode);
8483 rc |= VMXWriteVmcs32(VMX_VMCS32_CTRL_ENTRY_INSTR_LENGTH, cbInstr);
8484 AssertRC(rc);
8485
8486 /*
8487 * Update guest CR2 if this is a page-fault.
8488 */
8489 if (VMX_ENTRY_INT_INFO_IS_XCPT_PF(u32IntInfo))
8490 pCtx->cr2 = GCPtrFault;
8491
8492 Log4(("Injecting u32IntInfo=%#x u32ErrCode=%#x cbInstr=%#x CR2=%#RX64\n", u32IntInfo, u32ErrCode, cbInstr, pCtx->cr2));
8493 return VINF_SUCCESS;
8494}
8495
8496
8497/**
8498 * Evaluates the event to be delivered to the guest and sets it as the pending
8499 * event.
8500 *
8501 * @returns Strict VBox status code (i.e. informational status codes too).
8502 * @param pVCpu The cross context virtual CPU structure.
8503 * @param pVmxTransient The VMX-transient structure.
8504 * @param pfIntrState Where to store the VT-x guest-interruptibility state.
8505 */
8506static VBOXSTRICTRC hmR0VmxEvaluatePendingEvent(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient, uint32_t *pfIntrState)
8507{
8508 Assert(pfIntrState);
8509 Assert(!TRPMHasTrap(pVCpu));
8510
8511 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
8512 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
8513 bool const fIsNestedGuest = pVmxTransient->fIsNestedGuest;
8514
8515 /*
8516 * Get the current interruptibility-state of the guest or nested-guest and
8517 * then figure out what needs to be injected.
8518 */
8519 uint32_t const fIntrState = hmR0VmxGetGuestIntrState(pVCpu, pVmxTransient);
8520 bool const fBlockMovSS = RT_BOOL(fIntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_MOVSS);
8521 bool const fBlockSti = RT_BOOL(fIntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_STI);
8522 bool const fBlockNmi = RT_BOOL(fIntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_NMI);
8523
8524 /* We don't support block-by-SMI yet.*/
8525 Assert(!(fIntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_SMI));
8526
8527 /* Block-by-STI must not be set when interrupts are disabled. */
8528 if (fBlockSti)
8529 {
8530 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_RFLAGS);
8531 Assert(pCtx->eflags.Bits.u1IF);
8532 }
8533
8534 /* Update interruptibility state to the caller. */
8535 *pfIntrState = fIntrState;
8536
8537 /*
8538 * Toggling of interrupt force-flags here is safe since we update TRPM on
8539 * premature exits to ring-3 before executing guest code, see hmR0VmxExitToRing3().
8540 * We must NOT restore these force-flags.
8541 */
8542
8543 /** @todo SMI. SMIs take priority over NMIs. */
8544
8545 /*
8546 * Check if an NMI is pending and if the guest or nested-guest can receive them.
8547 * NMIs take priority over external interrupts.
8548 */
8549 if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_INTERRUPT_NMI))
8550 {
8551 /* On some CPUs block-by-STI also blocks NMIs. See Intel spec. 26.3.1.5 "Checks On Guest Non-Register State". */
8552 if ( !pVCpu->hm.s.Event.fPending
8553 && !fBlockNmi
8554 && !fBlockSti
8555 && !fBlockMovSS)
8556 {
8557#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
8558 if ( fIsNestedGuest
8559 && CPUMIsGuestVmxPinCtlsSet(pVCpu, pCtx, VMX_PIN_CTLS_NMI_EXIT))
8560 return IEMExecVmxVmexitXcptNmi(pVCpu);
8561#endif
8562 hmR0VmxSetPendingXcptNmi(pVCpu);
8563 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INTERRUPT_NMI);
8564 Log4Func(("Pending NMI\n"));
8565 }
8566 else if (!fIsNestedGuest)
8567 hmR0VmxSetNmiWindowExitVmcs(pVCpu, pVmcsInfo);
8568 /* else: for nested-guests, NMI-window exiting will be picked up when merging VMCS controls. */
8569 }
8570 /*
8571 * Check if an external interrupt (PIC/APIC) is pending and if the guest or nested-guest
8572 * can receive them. Once PDMGetInterrupt() returns a valid interrupt we -must- deliver
8573 * the interrupt. We can no longer re-request it from the APIC.
8574 */
8575 else if ( VMCPU_FF_IS_ANY_SET(pVCpu, VMCPU_FF_INTERRUPT_APIC | VMCPU_FF_INTERRUPT_PIC)
8576 && !pVCpu->hm.s.fSingleInstruction)
8577 {
8578 Assert(!DBGFIsStepping(pVCpu));
8579 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, CPUMCTX_EXTRN_RFLAGS);
8580 AssertRCReturn(rc, rc);
8581
8582 bool const fBlockInt = !(pCtx->eflags.u32 & X86_EFL_IF);
8583 if ( !pVCpu->hm.s.Event.fPending
8584 && !fBlockInt
8585 && !fBlockSti
8586 && !fBlockMovSS)
8587 {
8588#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
8589 if ( fIsNestedGuest
8590 && CPUMIsGuestVmxPinCtlsSet(pVCpu, pCtx, VMX_PIN_CTLS_EXT_INT_EXIT)
8591 && !CPUMIsGuestVmxExitCtlsSet(pVCpu, pCtx, VMX_EXIT_CTLS_ACK_EXT_INT))
8592 {
8593 VBOXSTRICTRC rcStrict = IEMExecVmxVmexitExtInt(pVCpu, 0 /* uVector */, true /* fIntPending */);
8594 Assert(rcStrict != VINF_VMX_INTERCEPT_NOT_ACTIVE);
8595 return rcStrict;
8596 }
8597#endif
8598 uint8_t u8Interrupt;
8599 rc = PDMGetInterrupt(pVCpu, &u8Interrupt);
8600 if (RT_SUCCESS(rc))
8601 {
8602#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
8603 if ( fIsNestedGuest
8604 && CPUMIsGuestVmxPinCtlsSet(pVCpu, pCtx, VMX_PIN_CTLS_EXT_INT_EXIT)
8605 && CPUMIsGuestVmxExitCtlsSet(pVCpu, pCtx, VMX_EXIT_CTLS_ACK_EXT_INT))
8606 {
8607 VBOXSTRICTRC rcStrict = IEMExecVmxVmexitExtInt(pVCpu, u8Interrupt, false /* fIntPending */);
8608 Assert(rcStrict != VINF_VMX_INTERCEPT_NOT_ACTIVE);
8609 return rcStrict;
8610 }
8611#endif
8612 hmR0VmxSetPendingExtInt(pVCpu, u8Interrupt);
8613 Log4Func(("Pending external interrupt vector %#x\n", u8Interrupt));
8614 }
8615 else if (rc == VERR_APIC_INTR_MASKED_BY_TPR)
8616 {
8617 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchTprMaskedIrq);
8618
8619 if ( !fIsNestedGuest
8620 && (pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_USE_TPR_SHADOW))
8621 hmR0VmxApicSetTprThreshold(pVmcsInfo, u8Interrupt >> 4);
8622 /* else: for nested-guests, TPR threshold is picked up while merging VMCS controls. */
8623
8624 /*
8625 * If the CPU doesn't have TPR shadowing, we will always get a VM-exit on TPR changes and
8626 * APICSetTpr() will end up setting the VMCPU_FF_INTERRUPT_APIC if required, so there is no
8627 * need to re-set this force-flag here.
8628 */
8629 }
8630 else
8631 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchGuestIrq);
8632 }
8633 else if (!fIsNestedGuest)
8634 hmR0VmxSetIntWindowExitVmcs(pVCpu, pVmcsInfo);
8635 /* else: for nested-guests, interrupt-window exiting will be picked up when merging VMCS controls. */
8636 }
8637
8638 return VINF_SUCCESS;
8639}
8640
8641
8642/**
8643 * Injects any pending events into the guest if the guest is in a state to
8644 * receive them.
8645 *
8646 * @returns Strict VBox status code (i.e. informational status codes too).
8647 * @param pVCpu The cross context virtual CPU structure.
8648 * @param pVmxTransient The VMX-transient structure.
8649 * @param fIntrState The VT-x guest-interruptibility state.
8650 * @param fStepping Whether we are single-stepping the guest using the
8651 * hypervisor debugger and should return
8652 * VINF_EM_DBG_STEPPED if the event was dispatched
8653 * directly.
8654 */
8655static VBOXSTRICTRC hmR0VmxInjectPendingEvent(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient, uint32_t fIntrState, bool fStepping)
8656{
8657 HMVMX_ASSERT_PREEMPT_SAFE(pVCpu);
8658 Assert(VMMRZCallRing3IsEnabled(pVCpu));
8659
8660 bool const fBlockMovSS = RT_BOOL(fIntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_MOVSS);
8661 bool const fBlockSti = RT_BOOL(fIntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_STI);
8662
8663 Assert(!fBlockSti || !(ASMAtomicUoReadU64(&pVCpu->cpum.GstCtx.fExtrn) & CPUMCTX_EXTRN_RFLAGS));
8664 Assert(!fBlockSti || pVCpu->cpum.GstCtx.eflags.Bits.u1IF); /* Cannot set block-by-STI when interrupts are disabled. */
8665 Assert(!(fIntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_SMI)); /* We don't support block-by-SMI yet.*/
8666 Assert(!TRPMHasTrap(pVCpu));
8667
8668 VBOXSTRICTRC rcStrict = VINF_SUCCESS;
8669 if (pVCpu->hm.s.Event.fPending)
8670 {
8671 /*
8672 * Do -not- clear any interrupt-window exiting control here. We might have an interrupt
8673 * pending even while injecting an event and in this case, we want a VM-exit as soon as
8674 * the guest is ready for the next interrupt, see @bugref{6208#c45}.
8675 *
8676 * See Intel spec. 26.6.5 "Interrupt-Window Exiting and Virtual-Interrupt Delivery".
8677 */
8678 uint32_t const uIntType = VMX_ENTRY_INT_INFO_TYPE(pVCpu->hm.s.Event.u64IntInfo);
8679#ifdef VBOX_STRICT
8680 if (uIntType == VMX_ENTRY_INT_INFO_TYPE_EXT_INT)
8681 {
8682 bool const fBlockInt = !(pVCpu->cpum.GstCtx.eflags.u32 & X86_EFL_IF);
8683 Assert(!fBlockInt);
8684 Assert(!fBlockSti);
8685 Assert(!fBlockMovSS);
8686 }
8687 else if (uIntType == VMX_ENTRY_INT_INFO_TYPE_NMI)
8688 {
8689 bool const fBlockNmi = RT_BOOL(fIntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_NMI);
8690 Assert(!fBlockSti);
8691 Assert(!fBlockMovSS);
8692 Assert(!fBlockNmi);
8693 }
8694#endif
8695 Log4(("Injecting pending event vcpu[%RU32] u64IntInfo=%#RX64 Type=%#RX32\n", pVCpu->idCpu, pVCpu->hm.s.Event.u64IntInfo,
8696 uIntType));
8697
8698 /*
8699 * Inject the event and get any changes to the guest-interruptibility state.
8700 *
8701 * The guest-interruptibility state may need to be updated if we inject the event
8702 * into the guest IDT ourselves (for real-on-v86 guest injecting software interrupts).
8703 */
8704 rcStrict = hmR0VmxInjectEventVmcs(pVCpu, pVmxTransient, &pVCpu->hm.s.Event, fStepping, &fIntrState);
8705 AssertRCReturn(VBOXSTRICTRC_VAL(rcStrict), rcStrict);
8706
8707 if (uIntType == VMX_ENTRY_INT_INFO_TYPE_EXT_INT)
8708 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectInterrupt);
8709 else
8710 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectXcpt);
8711 }
8712
8713 /*
8714 * Update the guest-interruptibility state.
8715 *
8716 * This is required for the real-on-v86 software interrupt injection case above, as well as
8717 * updates to the guest state from ring-3 or IEM/REM.
8718 */
8719 int rc = VMXWriteVmcs32(VMX_VMCS32_GUEST_INT_STATE, fIntrState);
8720 AssertRC(rc);
8721
8722 /*
8723 * There's no need to clear the VM-entry interruption-information field here if we're not
8724 * injecting anything. VT-x clears the valid bit on every VM-exit.
8725 *
8726 * See Intel spec. 24.8.3 "VM-Entry Controls for Event Injection".
8727 */
8728
8729 Assert(rcStrict == VINF_SUCCESS || rcStrict == VINF_EM_RESET || (rcStrict == VINF_EM_DBG_STEPPED && fStepping));
8730 NOREF(fBlockMovSS); NOREF(fBlockSti);
8731 return rcStrict;
8732}
8733
8734
8735/**
8736 * Enters the VT-x session.
8737 *
8738 * @returns VBox status code.
8739 * @param pVCpu The cross context virtual CPU structure.
8740 */
8741VMMR0DECL(int) VMXR0Enter(PVMCPUCC pVCpu)
8742{
8743 AssertPtr(pVCpu);
8744 Assert(pVCpu->CTX_SUFF(pVM)->hm.s.vmx.fSupported);
8745 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
8746
8747 LogFlowFunc(("pVCpu=%p\n", pVCpu));
8748 Assert((pVCpu->hm.s.fCtxChanged & (HM_CHANGED_HOST_CONTEXT | HM_CHANGED_VMX_HOST_GUEST_SHARED_STATE))
8749 == (HM_CHANGED_HOST_CONTEXT | HM_CHANGED_VMX_HOST_GUEST_SHARED_STATE));
8750
8751#ifdef VBOX_STRICT
8752 /* At least verify VMX is enabled, since we can't check if we're in VMX root mode without #GP'ing. */
8753 RTCCUINTREG uHostCr4 = ASMGetCR4();
8754 if (!(uHostCr4 & X86_CR4_VMXE))
8755 {
8756 LogRelFunc(("X86_CR4_VMXE bit in CR4 is not set!\n"));
8757 return VERR_VMX_X86_CR4_VMXE_CLEARED;
8758 }
8759#endif
8760
8761 /*
8762 * Load the appropriate VMCS as the current and active one.
8763 */
8764 PVMXVMCSINFO pVmcsInfo;
8765 bool const fInNestedGuestMode = CPUMIsGuestInVmxNonRootMode(&pVCpu->cpum.GstCtx);
8766 if (!fInNestedGuestMode)
8767 pVmcsInfo = &pVCpu->hm.s.vmx.VmcsInfo;
8768 else
8769 pVmcsInfo = &pVCpu->hm.s.vmx.VmcsInfoNstGst;
8770 int rc = hmR0VmxLoadVmcs(pVmcsInfo);
8771 if (RT_SUCCESS(rc))
8772 {
8773 pVCpu->hm.s.vmx.fSwitchedToNstGstVmcs = fInNestedGuestMode;
8774 pVCpu->hm.s.fLeaveDone = false;
8775 Log4Func(("Loaded Vmcs. HostCpuId=%u\n", RTMpCpuId()));
8776
8777 /*
8778 * Do the EMT scheduled L1D flush here if needed.
8779 */
8780 if (pVCpu->CTX_SUFF(pVM)->hm.s.fL1dFlushOnSched)
8781 ASMWrMsr(MSR_IA32_FLUSH_CMD, MSR_IA32_FLUSH_CMD_F_L1D);
8782 else if (pVCpu->CTX_SUFF(pVM)->hm.s.fMdsClearOnSched)
8783 hmR0MdsClear();
8784 }
8785 return rc;
8786}
8787
8788
8789/**
8790 * The thread-context callback (only on platforms which support it).
8791 *
8792 * @param enmEvent The thread-context event.
8793 * @param pVCpu The cross context virtual CPU structure.
8794 * @param fGlobalInit Whether global VT-x/AMD-V init. was used.
8795 * @thread EMT(pVCpu)
8796 */
8797VMMR0DECL(void) VMXR0ThreadCtxCallback(RTTHREADCTXEVENT enmEvent, PVMCPUCC pVCpu, bool fGlobalInit)
8798{
8799 AssertPtr(pVCpu);
8800 RT_NOREF1(fGlobalInit);
8801
8802 switch (enmEvent)
8803 {
8804 case RTTHREADCTXEVENT_OUT:
8805 {
8806 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
8807 Assert(VMMR0ThreadCtxHookIsEnabled(pVCpu));
8808 VMCPU_ASSERT_EMT(pVCpu);
8809
8810 /* No longjmps (logger flushes, locks) in this fragile context. */
8811 VMMRZCallRing3Disable(pVCpu);
8812 Log4Func(("Preempting: HostCpuId=%u\n", RTMpCpuId()));
8813
8814 /* Restore host-state (FPU, debug etc.) */
8815 if (!pVCpu->hm.s.fLeaveDone)
8816 {
8817 /*
8818 * Do -not- import the guest-state here as we might already be in the middle of importing
8819 * it, esp. bad if we're holding the PGM lock, see comment in hmR0VmxImportGuestState().
8820 */
8821 hmR0VmxLeave(pVCpu, false /* fImportState */);
8822 pVCpu->hm.s.fLeaveDone = true;
8823 }
8824
8825 /* Leave HM context, takes care of local init (term). */
8826 int rc = HMR0LeaveCpu(pVCpu);
8827 AssertRC(rc);
8828
8829 /* Restore longjmp state. */
8830 VMMRZCallRing3Enable(pVCpu);
8831 STAM_REL_COUNTER_INC(&pVCpu->hm.s.StatSwitchPreempt);
8832 break;
8833 }
8834
8835 case RTTHREADCTXEVENT_IN:
8836 {
8837 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
8838 Assert(VMMR0ThreadCtxHookIsEnabled(pVCpu));
8839 VMCPU_ASSERT_EMT(pVCpu);
8840
8841 /* No longjmps here, as we don't want to trigger preemption (& its hook) while resuming. */
8842 VMMRZCallRing3Disable(pVCpu);
8843 Log4Func(("Resumed: HostCpuId=%u\n", RTMpCpuId()));
8844
8845 /* Initialize the bare minimum state required for HM. This takes care of
8846 initializing VT-x if necessary (onlined CPUs, local init etc.) */
8847 int rc = hmR0EnterCpu(pVCpu);
8848 AssertRC(rc);
8849 Assert( (pVCpu->hm.s.fCtxChanged & (HM_CHANGED_HOST_CONTEXT | HM_CHANGED_VMX_HOST_GUEST_SHARED_STATE))
8850 == (HM_CHANGED_HOST_CONTEXT | HM_CHANGED_VMX_HOST_GUEST_SHARED_STATE));
8851
8852 /* Load the active VMCS as the current one. */
8853 PVMXVMCSINFO pVmcsInfo = hmGetVmxActiveVmcsInfo(pVCpu);
8854 rc = hmR0VmxLoadVmcs(pVmcsInfo);
8855 AssertRC(rc);
8856 Log4Func(("Resumed: Loaded Vmcs. HostCpuId=%u\n", RTMpCpuId()));
8857 pVCpu->hm.s.fLeaveDone = false;
8858
8859 /* Do the EMT scheduled L1D flush if needed. */
8860 if (pVCpu->CTX_SUFF(pVM)->hm.s.fL1dFlushOnSched)
8861 ASMWrMsr(MSR_IA32_FLUSH_CMD, MSR_IA32_FLUSH_CMD_F_L1D);
8862
8863 /* Restore longjmp state. */
8864 VMMRZCallRing3Enable(pVCpu);
8865 break;
8866 }
8867
8868 default:
8869 break;
8870 }
8871}
8872
8873
8874/**
8875 * Exports the host state into the VMCS host-state area.
8876 * Sets up the VM-exit MSR-load area.
8877 *
8878 * The CPU state will be loaded from these fields on every successful VM-exit.
8879 *
8880 * @returns VBox status code.
8881 * @param pVCpu The cross context virtual CPU structure.
8882 *
8883 * @remarks No-long-jump zone!!!
8884 */
8885static int hmR0VmxExportHostState(PVMCPUCC pVCpu)
8886{
8887 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
8888
8889 int rc = VINF_SUCCESS;
8890 if (pVCpu->hm.s.fCtxChanged & HM_CHANGED_HOST_CONTEXT)
8891 {
8892 hmR0VmxExportHostControlRegs();
8893
8894 rc = hmR0VmxExportHostSegmentRegs(pVCpu);
8895 AssertLogRelMsgRCReturn(rc, ("rc=%Rrc\n", rc), rc);
8896
8897 hmR0VmxExportHostMsrs(pVCpu);
8898
8899 pVCpu->hm.s.fCtxChanged &= ~HM_CHANGED_HOST_CONTEXT;
8900 }
8901 return rc;
8902}
8903
8904
8905/**
8906 * Saves the host state in the VMCS host-state.
8907 *
8908 * @returns VBox status code.
8909 * @param pVCpu The cross context virtual CPU structure.
8910 *
8911 * @remarks No-long-jump zone!!!
8912 */
8913VMMR0DECL(int) VMXR0ExportHostState(PVMCPUCC pVCpu)
8914{
8915 AssertPtr(pVCpu);
8916 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
8917
8918 /*
8919 * Export the host state here while entering HM context.
8920 * When thread-context hooks are used, we might get preempted and have to re-save the host
8921 * state but most of the time we won't be, so do it here before we disable interrupts.
8922 */
8923 return hmR0VmxExportHostState(pVCpu);
8924}
8925
8926
8927/**
8928 * Exports the guest state into the VMCS guest-state area.
8929 *
8930 * The will typically be done before VM-entry when the guest-CPU state and the
8931 * VMCS state may potentially be out of sync.
8932 *
8933 * Sets up the VM-entry MSR-load and VM-exit MSR-store areas. Sets up the
8934 * VM-entry controls.
8935 * Sets up the appropriate VMX non-root function to execute guest code based on
8936 * the guest CPU mode.
8937 *
8938 * @returns VBox strict status code.
8939 * @retval VINF_EM_RESCHEDULE_REM if we try to emulate non-paged guest code
8940 * without unrestricted guest execution and the VMMDev is not presently
8941 * mapped (e.g. EFI32).
8942 *
8943 * @param pVCpu The cross context virtual CPU structure.
8944 * @param pVmxTransient The VMX-transient structure.
8945 *
8946 * @remarks No-long-jump zone!!!
8947 */
8948static VBOXSTRICTRC hmR0VmxExportGuestState(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
8949{
8950 AssertPtr(pVCpu);
8951 HMVMX_ASSERT_PREEMPT_SAFE(pVCpu);
8952 LogFlowFunc(("pVCpu=%p\n", pVCpu));
8953
8954 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatExportGuestState, x);
8955
8956 /*
8957 * Determine real-on-v86 mode.
8958 * Used when the guest is in real-mode and unrestricted guest execution is not used.
8959 */
8960 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
8961 if ( pVCpu->CTX_SUFF(pVM)->hm.s.vmx.fUnrestrictedGuest
8962 || !CPUMIsGuestInRealModeEx(&pVCpu->cpum.GstCtx))
8963 pVmcsInfo->RealMode. fRealOnV86Active = false;
8964 else
8965 {
8966 Assert(!pVmxTransient->fIsNestedGuest);
8967 pVmcsInfo->RealMode.fRealOnV86Active = true;
8968 }
8969
8970 /*
8971 * Any ordering dependency among the sub-functions below must be explicitly stated using comments.
8972 * Ideally, assert that the cross-dependent bits are up-to-date at the point of using it.
8973 */
8974 /** @todo r=ramshankar: Move hmR0VmxSelectVMRunHandler inside
8975 * hmR0VmxExportGuestEntryExitCtls and do it conditionally. There shouldn't
8976 * be a need to evaluate this everytime since I'm pretty sure we intercept
8977 * all guest paging mode changes. */
8978 int rc = hmR0VmxSelectVMRunHandler(pVCpu, pVmxTransient);
8979 AssertLogRelMsgRCReturn(rc, ("rc=%Rrc\n", rc), rc);
8980
8981 rc = hmR0VmxExportGuestEntryExitCtls(pVCpu, pVmxTransient);
8982 AssertLogRelMsgRCReturn(rc, ("rc=%Rrc\n", rc), rc);
8983
8984 rc = hmR0VmxExportGuestCR0(pVCpu, pVmxTransient);
8985 AssertLogRelMsgRCReturn(rc, ("rc=%Rrc\n", rc), rc);
8986
8987 VBOXSTRICTRC rcStrict = hmR0VmxExportGuestCR3AndCR4(pVCpu, pVmxTransient);
8988 if (rcStrict == VINF_SUCCESS)
8989 { /* likely */ }
8990 else
8991 {
8992 Assert(rcStrict == VINF_EM_RESCHEDULE_REM || RT_FAILURE_NP(rcStrict));
8993 return rcStrict;
8994 }
8995
8996 rc = hmR0VmxExportGuestSegRegsXdtr(pVCpu, pVmxTransient);
8997 AssertLogRelMsgRCReturn(rc, ("rc=%Rrc\n", rc), rc);
8998
8999 rc = hmR0VmxExportGuestMsrs(pVCpu, pVmxTransient);
9000 AssertLogRelMsgRCReturn(rc, ("rc=%Rrc\n", rc), rc);
9001
9002 rc = hmR0VmxExportGuestApicTpr(pVCpu, pVmxTransient);
9003 AssertLogRelMsgRCReturn(rc, ("rc=%Rrc\n", rc), rc);
9004
9005 rc = hmR0VmxExportGuestXcptIntercepts(pVCpu, pVmxTransient);
9006 AssertLogRelMsgRCReturn(rc, ("rc=%Rrc\n", rc), rc);
9007
9008 rc = hmR0VmxExportGuestRip(pVCpu);
9009 rc |= hmR0VmxExportGuestRsp(pVCpu);
9010 rc |= hmR0VmxExportGuestRflags(pVCpu, pVmxTransient);
9011 AssertLogRelMsgRCReturn(rc, ("rc=%Rrc\n", rc), rc);
9012
9013 rc = hmR0VmxExportGuestHwvirtState(pVCpu, pVmxTransient);
9014 AssertLogRelMsgRCReturn(rc, ("rc=%Rrc\n", rc), rc);
9015
9016 /* Clear any bits that may be set but exported unconditionally or unused/reserved bits. */
9017 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~( (HM_CHANGED_GUEST_GPRS_MASK & ~HM_CHANGED_GUEST_RSP)
9018 | HM_CHANGED_GUEST_CR2
9019 | (HM_CHANGED_GUEST_DR_MASK & ~HM_CHANGED_GUEST_DR7)
9020 | HM_CHANGED_GUEST_X87
9021 | HM_CHANGED_GUEST_SSE_AVX
9022 | HM_CHANGED_GUEST_OTHER_XSAVE
9023 | HM_CHANGED_GUEST_XCRx
9024 | HM_CHANGED_GUEST_KERNEL_GS_BASE /* Part of lazy or auto load-store MSRs. */
9025 | HM_CHANGED_GUEST_SYSCALL_MSRS /* Part of lazy or auto load-store MSRs. */
9026 | HM_CHANGED_GUEST_TSC_AUX
9027 | HM_CHANGED_GUEST_OTHER_MSRS
9028 | (HM_CHANGED_KEEPER_STATE_MASK & ~HM_CHANGED_VMX_MASK)));
9029
9030 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExportGuestState, x);
9031 return rc;
9032}
9033
9034
9035/**
9036 * Exports the state shared between the host and guest into the VMCS.
9037 *
9038 * @param pVCpu The cross context virtual CPU structure.
9039 * @param pVmxTransient The VMX-transient structure.
9040 *
9041 * @remarks No-long-jump zone!!!
9042 */
9043static void hmR0VmxExportSharedState(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
9044{
9045 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
9046 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
9047
9048 if (pVCpu->hm.s.fCtxChanged & HM_CHANGED_GUEST_DR_MASK)
9049 {
9050 int rc = hmR0VmxExportSharedDebugState(pVCpu, pVmxTransient);
9051 AssertRC(rc);
9052 pVCpu->hm.s.fCtxChanged &= ~HM_CHANGED_GUEST_DR_MASK;
9053
9054 /* Loading shared debug bits might have changed eflags.TF bit for debugging purposes. */
9055 if (pVCpu->hm.s.fCtxChanged & HM_CHANGED_GUEST_RFLAGS)
9056 {
9057 rc = hmR0VmxExportGuestRflags(pVCpu, pVmxTransient);
9058 AssertRC(rc);
9059 }
9060 }
9061
9062 if (pVCpu->hm.s.fCtxChanged & HM_CHANGED_VMX_GUEST_LAZY_MSRS)
9063 {
9064 hmR0VmxLazyLoadGuestMsrs(pVCpu);
9065 pVCpu->hm.s.fCtxChanged &= ~HM_CHANGED_VMX_GUEST_LAZY_MSRS;
9066 }
9067
9068 AssertMsg(!(pVCpu->hm.s.fCtxChanged & HM_CHANGED_VMX_HOST_GUEST_SHARED_STATE),
9069 ("fCtxChanged=%#RX64\n", pVCpu->hm.s.fCtxChanged));
9070}
9071
9072
9073/**
9074 * Worker for loading the guest-state bits in the inner VT-x execution loop.
9075 *
9076 * @returns Strict VBox status code (i.e. informational status codes too).
9077 * @retval VINF_EM_RESCHEDULE_REM if we try to emulate non-paged guest code
9078 * without unrestricted guest execution and the VMMDev is not presently
9079 * mapped (e.g. EFI32).
9080 *
9081 * @param pVCpu The cross context virtual CPU structure.
9082 * @param pVmxTransient The VMX-transient structure.
9083 *
9084 * @remarks No-long-jump zone!!!
9085 */
9086static VBOXSTRICTRC hmR0VmxExportGuestStateOptimal(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
9087{
9088 HMVMX_ASSERT_PREEMPT_SAFE(pVCpu);
9089 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
9090 Assert(VMMR0IsLogFlushDisabled(pVCpu));
9091
9092#ifdef HMVMX_ALWAYS_SYNC_FULL_GUEST_STATE
9093 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_ALL_GUEST);
9094#endif
9095
9096 /*
9097 * For many exits it's only RIP that changes and hence try to export it first
9098 * without going through a lot of change flag checks.
9099 */
9100 VBOXSTRICTRC rcStrict;
9101 uint64_t fCtxChanged = ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged);
9102 RT_UNTRUSTED_NONVOLATILE_COPY_FENCE();
9103 if ((fCtxChanged & (HM_CHANGED_ALL_GUEST & ~HM_CHANGED_VMX_HOST_GUEST_SHARED_STATE)) == HM_CHANGED_GUEST_RIP)
9104 {
9105 rcStrict = hmR0VmxExportGuestRip(pVCpu);
9106 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
9107 { /* likely */}
9108 else
9109 AssertMsgFailedReturn(("Failed to export guest RIP! rc=%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)), rcStrict);
9110 STAM_COUNTER_INC(&pVCpu->hm.s.StatExportMinimal);
9111 }
9112 else if (fCtxChanged & (HM_CHANGED_ALL_GUEST & ~HM_CHANGED_VMX_HOST_GUEST_SHARED_STATE))
9113 {
9114 rcStrict = hmR0VmxExportGuestState(pVCpu, pVmxTransient);
9115 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
9116 { /* likely */}
9117 else
9118 {
9119 AssertMsg(rcStrict == VINF_EM_RESCHEDULE_REM, ("Failed to export guest state! rc=%Rrc\n",
9120 VBOXSTRICTRC_VAL(rcStrict)));
9121 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
9122 return rcStrict;
9123 }
9124 STAM_COUNTER_INC(&pVCpu->hm.s.StatExportFull);
9125 }
9126 else
9127 rcStrict = VINF_SUCCESS;
9128
9129#ifdef VBOX_STRICT
9130 /* All the guest state bits should be loaded except maybe the host context and/or the shared host/guest bits. */
9131 fCtxChanged = ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged);
9132 RT_UNTRUSTED_NONVOLATILE_COPY_FENCE();
9133 AssertMsg(!(fCtxChanged & (HM_CHANGED_ALL_GUEST & ~HM_CHANGED_VMX_HOST_GUEST_SHARED_STATE)),
9134 ("fCtxChanged=%#RX64\n", fCtxChanged));
9135#endif
9136 return rcStrict;
9137}
9138
9139
9140/**
9141 * Tries to determine what part of the guest-state VT-x has deemed as invalid
9142 * and update error record fields accordingly.
9143 *
9144 * @returns VMX_IGS_* error codes.
9145 * @retval VMX_IGS_REASON_NOT_FOUND if this function could not find anything
9146 * wrong with the guest state.
9147 *
9148 * @param pVCpu The cross context virtual CPU structure.
9149 * @param pVmcsInfo The VMCS info. object.
9150 *
9151 * @remarks This function assumes our cache of the VMCS controls
9152 * are valid, i.e. hmR0VmxCheckVmcsCtls() succeeded.
9153 */
9154static uint32_t hmR0VmxCheckGuestState(PVMCPUCC pVCpu, PCVMXVMCSINFO pVmcsInfo)
9155{
9156#define HMVMX_ERROR_BREAK(err) { uError = (err); break; }
9157#define HMVMX_CHECK_BREAK(expr, err) do { \
9158 if (!(expr)) { uError = (err); break; } \
9159 } while (0)
9160
9161 int rc;
9162 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
9163 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
9164 uint32_t uError = VMX_IGS_ERROR;
9165 uint32_t u32Val;
9166 bool const fUnrestrictedGuest = pVM->hm.s.vmx.fUnrestrictedGuest;
9167
9168 do
9169 {
9170 /*
9171 * CR0.
9172 */
9173 /** @todo Why do we need to OR and AND the fixed-0 and fixed-1 bits below? */
9174 uint64_t fSetCr0 = (pVM->hm.s.vmx.Msrs.u64Cr0Fixed0 & pVM->hm.s.vmx.Msrs.u64Cr0Fixed1);
9175 uint64_t const fZapCr0 = (pVM->hm.s.vmx.Msrs.u64Cr0Fixed0 | pVM->hm.s.vmx.Msrs.u64Cr0Fixed1);
9176 /* Exceptions for unrestricted guest execution for fixed CR0 bits (PE, PG).
9177 See Intel spec. 26.3.1 "Checks on Guest Control Registers, Debug Registers and MSRs." */
9178 if (fUnrestrictedGuest)
9179 fSetCr0 &= ~(uint64_t)(X86_CR0_PE | X86_CR0_PG);
9180
9181 uint64_t u64GuestCr0;
9182 rc = VMXReadVmcsNw(VMX_VMCS_GUEST_CR0, &u64GuestCr0);
9183 AssertRC(rc);
9184 HMVMX_CHECK_BREAK((u64GuestCr0 & fSetCr0) == fSetCr0, VMX_IGS_CR0_FIXED1);
9185 HMVMX_CHECK_BREAK(!(u64GuestCr0 & ~fZapCr0), VMX_IGS_CR0_FIXED0);
9186 if ( !fUnrestrictedGuest
9187 && (u64GuestCr0 & X86_CR0_PG)
9188 && !(u64GuestCr0 & X86_CR0_PE))
9189 {
9190 HMVMX_ERROR_BREAK(VMX_IGS_CR0_PG_PE_COMBO);
9191 }
9192
9193 /*
9194 * CR4.
9195 */
9196 /** @todo Why do we need to OR and AND the fixed-0 and fixed-1 bits below? */
9197 uint64_t const fSetCr4 = (pVM->hm.s.vmx.Msrs.u64Cr4Fixed0 & pVM->hm.s.vmx.Msrs.u64Cr4Fixed1);
9198 uint64_t const fZapCr4 = (pVM->hm.s.vmx.Msrs.u64Cr4Fixed0 | pVM->hm.s.vmx.Msrs.u64Cr4Fixed1);
9199
9200 uint64_t u64GuestCr4;
9201 rc = VMXReadVmcsNw(VMX_VMCS_GUEST_CR4, &u64GuestCr4);
9202 AssertRC(rc);
9203 HMVMX_CHECK_BREAK((u64GuestCr4 & fSetCr4) == fSetCr4, VMX_IGS_CR4_FIXED1);
9204 HMVMX_CHECK_BREAK(!(u64GuestCr4 & ~fZapCr4), VMX_IGS_CR4_FIXED0);
9205
9206 /*
9207 * IA32_DEBUGCTL MSR.
9208 */
9209 uint64_t u64Val;
9210 rc = VMXReadVmcs64(VMX_VMCS64_GUEST_DEBUGCTL_FULL, &u64Val);
9211 AssertRC(rc);
9212 if ( (pVmcsInfo->u32EntryCtls & VMX_ENTRY_CTLS_LOAD_DEBUG)
9213 && (u64Val & 0xfffffe3c)) /* Bits 31:9, bits 5:2 MBZ. */
9214 {
9215 HMVMX_ERROR_BREAK(VMX_IGS_DEBUGCTL_MSR_RESERVED);
9216 }
9217 uint64_t u64DebugCtlMsr = u64Val;
9218
9219#ifdef VBOX_STRICT
9220 rc = VMXReadVmcs32(VMX_VMCS32_CTRL_ENTRY, &u32Val);
9221 AssertRC(rc);
9222 Assert(u32Val == pVmcsInfo->u32EntryCtls);
9223#endif
9224 bool const fLongModeGuest = RT_BOOL(pVmcsInfo->u32EntryCtls & VMX_ENTRY_CTLS_IA32E_MODE_GUEST);
9225
9226 /*
9227 * RIP and RFLAGS.
9228 */
9229 rc = VMXReadVmcsNw(VMX_VMCS_GUEST_RIP, &u64Val);
9230 AssertRC(rc);
9231 /* pCtx->rip can be different than the one in the VMCS (e.g. run guest code and VM-exits that don't update it). */
9232 if ( !fLongModeGuest
9233 || !pCtx->cs.Attr.n.u1Long)
9234 {
9235 HMVMX_CHECK_BREAK(!(u64Val & UINT64_C(0xffffffff00000000)), VMX_IGS_LONGMODE_RIP_INVALID);
9236 }
9237 /** @todo If the processor supports N < 64 linear-address bits, bits 63:N
9238 * must be identical if the "IA-32e mode guest" VM-entry
9239 * control is 1 and CS.L is 1. No check applies if the
9240 * CPU supports 64 linear-address bits. */
9241
9242 /* Flags in pCtx can be different (real-on-v86 for instance). We are only concerned about the VMCS contents here. */
9243 rc = VMXReadVmcsNw(VMX_VMCS_GUEST_RFLAGS, &u64Val);
9244 AssertRC(rc);
9245 HMVMX_CHECK_BREAK(!(u64Val & UINT64_C(0xffffffffffc08028)), /* Bit 63:22, Bit 15, 5, 3 MBZ. */
9246 VMX_IGS_RFLAGS_RESERVED);
9247 HMVMX_CHECK_BREAK((u64Val & X86_EFL_RA1_MASK), VMX_IGS_RFLAGS_RESERVED1); /* Bit 1 MB1. */
9248 uint32_t const u32Eflags = u64Val;
9249
9250 if ( fLongModeGuest
9251 || ( fUnrestrictedGuest
9252 && !(u64GuestCr0 & X86_CR0_PE)))
9253 {
9254 HMVMX_CHECK_BREAK(!(u32Eflags & X86_EFL_VM), VMX_IGS_RFLAGS_VM_INVALID);
9255 }
9256
9257 uint32_t u32EntryInfo;
9258 rc = VMXReadVmcs32(VMX_VMCS32_CTRL_ENTRY_INTERRUPTION_INFO, &u32EntryInfo);
9259 AssertRC(rc);
9260 if (VMX_ENTRY_INT_INFO_IS_EXT_INT(u32EntryInfo))
9261 HMVMX_CHECK_BREAK(u32Eflags & X86_EFL_IF, VMX_IGS_RFLAGS_IF_INVALID);
9262
9263 /*
9264 * 64-bit checks.
9265 */
9266 if (fLongModeGuest)
9267 {
9268 HMVMX_CHECK_BREAK(u64GuestCr0 & X86_CR0_PG, VMX_IGS_CR0_PG_LONGMODE);
9269 HMVMX_CHECK_BREAK(u64GuestCr4 & X86_CR4_PAE, VMX_IGS_CR4_PAE_LONGMODE);
9270 }
9271
9272 if ( !fLongModeGuest
9273 && (u64GuestCr4 & X86_CR4_PCIDE))
9274 {
9275 HMVMX_ERROR_BREAK(VMX_IGS_CR4_PCIDE);
9276 }
9277
9278 /** @todo CR3 field must be such that bits 63:52 and bits in the range
9279 * 51:32 beyond the processor's physical-address width are 0. */
9280
9281 if ( (pVmcsInfo->u32EntryCtls & VMX_ENTRY_CTLS_LOAD_DEBUG)
9282 && (pCtx->dr[7] & X86_DR7_MBZ_MASK))
9283 {
9284 HMVMX_ERROR_BREAK(VMX_IGS_DR7_RESERVED);
9285 }
9286
9287 rc = VMXReadVmcsNw(VMX_VMCS_HOST_SYSENTER_ESP, &u64Val);
9288 AssertRC(rc);
9289 HMVMX_CHECK_BREAK(X86_IS_CANONICAL(u64Val), VMX_IGS_SYSENTER_ESP_NOT_CANONICAL);
9290
9291 rc = VMXReadVmcsNw(VMX_VMCS_HOST_SYSENTER_EIP, &u64Val);
9292 AssertRC(rc);
9293 HMVMX_CHECK_BREAK(X86_IS_CANONICAL(u64Val), VMX_IGS_SYSENTER_EIP_NOT_CANONICAL);
9294
9295 /*
9296 * PERF_GLOBAL MSR.
9297 */
9298 if (pVmcsInfo->u32EntryCtls & VMX_ENTRY_CTLS_LOAD_PERF_MSR)
9299 {
9300 rc = VMXReadVmcs64(VMX_VMCS64_GUEST_PERF_GLOBAL_CTRL_FULL, &u64Val);
9301 AssertRC(rc);
9302 HMVMX_CHECK_BREAK(!(u64Val & UINT64_C(0xfffffff8fffffffc)),
9303 VMX_IGS_PERF_GLOBAL_MSR_RESERVED); /* Bits 63:35, bits 31:2 MBZ. */
9304 }
9305
9306 /*
9307 * PAT MSR.
9308 */
9309 if (pVmcsInfo->u32EntryCtls & VMX_ENTRY_CTLS_LOAD_PAT_MSR)
9310 {
9311 rc = VMXReadVmcs64(VMX_VMCS64_GUEST_PAT_FULL, &u64Val);
9312 AssertRC(rc);
9313 HMVMX_CHECK_BREAK(!(u64Val & UINT64_C(0x707070707070707)), VMX_IGS_PAT_MSR_RESERVED);
9314 for (unsigned i = 0; i < 8; i++)
9315 {
9316 uint8_t u8Val = (u64Val & 0xff);
9317 if ( u8Val != 0 /* UC */
9318 && u8Val != 1 /* WC */
9319 && u8Val != 4 /* WT */
9320 && u8Val != 5 /* WP */
9321 && u8Val != 6 /* WB */
9322 && u8Val != 7 /* UC- */)
9323 {
9324 HMVMX_ERROR_BREAK(VMX_IGS_PAT_MSR_INVALID);
9325 }
9326 u64Val >>= 8;
9327 }
9328 }
9329
9330 /*
9331 * EFER MSR.
9332 */
9333 if (pVmcsInfo->u32EntryCtls & VMX_ENTRY_CTLS_LOAD_EFER_MSR)
9334 {
9335 Assert(pVM->hm.s.vmx.fSupportsVmcsEfer);
9336 rc = VMXReadVmcs64(VMX_VMCS64_GUEST_EFER_FULL, &u64Val);
9337 AssertRC(rc);
9338 HMVMX_CHECK_BREAK(!(u64Val & UINT64_C(0xfffffffffffff2fe)),
9339 VMX_IGS_EFER_MSR_RESERVED); /* Bits 63:12, bit 9, bits 7:1 MBZ. */
9340 HMVMX_CHECK_BREAK(RT_BOOL(u64Val & MSR_K6_EFER_LMA) == RT_BOOL( pVmcsInfo->u32EntryCtls
9341 & VMX_ENTRY_CTLS_IA32E_MODE_GUEST),
9342 VMX_IGS_EFER_LMA_GUEST_MODE_MISMATCH);
9343 /** @todo r=ramshankar: Unrestricted check here is probably wrong, see
9344 * iemVmxVmentryCheckGuestState(). */
9345 HMVMX_CHECK_BREAK( fUnrestrictedGuest
9346 || !(u64GuestCr0 & X86_CR0_PG)
9347 || RT_BOOL(u64Val & MSR_K6_EFER_LMA) == RT_BOOL(u64Val & MSR_K6_EFER_LME),
9348 VMX_IGS_EFER_LMA_LME_MISMATCH);
9349 }
9350
9351 /*
9352 * Segment registers.
9353 */
9354 HMVMX_CHECK_BREAK( (pCtx->ldtr.Attr.u & X86DESCATTR_UNUSABLE)
9355 || !(pCtx->ldtr.Sel & X86_SEL_LDT), VMX_IGS_LDTR_TI_INVALID);
9356 if (!(u32Eflags & X86_EFL_VM))
9357 {
9358 /* CS */
9359 HMVMX_CHECK_BREAK(pCtx->cs.Attr.n.u1Present, VMX_IGS_CS_ATTR_P_INVALID);
9360 HMVMX_CHECK_BREAK(!(pCtx->cs.Attr.u & 0xf00), VMX_IGS_CS_ATTR_RESERVED);
9361 HMVMX_CHECK_BREAK(!(pCtx->cs.Attr.u & 0xfffe0000), VMX_IGS_CS_ATTR_RESERVED);
9362 HMVMX_CHECK_BREAK( (pCtx->cs.u32Limit & 0xfff) == 0xfff
9363 || !(pCtx->cs.Attr.n.u1Granularity), VMX_IGS_CS_ATTR_G_INVALID);
9364 HMVMX_CHECK_BREAK( !(pCtx->cs.u32Limit & 0xfff00000)
9365 || (pCtx->cs.Attr.n.u1Granularity), VMX_IGS_CS_ATTR_G_INVALID);
9366 /* CS cannot be loaded with NULL in protected mode. */
9367 HMVMX_CHECK_BREAK(pCtx->cs.Attr.u && !(pCtx->cs.Attr.u & X86DESCATTR_UNUSABLE), VMX_IGS_CS_ATTR_UNUSABLE);
9368 HMVMX_CHECK_BREAK(pCtx->cs.Attr.n.u1DescType, VMX_IGS_CS_ATTR_S_INVALID);
9369 if (pCtx->cs.Attr.n.u4Type == 9 || pCtx->cs.Attr.n.u4Type == 11)
9370 HMVMX_CHECK_BREAK(pCtx->cs.Attr.n.u2Dpl == pCtx->ss.Attr.n.u2Dpl, VMX_IGS_CS_SS_ATTR_DPL_UNEQUAL);
9371 else if (pCtx->cs.Attr.n.u4Type == 13 || pCtx->cs.Attr.n.u4Type == 15)
9372 HMVMX_CHECK_BREAK(pCtx->cs.Attr.n.u2Dpl <= pCtx->ss.Attr.n.u2Dpl, VMX_IGS_CS_SS_ATTR_DPL_MISMATCH);
9373 else if (pVM->hm.s.vmx.fUnrestrictedGuest && pCtx->cs.Attr.n.u4Type == 3)
9374 HMVMX_CHECK_BREAK(pCtx->cs.Attr.n.u2Dpl == 0, VMX_IGS_CS_ATTR_DPL_INVALID);
9375 else
9376 HMVMX_ERROR_BREAK(VMX_IGS_CS_ATTR_TYPE_INVALID);
9377
9378 /* SS */
9379 HMVMX_CHECK_BREAK( pVM->hm.s.vmx.fUnrestrictedGuest
9380 || (pCtx->ss.Sel & X86_SEL_RPL) == (pCtx->cs.Sel & X86_SEL_RPL), VMX_IGS_SS_CS_RPL_UNEQUAL);
9381 HMVMX_CHECK_BREAK(pCtx->ss.Attr.n.u2Dpl == (pCtx->ss.Sel & X86_SEL_RPL), VMX_IGS_SS_ATTR_DPL_RPL_UNEQUAL);
9382 if ( !(pCtx->cr0 & X86_CR0_PE)
9383 || pCtx->cs.Attr.n.u4Type == 3)
9384 {
9385 HMVMX_CHECK_BREAK(!pCtx->ss.Attr.n.u2Dpl, VMX_IGS_SS_ATTR_DPL_INVALID);
9386 }
9387 if (!(pCtx->ss.Attr.u & X86DESCATTR_UNUSABLE))
9388 {
9389 HMVMX_CHECK_BREAK(pCtx->ss.Attr.n.u4Type == 3 || pCtx->ss.Attr.n.u4Type == 7, VMX_IGS_SS_ATTR_TYPE_INVALID);
9390 HMVMX_CHECK_BREAK(pCtx->ss.Attr.n.u1Present, VMX_IGS_SS_ATTR_P_INVALID);
9391 HMVMX_CHECK_BREAK(!(pCtx->ss.Attr.u & 0xf00), VMX_IGS_SS_ATTR_RESERVED);
9392 HMVMX_CHECK_BREAK(!(pCtx->ss.Attr.u & 0xfffe0000), VMX_IGS_SS_ATTR_RESERVED);
9393 HMVMX_CHECK_BREAK( (pCtx->ss.u32Limit & 0xfff) == 0xfff
9394 || !(pCtx->ss.Attr.n.u1Granularity), VMX_IGS_SS_ATTR_G_INVALID);
9395 HMVMX_CHECK_BREAK( !(pCtx->ss.u32Limit & 0xfff00000)
9396 || (pCtx->ss.Attr.n.u1Granularity), VMX_IGS_SS_ATTR_G_INVALID);
9397 }
9398
9399 /* DS, ES, FS, GS - only check for usable selectors, see hmR0VmxExportGuestSReg(). */
9400 if (!(pCtx->ds.Attr.u & X86DESCATTR_UNUSABLE))
9401 {
9402 HMVMX_CHECK_BREAK(pCtx->ds.Attr.n.u4Type & X86_SEL_TYPE_ACCESSED, VMX_IGS_DS_ATTR_A_INVALID);
9403 HMVMX_CHECK_BREAK(pCtx->ds.Attr.n.u1Present, VMX_IGS_DS_ATTR_P_INVALID);
9404 HMVMX_CHECK_BREAK( pVM->hm.s.vmx.fUnrestrictedGuest
9405 || pCtx->ds.Attr.n.u4Type > 11
9406 || pCtx->ds.Attr.n.u2Dpl >= (pCtx->ds.Sel & X86_SEL_RPL), VMX_IGS_DS_ATTR_DPL_RPL_UNEQUAL);
9407 HMVMX_CHECK_BREAK(!(pCtx->ds.Attr.u & 0xf00), VMX_IGS_DS_ATTR_RESERVED);
9408 HMVMX_CHECK_BREAK(!(pCtx->ds.Attr.u & 0xfffe0000), VMX_IGS_DS_ATTR_RESERVED);
9409 HMVMX_CHECK_BREAK( (pCtx->ds.u32Limit & 0xfff) == 0xfff
9410 || !(pCtx->ds.Attr.n.u1Granularity), VMX_IGS_DS_ATTR_G_INVALID);
9411 HMVMX_CHECK_BREAK( !(pCtx->ds.u32Limit & 0xfff00000)
9412 || (pCtx->ds.Attr.n.u1Granularity), VMX_IGS_DS_ATTR_G_INVALID);
9413 HMVMX_CHECK_BREAK( !(pCtx->ds.Attr.n.u4Type & X86_SEL_TYPE_CODE)
9414 || (pCtx->ds.Attr.n.u4Type & X86_SEL_TYPE_READ), VMX_IGS_DS_ATTR_TYPE_INVALID);
9415 }
9416 if (!(pCtx->es.Attr.u & X86DESCATTR_UNUSABLE))
9417 {
9418 HMVMX_CHECK_BREAK(pCtx->es.Attr.n.u4Type & X86_SEL_TYPE_ACCESSED, VMX_IGS_ES_ATTR_A_INVALID);
9419 HMVMX_CHECK_BREAK(pCtx->es.Attr.n.u1Present, VMX_IGS_ES_ATTR_P_INVALID);
9420 HMVMX_CHECK_BREAK( pVM->hm.s.vmx.fUnrestrictedGuest
9421 || pCtx->es.Attr.n.u4Type > 11
9422 || pCtx->es.Attr.n.u2Dpl >= (pCtx->es.Sel & X86_SEL_RPL), VMX_IGS_DS_ATTR_DPL_RPL_UNEQUAL);
9423 HMVMX_CHECK_BREAK(!(pCtx->es.Attr.u & 0xf00), VMX_IGS_ES_ATTR_RESERVED);
9424 HMVMX_CHECK_BREAK(!(pCtx->es.Attr.u & 0xfffe0000), VMX_IGS_ES_ATTR_RESERVED);
9425 HMVMX_CHECK_BREAK( (pCtx->es.u32Limit & 0xfff) == 0xfff
9426 || !(pCtx->es.Attr.n.u1Granularity), VMX_IGS_ES_ATTR_G_INVALID);
9427 HMVMX_CHECK_BREAK( !(pCtx->es.u32Limit & 0xfff00000)
9428 || (pCtx->es.Attr.n.u1Granularity), VMX_IGS_ES_ATTR_G_INVALID);
9429 HMVMX_CHECK_BREAK( !(pCtx->es.Attr.n.u4Type & X86_SEL_TYPE_CODE)
9430 || (pCtx->es.Attr.n.u4Type & X86_SEL_TYPE_READ), VMX_IGS_ES_ATTR_TYPE_INVALID);
9431 }
9432 if (!(pCtx->fs.Attr.u & X86DESCATTR_UNUSABLE))
9433 {
9434 HMVMX_CHECK_BREAK(pCtx->fs.Attr.n.u4Type & X86_SEL_TYPE_ACCESSED, VMX_IGS_FS_ATTR_A_INVALID);
9435 HMVMX_CHECK_BREAK(pCtx->fs.Attr.n.u1Present, VMX_IGS_FS_ATTR_P_INVALID);
9436 HMVMX_CHECK_BREAK( pVM->hm.s.vmx.fUnrestrictedGuest
9437 || pCtx->fs.Attr.n.u4Type > 11
9438 || pCtx->fs.Attr.n.u2Dpl >= (pCtx->fs.Sel & X86_SEL_RPL), VMX_IGS_FS_ATTR_DPL_RPL_UNEQUAL);
9439 HMVMX_CHECK_BREAK(!(pCtx->fs.Attr.u & 0xf00), VMX_IGS_FS_ATTR_RESERVED);
9440 HMVMX_CHECK_BREAK(!(pCtx->fs.Attr.u & 0xfffe0000), VMX_IGS_FS_ATTR_RESERVED);
9441 HMVMX_CHECK_BREAK( (pCtx->fs.u32Limit & 0xfff) == 0xfff
9442 || !(pCtx->fs.Attr.n.u1Granularity), VMX_IGS_FS_ATTR_G_INVALID);
9443 HMVMX_CHECK_BREAK( !(pCtx->fs.u32Limit & 0xfff00000)
9444 || (pCtx->fs.Attr.n.u1Granularity), VMX_IGS_FS_ATTR_G_INVALID);
9445 HMVMX_CHECK_BREAK( !(pCtx->fs.Attr.n.u4Type & X86_SEL_TYPE_CODE)
9446 || (pCtx->fs.Attr.n.u4Type & X86_SEL_TYPE_READ), VMX_IGS_FS_ATTR_TYPE_INVALID);
9447 }
9448 if (!(pCtx->gs.Attr.u & X86DESCATTR_UNUSABLE))
9449 {
9450 HMVMX_CHECK_BREAK(pCtx->gs.Attr.n.u4Type & X86_SEL_TYPE_ACCESSED, VMX_IGS_GS_ATTR_A_INVALID);
9451 HMVMX_CHECK_BREAK(pCtx->gs.Attr.n.u1Present, VMX_IGS_GS_ATTR_P_INVALID);
9452 HMVMX_CHECK_BREAK( pVM->hm.s.vmx.fUnrestrictedGuest
9453 || pCtx->gs.Attr.n.u4Type > 11
9454 || pCtx->gs.Attr.n.u2Dpl >= (pCtx->gs.Sel & X86_SEL_RPL), VMX_IGS_GS_ATTR_DPL_RPL_UNEQUAL);
9455 HMVMX_CHECK_BREAK(!(pCtx->gs.Attr.u & 0xf00), VMX_IGS_GS_ATTR_RESERVED);
9456 HMVMX_CHECK_BREAK(!(pCtx->gs.Attr.u & 0xfffe0000), VMX_IGS_GS_ATTR_RESERVED);
9457 HMVMX_CHECK_BREAK( (pCtx->gs.u32Limit & 0xfff) == 0xfff
9458 || !(pCtx->gs.Attr.n.u1Granularity), VMX_IGS_GS_ATTR_G_INVALID);
9459 HMVMX_CHECK_BREAK( !(pCtx->gs.u32Limit & 0xfff00000)
9460 || (pCtx->gs.Attr.n.u1Granularity), VMX_IGS_GS_ATTR_G_INVALID);
9461 HMVMX_CHECK_BREAK( !(pCtx->gs.Attr.n.u4Type & X86_SEL_TYPE_CODE)
9462 || (pCtx->gs.Attr.n.u4Type & X86_SEL_TYPE_READ), VMX_IGS_GS_ATTR_TYPE_INVALID);
9463 }
9464 /* 64-bit capable CPUs. */
9465 HMVMX_CHECK_BREAK(X86_IS_CANONICAL(pCtx->fs.u64Base), VMX_IGS_FS_BASE_NOT_CANONICAL);
9466 HMVMX_CHECK_BREAK(X86_IS_CANONICAL(pCtx->gs.u64Base), VMX_IGS_GS_BASE_NOT_CANONICAL);
9467 HMVMX_CHECK_BREAK( (pCtx->ldtr.Attr.u & X86DESCATTR_UNUSABLE)
9468 || X86_IS_CANONICAL(pCtx->ldtr.u64Base), VMX_IGS_LDTR_BASE_NOT_CANONICAL);
9469 HMVMX_CHECK_BREAK(!RT_HI_U32(pCtx->cs.u64Base), VMX_IGS_LONGMODE_CS_BASE_INVALID);
9470 HMVMX_CHECK_BREAK((pCtx->ss.Attr.u & X86DESCATTR_UNUSABLE) || !RT_HI_U32(pCtx->ss.u64Base),
9471 VMX_IGS_LONGMODE_SS_BASE_INVALID);
9472 HMVMX_CHECK_BREAK((pCtx->ds.Attr.u & X86DESCATTR_UNUSABLE) || !RT_HI_U32(pCtx->ds.u64Base),
9473 VMX_IGS_LONGMODE_DS_BASE_INVALID);
9474 HMVMX_CHECK_BREAK((pCtx->es.Attr.u & X86DESCATTR_UNUSABLE) || !RT_HI_U32(pCtx->es.u64Base),
9475 VMX_IGS_LONGMODE_ES_BASE_INVALID);
9476 }
9477 else
9478 {
9479 /* V86 mode checks. */
9480 uint32_t u32CSAttr, u32SSAttr, u32DSAttr, u32ESAttr, u32FSAttr, u32GSAttr;
9481 if (pVmcsInfo->RealMode.fRealOnV86Active)
9482 {
9483 u32CSAttr = 0xf3; u32SSAttr = 0xf3;
9484 u32DSAttr = 0xf3; u32ESAttr = 0xf3;
9485 u32FSAttr = 0xf3; u32GSAttr = 0xf3;
9486 }
9487 else
9488 {
9489 u32CSAttr = pCtx->cs.Attr.u; u32SSAttr = pCtx->ss.Attr.u;
9490 u32DSAttr = pCtx->ds.Attr.u; u32ESAttr = pCtx->es.Attr.u;
9491 u32FSAttr = pCtx->fs.Attr.u; u32GSAttr = pCtx->gs.Attr.u;
9492 }
9493
9494 /* CS */
9495 HMVMX_CHECK_BREAK((pCtx->cs.u64Base == (uint64_t)pCtx->cs.Sel << 4), VMX_IGS_V86_CS_BASE_INVALID);
9496 HMVMX_CHECK_BREAK(pCtx->cs.u32Limit == 0xffff, VMX_IGS_V86_CS_LIMIT_INVALID);
9497 HMVMX_CHECK_BREAK(u32CSAttr == 0xf3, VMX_IGS_V86_CS_ATTR_INVALID);
9498 /* SS */
9499 HMVMX_CHECK_BREAK((pCtx->ss.u64Base == (uint64_t)pCtx->ss.Sel << 4), VMX_IGS_V86_SS_BASE_INVALID);
9500 HMVMX_CHECK_BREAK(pCtx->ss.u32Limit == 0xffff, VMX_IGS_V86_SS_LIMIT_INVALID);
9501 HMVMX_CHECK_BREAK(u32SSAttr == 0xf3, VMX_IGS_V86_SS_ATTR_INVALID);
9502 /* DS */
9503 HMVMX_CHECK_BREAK((pCtx->ds.u64Base == (uint64_t)pCtx->ds.Sel << 4), VMX_IGS_V86_DS_BASE_INVALID);
9504 HMVMX_CHECK_BREAK(pCtx->ds.u32Limit == 0xffff, VMX_IGS_V86_DS_LIMIT_INVALID);
9505 HMVMX_CHECK_BREAK(u32DSAttr == 0xf3, VMX_IGS_V86_DS_ATTR_INVALID);
9506 /* ES */
9507 HMVMX_CHECK_BREAK((pCtx->es.u64Base == (uint64_t)pCtx->es.Sel << 4), VMX_IGS_V86_ES_BASE_INVALID);
9508 HMVMX_CHECK_BREAK(pCtx->es.u32Limit == 0xffff, VMX_IGS_V86_ES_LIMIT_INVALID);
9509 HMVMX_CHECK_BREAK(u32ESAttr == 0xf3, VMX_IGS_V86_ES_ATTR_INVALID);
9510 /* FS */
9511 HMVMX_CHECK_BREAK((pCtx->fs.u64Base == (uint64_t)pCtx->fs.Sel << 4), VMX_IGS_V86_FS_BASE_INVALID);
9512 HMVMX_CHECK_BREAK(pCtx->fs.u32Limit == 0xffff, VMX_IGS_V86_FS_LIMIT_INVALID);
9513 HMVMX_CHECK_BREAK(u32FSAttr == 0xf3, VMX_IGS_V86_FS_ATTR_INVALID);
9514 /* GS */
9515 HMVMX_CHECK_BREAK((pCtx->gs.u64Base == (uint64_t)pCtx->gs.Sel << 4), VMX_IGS_V86_GS_BASE_INVALID);
9516 HMVMX_CHECK_BREAK(pCtx->gs.u32Limit == 0xffff, VMX_IGS_V86_GS_LIMIT_INVALID);
9517 HMVMX_CHECK_BREAK(u32GSAttr == 0xf3, VMX_IGS_V86_GS_ATTR_INVALID);
9518 /* 64-bit capable CPUs. */
9519 HMVMX_CHECK_BREAK(X86_IS_CANONICAL(pCtx->fs.u64Base), VMX_IGS_FS_BASE_NOT_CANONICAL);
9520 HMVMX_CHECK_BREAK(X86_IS_CANONICAL(pCtx->gs.u64Base), VMX_IGS_GS_BASE_NOT_CANONICAL);
9521 HMVMX_CHECK_BREAK( (pCtx->ldtr.Attr.u & X86DESCATTR_UNUSABLE)
9522 || X86_IS_CANONICAL(pCtx->ldtr.u64Base), VMX_IGS_LDTR_BASE_NOT_CANONICAL);
9523 HMVMX_CHECK_BREAK(!RT_HI_U32(pCtx->cs.u64Base), VMX_IGS_LONGMODE_CS_BASE_INVALID);
9524 HMVMX_CHECK_BREAK((pCtx->ss.Attr.u & X86DESCATTR_UNUSABLE) || !RT_HI_U32(pCtx->ss.u64Base),
9525 VMX_IGS_LONGMODE_SS_BASE_INVALID);
9526 HMVMX_CHECK_BREAK((pCtx->ds.Attr.u & X86DESCATTR_UNUSABLE) || !RT_HI_U32(pCtx->ds.u64Base),
9527 VMX_IGS_LONGMODE_DS_BASE_INVALID);
9528 HMVMX_CHECK_BREAK((pCtx->es.Attr.u & X86DESCATTR_UNUSABLE) || !RT_HI_U32(pCtx->es.u64Base),
9529 VMX_IGS_LONGMODE_ES_BASE_INVALID);
9530 }
9531
9532 /*
9533 * TR.
9534 */
9535 HMVMX_CHECK_BREAK(!(pCtx->tr.Sel & X86_SEL_LDT), VMX_IGS_TR_TI_INVALID);
9536 /* 64-bit capable CPUs. */
9537 HMVMX_CHECK_BREAK(X86_IS_CANONICAL(pCtx->tr.u64Base), VMX_IGS_TR_BASE_NOT_CANONICAL);
9538 if (fLongModeGuest)
9539 {
9540 HMVMX_CHECK_BREAK(pCtx->tr.Attr.n.u4Type == 11, /* 64-bit busy TSS. */
9541 VMX_IGS_LONGMODE_TR_ATTR_TYPE_INVALID);
9542 }
9543 else
9544 {
9545 HMVMX_CHECK_BREAK( pCtx->tr.Attr.n.u4Type == 3 /* 16-bit busy TSS. */
9546 || pCtx->tr.Attr.n.u4Type == 11, /* 32-bit busy TSS.*/
9547 VMX_IGS_TR_ATTR_TYPE_INVALID);
9548 }
9549 HMVMX_CHECK_BREAK(!pCtx->tr.Attr.n.u1DescType, VMX_IGS_TR_ATTR_S_INVALID);
9550 HMVMX_CHECK_BREAK(pCtx->tr.Attr.n.u1Present, VMX_IGS_TR_ATTR_P_INVALID);
9551 HMVMX_CHECK_BREAK(!(pCtx->tr.Attr.u & 0xf00), VMX_IGS_TR_ATTR_RESERVED); /* Bits 11:8 MBZ. */
9552 HMVMX_CHECK_BREAK( (pCtx->tr.u32Limit & 0xfff) == 0xfff
9553 || !(pCtx->tr.Attr.n.u1Granularity), VMX_IGS_TR_ATTR_G_INVALID);
9554 HMVMX_CHECK_BREAK( !(pCtx->tr.u32Limit & 0xfff00000)
9555 || (pCtx->tr.Attr.n.u1Granularity), VMX_IGS_TR_ATTR_G_INVALID);
9556 HMVMX_CHECK_BREAK(!(pCtx->tr.Attr.u & X86DESCATTR_UNUSABLE), VMX_IGS_TR_ATTR_UNUSABLE);
9557
9558 /*
9559 * GDTR and IDTR (64-bit capable checks).
9560 */
9561 rc = VMXReadVmcsNw(VMX_VMCS_GUEST_GDTR_BASE, &u64Val);
9562 AssertRC(rc);
9563 HMVMX_CHECK_BREAK(X86_IS_CANONICAL(u64Val), VMX_IGS_GDTR_BASE_NOT_CANONICAL);
9564
9565 rc = VMXReadVmcsNw(VMX_VMCS_GUEST_IDTR_BASE, &u64Val);
9566 AssertRC(rc);
9567 HMVMX_CHECK_BREAK(X86_IS_CANONICAL(u64Val), VMX_IGS_IDTR_BASE_NOT_CANONICAL);
9568
9569 rc = VMXReadVmcs32(VMX_VMCS32_GUEST_GDTR_LIMIT, &u32Val);
9570 AssertRC(rc);
9571 HMVMX_CHECK_BREAK(!(u32Val & 0xffff0000), VMX_IGS_GDTR_LIMIT_INVALID); /* Bits 31:16 MBZ. */
9572
9573 rc = VMXReadVmcs32(VMX_VMCS32_GUEST_IDTR_LIMIT, &u32Val);
9574 AssertRC(rc);
9575 HMVMX_CHECK_BREAK(!(u32Val & 0xffff0000), VMX_IGS_IDTR_LIMIT_INVALID); /* Bits 31:16 MBZ. */
9576
9577 /*
9578 * Guest Non-Register State.
9579 */
9580 /* Activity State. */
9581 uint32_t u32ActivityState;
9582 rc = VMXReadVmcs32(VMX_VMCS32_GUEST_ACTIVITY_STATE, &u32ActivityState);
9583 AssertRC(rc);
9584 HMVMX_CHECK_BREAK( !u32ActivityState
9585 || (u32ActivityState & RT_BF_GET(pVM->hm.s.vmx.Msrs.u64Misc, VMX_BF_MISC_ACTIVITY_STATES)),
9586 VMX_IGS_ACTIVITY_STATE_INVALID);
9587 HMVMX_CHECK_BREAK( !(pCtx->ss.Attr.n.u2Dpl)
9588 || u32ActivityState != VMX_VMCS_GUEST_ACTIVITY_HLT, VMX_IGS_ACTIVITY_STATE_HLT_INVALID);
9589 uint32_t u32IntrState;
9590 rc = VMXReadVmcs32(VMX_VMCS32_GUEST_INT_STATE, &u32IntrState);
9591 AssertRC(rc);
9592 if ( u32IntrState == VMX_VMCS_GUEST_INT_STATE_BLOCK_MOVSS
9593 || u32IntrState == VMX_VMCS_GUEST_INT_STATE_BLOCK_STI)
9594 {
9595 HMVMX_CHECK_BREAK(u32ActivityState == VMX_VMCS_GUEST_ACTIVITY_ACTIVE, VMX_IGS_ACTIVITY_STATE_ACTIVE_INVALID);
9596 }
9597
9598 /** @todo Activity state and injecting interrupts. Left as a todo since we
9599 * currently don't use activity states but ACTIVE. */
9600
9601 HMVMX_CHECK_BREAK( !(pVmcsInfo->u32EntryCtls & VMX_ENTRY_CTLS_ENTRY_TO_SMM)
9602 || u32ActivityState != VMX_VMCS_GUEST_ACTIVITY_SIPI_WAIT, VMX_IGS_ACTIVITY_STATE_SIPI_WAIT_INVALID);
9603
9604 /* Guest interruptibility-state. */
9605 HMVMX_CHECK_BREAK(!(u32IntrState & 0xffffffe0), VMX_IGS_INTERRUPTIBILITY_STATE_RESERVED);
9606 HMVMX_CHECK_BREAK((u32IntrState & (VMX_VMCS_GUEST_INT_STATE_BLOCK_STI | VMX_VMCS_GUEST_INT_STATE_BLOCK_MOVSS))
9607 != (VMX_VMCS_GUEST_INT_STATE_BLOCK_STI | VMX_VMCS_GUEST_INT_STATE_BLOCK_MOVSS),
9608 VMX_IGS_INTERRUPTIBILITY_STATE_STI_MOVSS_INVALID);
9609 HMVMX_CHECK_BREAK( (u32Eflags & X86_EFL_IF)
9610 || !(u32IntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_STI),
9611 VMX_IGS_INTERRUPTIBILITY_STATE_STI_EFL_INVALID);
9612 if (VMX_ENTRY_INT_INFO_IS_EXT_INT(u32EntryInfo))
9613 {
9614 HMVMX_CHECK_BREAK( !(u32IntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_STI)
9615 && !(u32IntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_MOVSS),
9616 VMX_IGS_INTERRUPTIBILITY_STATE_EXT_INT_INVALID);
9617 }
9618 else if (VMX_ENTRY_INT_INFO_IS_XCPT_NMI(u32EntryInfo))
9619 {
9620 HMVMX_CHECK_BREAK(!(u32IntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_MOVSS),
9621 VMX_IGS_INTERRUPTIBILITY_STATE_MOVSS_INVALID);
9622 HMVMX_CHECK_BREAK(!(u32IntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_STI),
9623 VMX_IGS_INTERRUPTIBILITY_STATE_STI_INVALID);
9624 }
9625 /** @todo Assumes the processor is not in SMM. */
9626 HMVMX_CHECK_BREAK(!(u32IntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_SMI),
9627 VMX_IGS_INTERRUPTIBILITY_STATE_SMI_INVALID);
9628 HMVMX_CHECK_BREAK( !(pVmcsInfo->u32EntryCtls & VMX_ENTRY_CTLS_ENTRY_TO_SMM)
9629 || (u32IntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_SMI),
9630 VMX_IGS_INTERRUPTIBILITY_STATE_SMI_SMM_INVALID);
9631 if ( (pVmcsInfo->u32PinCtls & VMX_PIN_CTLS_VIRT_NMI)
9632 && VMX_ENTRY_INT_INFO_IS_XCPT_NMI(u32EntryInfo))
9633 {
9634 HMVMX_CHECK_BREAK(!(u32IntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_NMI),
9635 VMX_IGS_INTERRUPTIBILITY_STATE_NMI_INVALID);
9636 }
9637
9638 /* Pending debug exceptions. */
9639 rc = VMXReadVmcsNw(VMX_VMCS_GUEST_PENDING_DEBUG_XCPTS, &u64Val);
9640 AssertRC(rc);
9641 /* Bits 63:15, Bit 13, Bits 11:4 MBZ. */
9642 HMVMX_CHECK_BREAK(!(u64Val & UINT64_C(0xffffffffffffaff0)), VMX_IGS_LONGMODE_PENDING_DEBUG_RESERVED);
9643 u32Val = u64Val; /* For pending debug exceptions checks below. */
9644
9645 if ( (u32IntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_STI)
9646 || (u32IntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_MOVSS)
9647 || u32ActivityState == VMX_VMCS_GUEST_ACTIVITY_HLT)
9648 {
9649 if ( (u32Eflags & X86_EFL_TF)
9650 && !(u64DebugCtlMsr & RT_BIT_64(1))) /* Bit 1 is IA32_DEBUGCTL.BTF. */
9651 {
9652 /* Bit 14 is PendingDebug.BS. */
9653 HMVMX_CHECK_BREAK(u32Val & RT_BIT(14), VMX_IGS_PENDING_DEBUG_XCPT_BS_NOT_SET);
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_CLEAR);
9660 }
9661 }
9662
9663 /* VMCS link pointer. */
9664 rc = VMXReadVmcs64(VMX_VMCS64_GUEST_VMCS_LINK_PTR_FULL, &u64Val);
9665 AssertRC(rc);
9666 if (u64Val != UINT64_C(0xffffffffffffffff))
9667 {
9668 HMVMX_CHECK_BREAK(!(u64Val & 0xfff), VMX_IGS_VMCS_LINK_PTR_RESERVED);
9669 /** @todo Bits beyond the processor's physical-address width MBZ. */
9670 /** @todo SMM checks. */
9671 Assert(pVmcsInfo->HCPhysShadowVmcs == u64Val);
9672 Assert(pVmcsInfo->pvShadowVmcs);
9673 VMXVMCSREVID VmcsRevId;
9674 VmcsRevId.u = *(uint32_t *)pVmcsInfo->pvShadowVmcs;
9675 HMVMX_CHECK_BREAK(VmcsRevId.n.u31RevisionId == RT_BF_GET(pVM->hm.s.vmx.Msrs.u64Basic, VMX_BF_BASIC_VMCS_ID),
9676 VMX_IGS_VMCS_LINK_PTR_SHADOW_VMCS_ID_INVALID);
9677 HMVMX_CHECK_BREAK(VmcsRevId.n.fIsShadowVmcs == (uint32_t)!!(pVmcsInfo->u32ProcCtls2 & VMX_PROC_CTLS2_VMCS_SHADOWING),
9678 VMX_IGS_VMCS_LINK_PTR_NOT_SHADOW);
9679 }
9680
9681 /** @todo Checks on Guest Page-Directory-Pointer-Table Entries when guest is
9682 * not using nested paging? */
9683 if ( pVM->hm.s.fNestedPaging
9684 && !fLongModeGuest
9685 && CPUMIsGuestInPAEModeEx(pCtx))
9686 {
9687 rc = VMXReadVmcs64(VMX_VMCS64_GUEST_PDPTE0_FULL, &u64Val);
9688 AssertRC(rc);
9689 HMVMX_CHECK_BREAK(!(u64Val & X86_PDPE_PAE_MBZ_MASK), VMX_IGS_PAE_PDPTE_RESERVED);
9690
9691 rc = VMXReadVmcs64(VMX_VMCS64_GUEST_PDPTE1_FULL, &u64Val);
9692 AssertRC(rc);
9693 HMVMX_CHECK_BREAK(!(u64Val & X86_PDPE_PAE_MBZ_MASK), VMX_IGS_PAE_PDPTE_RESERVED);
9694
9695 rc = VMXReadVmcs64(VMX_VMCS64_GUEST_PDPTE2_FULL, &u64Val);
9696 AssertRC(rc);
9697 HMVMX_CHECK_BREAK(!(u64Val & X86_PDPE_PAE_MBZ_MASK), VMX_IGS_PAE_PDPTE_RESERVED);
9698
9699 rc = VMXReadVmcs64(VMX_VMCS64_GUEST_PDPTE3_FULL, &u64Val);
9700 AssertRC(rc);
9701 HMVMX_CHECK_BREAK(!(u64Val & X86_PDPE_PAE_MBZ_MASK), VMX_IGS_PAE_PDPTE_RESERVED);
9702 }
9703
9704 /* Shouldn't happen but distinguish it from AssertRCBreak() errors. */
9705 if (uError == VMX_IGS_ERROR)
9706 uError = VMX_IGS_REASON_NOT_FOUND;
9707 } while (0);
9708
9709 pVCpu->hm.s.u32HMError = uError;
9710 return uError;
9711
9712#undef HMVMX_ERROR_BREAK
9713#undef HMVMX_CHECK_BREAK
9714}
9715
9716
9717/**
9718 * Map the APIC-access page for virtualizing APIC accesses.
9719 *
9720 * This can cause a longjumps to R3 due to the acquisition of the PGM lock. Hence,
9721 * this not done as part of exporting guest state, see @bugref{8721}.
9722 *
9723 * @returns VBox status code.
9724 * @param pVCpu The cross context virtual CPU structure.
9725 */
9726static int hmR0VmxMapHCApicAccessPage(PVMCPUCC pVCpu)
9727{
9728 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
9729 uint64_t const u64MsrApicBase = APICGetBaseMsrNoCheck(pVCpu);
9730
9731 Assert(PDMHasApic(pVM));
9732 Assert(u64MsrApicBase);
9733
9734 RTGCPHYS const GCPhysApicBase = u64MsrApicBase & PAGE_BASE_GC_MASK;
9735 Log4Func(("Mappping HC APIC-access page at %#RGp\n", GCPhysApicBase));
9736
9737 /* Unalias the existing mapping. */
9738 int rc = PGMHandlerPhysicalReset(pVM, GCPhysApicBase);
9739 AssertRCReturn(rc, rc);
9740
9741 /* Map the HC APIC-access page in place of the MMIO page, also updates the shadow page tables if necessary. */
9742 Assert(pVM->hm.s.vmx.HCPhysApicAccess != NIL_RTHCPHYS);
9743 rc = IOMMMIOMapMMIOHCPage(pVM, pVCpu, GCPhysApicBase, pVM->hm.s.vmx.HCPhysApicAccess, X86_PTE_RW | X86_PTE_P);
9744 AssertRCReturn(rc, rc);
9745
9746 /* Update the per-VCPU cache of the APIC base MSR. */
9747 pVCpu->hm.s.vmx.u64GstMsrApicBase = u64MsrApicBase;
9748 return VINF_SUCCESS;
9749}
9750
9751
9752/**
9753 * Worker function passed to RTMpOnSpecific() that is to be called on the target
9754 * CPU.
9755 *
9756 * @param idCpu The ID for the CPU the function is called on.
9757 * @param pvUser1 Null, not used.
9758 * @param pvUser2 Null, not used.
9759 */
9760static DECLCALLBACK(void) hmR0DispatchHostNmi(RTCPUID idCpu, void *pvUser1, void *pvUser2)
9761{
9762 RT_NOREF3(idCpu, pvUser1, pvUser2);
9763 VMXDispatchHostNmi();
9764}
9765
9766
9767/**
9768 * Dispatching an NMI on the host CPU that received it.
9769 *
9770 * @returns VBox status code.
9771 * @param pVCpu The cross context virtual CPU structure.
9772 * @param pVmcsInfo The VMCS info. object corresponding to the VMCS that was
9773 * executing when receiving the host NMI in VMX non-root
9774 * operation.
9775 */
9776static int hmR0VmxExitHostNmi(PVMCPUCC pVCpu, PCVMXVMCSINFO pVmcsInfo)
9777{
9778 RTCPUID const idCpu = pVmcsInfo->idHostCpuExec;
9779 Assert(idCpu != NIL_RTCPUID);
9780
9781 /*
9782 * We don't want to delay dispatching the NMI any more than we have to. However,
9783 * we have already chosen -not- to dispatch NMIs when interrupts were still disabled
9784 * after executing guest or nested-guest code for the following reasons:
9785 *
9786 * - We would need to perform VMREADs with interrupts disabled and is orders of
9787 * magnitude worse when we run as a guest hypervisor without VMCS shadowing
9788 * supported by the host hypervisor.
9789 *
9790 * - It affects the common VM-exit scenario and keeps interrupts disabled for a
9791 * longer period of time just for handling an edge case like host NMIs which do
9792 * not occur nearly as frequently as other VM-exits.
9793 *
9794 * Let's cover the most likely scenario first. Check if we are on the target CPU
9795 * and dispatch the NMI right away. This should be much faster than calling into
9796 * RTMpOnSpecific() machinery.
9797 */
9798 bool fDispatched = false;
9799 RTCCUINTREG const fEFlags = ASMIntDisableFlags();
9800 if (idCpu == RTMpCpuId())
9801 {
9802 VMXDispatchHostNmi();
9803 fDispatched = true;
9804 }
9805 ASMSetFlags(fEFlags);
9806 if (fDispatched)
9807 {
9808 STAM_REL_COUNTER_INC(&pVCpu->hm.s.StatExitHostNmiInGC);
9809 return VINF_SUCCESS;
9810 }
9811
9812 /*
9813 * RTMpOnSpecific() waits until the worker function has run on the target CPU. So
9814 * there should be no race or recursion even if we are unlucky enough to be preempted
9815 * (to the target CPU) without dispatching the host NMI above.
9816 */
9817 STAM_REL_COUNTER_INC(&pVCpu->hm.s.StatExitHostNmiInGCIpi);
9818 return RTMpOnSpecific(idCpu, &hmR0DispatchHostNmi, NULL /* pvUser1 */, NULL /* pvUser2 */);
9819}
9820
9821
9822#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
9823/**
9824 * Merges the guest with the nested-guest MSR bitmap in preparation of executing the
9825 * nested-guest using hardware-assisted VMX.
9826 *
9827 * @param pVCpu The cross context virtual CPU structure.
9828 * @param pVmcsInfoNstGst The nested-guest VMCS info. object.
9829 * @param pVmcsInfoGst The guest VMCS info. object.
9830 */
9831static void hmR0VmxMergeMsrBitmapNested(PCVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfoNstGst, PCVMXVMCSINFO pVmcsInfoGst)
9832{
9833 uint32_t const cbMsrBitmap = X86_PAGE_4K_SIZE;
9834 uint64_t *pu64MsrBitmap = (uint64_t *)pVmcsInfoNstGst->pvMsrBitmap;
9835 Assert(pu64MsrBitmap);
9836
9837 /*
9838 * We merge the guest MSR bitmap with the nested-guest MSR bitmap such that any
9839 * MSR that is intercepted by the guest is also intercepted while executing the
9840 * nested-guest using hardware-assisted VMX.
9841 *
9842 * Note! If the nested-guest is not using an MSR bitmap, ever MSR must cause a
9843 * nested-guest VM-exit even if the outer guest is not intercepting some
9844 * MSRs. We cannot assume the caller has initialized the nested-guest
9845 * MSR bitmap in this case.
9846 *
9847 * The guest hypervisor may also switch whether it uses MSR bitmaps for
9848 * each VM-entry, hence initializing it once per-VM while setting up the
9849 * nested-guest VMCS is not sufficient.
9850 */
9851 PCVMXVVMCS pVmcsNstGst = pVCpu->cpum.GstCtx.hwvirt.vmx.CTX_SUFF(pVmcs);
9852 if (pVmcsNstGst->u32ProcCtls & VMX_PROC_CTLS_USE_MSR_BITMAPS)
9853 {
9854 uint64_t const *pu64MsrBitmapNstGst = (uint64_t const *)pVCpu->cpum.GstCtx.hwvirt.vmx.CTX_SUFF(pvMsrBitmap);
9855 uint64_t const *pu64MsrBitmapGst = (uint64_t const *)pVmcsInfoGst->pvMsrBitmap;
9856 Assert(pu64MsrBitmapNstGst);
9857 Assert(pu64MsrBitmapGst);
9858
9859 uint32_t const cFrags = cbMsrBitmap / sizeof(uint64_t);
9860 for (uint32_t i = 0; i < cFrags; i++)
9861 pu64MsrBitmap[i] = pu64MsrBitmapNstGst[i] | pu64MsrBitmapGst[i];
9862 }
9863 else
9864 ASMMemFill32(pu64MsrBitmap, cbMsrBitmap, UINT32_C(0xffffffff));
9865}
9866
9867
9868/**
9869 * Merges the guest VMCS in to the nested-guest VMCS controls in preparation of
9870 * hardware-assisted VMX execution of the nested-guest.
9871 *
9872 * For a guest, we don't modify these controls once we set up the VMCS and hence
9873 * this function is never called.
9874 *
9875 * For nested-guests since the guest hypervisor provides these controls on every
9876 * nested-guest VM-entry and could potentially change them everytime we need to
9877 * merge them before every nested-guest VM-entry.
9878 *
9879 * @returns VBox status code.
9880 * @param pVCpu The cross context virtual CPU structure.
9881 */
9882static int hmR0VmxMergeVmcsNested(PVMCPUCC pVCpu)
9883{
9884 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
9885 PCVMXVMCSINFO pVmcsInfoGst = &pVCpu->hm.s.vmx.VmcsInfo;
9886 PCVMXVVMCS pVmcsNstGst = pVCpu->cpum.GstCtx.hwvirt.vmx.CTX_SUFF(pVmcs);
9887 Assert(pVmcsNstGst);
9888
9889 /*
9890 * Merge the controls with the requirements of the guest VMCS.
9891 *
9892 * We do not need to validate the nested-guest VMX features specified in the nested-guest
9893 * VMCS with the features supported by the physical CPU as it's already done by the
9894 * VMLAUNCH/VMRESUME instruction emulation.
9895 *
9896 * This is because the VMX features exposed by CPUM (through CPUID/MSRs) to the guest are
9897 * derived from the VMX features supported by the physical CPU.
9898 */
9899
9900 /* Pin-based VM-execution controls. */
9901 uint32_t const u32PinCtls = pVmcsNstGst->u32PinCtls | pVmcsInfoGst->u32PinCtls;
9902
9903 /* Processor-based VM-execution controls. */
9904 uint32_t u32ProcCtls = (pVmcsNstGst->u32ProcCtls & ~VMX_PROC_CTLS_USE_IO_BITMAPS)
9905 | (pVmcsInfoGst->u32ProcCtls & ~( VMX_PROC_CTLS_INT_WINDOW_EXIT
9906 | VMX_PROC_CTLS_NMI_WINDOW_EXIT
9907 | VMX_PROC_CTLS_USE_TPR_SHADOW
9908 | VMX_PROC_CTLS_MONITOR_TRAP_FLAG));
9909
9910 /* Secondary processor-based VM-execution controls. */
9911 uint32_t const u32ProcCtls2 = (pVmcsNstGst->u32ProcCtls2 & ~VMX_PROC_CTLS2_VPID)
9912 | (pVmcsInfoGst->u32ProcCtls2 & ~( VMX_PROC_CTLS2_VIRT_APIC_ACCESS
9913 | VMX_PROC_CTLS2_INVPCID
9914 | VMX_PROC_CTLS2_VMCS_SHADOWING
9915 | VMX_PROC_CTLS2_RDTSCP
9916 | VMX_PROC_CTLS2_XSAVES_XRSTORS
9917 | VMX_PROC_CTLS2_APIC_REG_VIRT
9918 | VMX_PROC_CTLS2_VIRT_INT_DELIVERY
9919 | VMX_PROC_CTLS2_VMFUNC));
9920
9921 /*
9922 * VM-entry controls:
9923 * These controls contains state that depends on the nested-guest state (primarily
9924 * EFER MSR) and is thus not constant between VMLAUNCH/VMRESUME and the nested-guest
9925 * VM-exit. Although the guest hypervisor cannot change it, we need to in order to
9926 * properly continue executing the nested-guest if the EFER MSR changes but does not
9927 * cause a nested-guest VM-exits.
9928 *
9929 * VM-exit controls:
9930 * These controls specify the host state on return. We cannot use the controls from
9931 * the guest hypervisor state as is as it would contain the guest state rather than
9932 * the host state. Since the host state is subject to change (e.g. preemption, trips
9933 * to ring-3, longjmp and rescheduling to a different host CPU) they are not constant
9934 * through VMLAUNCH/VMRESUME and the nested-guest VM-exit.
9935 *
9936 * VM-entry MSR-load:
9937 * The guest MSRs from the VM-entry MSR-load area are already loaded into the guest-CPU
9938 * context by the VMLAUNCH/VMRESUME instruction emulation.
9939 *
9940 * VM-exit MSR-store:
9941 * The VM-exit emulation will take care of populating the MSRs from the guest-CPU context
9942 * back into the VM-exit MSR-store area.
9943 *
9944 * VM-exit MSR-load areas:
9945 * This must contain the real host MSRs with hardware-assisted VMX execution. Hence, we
9946 * can entirely ignore what the guest hypervisor wants to load here.
9947 */
9948
9949 /*
9950 * Exception bitmap.
9951 *
9952 * We could remove #UD from the guest bitmap and merge it with the nested-guest bitmap
9953 * here (and avoid doing anything while exporting nested-guest state), but to keep the
9954 * code more flexible if intercepting exceptions become more dynamic in the future we do
9955 * it as part of exporting the nested-guest state.
9956 */
9957 uint32_t const u32XcptBitmap = pVmcsNstGst->u32XcptBitmap | pVmcsInfoGst->u32XcptBitmap;
9958
9959 /*
9960 * CR0/CR4 guest/host mask.
9961 *
9962 * Modifications by the nested-guest to CR0/CR4 bits owned by the host and the guest must
9963 * cause VM-exits, so we need to merge them here.
9964 */
9965 uint64_t const u64Cr0Mask = pVmcsNstGst->u64Cr0Mask.u | pVmcsInfoGst->u64Cr0Mask;
9966 uint64_t const u64Cr4Mask = pVmcsNstGst->u64Cr4Mask.u | pVmcsInfoGst->u64Cr4Mask;
9967
9968 /*
9969 * Page-fault error-code mask and match.
9970 *
9971 * Although we require unrestricted guest execution (and thereby nested-paging) for
9972 * hardware-assisted VMX execution of nested-guests and thus the outer guest doesn't
9973 * normally intercept #PFs, it might intercept them for debugging purposes.
9974 *
9975 * If the outer guest is not intercepting #PFs, we can use the nested-guest #PF filters.
9976 * If the outer guest is intercepting #PFs, we must intercept all #PFs.
9977 */
9978 uint32_t u32XcptPFMask;
9979 uint32_t u32XcptPFMatch;
9980 if (!(pVmcsInfoGst->u32XcptBitmap & RT_BIT(X86_XCPT_PF)))
9981 {
9982 u32XcptPFMask = pVmcsNstGst->u32XcptPFMask;
9983 u32XcptPFMatch = pVmcsNstGst->u32XcptPFMatch;
9984 }
9985 else
9986 {
9987 u32XcptPFMask = 0;
9988 u32XcptPFMatch = 0;
9989 }
9990
9991 /*
9992 * Pause-Loop exiting.
9993 */
9994 uint32_t const cPleGapTicks = RT_MIN(pVM->hm.s.vmx.cPleGapTicks, pVmcsNstGst->u32PleGap);
9995 uint32_t const cPleWindowTicks = RT_MIN(pVM->hm.s.vmx.cPleWindowTicks, pVmcsNstGst->u32PleWindow);
9996
9997 /*
9998 * Pending debug exceptions.
9999 * Currently just copy whatever the nested-guest provides us.
10000 */
10001 uint64_t const uPendingDbgXcpts = pVmcsNstGst->u64GuestPendingDbgXcpts.u;
10002
10003 /*
10004 * I/O Bitmap.
10005 *
10006 * We do not use the I/O bitmap that may be provided by the guest hypervisor as we always
10007 * intercept all I/O port accesses.
10008 */
10009 Assert(u32ProcCtls & VMX_PROC_CTLS_UNCOND_IO_EXIT);
10010 Assert(!(u32ProcCtls & VMX_PROC_CTLS_USE_IO_BITMAPS));
10011
10012 /*
10013 * VMCS shadowing.
10014 *
10015 * We do not yet expose VMCS shadowing to the guest and thus VMCS shadowing should not be
10016 * enabled while executing the nested-guest.
10017 */
10018 Assert(!(u32ProcCtls2 & VMX_PROC_CTLS2_VMCS_SHADOWING));
10019
10020 /*
10021 * APIC-access page.
10022 */
10023 RTHCPHYS HCPhysApicAccess;
10024 if (u32ProcCtls2 & VMX_PROC_CTLS2_VIRT_APIC_ACCESS)
10025 {
10026 Assert(pVM->hm.s.vmx.Msrs.ProcCtls2.n.allowed1 & VMX_PROC_CTLS2_VIRT_APIC_ACCESS);
10027 RTGCPHYS const GCPhysApicAccess = pVmcsNstGst->u64AddrApicAccess.u;
10028
10029 /** @todo NSTVMX: This is not really correct but currently is required to make
10030 * things work. We need to re-enable the page handler when we fallback to
10031 * IEM execution of the nested-guest! */
10032 PGMHandlerPhysicalPageTempOff(pVM, GCPhysApicAccess, GCPhysApicAccess);
10033
10034 void *pvPage;
10035 PGMPAGEMAPLOCK PgLockApicAccess;
10036 int rc = PGMPhysGCPhys2CCPtr(pVM, GCPhysApicAccess, &pvPage, &PgLockApicAccess);
10037 if (RT_SUCCESS(rc))
10038 {
10039 rc = PGMPhysGCPhys2HCPhys(pVM, GCPhysApicAccess, &HCPhysApicAccess);
10040 AssertMsgRCReturn(rc, ("Failed to get host-physical address for APIC-access page at %#RGp\n", GCPhysApicAccess), rc);
10041
10042 /** @todo Handle proper releasing of page-mapping lock later. */
10043 PGMPhysReleasePageMappingLock(pVCpu->CTX_SUFF(pVM), &PgLockApicAccess);
10044 }
10045 else
10046 return rc;
10047 }
10048 else
10049 HCPhysApicAccess = 0;
10050
10051 /*
10052 * Virtual-APIC page and TPR threshold.
10053 */
10054 PVMXVMCSINFO pVmcsInfoNstGst = &pVCpu->hm.s.vmx.VmcsInfoNstGst;
10055 RTHCPHYS HCPhysVirtApic;
10056 uint32_t u32TprThreshold;
10057 if (u32ProcCtls & VMX_PROC_CTLS_USE_TPR_SHADOW)
10058 {
10059 Assert(pVM->hm.s.vmx.Msrs.ProcCtls.n.allowed1 & VMX_PROC_CTLS_USE_TPR_SHADOW);
10060 RTGCPHYS const GCPhysVirtApic = pVmcsNstGst->u64AddrVirtApic.u;
10061
10062 void *pvPage;
10063 PGMPAGEMAPLOCK PgLockVirtApic;
10064 int rc = PGMPhysGCPhys2CCPtr(pVM, GCPhysVirtApic, &pvPage, &PgLockVirtApic);
10065 if (RT_SUCCESS(rc))
10066 {
10067 rc = PGMPhysGCPhys2HCPhys(pVM, GCPhysVirtApic, &HCPhysVirtApic);
10068 AssertMsgRCReturn(rc, ("Failed to get host-physical address for virtual-APIC page at %#RGp\n", GCPhysVirtApic), rc);
10069
10070 /** @todo Handle proper releasing of page-mapping lock later. */
10071 PGMPhysReleasePageMappingLock(pVCpu->CTX_SUFF(pVM), &PgLockVirtApic);
10072 }
10073 else
10074 return rc;
10075
10076 u32TprThreshold = pVmcsNstGst->u32TprThreshold;
10077 }
10078 else
10079 {
10080 HCPhysVirtApic = 0;
10081 u32TprThreshold = 0;
10082
10083 /*
10084 * We must make sure CR8 reads/write must cause VM-exits when TPR shadowing is not
10085 * used by the guest hypervisor. Preventing MMIO accesses to the physical APIC will
10086 * be taken care of by EPT/shadow paging.
10087 */
10088 if (pVM->hm.s.fAllow64BitGuests)
10089 {
10090 u32ProcCtls |= VMX_PROC_CTLS_CR8_STORE_EXIT
10091 | VMX_PROC_CTLS_CR8_LOAD_EXIT;
10092 }
10093 }
10094
10095 /*
10096 * Validate basic assumptions.
10097 */
10098 Assert(pVM->hm.s.vmx.fAllowUnrestricted);
10099 Assert(pVM->hm.s.vmx.Msrs.ProcCtls.n.allowed1 & VMX_PROC_CTLS_USE_SECONDARY_CTLS);
10100 Assert(hmGetVmxActiveVmcsInfo(pVCpu) == pVmcsInfoNstGst);
10101
10102 /*
10103 * Commit it to the nested-guest VMCS.
10104 */
10105 int rc = VINF_SUCCESS;
10106 if (pVmcsInfoNstGst->u32PinCtls != u32PinCtls)
10107 rc |= VMXWriteVmcs32(VMX_VMCS32_CTRL_PIN_EXEC, u32PinCtls);
10108 if (pVmcsInfoNstGst->u32ProcCtls != u32ProcCtls)
10109 rc |= VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, u32ProcCtls);
10110 if (pVmcsInfoNstGst->u32ProcCtls2 != u32ProcCtls2)
10111 rc |= VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC2, u32ProcCtls2);
10112 if (pVmcsInfoNstGst->u32XcptBitmap != u32XcptBitmap)
10113 rc |= VMXWriteVmcs32(VMX_VMCS32_CTRL_EXCEPTION_BITMAP, u32XcptBitmap);
10114 if (pVmcsInfoNstGst->u64Cr0Mask != u64Cr0Mask)
10115 rc |= VMXWriteVmcsNw(VMX_VMCS_CTRL_CR0_MASK, u64Cr0Mask);
10116 if (pVmcsInfoNstGst->u64Cr4Mask != u64Cr4Mask)
10117 rc |= VMXWriteVmcsNw(VMX_VMCS_CTRL_CR4_MASK, u64Cr4Mask);
10118 if (pVmcsInfoNstGst->u32XcptPFMask != u32XcptPFMask)
10119 rc |= VMXWriteVmcs32(VMX_VMCS32_CTRL_PAGEFAULT_ERROR_MASK, u32XcptPFMask);
10120 if (pVmcsInfoNstGst->u32XcptPFMatch != u32XcptPFMatch)
10121 rc |= VMXWriteVmcs32(VMX_VMCS32_CTRL_PAGEFAULT_ERROR_MATCH, u32XcptPFMatch);
10122 if ( !(u32ProcCtls & VMX_PROC_CTLS_PAUSE_EXIT)
10123 && (u32ProcCtls2 & VMX_PROC_CTLS2_PAUSE_LOOP_EXIT))
10124 {
10125 Assert(pVM->hm.s.vmx.Msrs.ProcCtls2.n.allowed1 & VMX_PROC_CTLS2_PAUSE_LOOP_EXIT);
10126 rc |= VMXWriteVmcs32(VMX_VMCS32_CTRL_PLE_GAP, cPleGapTicks);
10127 rc |= VMXWriteVmcs32(VMX_VMCS32_CTRL_PLE_WINDOW, cPleWindowTicks);
10128 }
10129 if (u32ProcCtls & VMX_PROC_CTLS_USE_TPR_SHADOW)
10130 {
10131 rc |= VMXWriteVmcs32(VMX_VMCS32_CTRL_TPR_THRESHOLD, u32TprThreshold);
10132 rc |= VMXWriteVmcs64(VMX_VMCS64_CTRL_VIRT_APIC_PAGEADDR_FULL, HCPhysVirtApic);
10133 }
10134 if (u32ProcCtls2 & VMX_PROC_CTLS2_VIRT_APIC_ACCESS)
10135 rc |= VMXWriteVmcs64(VMX_VMCS64_CTRL_APIC_ACCESSADDR_FULL, HCPhysApicAccess);
10136 rc |= VMXWriteVmcsNw(VMX_VMCS_GUEST_PENDING_DEBUG_XCPTS, uPendingDbgXcpts);
10137 AssertRC(rc);
10138
10139 /*
10140 * Update the nested-guest VMCS cache.
10141 */
10142 pVmcsInfoNstGst->u32PinCtls = u32PinCtls;
10143 pVmcsInfoNstGst->u32ProcCtls = u32ProcCtls;
10144 pVmcsInfoNstGst->u32ProcCtls2 = u32ProcCtls2;
10145 pVmcsInfoNstGst->u32XcptBitmap = u32XcptBitmap;
10146 pVmcsInfoNstGst->u64Cr0Mask = u64Cr0Mask;
10147 pVmcsInfoNstGst->u64Cr4Mask = u64Cr4Mask;
10148 pVmcsInfoNstGst->u32XcptPFMask = u32XcptPFMask;
10149 pVmcsInfoNstGst->u32XcptPFMatch = u32XcptPFMatch;
10150 pVmcsInfoNstGst->HCPhysVirtApic = HCPhysVirtApic;
10151
10152 /*
10153 * We need to flush the TLB if we are switching the APIC-access page address.
10154 * See Intel spec. 28.3.3.4 "Guidelines for Use of the INVEPT Instruction".
10155 */
10156 if (u32ProcCtls2 & VMX_PROC_CTLS2_VIRT_APIC_ACCESS)
10157 pVCpu->hm.s.vmx.fSwitchedNstGstFlushTlb = true;
10158
10159 /*
10160 * MSR bitmap.
10161 *
10162 * The MSR bitmap address has already been initialized while setting up the nested-guest
10163 * VMCS, here we need to merge the MSR bitmaps.
10164 */
10165 if (u32ProcCtls & VMX_PROC_CTLS_USE_MSR_BITMAPS)
10166 hmR0VmxMergeMsrBitmapNested(pVCpu, pVmcsInfoNstGst, pVmcsInfoGst);
10167
10168 return VINF_SUCCESS;
10169}
10170#endif /* VBOX_WITH_NESTED_HWVIRT_VMX */
10171
10172
10173/**
10174 * Does the preparations before executing guest code in VT-x.
10175 *
10176 * This may cause longjmps to ring-3 and may even result in rescheduling to the
10177 * recompiler/IEM. We must be cautious what we do here regarding committing
10178 * guest-state information into the VMCS assuming we assuredly execute the
10179 * guest in VT-x mode.
10180 *
10181 * If we fall back to the recompiler/IEM after updating the VMCS and clearing
10182 * the common-state (TRPM/forceflags), we must undo those changes so that the
10183 * recompiler/IEM can (and should) use them when it resumes guest execution.
10184 * Otherwise such operations must be done when we can no longer exit to ring-3.
10185 *
10186 * @returns Strict VBox status code (i.e. informational status codes too).
10187 * @retval VINF_SUCCESS if we can proceed with running the guest, interrupts
10188 * have been disabled.
10189 * @retval VINF_VMX_VMEXIT if a nested-guest VM-exit occurs (e.g., while evaluating
10190 * pending events).
10191 * @retval VINF_EM_RESET if a triple-fault occurs while injecting a
10192 * double-fault into the guest.
10193 * @retval VINF_EM_DBG_STEPPED if @a fStepping is true and an event was
10194 * dispatched directly.
10195 * @retval VINF_* scheduling changes, we have to go back to ring-3.
10196 *
10197 * @param pVCpu The cross context virtual CPU structure.
10198 * @param pVmxTransient The VMX-transient structure.
10199 * @param fStepping Whether we are single-stepping the guest in the
10200 * hypervisor debugger. Makes us ignore some of the reasons
10201 * for returning to ring-3, and return VINF_EM_DBG_STEPPED
10202 * if event dispatching took place.
10203 */
10204static VBOXSTRICTRC hmR0VmxPreRunGuest(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient, bool fStepping)
10205{
10206 Assert(VMMRZCallRing3IsEnabled(pVCpu));
10207
10208 Log4Func(("fIsNested=%RTbool fStepping=%RTbool\n", pVmxTransient->fIsNestedGuest, fStepping));
10209
10210#ifdef VBOX_WITH_NESTED_HWVIRT_ONLY_IN_IEM
10211 if (pVmxTransient->fIsNestedGuest)
10212 {
10213 RT_NOREF2(pVCpu, fStepping);
10214 Log2Func(("Rescheduling to IEM due to nested-hwvirt or forced IEM exec -> VINF_EM_RESCHEDULE_REM\n"));
10215 return VINF_EM_RESCHEDULE_REM;
10216 }
10217#endif
10218
10219#ifdef VBOX_WITH_2X_4GB_ADDR_SPACE_IN_R0
10220 PGMRZDynMapFlushAutoSet(pVCpu);
10221#endif
10222
10223 /*
10224 * Check and process force flag actions, some of which might require us to go back to ring-3.
10225 */
10226 VBOXSTRICTRC rcStrict = hmR0VmxCheckForceFlags(pVCpu, fStepping);
10227 if (rcStrict == VINF_SUCCESS)
10228 {
10229 /* FFs don't get set all the time. */
10230#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
10231 if ( pVmxTransient->fIsNestedGuest
10232 && !CPUMIsGuestInVmxNonRootMode(&pVCpu->cpum.GstCtx))
10233 {
10234 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchNstGstVmexit);
10235 return VINF_VMX_VMEXIT;
10236 }
10237#endif
10238 }
10239 else
10240 return rcStrict;
10241
10242 /*
10243 * Virtualize memory-mapped accesses to the physical APIC (may take locks).
10244 */
10245 /** @todo Doing this from ring-3 after VM setup phase causes a
10246 * VERR_IOM_MMIO_RANGE_NOT_FOUND guru while booting Visa 64 SMP VM. No
10247 * idea why atm. */
10248 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
10249 if ( !pVCpu->hm.s.vmx.u64GstMsrApicBase
10250 && (pVM->hm.s.vmx.Msrs.ProcCtls2.n.allowed1 & VMX_PROC_CTLS2_VIRT_APIC_ACCESS)
10251 && PDMHasApic(pVM))
10252 {
10253 int rc = hmR0VmxMapHCApicAccessPage(pVCpu);
10254 AssertRCReturn(rc, rc);
10255 }
10256
10257#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
10258 /*
10259 * Merge guest VMCS controls with the nested-guest VMCS controls.
10260 *
10261 * Even if we have not executed the guest prior to this (e.g. when resuming from a
10262 * saved state), we should be okay with merging controls as we initialize the
10263 * guest VMCS controls as part of VM setup phase.
10264 */
10265 if ( pVmxTransient->fIsNestedGuest
10266 && !pVCpu->hm.s.vmx.fMergedNstGstCtls)
10267 {
10268 int rc = hmR0VmxMergeVmcsNested(pVCpu);
10269 AssertRCReturn(rc, rc);
10270 pVCpu->hm.s.vmx.fMergedNstGstCtls = true;
10271 }
10272#endif
10273
10274 /*
10275 * Evaluate events to be injected into the guest.
10276 *
10277 * Events in TRPM can be injected without inspecting the guest state.
10278 * If any new events (interrupts/NMI) are pending currently, we try to set up the
10279 * guest to cause a VM-exit the next time they are ready to receive the event.
10280 *
10281 * With nested-guests, evaluating pending events may cause VM-exits.
10282 */
10283 if (TRPMHasTrap(pVCpu))
10284 {
10285 Assert(!pVmxTransient->fIsNestedGuest || !pVCpu->cpum.GstCtx.hwvirt.vmx.fInterceptEvents);
10286 hmR0VmxTrpmTrapToPendingEvent(pVCpu);
10287 }
10288
10289 uint32_t fIntrState;
10290 rcStrict = hmR0VmxEvaluatePendingEvent(pVCpu, pVmxTransient, &fIntrState);
10291
10292#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
10293 /*
10294 * While evaluating pending events if something failed (unlikely) or if we were
10295 * preparing to run a nested-guest but performed a nested-guest VM-exit, we should bail.
10296 */
10297 if (rcStrict != VINF_SUCCESS)
10298 return rcStrict;
10299 if ( pVmxTransient->fIsNestedGuest
10300 && !CPUMIsGuestInVmxNonRootMode(&pVCpu->cpum.GstCtx))
10301 {
10302 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchNstGstVmexit);
10303 return VINF_VMX_VMEXIT;
10304 }
10305#else
10306 Assert(rcStrict == VINF_SUCCESS);
10307#endif
10308
10309 /*
10310 * Event injection may take locks (currently the PGM lock for real-on-v86 case) and thus
10311 * needs to be done with longjmps or interrupts + preemption enabled. Event injection might
10312 * also result in triple-faulting the VM.
10313 *
10314 * With nested-guests, the above does not apply since unrestricted guest execution is a
10315 * requirement. Regardless, we do this here to avoid duplicating code elsewhere.
10316 */
10317 rcStrict = hmR0VmxInjectPendingEvent(pVCpu, pVmxTransient, fIntrState, fStepping);
10318 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
10319 { /* likely */ }
10320 else
10321 {
10322 AssertMsg(rcStrict == VINF_EM_RESET || (rcStrict == VINF_EM_DBG_STEPPED && fStepping),
10323 ("%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
10324 return rcStrict;
10325 }
10326
10327 /*
10328 * A longjump might result in importing CR3 even for VM-exits that don't necessarily
10329 * import CR3 themselves. We will need to update them here, as even as late as the above
10330 * hmR0VmxInjectPendingEvent() call may lazily import guest-CPU state on demand causing
10331 * the below force flags to be set.
10332 */
10333 if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_HM_UPDATE_CR3))
10334 {
10335 Assert(!(ASMAtomicUoReadU64(&pVCpu->cpum.GstCtx.fExtrn) & CPUMCTX_EXTRN_CR3));
10336 int rc2 = PGMUpdateCR3(pVCpu, CPUMGetGuestCR3(pVCpu));
10337 AssertMsgReturn(rc2 == VINF_SUCCESS || rc2 == VINF_PGM_SYNC_CR3,
10338 ("%Rrc\n", rc2), RT_FAILURE_NP(rc2) ? rc2 : VERR_IPE_UNEXPECTED_INFO_STATUS);
10339 Assert(!VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_HM_UPDATE_CR3));
10340 }
10341 if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_HM_UPDATE_PAE_PDPES))
10342 {
10343 PGMGstUpdatePaePdpes(pVCpu, &pVCpu->hm.s.aPdpes[0]);
10344 Assert(!VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_HM_UPDATE_PAE_PDPES));
10345 }
10346
10347#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
10348 /* Paranoia. */
10349 Assert(!pVmxTransient->fIsNestedGuest || CPUMIsGuestInVmxNonRootMode(&pVCpu->cpum.GstCtx));
10350#endif
10351
10352 /*
10353 * No longjmps to ring-3 from this point on!!!
10354 * Asserts() will still longjmp to ring-3 (but won't return), which is intentional, better than a kernel panic.
10355 * This also disables flushing of the R0-logger instance (if any).
10356 */
10357 VMMRZCallRing3Disable(pVCpu);
10358
10359 /*
10360 * Export the guest state bits.
10361 *
10362 * We cannot perform longjmps while loading the guest state because we do not preserve the
10363 * host/guest state (although the VMCS will be preserved) across longjmps which can cause
10364 * CPU migration.
10365 *
10366 * If we are injecting events to a real-on-v86 mode guest, we would have updated RIP and some segment
10367 * registers. Hence, exporting of the guest state needs to be done -after- injection of events.
10368 */
10369 rcStrict = hmR0VmxExportGuestStateOptimal(pVCpu, pVmxTransient);
10370 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
10371 { /* likely */ }
10372 else
10373 {
10374 VMMRZCallRing3Enable(pVCpu);
10375 return rcStrict;
10376 }
10377
10378 /*
10379 * We disable interrupts so that we don't miss any interrupts that would flag preemption
10380 * (IPI/timers etc.) when thread-context hooks aren't used and we've been running with
10381 * preemption disabled for a while. Since this is purely to aid the
10382 * RTThreadPreemptIsPending() code, it doesn't matter that it may temporarily reenable and
10383 * disable interrupt on NT.
10384 *
10385 * We need to check for force-flags that could've possible been altered since we last
10386 * checked them (e.g. by PDMGetInterrupt() leaving the PDM critical section,
10387 * see @bugref{6398}).
10388 *
10389 * We also check a couple of other force-flags as a last opportunity to get the EMT back
10390 * to ring-3 before executing guest code.
10391 */
10392 pVmxTransient->fEFlags = ASMIntDisableFlags();
10393
10394 if ( ( !VM_FF_IS_ANY_SET(pVM, VM_FF_EMT_RENDEZVOUS | VM_FF_TM_VIRTUAL_SYNC)
10395 && !VMCPU_FF_IS_ANY_SET(pVCpu, VMCPU_FF_HM_TO_R3_MASK))
10396 || ( fStepping /* Optimized for the non-stepping case, so a bit of unnecessary work when stepping. */
10397 && !VMCPU_FF_IS_ANY_SET(pVCpu, VMCPU_FF_HM_TO_R3_MASK & ~(VMCPU_FF_TIMER | VMCPU_FF_PDM_CRITSECT))) )
10398 {
10399 if (!RTThreadPreemptIsPending(NIL_RTTHREAD))
10400 {
10401#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
10402 /*
10403 * If we are executing a nested-guest make sure that we should intercept subsequent
10404 * events. The one we are injecting might be part of VM-entry. This is mainly to keep
10405 * the VM-exit instruction emulation happy.
10406 */
10407 if (pVmxTransient->fIsNestedGuest)
10408 pVCpu->cpum.GstCtx.hwvirt.vmx.fInterceptEvents = true;
10409#endif
10410
10411 /*
10412 * We've injected any pending events. This is really the point of no return (to ring-3).
10413 *
10414 * Note! The caller expects to continue with interrupts & longjmps disabled on successful
10415 * returns from this function, so do -not- enable them here.
10416 */
10417 pVCpu->hm.s.Event.fPending = false;
10418 return VINF_SUCCESS;
10419 }
10420
10421 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchPendingHostIrq);
10422 rcStrict = VINF_EM_RAW_INTERRUPT;
10423 }
10424 else
10425 {
10426 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchHmToR3FF);
10427 rcStrict = VINF_EM_RAW_TO_R3;
10428 }
10429
10430 ASMSetFlags(pVmxTransient->fEFlags);
10431 VMMRZCallRing3Enable(pVCpu);
10432
10433 return rcStrict;
10434}
10435
10436
10437/**
10438 * Final preparations before executing guest code using hardware-assisted VMX.
10439 *
10440 * We can no longer get preempted to a different host CPU and there are no returns
10441 * to ring-3. We ignore any errors that may happen from this point (e.g. VMWRITE
10442 * failures), this function is not intended to fail sans unrecoverable hardware
10443 * errors.
10444 *
10445 * @param pVCpu The cross context virtual CPU structure.
10446 * @param pVmxTransient The VMX-transient structure.
10447 *
10448 * @remarks Called with preemption disabled.
10449 * @remarks No-long-jump zone!!!
10450 */
10451static void hmR0VmxPreRunGuestCommitted(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
10452{
10453 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
10454 Assert(VMMR0IsLogFlushDisabled(pVCpu));
10455 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
10456 Assert(!pVCpu->hm.s.Event.fPending);
10457
10458 /*
10459 * Indicate start of guest execution and where poking EMT out of guest-context is recognized.
10460 */
10461 VMCPU_ASSERT_STATE(pVCpu, VMCPUSTATE_STARTED_HM);
10462 VMCPU_SET_STATE(pVCpu, VMCPUSTATE_STARTED_EXEC);
10463
10464 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
10465 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
10466 PHMPHYSCPU pHostCpu = hmR0GetCurrentCpu();
10467 RTCPUID const idCurrentCpu = pHostCpu->idCpu;
10468
10469 if (!CPUMIsGuestFPUStateActive(pVCpu))
10470 {
10471 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatLoadGuestFpuState, x);
10472 if (CPUMR0LoadGuestFPU(pVM, pVCpu) == VINF_CPUM_HOST_CR0_MODIFIED)
10473 pVCpu->hm.s.fCtxChanged |= HM_CHANGED_HOST_CONTEXT;
10474 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatLoadGuestFpuState, x);
10475 STAM_COUNTER_INC(&pVCpu->hm.s.StatLoadGuestFpu);
10476 }
10477
10478 /*
10479 * Re-export the host state bits as we may've been preempted (only happens when
10480 * thread-context hooks are used or when the VM start function changes) or if
10481 * the host CR0 is modified while loading the guest FPU state above.
10482 *
10483 * The 64-on-32 switcher saves the (64-bit) host state into the VMCS and if we
10484 * changed the switcher back to 32-bit, we *must* save the 32-bit host state here,
10485 * see @bugref{8432}.
10486 *
10487 * This may also happen when switching to/from a nested-guest VMCS without leaving
10488 * ring-0.
10489 */
10490 if (pVCpu->hm.s.fCtxChanged & HM_CHANGED_HOST_CONTEXT)
10491 {
10492 hmR0VmxExportHostState(pVCpu);
10493 STAM_COUNTER_INC(&pVCpu->hm.s.StatExportHostState);
10494 }
10495 Assert(!(pVCpu->hm.s.fCtxChanged & HM_CHANGED_HOST_CONTEXT));
10496
10497 /*
10498 * Export the state shared between host and guest (FPU, debug, lazy MSRs).
10499 */
10500 if (pVCpu->hm.s.fCtxChanged & HM_CHANGED_VMX_HOST_GUEST_SHARED_STATE)
10501 hmR0VmxExportSharedState(pVCpu, pVmxTransient);
10502 AssertMsg(!pVCpu->hm.s.fCtxChanged, ("fCtxChanged=%#RX64\n", pVCpu->hm.s.fCtxChanged));
10503
10504 /*
10505 * Store status of the shared guest/host debug state at the time of VM-entry.
10506 */
10507 pVmxTransient->fWasGuestDebugStateActive = CPUMIsGuestDebugStateActive(pVCpu);
10508 pVmxTransient->fWasHyperDebugStateActive = CPUMIsHyperDebugStateActive(pVCpu);
10509
10510 /*
10511 * Always cache the TPR-shadow if the virtual-APIC page exists, thereby skipping
10512 * more than one conditional check. The post-run side of our code shall determine
10513 * if it needs to sync. the virtual APIC TPR with the TPR-shadow.
10514 */
10515 if (pVmcsInfo->pbVirtApic)
10516 pVmxTransient->u8GuestTpr = pVmcsInfo->pbVirtApic[XAPIC_OFF_TPR];
10517
10518 /*
10519 * Update the host MSRs values in the VM-exit MSR-load area.
10520 */
10521 if (!pVCpu->hm.s.vmx.fUpdatedHostAutoMsrs)
10522 {
10523 if (pVmcsInfo->cExitMsrLoad > 0)
10524 hmR0VmxUpdateAutoLoadHostMsrs(pVCpu, pVmcsInfo);
10525 pVCpu->hm.s.vmx.fUpdatedHostAutoMsrs = true;
10526 }
10527
10528 /*
10529 * Evaluate if we need to intercept guest RDTSC/P accesses. Set up the
10530 * VMX-preemption timer based on the next virtual sync clock deadline.
10531 */
10532 if ( !pVmxTransient->fUpdatedTscOffsettingAndPreemptTimer
10533 || idCurrentCpu != pVCpu->hm.s.idLastCpu)
10534 {
10535 hmR0VmxUpdateTscOffsettingAndPreemptTimer(pVCpu, pVmxTransient);
10536 pVmxTransient->fUpdatedTscOffsettingAndPreemptTimer = true;
10537 }
10538
10539 /* Record statistics of how often we use TSC offsetting as opposed to intercepting RDTSC/P. */
10540 bool const fIsRdtscIntercepted = RT_BOOL(pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_RDTSC_EXIT);
10541 if (!fIsRdtscIntercepted)
10542 STAM_COUNTER_INC(&pVCpu->hm.s.StatTscOffset);
10543 else
10544 STAM_COUNTER_INC(&pVCpu->hm.s.StatTscIntercept);
10545
10546 ASMAtomicWriteBool(&pVCpu->hm.s.fCheckedTLBFlush, true); /* Used for TLB flushing, set this across the world switch. */
10547 hmR0VmxFlushTaggedTlb(pHostCpu, pVCpu, pVmcsInfo); /* Invalidate the appropriate guest entries from the TLB. */
10548 Assert(idCurrentCpu == pVCpu->hm.s.idLastCpu);
10549 pVCpu->hm.s.vmx.LastError.idCurrentCpu = idCurrentCpu; /* Record the error reporting info. with the current host CPU. */
10550 pVmcsInfo->idHostCpuState = idCurrentCpu; /* Record the CPU for which the host-state has been exported. */
10551 pVmcsInfo->idHostCpuExec = idCurrentCpu; /* Record the CPU on which we shall execute. */
10552
10553 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatEntry, &pVCpu->hm.s.StatInGC, x);
10554
10555 TMNotifyStartOfExecution(pVM, pVCpu); /* Notify TM to resume its clocks when TSC is tied to execution,
10556 as we're about to start executing the guest. */
10557
10558 /*
10559 * Load the guest TSC_AUX MSR when we are not intercepting RDTSCP.
10560 *
10561 * This is done this late as updating the TSC offsetting/preemption timer above
10562 * figures out if we can skip intercepting RDTSCP by calculating the number of
10563 * host CPU ticks till the next virtual sync deadline (for the dynamic case).
10564 */
10565 if ( (pVmcsInfo->u32ProcCtls2 & VMX_PROC_CTLS2_RDTSCP)
10566 && !fIsRdtscIntercepted)
10567 {
10568 hmR0VmxImportGuestState(pVCpu, pVmcsInfo, CPUMCTX_EXTRN_TSC_AUX);
10569
10570 /* NB: Because we call hmR0VmxAddAutoLoadStoreMsr with fUpdateHostMsr=true,
10571 it's safe even after hmR0VmxUpdateAutoLoadHostMsrs has already been done. */
10572 int rc = hmR0VmxAddAutoLoadStoreMsr(pVCpu, pVmxTransient, MSR_K8_TSC_AUX, CPUMGetGuestTscAux(pVCpu),
10573 true /* fSetReadWrite */, true /* fUpdateHostMsr */);
10574 AssertRC(rc);
10575 Assert(!pVmxTransient->fRemoveTscAuxMsr);
10576 pVmxTransient->fRemoveTscAuxMsr = true;
10577 }
10578
10579#ifdef VBOX_STRICT
10580 Assert(pVCpu->hm.s.vmx.fUpdatedHostAutoMsrs);
10581 hmR0VmxCheckAutoLoadStoreMsrs(pVCpu, pVmcsInfo, pVmxTransient->fIsNestedGuest);
10582 hmR0VmxCheckHostEferMsr(pVCpu, pVmcsInfo);
10583 AssertRC(hmR0VmxCheckVmcsCtls(pVCpu, pVmcsInfo, pVmxTransient->fIsNestedGuest));
10584#endif
10585
10586#ifdef HMVMX_ALWAYS_CHECK_GUEST_STATE
10587 /** @todo r=ramshankar: We can now probably use iemVmxVmentryCheckGuestState here.
10588 * Add a PVMXMSRS parameter to it, so that IEM can look at the host MSRs,
10589 * see @bugref{9180#c54}. */
10590 uint32_t const uInvalidReason = hmR0VmxCheckGuestState(pVCpu, pVmcsInfo);
10591 if (uInvalidReason != VMX_IGS_REASON_NOT_FOUND)
10592 Log4(("hmR0VmxCheckGuestState returned %#x\n", uInvalidReason));
10593#endif
10594}
10595
10596
10597/**
10598 * First C routine invoked after running guest code using hardware-assisted VMX.
10599 *
10600 * @param pVCpu The cross context virtual CPU structure.
10601 * @param pVmxTransient The VMX-transient structure.
10602 * @param rcVMRun Return code of VMLAUNCH/VMRESUME.
10603 *
10604 * @remarks Called with interrupts disabled, and returns with interrupts enabled!
10605 *
10606 * @remarks No-long-jump zone!!! This function will however re-enable longjmps
10607 * unconditionally when it is safe to do so.
10608 */
10609static void hmR0VmxPostRunGuest(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient, int rcVMRun)
10610{
10611 uint64_t const uHostTsc = ASMReadTSC(); /** @todo We can do a lot better here, see @bugref{9180#c38}. */
10612
10613 ASMAtomicWriteBool(&pVCpu->hm.s.fCheckedTLBFlush, false); /* See HMInvalidatePageOnAllVCpus(): used for TLB flushing. */
10614 ASMAtomicIncU32(&pVCpu->hm.s.cWorldSwitchExits); /* Initialized in vmR3CreateUVM(): used for EMT poking. */
10615 pVCpu->hm.s.fCtxChanged = 0; /* Exits/longjmps to ring-3 requires saving the guest state. */
10616 pVmxTransient->fVmcsFieldsRead = 0; /* Transient fields need to be read from the VMCS. */
10617 pVmxTransient->fVectoringPF = false; /* Vectoring page-fault needs to be determined later. */
10618 pVmxTransient->fVectoringDoublePF = false; /* Vectoring double page-fault needs to be determined later. */
10619
10620 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
10621 if (!(pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_RDTSC_EXIT))
10622 {
10623 uint64_t uGstTsc;
10624 if (!pVmxTransient->fIsNestedGuest)
10625 uGstTsc = uHostTsc + pVmcsInfo->u64TscOffset;
10626 else
10627 {
10628 uint64_t const uNstGstTsc = uHostTsc + pVmcsInfo->u64TscOffset;
10629 uGstTsc = CPUMRemoveNestedGuestTscOffset(pVCpu, uNstGstTsc);
10630 }
10631 TMCpuTickSetLastSeen(pVCpu, uGstTsc); /* Update TM with the guest TSC. */
10632 }
10633
10634 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatInGC, &pVCpu->hm.s.StatPreExit, x);
10635 TMNotifyEndOfExecution(pVCpu->CTX_SUFF(pVM), pVCpu); /* Notify TM that the guest is no longer running. */
10636 VMCPU_SET_STATE(pVCpu, VMCPUSTATE_STARTED_HM);
10637
10638 pVCpu->hm.s.vmx.fRestoreHostFlags |= VMX_RESTORE_HOST_REQUIRED; /* Some host state messed up by VMX needs restoring. */
10639 pVmcsInfo->fVmcsState |= VMX_V_VMCS_LAUNCH_STATE_LAUNCHED; /* Use VMRESUME instead of VMLAUNCH in the next run. */
10640#ifdef VBOX_STRICT
10641 hmR0VmxCheckHostEferMsr(pVCpu, pVmcsInfo); /* Verify that the host EFER MSR wasn't modified. */
10642#endif
10643 Assert(!ASMIntAreEnabled());
10644 ASMSetFlags(pVmxTransient->fEFlags); /* Enable interrupts. */
10645 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
10646
10647#ifdef HMVMX_ALWAYS_CLEAN_TRANSIENT
10648 /*
10649 * Clean all the VMCS fields in the transient structure before reading
10650 * anything from the VMCS.
10651 */
10652 pVmxTransient->uExitReason = 0;
10653 pVmxTransient->uExitIntErrorCode = 0;
10654 pVmxTransient->uExitQual = 0;
10655 pVmxTransient->uGuestLinearAddr = 0;
10656 pVmxTransient->uExitIntInfo = 0;
10657 pVmxTransient->cbExitInstr = 0;
10658 pVmxTransient->ExitInstrInfo.u = 0;
10659 pVmxTransient->uEntryIntInfo = 0;
10660 pVmxTransient->uEntryXcptErrorCode = 0;
10661 pVmxTransient->cbEntryInstr = 0;
10662 pVmxTransient->uIdtVectoringInfo = 0;
10663 pVmxTransient->uIdtVectoringErrorCode = 0;
10664#endif
10665
10666 /*
10667 * Save the basic VM-exit reason and check if the VM-entry failed.
10668 * See Intel spec. 24.9.1 "Basic VM-exit Information".
10669 */
10670 uint32_t uExitReason;
10671 int rc = VMXReadVmcs32(VMX_VMCS32_RO_EXIT_REASON, &uExitReason);
10672 AssertRC(rc);
10673 pVmxTransient->uExitReason = VMX_EXIT_REASON_BASIC(uExitReason);
10674 pVmxTransient->fVMEntryFailed = VMX_EXIT_REASON_HAS_ENTRY_FAILED(uExitReason);
10675
10676 /*
10677 * Log the VM-exit before logging anything else as otherwise it might be a
10678 * tad confusing what happens before and after the world-switch.
10679 */
10680 HMVMX_LOG_EXIT(pVCpu, uExitReason);
10681
10682 /*
10683 * Remove the TSC_AUX MSR from the auto-load/store MSR area and reset any MSR
10684 * bitmap permissions, if it was added before VM-entry.
10685 */
10686 if (pVmxTransient->fRemoveTscAuxMsr)
10687 {
10688 hmR0VmxRemoveAutoLoadStoreMsr(pVCpu, pVmxTransient, MSR_K8_TSC_AUX);
10689 pVmxTransient->fRemoveTscAuxMsr = false;
10690 }
10691
10692 /*
10693 * Check if VMLAUNCH/VMRESUME succeeded.
10694 * If this failed, we cause a guru meditation and cease further execution.
10695 *
10696 * However, if we are executing a nested-guest we might fail if we use the
10697 * fast path rather than fully emulating VMLAUNCH/VMRESUME instruction in IEM.
10698 */
10699 if (RT_LIKELY(rcVMRun == VINF_SUCCESS))
10700 {
10701 /*
10702 * Update the VM-exit history array here even if the VM-entry failed due to:
10703 * - Invalid guest state.
10704 * - MSR loading.
10705 * - Machine-check event.
10706 *
10707 * In any of the above cases we will still have a "valid" VM-exit reason
10708 * despite @a fVMEntryFailed being false.
10709 *
10710 * See Intel spec. 26.7 "VM-Entry failures during or after loading guest state".
10711 *
10712 * Note! We don't have CS or RIP at this point. Will probably address that later
10713 * by amending the history entry added here.
10714 */
10715 EMHistoryAddExit(pVCpu, EMEXIT_MAKE_FT(EMEXIT_F_KIND_VMX, pVmxTransient->uExitReason & EMEXIT_F_TYPE_MASK),
10716 UINT64_MAX, uHostTsc);
10717
10718 if (RT_LIKELY(!pVmxTransient->fVMEntryFailed))
10719 {
10720 VMMRZCallRing3Enable(pVCpu);
10721
10722 Assert(!VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_HM_UPDATE_CR3));
10723 Assert(!VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_HM_UPDATE_PAE_PDPES));
10724
10725#ifdef HMVMX_ALWAYS_SAVE_RO_GUEST_STATE
10726 hmR0VmxReadAllRoFieldsVmcs(pVmxTransient);
10727#endif
10728#if defined(HMVMX_ALWAYS_SYNC_FULL_GUEST_STATE) || defined(HMVMX_ALWAYS_SAVE_FULL_GUEST_STATE)
10729 rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, HMVMX_CPUMCTX_EXTRN_ALL);
10730 AssertRC(rc);
10731#elif defined(HMVMX_ALWAYS_SAVE_GUEST_RFLAGS)
10732 rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, HMVMX_CPUMCTX_EXTRN_RFLAGS);
10733 AssertRC(rc);
10734#else
10735 /*
10736 * Import the guest-interruptibility state always as we need it while evaluating
10737 * injecting events on re-entry.
10738 *
10739 * We don't import CR0 (when unrestricted guest execution is unavailable) despite
10740 * checking for real-mode while exporting the state because all bits that cause
10741 * mode changes wrt CR0 are intercepted.
10742 */
10743 rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, CPUMCTX_EXTRN_HM_VMX_INT_STATE);
10744 AssertRC(rc);
10745#endif
10746
10747 /*
10748 * Sync the TPR shadow with our APIC state.
10749 */
10750 if ( !pVmxTransient->fIsNestedGuest
10751 && (pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_USE_TPR_SHADOW))
10752 {
10753 Assert(pVmcsInfo->pbVirtApic);
10754 if (pVmxTransient->u8GuestTpr != pVmcsInfo->pbVirtApic[XAPIC_OFF_TPR])
10755 {
10756 rc = APICSetTpr(pVCpu, pVmcsInfo->pbVirtApic[XAPIC_OFF_TPR]);
10757 AssertRC(rc);
10758 ASMAtomicOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_APIC_TPR);
10759 }
10760 }
10761
10762 Assert(VMMRZCallRing3IsEnabled(pVCpu));
10763 return;
10764 }
10765 }
10766#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
10767 else if (pVmxTransient->fIsNestedGuest)
10768 AssertMsgFailed(("VMLAUNCH/VMRESUME failed but shouldn't happen when VMLAUNCH/VMRESUME was emulated in IEM!\n"));
10769#endif
10770 else
10771 Log4Func(("VM-entry failure: rcVMRun=%Rrc fVMEntryFailed=%RTbool\n", rcVMRun, pVmxTransient->fVMEntryFailed));
10772
10773 VMMRZCallRing3Enable(pVCpu);
10774}
10775
10776
10777/**
10778 * Runs the guest code using hardware-assisted VMX the normal way.
10779 *
10780 * @returns VBox status code.
10781 * @param pVCpu The cross context virtual CPU structure.
10782 * @param pcLoops Pointer to the number of executed loops.
10783 */
10784static VBOXSTRICTRC hmR0VmxRunGuestCodeNormal(PVMCPUCC pVCpu, uint32_t *pcLoops)
10785{
10786 uint32_t const cMaxResumeLoops = pVCpu->CTX_SUFF(pVM)->hm.s.cMaxResumeLoops;
10787 Assert(pcLoops);
10788 Assert(*pcLoops <= cMaxResumeLoops);
10789 Assert(!CPUMIsGuestInVmxNonRootMode(&pVCpu->cpum.GstCtx));
10790
10791#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
10792 /*
10793 * Switch to the guest VMCS as we may have transitioned from executing the nested-guest
10794 * without leaving ring-0. Otherwise, if we came from ring-3 we would have loaded the
10795 * guest VMCS while entering the VMX ring-0 session.
10796 */
10797 if (pVCpu->hm.s.vmx.fSwitchedToNstGstVmcs)
10798 {
10799 int rc = hmR0VmxSwitchToGstOrNstGstVmcs(pVCpu, false /* fSwitchToNstGstVmcs */);
10800 if (RT_SUCCESS(rc))
10801 { /* likely */ }
10802 else
10803 {
10804 LogRelFunc(("Failed to switch to the guest VMCS. rc=%Rrc\n", rc));
10805 return rc;
10806 }
10807 }
10808#endif
10809
10810 VMXTRANSIENT VmxTransient;
10811 RT_ZERO(VmxTransient);
10812 VmxTransient.pVmcsInfo = hmGetVmxActiveVmcsInfo(pVCpu);
10813
10814 /* Paranoia. */
10815 Assert(VmxTransient.pVmcsInfo == &pVCpu->hm.s.vmx.VmcsInfo);
10816
10817 VBOXSTRICTRC rcStrict = VERR_INTERNAL_ERROR_5;
10818 for (;;)
10819 {
10820 Assert(!HMR0SuspendPending());
10821 HMVMX_ASSERT_CPU_SAFE(pVCpu);
10822 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatEntry, x);
10823
10824 /*
10825 * Preparatory work for running nested-guest code, this may force us to
10826 * return to ring-3.
10827 *
10828 * Warning! This bugger disables interrupts on VINF_SUCCESS!
10829 */
10830 rcStrict = hmR0VmxPreRunGuest(pVCpu, &VmxTransient, false /* fStepping */);
10831 if (rcStrict != VINF_SUCCESS)
10832 break;
10833
10834 /* Interrupts are disabled at this point! */
10835 hmR0VmxPreRunGuestCommitted(pVCpu, &VmxTransient);
10836 int rcRun = hmR0VmxRunGuest(pVCpu, &VmxTransient);
10837 hmR0VmxPostRunGuest(pVCpu, &VmxTransient, rcRun);
10838 /* Interrupts are re-enabled at this point! */
10839
10840 /*
10841 * Check for errors with running the VM (VMLAUNCH/VMRESUME).
10842 */
10843 if (RT_SUCCESS(rcRun))
10844 { /* very likely */ }
10845 else
10846 {
10847 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatPreExit, x);
10848 hmR0VmxReportWorldSwitchError(pVCpu, rcRun, &VmxTransient);
10849 return rcRun;
10850 }
10851
10852 /*
10853 * Profile the VM-exit.
10854 */
10855 AssertMsg(VmxTransient.uExitReason <= VMX_EXIT_MAX, ("%#x\n", VmxTransient.uExitReason));
10856 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitAll);
10857 STAM_COUNTER_INC(&pVCpu->hm.s.paStatExitReasonR0[VmxTransient.uExitReason & MASK_EXITREASON_STAT]);
10858 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatPreExit, &pVCpu->hm.s.StatExitHandling, x);
10859 HMVMX_START_EXIT_DISPATCH_PROF();
10860
10861 VBOXVMM_R0_HMVMX_VMEXIT_NOCTX(pVCpu, &pVCpu->cpum.GstCtx, VmxTransient.uExitReason);
10862
10863 /*
10864 * Handle the VM-exit.
10865 */
10866#ifdef HMVMX_USE_FUNCTION_TABLE
10867 rcStrict = g_apfnVMExitHandlers[VmxTransient.uExitReason](pVCpu, &VmxTransient);
10868#else
10869 rcStrict = hmR0VmxHandleExit(pVCpu, &VmxTransient);
10870#endif
10871 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExitHandling, x);
10872 if (rcStrict == VINF_SUCCESS)
10873 {
10874 if (++(*pcLoops) <= cMaxResumeLoops)
10875 continue;
10876 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchMaxResumeLoops);
10877 rcStrict = VINF_EM_RAW_INTERRUPT;
10878 }
10879 break;
10880 }
10881
10882 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatEntry, x);
10883 return rcStrict;
10884}
10885
10886
10887#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
10888/**
10889 * Runs the nested-guest code using hardware-assisted VMX.
10890 *
10891 * @returns VBox status code.
10892 * @param pVCpu The cross context virtual CPU structure.
10893 * @param pcLoops Pointer to the number of executed loops.
10894 *
10895 * @sa hmR0VmxRunGuestCodeNormal.
10896 */
10897static VBOXSTRICTRC hmR0VmxRunGuestCodeNested(PVMCPUCC pVCpu, uint32_t *pcLoops)
10898{
10899 uint32_t const cMaxResumeLoops = pVCpu->CTX_SUFF(pVM)->hm.s.cMaxResumeLoops;
10900 Assert(pcLoops);
10901 Assert(*pcLoops <= cMaxResumeLoops);
10902 Assert(CPUMIsGuestInVmxNonRootMode(&pVCpu->cpum.GstCtx));
10903
10904 /*
10905 * Switch to the nested-guest VMCS as we may have transitioned from executing the
10906 * guest without leaving ring-0. Otherwise, if we came from ring-3 we would have
10907 * loaded the nested-guest VMCS while entering the VMX ring-0 session.
10908 */
10909 if (!pVCpu->hm.s.vmx.fSwitchedToNstGstVmcs)
10910 {
10911 int rc = hmR0VmxSwitchToGstOrNstGstVmcs(pVCpu, true /* fSwitchToNstGstVmcs */);
10912 if (RT_SUCCESS(rc))
10913 { /* likely */ }
10914 else
10915 {
10916 LogRelFunc(("Failed to switch to the nested-guest VMCS. rc=%Rrc\n", rc));
10917 return rc;
10918 }
10919 }
10920
10921 VMXTRANSIENT VmxTransient;
10922 RT_ZERO(VmxTransient);
10923 VmxTransient.pVmcsInfo = hmGetVmxActiveVmcsInfo(pVCpu);
10924 VmxTransient.fIsNestedGuest = true;
10925
10926 /* Paranoia. */
10927 Assert(VmxTransient.pVmcsInfo == &pVCpu->hm.s.vmx.VmcsInfoNstGst);
10928
10929 VBOXSTRICTRC rcStrict = VERR_INTERNAL_ERROR_5;
10930 for (;;)
10931 {
10932 Assert(!HMR0SuspendPending());
10933 HMVMX_ASSERT_CPU_SAFE(pVCpu);
10934 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatEntry, x);
10935
10936 /*
10937 * Preparatory work for running guest code, this may force us to
10938 * return to ring-3.
10939 *
10940 * Warning! This bugger disables interrupts on VINF_SUCCESS!
10941 */
10942 rcStrict = hmR0VmxPreRunGuest(pVCpu, &VmxTransient, false /* fStepping */);
10943 if (rcStrict != VINF_SUCCESS)
10944 break;
10945
10946 /* Interrupts are disabled at this point! */
10947 hmR0VmxPreRunGuestCommitted(pVCpu, &VmxTransient);
10948 int rcRun = hmR0VmxRunGuest(pVCpu, &VmxTransient);
10949 hmR0VmxPostRunGuest(pVCpu, &VmxTransient, rcRun);
10950 /* Interrupts are re-enabled at this point! */
10951
10952 /*
10953 * Check for errors with running the VM (VMLAUNCH/VMRESUME).
10954 */
10955 if (RT_SUCCESS(rcRun))
10956 { /* very likely */ }
10957 else
10958 {
10959 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatPreExit, x);
10960 hmR0VmxReportWorldSwitchError(pVCpu, rcRun, &VmxTransient);
10961 return rcRun;
10962 }
10963
10964 /*
10965 * Profile the VM-exit.
10966 */
10967 AssertMsg(VmxTransient.uExitReason <= VMX_EXIT_MAX, ("%#x\n", VmxTransient.uExitReason));
10968 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitAll);
10969 STAM_COUNTER_INC(&pVCpu->hm.s.StatNestedExitAll);
10970 STAM_COUNTER_INC(&pVCpu->hm.s.paStatNestedExitReasonR0[VmxTransient.uExitReason & MASK_EXITREASON_STAT]);
10971 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatPreExit, &pVCpu->hm.s.StatExitHandling, x);
10972 HMVMX_START_EXIT_DISPATCH_PROF();
10973
10974 VBOXVMM_R0_HMVMX_VMEXIT_NOCTX(pVCpu, &pVCpu->cpum.GstCtx, VmxTransient.uExitReason);
10975
10976 /*
10977 * Handle the VM-exit.
10978 */
10979 rcStrict = hmR0VmxHandleExitNested(pVCpu, &VmxTransient);
10980 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExitHandling, x);
10981 if (rcStrict == VINF_SUCCESS)
10982 {
10983 if (!CPUMIsGuestInVmxNonRootMode(&pVCpu->cpum.GstCtx))
10984 {
10985 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchNstGstVmexit);
10986 rcStrict = VINF_VMX_VMEXIT;
10987 }
10988 else
10989 {
10990 if (++(*pcLoops) <= cMaxResumeLoops)
10991 continue;
10992 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchMaxResumeLoops);
10993 rcStrict = VINF_EM_RAW_INTERRUPT;
10994 }
10995 }
10996 else
10997 Assert(rcStrict != VINF_VMX_VMEXIT);
10998 break;
10999 }
11000
11001 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatEntry, x);
11002 return rcStrict;
11003}
11004#endif /* VBOX_WITH_NESTED_HWVIRT_VMX */
11005
11006
11007/** @name Execution loop for single stepping, DBGF events and expensive Dtrace
11008 * probes.
11009 *
11010 * The following few functions and associated structure contains the bloat
11011 * necessary for providing detailed debug events and dtrace probes as well as
11012 * reliable host side single stepping. This works on the principle of
11013 * "subclassing" the normal execution loop and workers. We replace the loop
11014 * method completely and override selected helpers to add necessary adjustments
11015 * to their core operation.
11016 *
11017 * The goal is to keep the "parent" code lean and mean, so as not to sacrifice
11018 * any performance for debug and analysis features.
11019 *
11020 * @{
11021 */
11022
11023/**
11024 * Transient per-VCPU debug state of VMCS and related info. we save/restore in
11025 * the debug run loop.
11026 */
11027typedef struct VMXRUNDBGSTATE
11028{
11029 /** The RIP we started executing at. This is for detecting that we stepped. */
11030 uint64_t uRipStart;
11031 /** The CS we started executing with. */
11032 uint16_t uCsStart;
11033
11034 /** Whether we've actually modified the 1st execution control field. */
11035 bool fModifiedProcCtls : 1;
11036 /** Whether we've actually modified the 2nd execution control field. */
11037 bool fModifiedProcCtls2 : 1;
11038 /** Whether we've actually modified the exception bitmap. */
11039 bool fModifiedXcptBitmap : 1;
11040
11041 /** We desire the modified the CR0 mask to be cleared. */
11042 bool fClearCr0Mask : 1;
11043 /** We desire the modified the CR4 mask to be cleared. */
11044 bool fClearCr4Mask : 1;
11045 /** Stuff we need in VMX_VMCS32_CTRL_PROC_EXEC. */
11046 uint32_t fCpe1Extra;
11047 /** Stuff we do not want in VMX_VMCS32_CTRL_PROC_EXEC. */
11048 uint32_t fCpe1Unwanted;
11049 /** Stuff we need in VMX_VMCS32_CTRL_PROC_EXEC2. */
11050 uint32_t fCpe2Extra;
11051 /** Extra stuff we need in VMX_VMCS32_CTRL_EXCEPTION_BITMAP. */
11052 uint32_t bmXcptExtra;
11053 /** The sequence number of the Dtrace provider settings the state was
11054 * configured against. */
11055 uint32_t uDtraceSettingsSeqNo;
11056 /** VM-exits to check (one bit per VM-exit). */
11057 uint32_t bmExitsToCheck[3];
11058
11059 /** The initial VMX_VMCS32_CTRL_PROC_EXEC value (helps with restore). */
11060 uint32_t fProcCtlsInitial;
11061 /** The initial VMX_VMCS32_CTRL_PROC_EXEC2 value (helps with restore). */
11062 uint32_t fProcCtls2Initial;
11063 /** The initial VMX_VMCS32_CTRL_EXCEPTION_BITMAP value (helps with restore). */
11064 uint32_t bmXcptInitial;
11065} VMXRUNDBGSTATE;
11066AssertCompileMemberSize(VMXRUNDBGSTATE, bmExitsToCheck, (VMX_EXIT_MAX + 1 + 31) / 32 * 4);
11067typedef VMXRUNDBGSTATE *PVMXRUNDBGSTATE;
11068
11069
11070/**
11071 * Initializes the VMXRUNDBGSTATE structure.
11072 *
11073 * @param pVCpu The cross context virtual CPU structure of the
11074 * calling EMT.
11075 * @param pVmxTransient The VMX-transient structure.
11076 * @param pDbgState The debug state to initialize.
11077 */
11078static void hmR0VmxRunDebugStateInit(PVMCPUCC pVCpu, PCVMXTRANSIENT pVmxTransient, PVMXRUNDBGSTATE pDbgState)
11079{
11080 pDbgState->uRipStart = pVCpu->cpum.GstCtx.rip;
11081 pDbgState->uCsStart = pVCpu->cpum.GstCtx.cs.Sel;
11082
11083 pDbgState->fModifiedProcCtls = false;
11084 pDbgState->fModifiedProcCtls2 = false;
11085 pDbgState->fModifiedXcptBitmap = false;
11086 pDbgState->fClearCr0Mask = false;
11087 pDbgState->fClearCr4Mask = false;
11088 pDbgState->fCpe1Extra = 0;
11089 pDbgState->fCpe1Unwanted = 0;
11090 pDbgState->fCpe2Extra = 0;
11091 pDbgState->bmXcptExtra = 0;
11092 pDbgState->fProcCtlsInitial = pVmxTransient->pVmcsInfo->u32ProcCtls;
11093 pDbgState->fProcCtls2Initial = pVmxTransient->pVmcsInfo->u32ProcCtls2;
11094 pDbgState->bmXcptInitial = pVmxTransient->pVmcsInfo->u32XcptBitmap;
11095}
11096
11097
11098/**
11099 * Updates the VMSC fields with changes requested by @a pDbgState.
11100 *
11101 * This is performed after hmR0VmxPreRunGuestDebugStateUpdate as well
11102 * immediately before executing guest code, i.e. when interrupts are disabled.
11103 * We don't check status codes here as we cannot easily assert or return in the
11104 * latter case.
11105 *
11106 * @param pVCpu The cross context virtual CPU structure.
11107 * @param pVmxTransient The VMX-transient structure.
11108 * @param pDbgState The debug state.
11109 */
11110static void hmR0VmxPreRunGuestDebugStateApply(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient, PVMXRUNDBGSTATE pDbgState)
11111{
11112 /*
11113 * Ensure desired flags in VMCS control fields are set.
11114 * (Ignoring write failure here, as we're committed and it's just debug extras.)
11115 *
11116 * Note! We load the shadow CR0 & CR4 bits when we flag the clearing, so
11117 * there should be no stale data in pCtx at this point.
11118 */
11119 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
11120 if ( (pVmcsInfo->u32ProcCtls & pDbgState->fCpe1Extra) != pDbgState->fCpe1Extra
11121 || (pVmcsInfo->u32ProcCtls & pDbgState->fCpe1Unwanted))
11122 {
11123 pVmcsInfo->u32ProcCtls |= pDbgState->fCpe1Extra;
11124 pVmcsInfo->u32ProcCtls &= ~pDbgState->fCpe1Unwanted;
11125 VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, pVmcsInfo->u32ProcCtls);
11126 Log6Func(("VMX_VMCS32_CTRL_PROC_EXEC: %#RX32\n", pVmcsInfo->u32ProcCtls));
11127 pDbgState->fModifiedProcCtls = true;
11128 }
11129
11130 if ((pVmcsInfo->u32ProcCtls2 & pDbgState->fCpe2Extra) != pDbgState->fCpe2Extra)
11131 {
11132 pVmcsInfo->u32ProcCtls2 |= pDbgState->fCpe2Extra;
11133 VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC2, pVmcsInfo->u32ProcCtls2);
11134 Log6Func(("VMX_VMCS32_CTRL_PROC_EXEC2: %#RX32\n", pVmcsInfo->u32ProcCtls2));
11135 pDbgState->fModifiedProcCtls2 = true;
11136 }
11137
11138 if ((pVmcsInfo->u32XcptBitmap & pDbgState->bmXcptExtra) != pDbgState->bmXcptExtra)
11139 {
11140 pVmcsInfo->u32XcptBitmap |= pDbgState->bmXcptExtra;
11141 VMXWriteVmcs32(VMX_VMCS32_CTRL_EXCEPTION_BITMAP, pVmcsInfo->u32XcptBitmap);
11142 Log6Func(("VMX_VMCS32_CTRL_EXCEPTION_BITMAP: %#RX32\n", pVmcsInfo->u32XcptBitmap));
11143 pDbgState->fModifiedXcptBitmap = true;
11144 }
11145
11146 if (pDbgState->fClearCr0Mask && pVmcsInfo->u64Cr0Mask != 0)
11147 {
11148 pVmcsInfo->u64Cr0Mask = 0;
11149 VMXWriteVmcsNw(VMX_VMCS_CTRL_CR0_MASK, 0);
11150 Log6Func(("VMX_VMCS_CTRL_CR0_MASK: 0\n"));
11151 }
11152
11153 if (pDbgState->fClearCr4Mask && pVmcsInfo->u64Cr4Mask != 0)
11154 {
11155 pVmcsInfo->u64Cr4Mask = 0;
11156 VMXWriteVmcsNw(VMX_VMCS_CTRL_CR4_MASK, 0);
11157 Log6Func(("VMX_VMCS_CTRL_CR4_MASK: 0\n"));
11158 }
11159
11160 NOREF(pVCpu);
11161}
11162
11163
11164/**
11165 * Restores VMCS fields that were changed by hmR0VmxPreRunGuestDebugStateApply for
11166 * re-entry next time around.
11167 *
11168 * @returns Strict VBox status code (i.e. informational status codes too).
11169 * @param pVCpu The cross context virtual CPU structure.
11170 * @param pVmxTransient The VMX-transient structure.
11171 * @param pDbgState The debug state.
11172 * @param rcStrict The return code from executing the guest using single
11173 * stepping.
11174 */
11175static VBOXSTRICTRC hmR0VmxRunDebugStateRevert(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient, PVMXRUNDBGSTATE pDbgState,
11176 VBOXSTRICTRC rcStrict)
11177{
11178 /*
11179 * Restore VM-exit control settings as we may not reenter this function the
11180 * next time around.
11181 */
11182 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
11183
11184 /* We reload the initial value, trigger what we can of recalculations the
11185 next time around. From the looks of things, that's all that's required atm. */
11186 if (pDbgState->fModifiedProcCtls)
11187 {
11188 if (!(pDbgState->fProcCtlsInitial & VMX_PROC_CTLS_MOV_DR_EXIT) && CPUMIsHyperDebugStateActive(pVCpu))
11189 pDbgState->fProcCtlsInitial |= VMX_PROC_CTLS_MOV_DR_EXIT; /* Avoid assertion in hmR0VmxLeave */
11190 int rc2 = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, pDbgState->fProcCtlsInitial);
11191 AssertRC(rc2);
11192 pVmcsInfo->u32ProcCtls = pDbgState->fProcCtlsInitial;
11193 }
11194
11195 /* We're currently the only ones messing with this one, so just restore the
11196 cached value and reload the field. */
11197 if ( pDbgState->fModifiedProcCtls2
11198 && pVmcsInfo->u32ProcCtls2 != pDbgState->fProcCtls2Initial)
11199 {
11200 int rc2 = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC2, pDbgState->fProcCtls2Initial);
11201 AssertRC(rc2);
11202 pVmcsInfo->u32ProcCtls2 = pDbgState->fProcCtls2Initial;
11203 }
11204
11205 /* If we've modified the exception bitmap, we restore it and trigger
11206 reloading and partial recalculation the next time around. */
11207 if (pDbgState->fModifiedXcptBitmap)
11208 pVmcsInfo->u32XcptBitmap = pDbgState->bmXcptInitial;
11209
11210 return rcStrict;
11211}
11212
11213
11214/**
11215 * Configures VM-exit controls for current DBGF and DTrace settings.
11216 *
11217 * This updates @a pDbgState and the VMCS execution control fields to reflect
11218 * the necessary VM-exits demanded by DBGF and DTrace.
11219 *
11220 * @param pVCpu The cross context virtual CPU structure.
11221 * @param pVmxTransient The VMX-transient structure. May update
11222 * fUpdatedTscOffsettingAndPreemptTimer.
11223 * @param pDbgState The debug state.
11224 */
11225static void hmR0VmxPreRunGuestDebugStateUpdate(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient, PVMXRUNDBGSTATE pDbgState)
11226{
11227 /*
11228 * Take down the dtrace serial number so we can spot changes.
11229 */
11230 pDbgState->uDtraceSettingsSeqNo = VBOXVMM_GET_SETTINGS_SEQ_NO();
11231 ASMCompilerBarrier();
11232
11233 /*
11234 * We'll rebuild most of the middle block of data members (holding the
11235 * current settings) as we go along here, so start by clearing it all.
11236 */
11237 pDbgState->bmXcptExtra = 0;
11238 pDbgState->fCpe1Extra = 0;
11239 pDbgState->fCpe1Unwanted = 0;
11240 pDbgState->fCpe2Extra = 0;
11241 for (unsigned i = 0; i < RT_ELEMENTS(pDbgState->bmExitsToCheck); i++)
11242 pDbgState->bmExitsToCheck[i] = 0;
11243
11244 /*
11245 * Software interrupts (INT XXh) - no idea how to trigger these...
11246 */
11247 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
11248 if ( DBGF_IS_EVENT_ENABLED(pVM, DBGFEVENT_INTERRUPT_SOFTWARE)
11249 || VBOXVMM_INT_SOFTWARE_ENABLED())
11250 {
11251 ASMBitSet(pDbgState->bmExitsToCheck, VMX_EXIT_XCPT_OR_NMI);
11252 }
11253
11254 /*
11255 * INT3 breakpoints - triggered by #BP exceptions.
11256 */
11257 if (pVM->dbgf.ro.cEnabledInt3Breakpoints > 0)
11258 pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_BP);
11259
11260 /*
11261 * Exception bitmap and XCPT events+probes.
11262 */
11263 for (int iXcpt = 0; iXcpt < (DBGFEVENT_XCPT_LAST - DBGFEVENT_XCPT_FIRST + 1); iXcpt++)
11264 if (DBGF_IS_EVENT_ENABLED(pVM, (DBGFEVENTTYPE)(DBGFEVENT_XCPT_FIRST + iXcpt)))
11265 pDbgState->bmXcptExtra |= RT_BIT_32(iXcpt);
11266
11267 if (VBOXVMM_XCPT_DE_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_DE);
11268 if (VBOXVMM_XCPT_DB_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_DB);
11269 if (VBOXVMM_XCPT_BP_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_BP);
11270 if (VBOXVMM_XCPT_OF_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_OF);
11271 if (VBOXVMM_XCPT_BR_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_BR);
11272 if (VBOXVMM_XCPT_UD_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_UD);
11273 if (VBOXVMM_XCPT_NM_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_NM);
11274 if (VBOXVMM_XCPT_DF_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_DF);
11275 if (VBOXVMM_XCPT_TS_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_TS);
11276 if (VBOXVMM_XCPT_NP_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_NP);
11277 if (VBOXVMM_XCPT_SS_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_SS);
11278 if (VBOXVMM_XCPT_GP_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_GP);
11279 if (VBOXVMM_XCPT_PF_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_PF);
11280 if (VBOXVMM_XCPT_MF_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_MF);
11281 if (VBOXVMM_XCPT_AC_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_AC);
11282 if (VBOXVMM_XCPT_XF_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_XF);
11283 if (VBOXVMM_XCPT_VE_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_VE);
11284 if (VBOXVMM_XCPT_SX_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_SX);
11285
11286 if (pDbgState->bmXcptExtra)
11287 ASMBitSet(pDbgState->bmExitsToCheck, VMX_EXIT_XCPT_OR_NMI);
11288
11289 /*
11290 * Process events and probes for VM-exits, making sure we get the wanted VM-exits.
11291 *
11292 * Note! This is the reverse of what hmR0VmxHandleExitDtraceEvents does.
11293 * So, when adding/changing/removing please don't forget to update it.
11294 *
11295 * Some of the macros are picking up local variables to save horizontal space,
11296 * (being able to see it in a table is the lesser evil here).
11297 */
11298#define IS_EITHER_ENABLED(a_pVM, a_EventSubName) \
11299 ( DBGF_IS_EVENT_ENABLED(a_pVM, RT_CONCAT(DBGFEVENT_, a_EventSubName)) \
11300 || RT_CONCAT3(VBOXVMM_, a_EventSubName, _ENABLED)() )
11301#define SET_ONLY_XBM_IF_EITHER_EN(a_EventSubName, a_uExit) \
11302 if (IS_EITHER_ENABLED(pVM, a_EventSubName)) \
11303 { AssertCompile((unsigned)(a_uExit) < sizeof(pDbgState->bmExitsToCheck) * 8); \
11304 ASMBitSet((pDbgState)->bmExitsToCheck, a_uExit); \
11305 } else do { } while (0)
11306#define SET_CPE1_XBM_IF_EITHER_EN(a_EventSubName, a_uExit, a_fCtrlProcExec) \
11307 if (IS_EITHER_ENABLED(pVM, a_EventSubName)) \
11308 { \
11309 (pDbgState)->fCpe1Extra |= (a_fCtrlProcExec); \
11310 AssertCompile((unsigned)(a_uExit) < sizeof(pDbgState->bmExitsToCheck) * 8); \
11311 ASMBitSet((pDbgState)->bmExitsToCheck, a_uExit); \
11312 } else do { } while (0)
11313#define SET_CPEU_XBM_IF_EITHER_EN(a_EventSubName, a_uExit, a_fUnwantedCtrlProcExec) \
11314 if (IS_EITHER_ENABLED(pVM, a_EventSubName)) \
11315 { \
11316 (pDbgState)->fCpe1Unwanted |= (a_fUnwantedCtrlProcExec); \
11317 AssertCompile((unsigned)(a_uExit) < sizeof(pDbgState->bmExitsToCheck) * 8); \
11318 ASMBitSet((pDbgState)->bmExitsToCheck, a_uExit); \
11319 } else do { } while (0)
11320#define SET_CPE2_XBM_IF_EITHER_EN(a_EventSubName, a_uExit, a_fCtrlProcExec2) \
11321 if (IS_EITHER_ENABLED(pVM, a_EventSubName)) \
11322 { \
11323 (pDbgState)->fCpe2Extra |= (a_fCtrlProcExec2); \
11324 AssertCompile((unsigned)(a_uExit) < sizeof(pDbgState->bmExitsToCheck) * 8); \
11325 ASMBitSet((pDbgState)->bmExitsToCheck, a_uExit); \
11326 } else do { } while (0)
11327
11328 SET_ONLY_XBM_IF_EITHER_EN(EXIT_TASK_SWITCH, VMX_EXIT_TASK_SWITCH); /* unconditional */
11329 SET_ONLY_XBM_IF_EITHER_EN(EXIT_VMX_EPT_VIOLATION, VMX_EXIT_EPT_VIOLATION); /* unconditional */
11330 SET_ONLY_XBM_IF_EITHER_EN(EXIT_VMX_EPT_MISCONFIG, VMX_EXIT_EPT_MISCONFIG); /* unconditional (unless #VE) */
11331 SET_ONLY_XBM_IF_EITHER_EN(EXIT_VMX_VAPIC_ACCESS, VMX_EXIT_APIC_ACCESS); /* feature dependent, nothing to enable here */
11332 SET_ONLY_XBM_IF_EITHER_EN(EXIT_VMX_VAPIC_WRITE, VMX_EXIT_APIC_WRITE); /* feature dependent, nothing to enable here */
11333
11334 SET_ONLY_XBM_IF_EITHER_EN(INSTR_CPUID, VMX_EXIT_CPUID); /* unconditional */
11335 SET_ONLY_XBM_IF_EITHER_EN( EXIT_CPUID, VMX_EXIT_CPUID);
11336 SET_ONLY_XBM_IF_EITHER_EN(INSTR_GETSEC, VMX_EXIT_GETSEC); /* unconditional */
11337 SET_ONLY_XBM_IF_EITHER_EN( EXIT_GETSEC, VMX_EXIT_GETSEC);
11338 SET_CPE1_XBM_IF_EITHER_EN(INSTR_HALT, VMX_EXIT_HLT, VMX_PROC_CTLS_HLT_EXIT); /* paranoia */
11339 SET_ONLY_XBM_IF_EITHER_EN( EXIT_HALT, VMX_EXIT_HLT);
11340 SET_ONLY_XBM_IF_EITHER_EN(INSTR_INVD, VMX_EXIT_INVD); /* unconditional */
11341 SET_ONLY_XBM_IF_EITHER_EN( EXIT_INVD, VMX_EXIT_INVD);
11342 SET_CPE1_XBM_IF_EITHER_EN(INSTR_INVLPG, VMX_EXIT_INVLPG, VMX_PROC_CTLS_INVLPG_EXIT);
11343 SET_ONLY_XBM_IF_EITHER_EN( EXIT_INVLPG, VMX_EXIT_INVLPG);
11344 SET_CPE1_XBM_IF_EITHER_EN(INSTR_RDPMC, VMX_EXIT_RDPMC, VMX_PROC_CTLS_RDPMC_EXIT);
11345 SET_ONLY_XBM_IF_EITHER_EN( EXIT_RDPMC, VMX_EXIT_RDPMC);
11346 SET_CPE1_XBM_IF_EITHER_EN(INSTR_RDTSC, VMX_EXIT_RDTSC, VMX_PROC_CTLS_RDTSC_EXIT);
11347 SET_ONLY_XBM_IF_EITHER_EN( EXIT_RDTSC, VMX_EXIT_RDTSC);
11348 SET_ONLY_XBM_IF_EITHER_EN(INSTR_RSM, VMX_EXIT_RSM); /* unconditional */
11349 SET_ONLY_XBM_IF_EITHER_EN( EXIT_RSM, VMX_EXIT_RSM);
11350 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMM_CALL, VMX_EXIT_VMCALL); /* unconditional */
11351 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMM_CALL, VMX_EXIT_VMCALL);
11352 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMX_VMCLEAR, VMX_EXIT_VMCLEAR); /* unconditional */
11353 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_VMCLEAR, VMX_EXIT_VMCLEAR);
11354 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMX_VMLAUNCH, VMX_EXIT_VMLAUNCH); /* unconditional */
11355 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_VMLAUNCH, VMX_EXIT_VMLAUNCH);
11356 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMX_VMPTRLD, VMX_EXIT_VMPTRLD); /* unconditional */
11357 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_VMPTRLD, VMX_EXIT_VMPTRLD);
11358 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMX_VMPTRST, VMX_EXIT_VMPTRST); /* unconditional */
11359 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_VMPTRST, VMX_EXIT_VMPTRST);
11360 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMX_VMREAD, VMX_EXIT_VMREAD); /* unconditional */
11361 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_VMREAD, VMX_EXIT_VMREAD);
11362 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMX_VMRESUME, VMX_EXIT_VMRESUME); /* unconditional */
11363 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_VMRESUME, VMX_EXIT_VMRESUME);
11364 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMX_VMWRITE, VMX_EXIT_VMWRITE); /* unconditional */
11365 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_VMWRITE, VMX_EXIT_VMWRITE);
11366 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMX_VMXOFF, VMX_EXIT_VMXOFF); /* unconditional */
11367 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_VMXOFF, VMX_EXIT_VMXOFF);
11368 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMX_VMXON, VMX_EXIT_VMXON); /* unconditional */
11369 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_VMXON, VMX_EXIT_VMXON);
11370
11371 if ( IS_EITHER_ENABLED(pVM, INSTR_CRX_READ)
11372 || IS_EITHER_ENABLED(pVM, INSTR_CRX_WRITE))
11373 {
11374 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, CPUMCTX_EXTRN_CR0 | CPUMCTX_EXTRN_CR4
11375 | CPUMCTX_EXTRN_APIC_TPR);
11376 AssertRC(rc);
11377
11378#if 0 /** @todo fix me */
11379 pDbgState->fClearCr0Mask = true;
11380 pDbgState->fClearCr4Mask = true;
11381#endif
11382 if (IS_EITHER_ENABLED(pVM, INSTR_CRX_READ))
11383 pDbgState->fCpe1Extra |= VMX_PROC_CTLS_CR3_STORE_EXIT | VMX_PROC_CTLS_CR8_STORE_EXIT;
11384 if (IS_EITHER_ENABLED(pVM, INSTR_CRX_WRITE))
11385 pDbgState->fCpe1Extra |= VMX_PROC_CTLS_CR3_LOAD_EXIT | VMX_PROC_CTLS_CR8_LOAD_EXIT;
11386 pDbgState->fCpe1Unwanted |= VMX_PROC_CTLS_USE_TPR_SHADOW; /* risky? */
11387 /* Note! We currently don't use VMX_VMCS32_CTRL_CR3_TARGET_COUNT. It would
11388 require clearing here and in the loop if we start using it. */
11389 ASMBitSet(pDbgState->bmExitsToCheck, VMX_EXIT_MOV_CRX);
11390 }
11391 else
11392 {
11393 if (pDbgState->fClearCr0Mask)
11394 {
11395 pDbgState->fClearCr0Mask = false;
11396 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_CR0);
11397 }
11398 if (pDbgState->fClearCr4Mask)
11399 {
11400 pDbgState->fClearCr4Mask = false;
11401 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_CR4);
11402 }
11403 }
11404 SET_ONLY_XBM_IF_EITHER_EN( EXIT_CRX_READ, VMX_EXIT_MOV_CRX);
11405 SET_ONLY_XBM_IF_EITHER_EN( EXIT_CRX_WRITE, VMX_EXIT_MOV_CRX);
11406
11407 if ( IS_EITHER_ENABLED(pVM, INSTR_DRX_READ)
11408 || IS_EITHER_ENABLED(pVM, INSTR_DRX_WRITE))
11409 {
11410 /** @todo later, need to fix handler as it assumes this won't usually happen. */
11411 ASMBitSet(pDbgState->bmExitsToCheck, VMX_EXIT_MOV_DRX);
11412 }
11413 SET_ONLY_XBM_IF_EITHER_EN( EXIT_DRX_READ, VMX_EXIT_MOV_DRX);
11414 SET_ONLY_XBM_IF_EITHER_EN( EXIT_DRX_WRITE, VMX_EXIT_MOV_DRX);
11415
11416 SET_CPEU_XBM_IF_EITHER_EN(INSTR_RDMSR, VMX_EXIT_RDMSR, VMX_PROC_CTLS_USE_MSR_BITMAPS); /* risky clearing this? */
11417 SET_ONLY_XBM_IF_EITHER_EN( EXIT_RDMSR, VMX_EXIT_RDMSR);
11418 SET_CPEU_XBM_IF_EITHER_EN(INSTR_WRMSR, VMX_EXIT_WRMSR, VMX_PROC_CTLS_USE_MSR_BITMAPS);
11419 SET_ONLY_XBM_IF_EITHER_EN( EXIT_WRMSR, VMX_EXIT_WRMSR);
11420 SET_CPE1_XBM_IF_EITHER_EN(INSTR_MWAIT, VMX_EXIT_MWAIT, VMX_PROC_CTLS_MWAIT_EXIT); /* paranoia */
11421 SET_ONLY_XBM_IF_EITHER_EN( EXIT_MWAIT, VMX_EXIT_MWAIT);
11422 SET_CPE1_XBM_IF_EITHER_EN(INSTR_MONITOR, VMX_EXIT_MONITOR, VMX_PROC_CTLS_MONITOR_EXIT); /* paranoia */
11423 SET_ONLY_XBM_IF_EITHER_EN( EXIT_MONITOR, VMX_EXIT_MONITOR);
11424#if 0 /** @todo too slow, fix handler. */
11425 SET_CPE1_XBM_IF_EITHER_EN(INSTR_PAUSE, VMX_EXIT_PAUSE, VMX_PROC_CTLS_PAUSE_EXIT);
11426#endif
11427 SET_ONLY_XBM_IF_EITHER_EN( EXIT_PAUSE, VMX_EXIT_PAUSE);
11428
11429 if ( IS_EITHER_ENABLED(pVM, INSTR_SGDT)
11430 || IS_EITHER_ENABLED(pVM, INSTR_SIDT)
11431 || IS_EITHER_ENABLED(pVM, INSTR_LGDT)
11432 || IS_EITHER_ENABLED(pVM, INSTR_LIDT))
11433 {
11434 pDbgState->fCpe2Extra |= VMX_PROC_CTLS2_DESC_TABLE_EXIT;
11435 ASMBitSet(pDbgState->bmExitsToCheck, VMX_EXIT_GDTR_IDTR_ACCESS);
11436 }
11437 SET_ONLY_XBM_IF_EITHER_EN( EXIT_SGDT, VMX_EXIT_GDTR_IDTR_ACCESS);
11438 SET_ONLY_XBM_IF_EITHER_EN( EXIT_SIDT, VMX_EXIT_GDTR_IDTR_ACCESS);
11439 SET_ONLY_XBM_IF_EITHER_EN( EXIT_LGDT, VMX_EXIT_GDTR_IDTR_ACCESS);
11440 SET_ONLY_XBM_IF_EITHER_EN( EXIT_LIDT, VMX_EXIT_GDTR_IDTR_ACCESS);
11441
11442 if ( IS_EITHER_ENABLED(pVM, INSTR_SLDT)
11443 || IS_EITHER_ENABLED(pVM, INSTR_STR)
11444 || IS_EITHER_ENABLED(pVM, INSTR_LLDT)
11445 || IS_EITHER_ENABLED(pVM, INSTR_LTR))
11446 {
11447 pDbgState->fCpe2Extra |= VMX_PROC_CTLS2_DESC_TABLE_EXIT;
11448 ASMBitSet(pDbgState->bmExitsToCheck, VMX_EXIT_LDTR_TR_ACCESS);
11449 }
11450 SET_ONLY_XBM_IF_EITHER_EN( EXIT_SLDT, VMX_EXIT_LDTR_TR_ACCESS);
11451 SET_ONLY_XBM_IF_EITHER_EN( EXIT_STR, VMX_EXIT_LDTR_TR_ACCESS);
11452 SET_ONLY_XBM_IF_EITHER_EN( EXIT_LLDT, VMX_EXIT_LDTR_TR_ACCESS);
11453 SET_ONLY_XBM_IF_EITHER_EN( EXIT_LTR, VMX_EXIT_LDTR_TR_ACCESS);
11454
11455 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMX_INVEPT, VMX_EXIT_INVEPT); /* unconditional */
11456 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_INVEPT, VMX_EXIT_INVEPT);
11457 SET_CPE1_XBM_IF_EITHER_EN(INSTR_RDTSCP, VMX_EXIT_RDTSCP, VMX_PROC_CTLS_RDTSC_EXIT);
11458 SET_ONLY_XBM_IF_EITHER_EN( EXIT_RDTSCP, VMX_EXIT_RDTSCP);
11459 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMX_INVVPID, VMX_EXIT_INVVPID); /* unconditional */
11460 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_INVVPID, VMX_EXIT_INVVPID);
11461 SET_CPE2_XBM_IF_EITHER_EN(INSTR_WBINVD, VMX_EXIT_WBINVD, VMX_PROC_CTLS2_WBINVD_EXIT);
11462 SET_ONLY_XBM_IF_EITHER_EN( EXIT_WBINVD, VMX_EXIT_WBINVD);
11463 SET_ONLY_XBM_IF_EITHER_EN(INSTR_XSETBV, VMX_EXIT_XSETBV); /* unconditional */
11464 SET_ONLY_XBM_IF_EITHER_EN( EXIT_XSETBV, VMX_EXIT_XSETBV);
11465 SET_CPE2_XBM_IF_EITHER_EN(INSTR_RDRAND, VMX_EXIT_RDRAND, VMX_PROC_CTLS2_RDRAND_EXIT);
11466 SET_ONLY_XBM_IF_EITHER_EN( EXIT_RDRAND, VMX_EXIT_RDRAND);
11467 SET_CPE1_XBM_IF_EITHER_EN(INSTR_VMX_INVPCID, VMX_EXIT_INVPCID, VMX_PROC_CTLS_INVLPG_EXIT);
11468 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_INVPCID, VMX_EXIT_INVPCID);
11469 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMX_VMFUNC, VMX_EXIT_VMFUNC); /* unconditional for the current setup */
11470 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_VMFUNC, VMX_EXIT_VMFUNC);
11471 SET_CPE2_XBM_IF_EITHER_EN(INSTR_RDSEED, VMX_EXIT_RDSEED, VMX_PROC_CTLS2_RDSEED_EXIT);
11472 SET_ONLY_XBM_IF_EITHER_EN( EXIT_RDSEED, VMX_EXIT_RDSEED);
11473 SET_ONLY_XBM_IF_EITHER_EN(INSTR_XSAVES, VMX_EXIT_XSAVES); /* unconditional (enabled by host, guest cfg) */
11474 SET_ONLY_XBM_IF_EITHER_EN(EXIT_XSAVES, VMX_EXIT_XSAVES);
11475 SET_ONLY_XBM_IF_EITHER_EN(INSTR_XRSTORS, VMX_EXIT_XRSTORS); /* unconditional (enabled by host, guest cfg) */
11476 SET_ONLY_XBM_IF_EITHER_EN( EXIT_XRSTORS, VMX_EXIT_XRSTORS);
11477
11478#undef IS_EITHER_ENABLED
11479#undef SET_ONLY_XBM_IF_EITHER_EN
11480#undef SET_CPE1_XBM_IF_EITHER_EN
11481#undef SET_CPEU_XBM_IF_EITHER_EN
11482#undef SET_CPE2_XBM_IF_EITHER_EN
11483
11484 /*
11485 * Sanitize the control stuff.
11486 */
11487 pDbgState->fCpe2Extra &= pVM->hm.s.vmx.Msrs.ProcCtls2.n.allowed1;
11488 if (pDbgState->fCpe2Extra)
11489 pDbgState->fCpe1Extra |= VMX_PROC_CTLS_USE_SECONDARY_CTLS;
11490 pDbgState->fCpe1Extra &= pVM->hm.s.vmx.Msrs.ProcCtls.n.allowed1;
11491 pDbgState->fCpe1Unwanted &= ~pVM->hm.s.vmx.Msrs.ProcCtls.n.allowed0;
11492 if (pVCpu->hm.s.fDebugWantRdTscExit != RT_BOOL(pDbgState->fCpe1Extra & VMX_PROC_CTLS_RDTSC_EXIT))
11493 {
11494 pVCpu->hm.s.fDebugWantRdTscExit ^= true;
11495 pVmxTransient->fUpdatedTscOffsettingAndPreemptTimer = false;
11496 }
11497
11498 Log6(("HM: debug state: cpe1=%#RX32 cpeu=%#RX32 cpe2=%#RX32%s%s\n",
11499 pDbgState->fCpe1Extra, pDbgState->fCpe1Unwanted, pDbgState->fCpe2Extra,
11500 pDbgState->fClearCr0Mask ? " clr-cr0" : "",
11501 pDbgState->fClearCr4Mask ? " clr-cr4" : ""));
11502}
11503
11504
11505/**
11506 * Fires off DBGF events and dtrace probes for a VM-exit, when it's
11507 * appropriate.
11508 *
11509 * The caller has checked the VM-exit against the
11510 * VMXRUNDBGSTATE::bmExitsToCheck bitmap. The caller has checked for NMIs
11511 * already, so we don't have to do that either.
11512 *
11513 * @returns Strict VBox status code (i.e. informational status codes too).
11514 * @param pVCpu The cross context virtual CPU structure.
11515 * @param pVmxTransient The VMX-transient structure.
11516 * @param uExitReason The VM-exit reason.
11517 *
11518 * @remarks The name of this function is displayed by dtrace, so keep it short
11519 * and to the point. No longer than 33 chars long, please.
11520 */
11521static VBOXSTRICTRC hmR0VmxHandleExitDtraceEvents(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient, uint32_t uExitReason)
11522{
11523 /*
11524 * Translate the event into a DBGF event (enmEvent + uEventArg) and at the
11525 * same time check whether any corresponding Dtrace event is enabled (fDtrace).
11526 *
11527 * Note! This is the reverse operation of what hmR0VmxPreRunGuestDebugStateUpdate
11528 * does. Must add/change/remove both places. Same ordering, please.
11529 *
11530 * Added/removed events must also be reflected in the next section
11531 * where we dispatch dtrace events.
11532 */
11533 bool fDtrace1 = false;
11534 bool fDtrace2 = false;
11535 DBGFEVENTTYPE enmEvent1 = DBGFEVENT_END;
11536 DBGFEVENTTYPE enmEvent2 = DBGFEVENT_END;
11537 uint32_t uEventArg = 0;
11538#define SET_EXIT(a_EventSubName) \
11539 do { \
11540 enmEvent2 = RT_CONCAT(DBGFEVENT_EXIT_, a_EventSubName); \
11541 fDtrace2 = RT_CONCAT3(VBOXVMM_EXIT_, a_EventSubName, _ENABLED)(); \
11542 } while (0)
11543#define SET_BOTH(a_EventSubName) \
11544 do { \
11545 enmEvent1 = RT_CONCAT(DBGFEVENT_INSTR_, a_EventSubName); \
11546 enmEvent2 = RT_CONCAT(DBGFEVENT_EXIT_, a_EventSubName); \
11547 fDtrace1 = RT_CONCAT3(VBOXVMM_INSTR_, a_EventSubName, _ENABLED)(); \
11548 fDtrace2 = RT_CONCAT3(VBOXVMM_EXIT_, a_EventSubName, _ENABLED)(); \
11549 } while (0)
11550 switch (uExitReason)
11551 {
11552 case VMX_EXIT_MTF:
11553 return hmR0VmxExitMtf(pVCpu, pVmxTransient);
11554
11555 case VMX_EXIT_XCPT_OR_NMI:
11556 {
11557 uint8_t const idxVector = VMX_EXIT_INT_INFO_VECTOR(pVmxTransient->uExitIntInfo);
11558 switch (VMX_EXIT_INT_INFO_TYPE(pVmxTransient->uExitIntInfo))
11559 {
11560 case VMX_EXIT_INT_INFO_TYPE_HW_XCPT:
11561 case VMX_EXIT_INT_INFO_TYPE_SW_XCPT:
11562 case VMX_EXIT_INT_INFO_TYPE_PRIV_SW_XCPT:
11563 if (idxVector <= (unsigned)(DBGFEVENT_XCPT_LAST - DBGFEVENT_XCPT_FIRST))
11564 {
11565 if (VMX_EXIT_INT_INFO_IS_ERROR_CODE_VALID(pVmxTransient->uExitIntInfo))
11566 {
11567 hmR0VmxReadExitIntErrorCodeVmcs(pVmxTransient);
11568 uEventArg = pVmxTransient->uExitIntErrorCode;
11569 }
11570 enmEvent1 = (DBGFEVENTTYPE)(DBGFEVENT_XCPT_FIRST + idxVector);
11571 switch (enmEvent1)
11572 {
11573 case DBGFEVENT_XCPT_DE: fDtrace1 = VBOXVMM_XCPT_DE_ENABLED(); break;
11574 case DBGFEVENT_XCPT_DB: fDtrace1 = VBOXVMM_XCPT_DB_ENABLED(); break;
11575 case DBGFEVENT_XCPT_BP: fDtrace1 = VBOXVMM_XCPT_BP_ENABLED(); break;
11576 case DBGFEVENT_XCPT_OF: fDtrace1 = VBOXVMM_XCPT_OF_ENABLED(); break;
11577 case DBGFEVENT_XCPT_BR: fDtrace1 = VBOXVMM_XCPT_BR_ENABLED(); break;
11578 case DBGFEVENT_XCPT_UD: fDtrace1 = VBOXVMM_XCPT_UD_ENABLED(); break;
11579 case DBGFEVENT_XCPT_NM: fDtrace1 = VBOXVMM_XCPT_NM_ENABLED(); break;
11580 case DBGFEVENT_XCPT_DF: fDtrace1 = VBOXVMM_XCPT_DF_ENABLED(); break;
11581 case DBGFEVENT_XCPT_TS: fDtrace1 = VBOXVMM_XCPT_TS_ENABLED(); break;
11582 case DBGFEVENT_XCPT_NP: fDtrace1 = VBOXVMM_XCPT_NP_ENABLED(); break;
11583 case DBGFEVENT_XCPT_SS: fDtrace1 = VBOXVMM_XCPT_SS_ENABLED(); break;
11584 case DBGFEVENT_XCPT_GP: fDtrace1 = VBOXVMM_XCPT_GP_ENABLED(); break;
11585 case DBGFEVENT_XCPT_PF: fDtrace1 = VBOXVMM_XCPT_PF_ENABLED(); break;
11586 case DBGFEVENT_XCPT_MF: fDtrace1 = VBOXVMM_XCPT_MF_ENABLED(); break;
11587 case DBGFEVENT_XCPT_AC: fDtrace1 = VBOXVMM_XCPT_AC_ENABLED(); break;
11588 case DBGFEVENT_XCPT_XF: fDtrace1 = VBOXVMM_XCPT_XF_ENABLED(); break;
11589 case DBGFEVENT_XCPT_VE: fDtrace1 = VBOXVMM_XCPT_VE_ENABLED(); break;
11590 case DBGFEVENT_XCPT_SX: fDtrace1 = VBOXVMM_XCPT_SX_ENABLED(); break;
11591 default: break;
11592 }
11593 }
11594 else
11595 AssertFailed();
11596 break;
11597
11598 case VMX_EXIT_INT_INFO_TYPE_SW_INT:
11599 uEventArg = idxVector;
11600 enmEvent1 = DBGFEVENT_INTERRUPT_SOFTWARE;
11601 fDtrace1 = VBOXVMM_INT_SOFTWARE_ENABLED();
11602 break;
11603 }
11604 break;
11605 }
11606
11607 case VMX_EXIT_TRIPLE_FAULT:
11608 enmEvent1 = DBGFEVENT_TRIPLE_FAULT;
11609 //fDtrace1 = VBOXVMM_EXIT_TRIPLE_FAULT_ENABLED();
11610 break;
11611 case VMX_EXIT_TASK_SWITCH: SET_EXIT(TASK_SWITCH); break;
11612 case VMX_EXIT_EPT_VIOLATION: SET_EXIT(VMX_EPT_VIOLATION); break;
11613 case VMX_EXIT_EPT_MISCONFIG: SET_EXIT(VMX_EPT_MISCONFIG); break;
11614 case VMX_EXIT_APIC_ACCESS: SET_EXIT(VMX_VAPIC_ACCESS); break;
11615 case VMX_EXIT_APIC_WRITE: SET_EXIT(VMX_VAPIC_WRITE); break;
11616
11617 /* Instruction specific VM-exits: */
11618 case VMX_EXIT_CPUID: SET_BOTH(CPUID); break;
11619 case VMX_EXIT_GETSEC: SET_BOTH(GETSEC); break;
11620 case VMX_EXIT_HLT: SET_BOTH(HALT); break;
11621 case VMX_EXIT_INVD: SET_BOTH(INVD); break;
11622 case VMX_EXIT_INVLPG: SET_BOTH(INVLPG); break;
11623 case VMX_EXIT_RDPMC: SET_BOTH(RDPMC); break;
11624 case VMX_EXIT_RDTSC: SET_BOTH(RDTSC); break;
11625 case VMX_EXIT_RSM: SET_BOTH(RSM); break;
11626 case VMX_EXIT_VMCALL: SET_BOTH(VMM_CALL); break;
11627 case VMX_EXIT_VMCLEAR: SET_BOTH(VMX_VMCLEAR); break;
11628 case VMX_EXIT_VMLAUNCH: SET_BOTH(VMX_VMLAUNCH); break;
11629 case VMX_EXIT_VMPTRLD: SET_BOTH(VMX_VMPTRLD); break;
11630 case VMX_EXIT_VMPTRST: SET_BOTH(VMX_VMPTRST); break;
11631 case VMX_EXIT_VMREAD: SET_BOTH(VMX_VMREAD); break;
11632 case VMX_EXIT_VMRESUME: SET_BOTH(VMX_VMRESUME); break;
11633 case VMX_EXIT_VMWRITE: SET_BOTH(VMX_VMWRITE); break;
11634 case VMX_EXIT_VMXOFF: SET_BOTH(VMX_VMXOFF); break;
11635 case VMX_EXIT_VMXON: SET_BOTH(VMX_VMXON); break;
11636 case VMX_EXIT_MOV_CRX:
11637 hmR0VmxReadExitQualVmcs(pVmxTransient);
11638 if (VMX_EXIT_QUAL_CRX_ACCESS(pVmxTransient->uExitQual) == VMX_EXIT_QUAL_CRX_ACCESS_READ)
11639 SET_BOTH(CRX_READ);
11640 else
11641 SET_BOTH(CRX_WRITE);
11642 uEventArg = VMX_EXIT_QUAL_CRX_REGISTER(pVmxTransient->uExitQual);
11643 break;
11644 case VMX_EXIT_MOV_DRX:
11645 hmR0VmxReadExitQualVmcs(pVmxTransient);
11646 if ( VMX_EXIT_QUAL_DRX_DIRECTION(pVmxTransient->uExitQual)
11647 == VMX_EXIT_QUAL_DRX_DIRECTION_READ)
11648 SET_BOTH(DRX_READ);
11649 else
11650 SET_BOTH(DRX_WRITE);
11651 uEventArg = VMX_EXIT_QUAL_DRX_REGISTER(pVmxTransient->uExitQual);
11652 break;
11653 case VMX_EXIT_RDMSR: SET_BOTH(RDMSR); break;
11654 case VMX_EXIT_WRMSR: SET_BOTH(WRMSR); break;
11655 case VMX_EXIT_MWAIT: SET_BOTH(MWAIT); break;
11656 case VMX_EXIT_MONITOR: SET_BOTH(MONITOR); break;
11657 case VMX_EXIT_PAUSE: SET_BOTH(PAUSE); break;
11658 case VMX_EXIT_GDTR_IDTR_ACCESS:
11659 hmR0VmxReadExitInstrInfoVmcs(pVmxTransient);
11660 switch (RT_BF_GET(pVmxTransient->ExitInstrInfo.u, VMX_BF_XDTR_INSINFO_INSTR_ID))
11661 {
11662 case VMX_XDTR_INSINFO_II_SGDT: SET_BOTH(SGDT); break;
11663 case VMX_XDTR_INSINFO_II_SIDT: SET_BOTH(SIDT); break;
11664 case VMX_XDTR_INSINFO_II_LGDT: SET_BOTH(LGDT); break;
11665 case VMX_XDTR_INSINFO_II_LIDT: SET_BOTH(LIDT); break;
11666 }
11667 break;
11668
11669 case VMX_EXIT_LDTR_TR_ACCESS:
11670 hmR0VmxReadExitInstrInfoVmcs(pVmxTransient);
11671 switch (RT_BF_GET(pVmxTransient->ExitInstrInfo.u, VMX_BF_YYTR_INSINFO_INSTR_ID))
11672 {
11673 case VMX_YYTR_INSINFO_II_SLDT: SET_BOTH(SLDT); break;
11674 case VMX_YYTR_INSINFO_II_STR: SET_BOTH(STR); break;
11675 case VMX_YYTR_INSINFO_II_LLDT: SET_BOTH(LLDT); break;
11676 case VMX_YYTR_INSINFO_II_LTR: SET_BOTH(LTR); break;
11677 }
11678 break;
11679
11680 case VMX_EXIT_INVEPT: SET_BOTH(VMX_INVEPT); break;
11681 case VMX_EXIT_RDTSCP: SET_BOTH(RDTSCP); break;
11682 case VMX_EXIT_INVVPID: SET_BOTH(VMX_INVVPID); break;
11683 case VMX_EXIT_WBINVD: SET_BOTH(WBINVD); break;
11684 case VMX_EXIT_XSETBV: SET_BOTH(XSETBV); break;
11685 case VMX_EXIT_RDRAND: SET_BOTH(RDRAND); break;
11686 case VMX_EXIT_INVPCID: SET_BOTH(VMX_INVPCID); break;
11687 case VMX_EXIT_VMFUNC: SET_BOTH(VMX_VMFUNC); break;
11688 case VMX_EXIT_RDSEED: SET_BOTH(RDSEED); break;
11689 case VMX_EXIT_XSAVES: SET_BOTH(XSAVES); break;
11690 case VMX_EXIT_XRSTORS: SET_BOTH(XRSTORS); break;
11691
11692 /* Events that aren't relevant at this point. */
11693 case VMX_EXIT_EXT_INT:
11694 case VMX_EXIT_INT_WINDOW:
11695 case VMX_EXIT_NMI_WINDOW:
11696 case VMX_EXIT_TPR_BELOW_THRESHOLD:
11697 case VMX_EXIT_PREEMPT_TIMER:
11698 case VMX_EXIT_IO_INSTR:
11699 break;
11700
11701 /* Errors and unexpected events. */
11702 case VMX_EXIT_INIT_SIGNAL:
11703 case VMX_EXIT_SIPI:
11704 case VMX_EXIT_IO_SMI:
11705 case VMX_EXIT_SMI:
11706 case VMX_EXIT_ERR_INVALID_GUEST_STATE:
11707 case VMX_EXIT_ERR_MSR_LOAD:
11708 case VMX_EXIT_ERR_MACHINE_CHECK:
11709 case VMX_EXIT_PML_FULL:
11710 case VMX_EXIT_VIRTUALIZED_EOI:
11711 break;
11712
11713 default:
11714 AssertMsgFailed(("Unexpected VM-exit=%#x\n", uExitReason));
11715 break;
11716 }
11717#undef SET_BOTH
11718#undef SET_EXIT
11719
11720 /*
11721 * Dtrace tracepoints go first. We do them here at once so we don't
11722 * have to copy the guest state saving and stuff a few dozen times.
11723 * Down side is that we've got to repeat the switch, though this time
11724 * we use enmEvent since the probes are a subset of what DBGF does.
11725 */
11726 if (fDtrace1 || fDtrace2)
11727 {
11728 hmR0VmxReadExitQualVmcs(pVmxTransient);
11729 hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, HMVMX_CPUMCTX_EXTRN_ALL);
11730 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
11731 switch (enmEvent1)
11732 {
11733 /** @todo consider which extra parameters would be helpful for each probe. */
11734 case DBGFEVENT_END: break;
11735 case DBGFEVENT_XCPT_DE: VBOXVMM_XCPT_DE(pVCpu, pCtx); break;
11736 case DBGFEVENT_XCPT_DB: VBOXVMM_XCPT_DB(pVCpu, pCtx, pCtx->dr[6]); break;
11737 case DBGFEVENT_XCPT_BP: VBOXVMM_XCPT_BP(pVCpu, pCtx); break;
11738 case DBGFEVENT_XCPT_OF: VBOXVMM_XCPT_OF(pVCpu, pCtx); break;
11739 case DBGFEVENT_XCPT_BR: VBOXVMM_XCPT_BR(pVCpu, pCtx); break;
11740 case DBGFEVENT_XCPT_UD: VBOXVMM_XCPT_UD(pVCpu, pCtx); break;
11741 case DBGFEVENT_XCPT_NM: VBOXVMM_XCPT_NM(pVCpu, pCtx); break;
11742 case DBGFEVENT_XCPT_DF: VBOXVMM_XCPT_DF(pVCpu, pCtx); break;
11743 case DBGFEVENT_XCPT_TS: VBOXVMM_XCPT_TS(pVCpu, pCtx, uEventArg); break;
11744 case DBGFEVENT_XCPT_NP: VBOXVMM_XCPT_NP(pVCpu, pCtx, uEventArg); break;
11745 case DBGFEVENT_XCPT_SS: VBOXVMM_XCPT_SS(pVCpu, pCtx, uEventArg); break;
11746 case DBGFEVENT_XCPT_GP: VBOXVMM_XCPT_GP(pVCpu, pCtx, uEventArg); break;
11747 case DBGFEVENT_XCPT_PF: VBOXVMM_XCPT_PF(pVCpu, pCtx, uEventArg, pCtx->cr2); break;
11748 case DBGFEVENT_XCPT_MF: VBOXVMM_XCPT_MF(pVCpu, pCtx); break;
11749 case DBGFEVENT_XCPT_AC: VBOXVMM_XCPT_AC(pVCpu, pCtx); break;
11750 case DBGFEVENT_XCPT_XF: VBOXVMM_XCPT_XF(pVCpu, pCtx); break;
11751 case DBGFEVENT_XCPT_VE: VBOXVMM_XCPT_VE(pVCpu, pCtx); break;
11752 case DBGFEVENT_XCPT_SX: VBOXVMM_XCPT_SX(pVCpu, pCtx, uEventArg); break;
11753 case DBGFEVENT_INTERRUPT_SOFTWARE: VBOXVMM_INT_SOFTWARE(pVCpu, pCtx, (uint8_t)uEventArg); break;
11754 case DBGFEVENT_INSTR_CPUID: VBOXVMM_INSTR_CPUID(pVCpu, pCtx, pCtx->eax, pCtx->ecx); break;
11755 case DBGFEVENT_INSTR_GETSEC: VBOXVMM_INSTR_GETSEC(pVCpu, pCtx); break;
11756 case DBGFEVENT_INSTR_HALT: VBOXVMM_INSTR_HALT(pVCpu, pCtx); break;
11757 case DBGFEVENT_INSTR_INVD: VBOXVMM_INSTR_INVD(pVCpu, pCtx); break;
11758 case DBGFEVENT_INSTR_INVLPG: VBOXVMM_INSTR_INVLPG(pVCpu, pCtx); break;
11759 case DBGFEVENT_INSTR_RDPMC: VBOXVMM_INSTR_RDPMC(pVCpu, pCtx); break;
11760 case DBGFEVENT_INSTR_RDTSC: VBOXVMM_INSTR_RDTSC(pVCpu, pCtx); break;
11761 case DBGFEVENT_INSTR_RSM: VBOXVMM_INSTR_RSM(pVCpu, pCtx); break;
11762 case DBGFEVENT_INSTR_CRX_READ: VBOXVMM_INSTR_CRX_READ(pVCpu, pCtx, (uint8_t)uEventArg); break;
11763 case DBGFEVENT_INSTR_CRX_WRITE: VBOXVMM_INSTR_CRX_WRITE(pVCpu, pCtx, (uint8_t)uEventArg); break;
11764 case DBGFEVENT_INSTR_DRX_READ: VBOXVMM_INSTR_DRX_READ(pVCpu, pCtx, (uint8_t)uEventArg); break;
11765 case DBGFEVENT_INSTR_DRX_WRITE: VBOXVMM_INSTR_DRX_WRITE(pVCpu, pCtx, (uint8_t)uEventArg); break;
11766 case DBGFEVENT_INSTR_RDMSR: VBOXVMM_INSTR_RDMSR(pVCpu, pCtx, pCtx->ecx); break;
11767 case DBGFEVENT_INSTR_WRMSR: VBOXVMM_INSTR_WRMSR(pVCpu, pCtx, pCtx->ecx,
11768 RT_MAKE_U64(pCtx->eax, pCtx->edx)); break;
11769 case DBGFEVENT_INSTR_MWAIT: VBOXVMM_INSTR_MWAIT(pVCpu, pCtx); break;
11770 case DBGFEVENT_INSTR_MONITOR: VBOXVMM_INSTR_MONITOR(pVCpu, pCtx); break;
11771 case DBGFEVENT_INSTR_PAUSE: VBOXVMM_INSTR_PAUSE(pVCpu, pCtx); break;
11772 case DBGFEVENT_INSTR_SGDT: VBOXVMM_INSTR_SGDT(pVCpu, pCtx); break;
11773 case DBGFEVENT_INSTR_SIDT: VBOXVMM_INSTR_SIDT(pVCpu, pCtx); break;
11774 case DBGFEVENT_INSTR_LGDT: VBOXVMM_INSTR_LGDT(pVCpu, pCtx); break;
11775 case DBGFEVENT_INSTR_LIDT: VBOXVMM_INSTR_LIDT(pVCpu, pCtx); break;
11776 case DBGFEVENT_INSTR_SLDT: VBOXVMM_INSTR_SLDT(pVCpu, pCtx); break;
11777 case DBGFEVENT_INSTR_STR: VBOXVMM_INSTR_STR(pVCpu, pCtx); break;
11778 case DBGFEVENT_INSTR_LLDT: VBOXVMM_INSTR_LLDT(pVCpu, pCtx); break;
11779 case DBGFEVENT_INSTR_LTR: VBOXVMM_INSTR_LTR(pVCpu, pCtx); break;
11780 case DBGFEVENT_INSTR_RDTSCP: VBOXVMM_INSTR_RDTSCP(pVCpu, pCtx); break;
11781 case DBGFEVENT_INSTR_WBINVD: VBOXVMM_INSTR_WBINVD(pVCpu, pCtx); break;
11782 case DBGFEVENT_INSTR_XSETBV: VBOXVMM_INSTR_XSETBV(pVCpu, pCtx); break;
11783 case DBGFEVENT_INSTR_RDRAND: VBOXVMM_INSTR_RDRAND(pVCpu, pCtx); break;
11784 case DBGFEVENT_INSTR_RDSEED: VBOXVMM_INSTR_RDSEED(pVCpu, pCtx); break;
11785 case DBGFEVENT_INSTR_XSAVES: VBOXVMM_INSTR_XSAVES(pVCpu, pCtx); break;
11786 case DBGFEVENT_INSTR_XRSTORS: VBOXVMM_INSTR_XRSTORS(pVCpu, pCtx); break;
11787 case DBGFEVENT_INSTR_VMM_CALL: VBOXVMM_INSTR_VMM_CALL(pVCpu, pCtx); break;
11788 case DBGFEVENT_INSTR_VMX_VMCLEAR: VBOXVMM_INSTR_VMX_VMCLEAR(pVCpu, pCtx); break;
11789 case DBGFEVENT_INSTR_VMX_VMLAUNCH: VBOXVMM_INSTR_VMX_VMLAUNCH(pVCpu, pCtx); break;
11790 case DBGFEVENT_INSTR_VMX_VMPTRLD: VBOXVMM_INSTR_VMX_VMPTRLD(pVCpu, pCtx); break;
11791 case DBGFEVENT_INSTR_VMX_VMPTRST: VBOXVMM_INSTR_VMX_VMPTRST(pVCpu, pCtx); break;
11792 case DBGFEVENT_INSTR_VMX_VMREAD: VBOXVMM_INSTR_VMX_VMREAD(pVCpu, pCtx); break;
11793 case DBGFEVENT_INSTR_VMX_VMRESUME: VBOXVMM_INSTR_VMX_VMRESUME(pVCpu, pCtx); break;
11794 case DBGFEVENT_INSTR_VMX_VMWRITE: VBOXVMM_INSTR_VMX_VMWRITE(pVCpu, pCtx); break;
11795 case DBGFEVENT_INSTR_VMX_VMXOFF: VBOXVMM_INSTR_VMX_VMXOFF(pVCpu, pCtx); break;
11796 case DBGFEVENT_INSTR_VMX_VMXON: VBOXVMM_INSTR_VMX_VMXON(pVCpu, pCtx); break;
11797 case DBGFEVENT_INSTR_VMX_INVEPT: VBOXVMM_INSTR_VMX_INVEPT(pVCpu, pCtx); break;
11798 case DBGFEVENT_INSTR_VMX_INVVPID: VBOXVMM_INSTR_VMX_INVVPID(pVCpu, pCtx); break;
11799 case DBGFEVENT_INSTR_VMX_INVPCID: VBOXVMM_INSTR_VMX_INVPCID(pVCpu, pCtx); break;
11800 case DBGFEVENT_INSTR_VMX_VMFUNC: VBOXVMM_INSTR_VMX_VMFUNC(pVCpu, pCtx); break;
11801 default: AssertMsgFailed(("enmEvent1=%d uExitReason=%d\n", enmEvent1, uExitReason)); break;
11802 }
11803 switch (enmEvent2)
11804 {
11805 /** @todo consider which extra parameters would be helpful for each probe. */
11806 case DBGFEVENT_END: break;
11807 case DBGFEVENT_EXIT_TASK_SWITCH: VBOXVMM_EXIT_TASK_SWITCH(pVCpu, pCtx); break;
11808 case DBGFEVENT_EXIT_CPUID: VBOXVMM_EXIT_CPUID(pVCpu, pCtx, pCtx->eax, pCtx->ecx); break;
11809 case DBGFEVENT_EXIT_GETSEC: VBOXVMM_EXIT_GETSEC(pVCpu, pCtx); break;
11810 case DBGFEVENT_EXIT_HALT: VBOXVMM_EXIT_HALT(pVCpu, pCtx); break;
11811 case DBGFEVENT_EXIT_INVD: VBOXVMM_EXIT_INVD(pVCpu, pCtx); break;
11812 case DBGFEVENT_EXIT_INVLPG: VBOXVMM_EXIT_INVLPG(pVCpu, pCtx); break;
11813 case DBGFEVENT_EXIT_RDPMC: VBOXVMM_EXIT_RDPMC(pVCpu, pCtx); break;
11814 case DBGFEVENT_EXIT_RDTSC: VBOXVMM_EXIT_RDTSC(pVCpu, pCtx); break;
11815 case DBGFEVENT_EXIT_RSM: VBOXVMM_EXIT_RSM(pVCpu, pCtx); break;
11816 case DBGFEVENT_EXIT_CRX_READ: VBOXVMM_EXIT_CRX_READ(pVCpu, pCtx, (uint8_t)uEventArg); break;
11817 case DBGFEVENT_EXIT_CRX_WRITE: VBOXVMM_EXIT_CRX_WRITE(pVCpu, pCtx, (uint8_t)uEventArg); break;
11818 case DBGFEVENT_EXIT_DRX_READ: VBOXVMM_EXIT_DRX_READ(pVCpu, pCtx, (uint8_t)uEventArg); break;
11819 case DBGFEVENT_EXIT_DRX_WRITE: VBOXVMM_EXIT_DRX_WRITE(pVCpu, pCtx, (uint8_t)uEventArg); break;
11820 case DBGFEVENT_EXIT_RDMSR: VBOXVMM_EXIT_RDMSR(pVCpu, pCtx, pCtx->ecx); break;
11821 case DBGFEVENT_EXIT_WRMSR: VBOXVMM_EXIT_WRMSR(pVCpu, pCtx, pCtx->ecx,
11822 RT_MAKE_U64(pCtx->eax, pCtx->edx)); break;
11823 case DBGFEVENT_EXIT_MWAIT: VBOXVMM_EXIT_MWAIT(pVCpu, pCtx); break;
11824 case DBGFEVENT_EXIT_MONITOR: VBOXVMM_EXIT_MONITOR(pVCpu, pCtx); break;
11825 case DBGFEVENT_EXIT_PAUSE: VBOXVMM_EXIT_PAUSE(pVCpu, pCtx); break;
11826 case DBGFEVENT_EXIT_SGDT: VBOXVMM_EXIT_SGDT(pVCpu, pCtx); break;
11827 case DBGFEVENT_EXIT_SIDT: VBOXVMM_EXIT_SIDT(pVCpu, pCtx); break;
11828 case DBGFEVENT_EXIT_LGDT: VBOXVMM_EXIT_LGDT(pVCpu, pCtx); break;
11829 case DBGFEVENT_EXIT_LIDT: VBOXVMM_EXIT_LIDT(pVCpu, pCtx); break;
11830 case DBGFEVENT_EXIT_SLDT: VBOXVMM_EXIT_SLDT(pVCpu, pCtx); break;
11831 case DBGFEVENT_EXIT_STR: VBOXVMM_EXIT_STR(pVCpu, pCtx); break;
11832 case DBGFEVENT_EXIT_LLDT: VBOXVMM_EXIT_LLDT(pVCpu, pCtx); break;
11833 case DBGFEVENT_EXIT_LTR: VBOXVMM_EXIT_LTR(pVCpu, pCtx); break;
11834 case DBGFEVENT_EXIT_RDTSCP: VBOXVMM_EXIT_RDTSCP(pVCpu, pCtx); break;
11835 case DBGFEVENT_EXIT_WBINVD: VBOXVMM_EXIT_WBINVD(pVCpu, pCtx); break;
11836 case DBGFEVENT_EXIT_XSETBV: VBOXVMM_EXIT_XSETBV(pVCpu, pCtx); break;
11837 case DBGFEVENT_EXIT_RDRAND: VBOXVMM_EXIT_RDRAND(pVCpu, pCtx); break;
11838 case DBGFEVENT_EXIT_RDSEED: VBOXVMM_EXIT_RDSEED(pVCpu, pCtx); break;
11839 case DBGFEVENT_EXIT_XSAVES: VBOXVMM_EXIT_XSAVES(pVCpu, pCtx); break;
11840 case DBGFEVENT_EXIT_XRSTORS: VBOXVMM_EXIT_XRSTORS(pVCpu, pCtx); break;
11841 case DBGFEVENT_EXIT_VMM_CALL: VBOXVMM_EXIT_VMM_CALL(pVCpu, pCtx); break;
11842 case DBGFEVENT_EXIT_VMX_VMCLEAR: VBOXVMM_EXIT_VMX_VMCLEAR(pVCpu, pCtx); break;
11843 case DBGFEVENT_EXIT_VMX_VMLAUNCH: VBOXVMM_EXIT_VMX_VMLAUNCH(pVCpu, pCtx); break;
11844 case DBGFEVENT_EXIT_VMX_VMPTRLD: VBOXVMM_EXIT_VMX_VMPTRLD(pVCpu, pCtx); break;
11845 case DBGFEVENT_EXIT_VMX_VMPTRST: VBOXVMM_EXIT_VMX_VMPTRST(pVCpu, pCtx); break;
11846 case DBGFEVENT_EXIT_VMX_VMREAD: VBOXVMM_EXIT_VMX_VMREAD(pVCpu, pCtx); break;
11847 case DBGFEVENT_EXIT_VMX_VMRESUME: VBOXVMM_EXIT_VMX_VMRESUME(pVCpu, pCtx); break;
11848 case DBGFEVENT_EXIT_VMX_VMWRITE: VBOXVMM_EXIT_VMX_VMWRITE(pVCpu, pCtx); break;
11849 case DBGFEVENT_EXIT_VMX_VMXOFF: VBOXVMM_EXIT_VMX_VMXOFF(pVCpu, pCtx); break;
11850 case DBGFEVENT_EXIT_VMX_VMXON: VBOXVMM_EXIT_VMX_VMXON(pVCpu, pCtx); break;
11851 case DBGFEVENT_EXIT_VMX_INVEPT: VBOXVMM_EXIT_VMX_INVEPT(pVCpu, pCtx); break;
11852 case DBGFEVENT_EXIT_VMX_INVVPID: VBOXVMM_EXIT_VMX_INVVPID(pVCpu, pCtx); break;
11853 case DBGFEVENT_EXIT_VMX_INVPCID: VBOXVMM_EXIT_VMX_INVPCID(pVCpu, pCtx); break;
11854 case DBGFEVENT_EXIT_VMX_VMFUNC: VBOXVMM_EXIT_VMX_VMFUNC(pVCpu, pCtx); break;
11855 case DBGFEVENT_EXIT_VMX_EPT_MISCONFIG: VBOXVMM_EXIT_VMX_EPT_MISCONFIG(pVCpu, pCtx); break;
11856 case DBGFEVENT_EXIT_VMX_EPT_VIOLATION: VBOXVMM_EXIT_VMX_EPT_VIOLATION(pVCpu, pCtx); break;
11857 case DBGFEVENT_EXIT_VMX_VAPIC_ACCESS: VBOXVMM_EXIT_VMX_VAPIC_ACCESS(pVCpu, pCtx); break;
11858 case DBGFEVENT_EXIT_VMX_VAPIC_WRITE: VBOXVMM_EXIT_VMX_VAPIC_WRITE(pVCpu, pCtx); break;
11859 default: AssertMsgFailed(("enmEvent2=%d uExitReason=%d\n", enmEvent2, uExitReason)); break;
11860 }
11861 }
11862
11863 /*
11864 * Fire of the DBGF event, if enabled (our check here is just a quick one,
11865 * the DBGF call will do a full check).
11866 *
11867 * Note! DBGF sets DBGFEVENT_INTERRUPT_SOFTWARE in the bitmap.
11868 * Note! If we have to events, we prioritize the first, i.e. the instruction
11869 * one, in order to avoid event nesting.
11870 */
11871 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
11872 if ( enmEvent1 != DBGFEVENT_END
11873 && DBGF_IS_EVENT_ENABLED(pVM, enmEvent1))
11874 {
11875 hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, CPUMCTX_EXTRN_CS | CPUMCTX_EXTRN_RIP);
11876 VBOXSTRICTRC rcStrict = DBGFEventGenericWithArgs(pVM, pVCpu, enmEvent1, DBGFEVENTCTX_HM, 1, uEventArg);
11877 if (rcStrict != VINF_SUCCESS)
11878 return rcStrict;
11879 }
11880 else if ( enmEvent2 != DBGFEVENT_END
11881 && DBGF_IS_EVENT_ENABLED(pVM, enmEvent2))
11882 {
11883 hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, CPUMCTX_EXTRN_CS | CPUMCTX_EXTRN_RIP);
11884 VBOXSTRICTRC rcStrict = DBGFEventGenericWithArgs(pVM, pVCpu, enmEvent2, DBGFEVENTCTX_HM, 1, uEventArg);
11885 if (rcStrict != VINF_SUCCESS)
11886 return rcStrict;
11887 }
11888
11889 return VINF_SUCCESS;
11890}
11891
11892
11893/**
11894 * Single-stepping VM-exit filtering.
11895 *
11896 * This is preprocessing the VM-exits and deciding whether we've gotten far
11897 * enough to return VINF_EM_DBG_STEPPED already. If not, normal VM-exit
11898 * handling is performed.
11899 *
11900 * @returns Strict VBox status code (i.e. informational status codes too).
11901 * @param pVCpu The cross context virtual CPU structure of the calling EMT.
11902 * @param pVmxTransient The VMX-transient structure.
11903 * @param pDbgState The debug state.
11904 */
11905DECLINLINE(VBOXSTRICTRC) hmR0VmxRunDebugHandleExit(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient, PVMXRUNDBGSTATE pDbgState)
11906{
11907 /*
11908 * Expensive (saves context) generic dtrace VM-exit probe.
11909 */
11910 uint32_t const uExitReason = pVmxTransient->uExitReason;
11911 if (!VBOXVMM_R0_HMVMX_VMEXIT_ENABLED())
11912 { /* more likely */ }
11913 else
11914 {
11915 hmR0VmxReadExitQualVmcs(pVmxTransient);
11916 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, HMVMX_CPUMCTX_EXTRN_ALL);
11917 AssertRC(rc);
11918 VBOXVMM_R0_HMVMX_VMEXIT(pVCpu, &pVCpu->cpum.GstCtx, pVmxTransient->uExitReason, pVmxTransient->uExitQual);
11919 }
11920
11921 /*
11922 * Check for host NMI, just to get that out of the way.
11923 */
11924 if (uExitReason != VMX_EXIT_XCPT_OR_NMI)
11925 { /* normally likely */ }
11926 else
11927 {
11928 hmR0VmxReadExitIntInfoVmcs(pVmxTransient);
11929 uint32_t const uIntType = VMX_EXIT_INT_INFO_TYPE(pVmxTransient->uExitIntInfo);
11930 if (uIntType == VMX_EXIT_INT_INFO_TYPE_NMI)
11931 return hmR0VmxExitHostNmi(pVCpu, pVmxTransient->pVmcsInfo);
11932 }
11933
11934 /*
11935 * Check for single stepping event if we're stepping.
11936 */
11937 if (pVCpu->hm.s.fSingleInstruction)
11938 {
11939 switch (uExitReason)
11940 {
11941 case VMX_EXIT_MTF:
11942 return hmR0VmxExitMtf(pVCpu, pVmxTransient);
11943
11944 /* Various events: */
11945 case VMX_EXIT_XCPT_OR_NMI:
11946 case VMX_EXIT_EXT_INT:
11947 case VMX_EXIT_TRIPLE_FAULT:
11948 case VMX_EXIT_INT_WINDOW:
11949 case VMX_EXIT_NMI_WINDOW:
11950 case VMX_EXIT_TASK_SWITCH:
11951 case VMX_EXIT_TPR_BELOW_THRESHOLD:
11952 case VMX_EXIT_APIC_ACCESS:
11953 case VMX_EXIT_EPT_VIOLATION:
11954 case VMX_EXIT_EPT_MISCONFIG:
11955 case VMX_EXIT_PREEMPT_TIMER:
11956
11957 /* Instruction specific VM-exits: */
11958 case VMX_EXIT_CPUID:
11959 case VMX_EXIT_GETSEC:
11960 case VMX_EXIT_HLT:
11961 case VMX_EXIT_INVD:
11962 case VMX_EXIT_INVLPG:
11963 case VMX_EXIT_RDPMC:
11964 case VMX_EXIT_RDTSC:
11965 case VMX_EXIT_RSM:
11966 case VMX_EXIT_VMCALL:
11967 case VMX_EXIT_VMCLEAR:
11968 case VMX_EXIT_VMLAUNCH:
11969 case VMX_EXIT_VMPTRLD:
11970 case VMX_EXIT_VMPTRST:
11971 case VMX_EXIT_VMREAD:
11972 case VMX_EXIT_VMRESUME:
11973 case VMX_EXIT_VMWRITE:
11974 case VMX_EXIT_VMXOFF:
11975 case VMX_EXIT_VMXON:
11976 case VMX_EXIT_MOV_CRX:
11977 case VMX_EXIT_MOV_DRX:
11978 case VMX_EXIT_IO_INSTR:
11979 case VMX_EXIT_RDMSR:
11980 case VMX_EXIT_WRMSR:
11981 case VMX_EXIT_MWAIT:
11982 case VMX_EXIT_MONITOR:
11983 case VMX_EXIT_PAUSE:
11984 case VMX_EXIT_GDTR_IDTR_ACCESS:
11985 case VMX_EXIT_LDTR_TR_ACCESS:
11986 case VMX_EXIT_INVEPT:
11987 case VMX_EXIT_RDTSCP:
11988 case VMX_EXIT_INVVPID:
11989 case VMX_EXIT_WBINVD:
11990 case VMX_EXIT_XSETBV:
11991 case VMX_EXIT_RDRAND:
11992 case VMX_EXIT_INVPCID:
11993 case VMX_EXIT_VMFUNC:
11994 case VMX_EXIT_RDSEED:
11995 case VMX_EXIT_XSAVES:
11996 case VMX_EXIT_XRSTORS:
11997 {
11998 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, CPUMCTX_EXTRN_CS | CPUMCTX_EXTRN_RIP);
11999 AssertRCReturn(rc, rc);
12000 if ( pVCpu->cpum.GstCtx.rip != pDbgState->uRipStart
12001 || pVCpu->cpum.GstCtx.cs.Sel != pDbgState->uCsStart)
12002 return VINF_EM_DBG_STEPPED;
12003 break;
12004 }
12005
12006 /* Errors and unexpected events: */
12007 case VMX_EXIT_INIT_SIGNAL:
12008 case VMX_EXIT_SIPI:
12009 case VMX_EXIT_IO_SMI:
12010 case VMX_EXIT_SMI:
12011 case VMX_EXIT_ERR_INVALID_GUEST_STATE:
12012 case VMX_EXIT_ERR_MSR_LOAD:
12013 case VMX_EXIT_ERR_MACHINE_CHECK:
12014 case VMX_EXIT_PML_FULL:
12015 case VMX_EXIT_VIRTUALIZED_EOI:
12016 case VMX_EXIT_APIC_WRITE: /* Some talk about this being fault like, so I guess we must process it? */
12017 break;
12018
12019 default:
12020 AssertMsgFailed(("Unexpected VM-exit=%#x\n", uExitReason));
12021 break;
12022 }
12023 }
12024
12025 /*
12026 * Check for debugger event breakpoints and dtrace probes.
12027 */
12028 if ( uExitReason < RT_ELEMENTS(pDbgState->bmExitsToCheck) * 32U
12029 && ASMBitTest(pDbgState->bmExitsToCheck, uExitReason) )
12030 {
12031 VBOXSTRICTRC rcStrict = hmR0VmxHandleExitDtraceEvents(pVCpu, pVmxTransient, uExitReason);
12032 if (rcStrict != VINF_SUCCESS)
12033 return rcStrict;
12034 }
12035
12036 /*
12037 * Normal processing.
12038 */
12039#ifdef HMVMX_USE_FUNCTION_TABLE
12040 return g_apfnVMExitHandlers[uExitReason](pVCpu, pVmxTransient);
12041#else
12042 return hmR0VmxHandleExit(pVCpu, pVmxTransient, uExitReason);
12043#endif
12044}
12045
12046
12047/**
12048 * Single steps guest code using hardware-assisted VMX.
12049 *
12050 * This is -not- the same as the guest single-stepping itself (say using EFLAGS.TF)
12051 * but single-stepping through the hypervisor debugger.
12052 *
12053 * @returns Strict VBox status code (i.e. informational status codes too).
12054 * @param pVCpu The cross context virtual CPU structure.
12055 * @param pcLoops Pointer to the number of executed loops.
12056 *
12057 * @note Mostly the same as hmR0VmxRunGuestCodeNormal().
12058 */
12059static VBOXSTRICTRC hmR0VmxRunGuestCodeDebug(PVMCPUCC pVCpu, uint32_t *pcLoops)
12060{
12061 uint32_t const cMaxResumeLoops = pVCpu->CTX_SUFF(pVM)->hm.s.cMaxResumeLoops;
12062 Assert(pcLoops);
12063 Assert(*pcLoops <= cMaxResumeLoops);
12064
12065 VMXTRANSIENT VmxTransient;
12066 RT_ZERO(VmxTransient);
12067 VmxTransient.pVmcsInfo = hmGetVmxActiveVmcsInfo(pVCpu);
12068
12069 /* Set HMCPU indicators. */
12070 bool const fSavedSingleInstruction = pVCpu->hm.s.fSingleInstruction;
12071 pVCpu->hm.s.fSingleInstruction = pVCpu->hm.s.fSingleInstruction || DBGFIsStepping(pVCpu);
12072 pVCpu->hm.s.fDebugWantRdTscExit = false;
12073 pVCpu->hm.s.fUsingDebugLoop = true;
12074
12075 /* State we keep to help modify and later restore the VMCS fields we alter, and for detecting steps. */
12076 VMXRUNDBGSTATE DbgState;
12077 hmR0VmxRunDebugStateInit(pVCpu, &VmxTransient, &DbgState);
12078 hmR0VmxPreRunGuestDebugStateUpdate(pVCpu, &VmxTransient, &DbgState);
12079
12080 /*
12081 * The loop.
12082 */
12083 VBOXSTRICTRC rcStrict = VERR_INTERNAL_ERROR_5;
12084 for (;;)
12085 {
12086 Assert(!HMR0SuspendPending());
12087 HMVMX_ASSERT_CPU_SAFE(pVCpu);
12088 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatEntry, x);
12089 bool fStepping = pVCpu->hm.s.fSingleInstruction;
12090
12091 /* Set up VM-execution controls the next two can respond to. */
12092 hmR0VmxPreRunGuestDebugStateApply(pVCpu, &VmxTransient, &DbgState);
12093
12094 /*
12095 * Preparatory work for running guest code, this may force us to
12096 * return to ring-3.
12097 *
12098 * Warning! This bugger disables interrupts on VINF_SUCCESS!
12099 */
12100 rcStrict = hmR0VmxPreRunGuest(pVCpu, &VmxTransient, fStepping);
12101 if (rcStrict != VINF_SUCCESS)
12102 break;
12103
12104 /* Interrupts are disabled at this point! */
12105 hmR0VmxPreRunGuestCommitted(pVCpu, &VmxTransient);
12106
12107 /* Override any obnoxious code in the above two calls. */
12108 hmR0VmxPreRunGuestDebugStateApply(pVCpu, &VmxTransient, &DbgState);
12109
12110 /*
12111 * Finally execute the guest.
12112 */
12113 int rcRun = hmR0VmxRunGuest(pVCpu, &VmxTransient);
12114
12115 hmR0VmxPostRunGuest(pVCpu, &VmxTransient, rcRun);
12116 /* Interrupts are re-enabled at this point! */
12117
12118 /* Check for errors with running the VM (VMLAUNCH/VMRESUME). */
12119 if (RT_SUCCESS(rcRun))
12120 { /* very likely */ }
12121 else
12122 {
12123 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatPreExit, x);
12124 hmR0VmxReportWorldSwitchError(pVCpu, rcRun, &VmxTransient);
12125 return rcRun;
12126 }
12127
12128 /* Profile the VM-exit. */
12129 AssertMsg(VmxTransient.uExitReason <= VMX_EXIT_MAX, ("%#x\n", VmxTransient.uExitReason));
12130 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitAll);
12131 STAM_COUNTER_INC(&pVCpu->hm.s.paStatExitReasonR0[VmxTransient.uExitReason & MASK_EXITREASON_STAT]);
12132 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatPreExit, &pVCpu->hm.s.StatExitHandling, x);
12133 HMVMX_START_EXIT_DISPATCH_PROF();
12134
12135 VBOXVMM_R0_HMVMX_VMEXIT_NOCTX(pVCpu, &pVCpu->cpum.GstCtx, VmxTransient.uExitReason);
12136
12137 /*
12138 * Handle the VM-exit - we quit earlier on certain VM-exits, see hmR0VmxHandleExitDebug().
12139 */
12140 rcStrict = hmR0VmxRunDebugHandleExit(pVCpu, &VmxTransient, &DbgState);
12141 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExitHandling, x);
12142 if (rcStrict != VINF_SUCCESS)
12143 break;
12144 if (++(*pcLoops) > cMaxResumeLoops)
12145 {
12146 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchMaxResumeLoops);
12147 rcStrict = VINF_EM_RAW_INTERRUPT;
12148 break;
12149 }
12150
12151 /*
12152 * Stepping: Did the RIP change, if so, consider it a single step.
12153 * Otherwise, make sure one of the TFs gets set.
12154 */
12155 if (fStepping)
12156 {
12157 int rc = hmR0VmxImportGuestState(pVCpu, VmxTransient.pVmcsInfo, CPUMCTX_EXTRN_CS | CPUMCTX_EXTRN_RIP);
12158 AssertRC(rc);
12159 if ( pVCpu->cpum.GstCtx.rip != DbgState.uRipStart
12160 || pVCpu->cpum.GstCtx.cs.Sel != DbgState.uCsStart)
12161 {
12162 rcStrict = VINF_EM_DBG_STEPPED;
12163 break;
12164 }
12165 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_DR7);
12166 }
12167
12168 /*
12169 * Update when dtrace settings changes (DBGF kicks us, so no need to check).
12170 */
12171 if (VBOXVMM_GET_SETTINGS_SEQ_NO() != DbgState.uDtraceSettingsSeqNo)
12172 hmR0VmxPreRunGuestDebugStateUpdate(pVCpu, &VmxTransient, &DbgState);
12173 }
12174
12175 /*
12176 * Clear the X86_EFL_TF if necessary.
12177 */
12178 if (pVCpu->hm.s.fClearTrapFlag)
12179 {
12180 int rc = hmR0VmxImportGuestState(pVCpu, VmxTransient.pVmcsInfo, CPUMCTX_EXTRN_RFLAGS);
12181 AssertRC(rc);
12182 pVCpu->hm.s.fClearTrapFlag = false;
12183 pVCpu->cpum.GstCtx.eflags.Bits.u1TF = 0;
12184 }
12185 /** @todo there seems to be issues with the resume flag when the monitor trap
12186 * flag is pending without being used. Seen early in bios init when
12187 * accessing APIC page in protected mode. */
12188
12189 /*
12190 * Restore VM-exit control settings as we may not re-enter this function the
12191 * next time around.
12192 */
12193 rcStrict = hmR0VmxRunDebugStateRevert(pVCpu, &VmxTransient, &DbgState, rcStrict);
12194
12195 /* Restore HMCPU indicators. */
12196 pVCpu->hm.s.fUsingDebugLoop = false;
12197 pVCpu->hm.s.fDebugWantRdTscExit = false;
12198 pVCpu->hm.s.fSingleInstruction = fSavedSingleInstruction;
12199
12200 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatEntry, x);
12201 return rcStrict;
12202}
12203
12204
12205/** @} */
12206
12207
12208/**
12209 * Checks if any expensive dtrace probes are enabled and we should go to the
12210 * debug loop.
12211 *
12212 * @returns true if we should use debug loop, false if not.
12213 */
12214static bool hmR0VmxAnyExpensiveProbesEnabled(void)
12215{
12216 /* It's probably faster to OR the raw 32-bit counter variables together.
12217 Since the variables are in an array and the probes are next to one
12218 another (more or less), we have good locality. So, better read
12219 eight-nine cache lines ever time and only have one conditional, than
12220 128+ conditionals, right? */
12221 return ( VBOXVMM_R0_HMVMX_VMEXIT_ENABLED_RAW() /* expensive too due to context */
12222 | VBOXVMM_XCPT_DE_ENABLED_RAW()
12223 | VBOXVMM_XCPT_DB_ENABLED_RAW()
12224 | VBOXVMM_XCPT_BP_ENABLED_RAW()
12225 | VBOXVMM_XCPT_OF_ENABLED_RAW()
12226 | VBOXVMM_XCPT_BR_ENABLED_RAW()
12227 | VBOXVMM_XCPT_UD_ENABLED_RAW()
12228 | VBOXVMM_XCPT_NM_ENABLED_RAW()
12229 | VBOXVMM_XCPT_DF_ENABLED_RAW()
12230 | VBOXVMM_XCPT_TS_ENABLED_RAW()
12231 | VBOXVMM_XCPT_NP_ENABLED_RAW()
12232 | VBOXVMM_XCPT_SS_ENABLED_RAW()
12233 | VBOXVMM_XCPT_GP_ENABLED_RAW()
12234 | VBOXVMM_XCPT_PF_ENABLED_RAW()
12235 | VBOXVMM_XCPT_MF_ENABLED_RAW()
12236 | VBOXVMM_XCPT_AC_ENABLED_RAW()
12237 | VBOXVMM_XCPT_XF_ENABLED_RAW()
12238 | VBOXVMM_XCPT_VE_ENABLED_RAW()
12239 | VBOXVMM_XCPT_SX_ENABLED_RAW()
12240 | VBOXVMM_INT_SOFTWARE_ENABLED_RAW()
12241 | VBOXVMM_INT_HARDWARE_ENABLED_RAW()
12242 ) != 0
12243 || ( VBOXVMM_INSTR_HALT_ENABLED_RAW()
12244 | VBOXVMM_INSTR_MWAIT_ENABLED_RAW()
12245 | VBOXVMM_INSTR_MONITOR_ENABLED_RAW()
12246 | VBOXVMM_INSTR_CPUID_ENABLED_RAW()
12247 | VBOXVMM_INSTR_INVD_ENABLED_RAW()
12248 | VBOXVMM_INSTR_WBINVD_ENABLED_RAW()
12249 | VBOXVMM_INSTR_INVLPG_ENABLED_RAW()
12250 | VBOXVMM_INSTR_RDTSC_ENABLED_RAW()
12251 | VBOXVMM_INSTR_RDTSCP_ENABLED_RAW()
12252 | VBOXVMM_INSTR_RDPMC_ENABLED_RAW()
12253 | VBOXVMM_INSTR_RDMSR_ENABLED_RAW()
12254 | VBOXVMM_INSTR_WRMSR_ENABLED_RAW()
12255 | VBOXVMM_INSTR_CRX_READ_ENABLED_RAW()
12256 | VBOXVMM_INSTR_CRX_WRITE_ENABLED_RAW()
12257 | VBOXVMM_INSTR_DRX_READ_ENABLED_RAW()
12258 | VBOXVMM_INSTR_DRX_WRITE_ENABLED_RAW()
12259 | VBOXVMM_INSTR_PAUSE_ENABLED_RAW()
12260 | VBOXVMM_INSTR_XSETBV_ENABLED_RAW()
12261 | VBOXVMM_INSTR_SIDT_ENABLED_RAW()
12262 | VBOXVMM_INSTR_LIDT_ENABLED_RAW()
12263 | VBOXVMM_INSTR_SGDT_ENABLED_RAW()
12264 | VBOXVMM_INSTR_LGDT_ENABLED_RAW()
12265 | VBOXVMM_INSTR_SLDT_ENABLED_RAW()
12266 | VBOXVMM_INSTR_LLDT_ENABLED_RAW()
12267 | VBOXVMM_INSTR_STR_ENABLED_RAW()
12268 | VBOXVMM_INSTR_LTR_ENABLED_RAW()
12269 | VBOXVMM_INSTR_GETSEC_ENABLED_RAW()
12270 | VBOXVMM_INSTR_RSM_ENABLED_RAW()
12271 | VBOXVMM_INSTR_RDRAND_ENABLED_RAW()
12272 | VBOXVMM_INSTR_RDSEED_ENABLED_RAW()
12273 | VBOXVMM_INSTR_XSAVES_ENABLED_RAW()
12274 | VBOXVMM_INSTR_XRSTORS_ENABLED_RAW()
12275 | VBOXVMM_INSTR_VMM_CALL_ENABLED_RAW()
12276 | VBOXVMM_INSTR_VMX_VMCLEAR_ENABLED_RAW()
12277 | VBOXVMM_INSTR_VMX_VMLAUNCH_ENABLED_RAW()
12278 | VBOXVMM_INSTR_VMX_VMPTRLD_ENABLED_RAW()
12279 | VBOXVMM_INSTR_VMX_VMPTRST_ENABLED_RAW()
12280 | VBOXVMM_INSTR_VMX_VMREAD_ENABLED_RAW()
12281 | VBOXVMM_INSTR_VMX_VMRESUME_ENABLED_RAW()
12282 | VBOXVMM_INSTR_VMX_VMWRITE_ENABLED_RAW()
12283 | VBOXVMM_INSTR_VMX_VMXOFF_ENABLED_RAW()
12284 | VBOXVMM_INSTR_VMX_VMXON_ENABLED_RAW()
12285 | VBOXVMM_INSTR_VMX_VMFUNC_ENABLED_RAW()
12286 | VBOXVMM_INSTR_VMX_INVEPT_ENABLED_RAW()
12287 | VBOXVMM_INSTR_VMX_INVVPID_ENABLED_RAW()
12288 | VBOXVMM_INSTR_VMX_INVPCID_ENABLED_RAW()
12289 ) != 0
12290 || ( VBOXVMM_EXIT_TASK_SWITCH_ENABLED_RAW()
12291 | VBOXVMM_EXIT_HALT_ENABLED_RAW()
12292 | VBOXVMM_EXIT_MWAIT_ENABLED_RAW()
12293 | VBOXVMM_EXIT_MONITOR_ENABLED_RAW()
12294 | VBOXVMM_EXIT_CPUID_ENABLED_RAW()
12295 | VBOXVMM_EXIT_INVD_ENABLED_RAW()
12296 | VBOXVMM_EXIT_WBINVD_ENABLED_RAW()
12297 | VBOXVMM_EXIT_INVLPG_ENABLED_RAW()
12298 | VBOXVMM_EXIT_RDTSC_ENABLED_RAW()
12299 | VBOXVMM_EXIT_RDTSCP_ENABLED_RAW()
12300 | VBOXVMM_EXIT_RDPMC_ENABLED_RAW()
12301 | VBOXVMM_EXIT_RDMSR_ENABLED_RAW()
12302 | VBOXVMM_EXIT_WRMSR_ENABLED_RAW()
12303 | VBOXVMM_EXIT_CRX_READ_ENABLED_RAW()
12304 | VBOXVMM_EXIT_CRX_WRITE_ENABLED_RAW()
12305 | VBOXVMM_EXIT_DRX_READ_ENABLED_RAW()
12306 | VBOXVMM_EXIT_DRX_WRITE_ENABLED_RAW()
12307 | VBOXVMM_EXIT_PAUSE_ENABLED_RAW()
12308 | VBOXVMM_EXIT_XSETBV_ENABLED_RAW()
12309 | VBOXVMM_EXIT_SIDT_ENABLED_RAW()
12310 | VBOXVMM_EXIT_LIDT_ENABLED_RAW()
12311 | VBOXVMM_EXIT_SGDT_ENABLED_RAW()
12312 | VBOXVMM_EXIT_LGDT_ENABLED_RAW()
12313 | VBOXVMM_EXIT_SLDT_ENABLED_RAW()
12314 | VBOXVMM_EXIT_LLDT_ENABLED_RAW()
12315 | VBOXVMM_EXIT_STR_ENABLED_RAW()
12316 | VBOXVMM_EXIT_LTR_ENABLED_RAW()
12317 | VBOXVMM_EXIT_GETSEC_ENABLED_RAW()
12318 | VBOXVMM_EXIT_RSM_ENABLED_RAW()
12319 | VBOXVMM_EXIT_RDRAND_ENABLED_RAW()
12320 | VBOXVMM_EXIT_RDSEED_ENABLED_RAW()
12321 | VBOXVMM_EXIT_XSAVES_ENABLED_RAW()
12322 | VBOXVMM_EXIT_XRSTORS_ENABLED_RAW()
12323 | VBOXVMM_EXIT_VMM_CALL_ENABLED_RAW()
12324 | VBOXVMM_EXIT_VMX_VMCLEAR_ENABLED_RAW()
12325 | VBOXVMM_EXIT_VMX_VMLAUNCH_ENABLED_RAW()
12326 | VBOXVMM_EXIT_VMX_VMPTRLD_ENABLED_RAW()
12327 | VBOXVMM_EXIT_VMX_VMPTRST_ENABLED_RAW()
12328 | VBOXVMM_EXIT_VMX_VMREAD_ENABLED_RAW()
12329 | VBOXVMM_EXIT_VMX_VMRESUME_ENABLED_RAW()
12330 | VBOXVMM_EXIT_VMX_VMWRITE_ENABLED_RAW()
12331 | VBOXVMM_EXIT_VMX_VMXOFF_ENABLED_RAW()
12332 | VBOXVMM_EXIT_VMX_VMXON_ENABLED_RAW()
12333 | VBOXVMM_EXIT_VMX_VMFUNC_ENABLED_RAW()
12334 | VBOXVMM_EXIT_VMX_INVEPT_ENABLED_RAW()
12335 | VBOXVMM_EXIT_VMX_INVVPID_ENABLED_RAW()
12336 | VBOXVMM_EXIT_VMX_INVPCID_ENABLED_RAW()
12337 | VBOXVMM_EXIT_VMX_EPT_VIOLATION_ENABLED_RAW()
12338 | VBOXVMM_EXIT_VMX_EPT_MISCONFIG_ENABLED_RAW()
12339 | VBOXVMM_EXIT_VMX_VAPIC_ACCESS_ENABLED_RAW()
12340 | VBOXVMM_EXIT_VMX_VAPIC_WRITE_ENABLED_RAW()
12341 ) != 0;
12342}
12343
12344
12345/**
12346 * Runs the guest using hardware-assisted VMX.
12347 *
12348 * @returns Strict VBox status code (i.e. informational status codes too).
12349 * @param pVCpu The cross context virtual CPU structure.
12350 */
12351VMMR0DECL(VBOXSTRICTRC) VMXR0RunGuestCode(PVMCPUCC pVCpu)
12352{
12353 AssertPtr(pVCpu);
12354 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
12355 Assert(VMMRZCallRing3IsEnabled(pVCpu));
12356 Assert(!ASMAtomicUoReadU64(&pCtx->fExtrn));
12357 HMVMX_ASSERT_PREEMPT_SAFE(pVCpu);
12358
12359 VBOXSTRICTRC rcStrict;
12360 uint32_t cLoops = 0;
12361 for (;;)
12362 {
12363#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
12364 bool const fInNestedGuestMode = CPUMIsGuestInVmxNonRootMode(pCtx);
12365#else
12366 bool const fInNestedGuestMode = false;
12367#endif
12368 if (!fInNestedGuestMode)
12369 {
12370 if ( !pVCpu->hm.s.fUseDebugLoop
12371 && (!VBOXVMM_ANY_PROBES_ENABLED() || !hmR0VmxAnyExpensiveProbesEnabled())
12372 && !DBGFIsStepping(pVCpu)
12373 && !pVCpu->CTX_SUFF(pVM)->dbgf.ro.cEnabledInt3Breakpoints)
12374 rcStrict = hmR0VmxRunGuestCodeNormal(pVCpu, &cLoops);
12375 else
12376 rcStrict = hmR0VmxRunGuestCodeDebug(pVCpu, &cLoops);
12377 }
12378#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
12379 else
12380 rcStrict = hmR0VmxRunGuestCodeNested(pVCpu, &cLoops);
12381
12382 if (rcStrict == VINF_VMX_VMLAUNCH_VMRESUME)
12383 {
12384 Assert(CPUMIsGuestInVmxNonRootMode(pCtx));
12385 continue;
12386 }
12387 if (rcStrict == VINF_VMX_VMEXIT)
12388 {
12389 Assert(!CPUMIsGuestInVmxNonRootMode(pCtx));
12390 continue;
12391 }
12392#endif
12393 break;
12394 }
12395
12396 int const rcLoop = VBOXSTRICTRC_VAL(rcStrict);
12397 switch (rcLoop)
12398 {
12399 case VERR_EM_INTERPRETER: rcStrict = VINF_EM_RAW_EMULATE_INSTR; break;
12400 case VINF_EM_RESET: rcStrict = VINF_EM_TRIPLE_FAULT; break;
12401 }
12402
12403 int rc2 = hmR0VmxExitToRing3(pVCpu, rcStrict);
12404 if (RT_FAILURE(rc2))
12405 {
12406 pVCpu->hm.s.u32HMError = (uint32_t)VBOXSTRICTRC_VAL(rcStrict);
12407 rcStrict = rc2;
12408 }
12409 Assert(!ASMAtomicUoReadU64(&pCtx->fExtrn));
12410 Assert(!VMMRZCallRing3IsNotificationSet(pVCpu));
12411 return rcStrict;
12412}
12413
12414
12415#ifndef HMVMX_USE_FUNCTION_TABLE
12416/**
12417 * Handles a guest VM-exit from hardware-assisted VMX execution.
12418 *
12419 * @returns Strict VBox status code (i.e. informational status codes too).
12420 * @param pVCpu The cross context virtual CPU structure.
12421 * @param pVmxTransient The VMX-transient structure.
12422 */
12423DECLINLINE(VBOXSTRICTRC) hmR0VmxHandleExit(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
12424{
12425#ifdef DEBUG_ramshankar
12426# define VMEXIT_CALL_RET(a_fSave, a_CallExpr) \
12427 do { \
12428 if (a_fSave != 0) \
12429 hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, HMVMX_CPUMCTX_EXTRN_ALL); \
12430 VBOXSTRICTRC rcStrict = a_CallExpr; \
12431 if (a_fSave != 0) \
12432 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_ALL_GUEST); \
12433 return rcStrict; \
12434 } while (0)
12435#else
12436# define VMEXIT_CALL_RET(a_fSave, a_CallExpr) return a_CallExpr
12437#endif
12438 uint32_t const uExitReason = pVmxTransient->uExitReason;
12439 switch (uExitReason)
12440 {
12441 case VMX_EXIT_EPT_MISCONFIG: VMEXIT_CALL_RET(0, hmR0VmxExitEptMisconfig(pVCpu, pVmxTransient));
12442 case VMX_EXIT_EPT_VIOLATION: VMEXIT_CALL_RET(0, hmR0VmxExitEptViolation(pVCpu, pVmxTransient));
12443 case VMX_EXIT_IO_INSTR: VMEXIT_CALL_RET(0, hmR0VmxExitIoInstr(pVCpu, pVmxTransient));
12444 case VMX_EXIT_CPUID: VMEXIT_CALL_RET(0, hmR0VmxExitCpuid(pVCpu, pVmxTransient));
12445 case VMX_EXIT_RDTSC: VMEXIT_CALL_RET(0, hmR0VmxExitRdtsc(pVCpu, pVmxTransient));
12446 case VMX_EXIT_RDTSCP: VMEXIT_CALL_RET(0, hmR0VmxExitRdtscp(pVCpu, pVmxTransient));
12447 case VMX_EXIT_APIC_ACCESS: VMEXIT_CALL_RET(0, hmR0VmxExitApicAccess(pVCpu, pVmxTransient));
12448 case VMX_EXIT_XCPT_OR_NMI: VMEXIT_CALL_RET(0, hmR0VmxExitXcptOrNmi(pVCpu, pVmxTransient));
12449 case VMX_EXIT_MOV_CRX: VMEXIT_CALL_RET(0, hmR0VmxExitMovCRx(pVCpu, pVmxTransient));
12450 case VMX_EXIT_EXT_INT: VMEXIT_CALL_RET(0, hmR0VmxExitExtInt(pVCpu, pVmxTransient));
12451 case VMX_EXIT_INT_WINDOW: VMEXIT_CALL_RET(0, hmR0VmxExitIntWindow(pVCpu, pVmxTransient));
12452 case VMX_EXIT_TPR_BELOW_THRESHOLD: VMEXIT_CALL_RET(0, hmR0VmxExitTprBelowThreshold(pVCpu, pVmxTransient));
12453 case VMX_EXIT_MWAIT: VMEXIT_CALL_RET(0, hmR0VmxExitMwait(pVCpu, pVmxTransient));
12454 case VMX_EXIT_MONITOR: VMEXIT_CALL_RET(0, hmR0VmxExitMonitor(pVCpu, pVmxTransient));
12455 case VMX_EXIT_TASK_SWITCH: VMEXIT_CALL_RET(0, hmR0VmxExitTaskSwitch(pVCpu, pVmxTransient));
12456 case VMX_EXIT_PREEMPT_TIMER: VMEXIT_CALL_RET(0, hmR0VmxExitPreemptTimer(pVCpu, pVmxTransient));
12457 case VMX_EXIT_RDMSR: VMEXIT_CALL_RET(0, hmR0VmxExitRdmsr(pVCpu, pVmxTransient));
12458 case VMX_EXIT_WRMSR: VMEXIT_CALL_RET(0, hmR0VmxExitWrmsr(pVCpu, pVmxTransient));
12459 case VMX_EXIT_VMCALL: VMEXIT_CALL_RET(0, hmR0VmxExitVmcall(pVCpu, pVmxTransient));
12460 case VMX_EXIT_MOV_DRX: VMEXIT_CALL_RET(0, hmR0VmxExitMovDRx(pVCpu, pVmxTransient));
12461 case VMX_EXIT_HLT: VMEXIT_CALL_RET(0, hmR0VmxExitHlt(pVCpu, pVmxTransient));
12462 case VMX_EXIT_INVD: VMEXIT_CALL_RET(0, hmR0VmxExitInvd(pVCpu, pVmxTransient));
12463 case VMX_EXIT_INVLPG: VMEXIT_CALL_RET(0, hmR0VmxExitInvlpg(pVCpu, pVmxTransient));
12464 case VMX_EXIT_MTF: VMEXIT_CALL_RET(0, hmR0VmxExitMtf(pVCpu, pVmxTransient));
12465 case VMX_EXIT_PAUSE: VMEXIT_CALL_RET(0, hmR0VmxExitPause(pVCpu, pVmxTransient));
12466 case VMX_EXIT_WBINVD: VMEXIT_CALL_RET(0, hmR0VmxExitWbinvd(pVCpu, pVmxTransient));
12467 case VMX_EXIT_XSETBV: VMEXIT_CALL_RET(0, hmR0VmxExitXsetbv(pVCpu, pVmxTransient));
12468 case VMX_EXIT_INVPCID: VMEXIT_CALL_RET(0, hmR0VmxExitInvpcid(pVCpu, pVmxTransient));
12469 case VMX_EXIT_GETSEC: VMEXIT_CALL_RET(0, hmR0VmxExitGetsec(pVCpu, pVmxTransient));
12470 case VMX_EXIT_RDPMC: VMEXIT_CALL_RET(0, hmR0VmxExitRdpmc(pVCpu, pVmxTransient));
12471#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
12472 case VMX_EXIT_VMCLEAR: VMEXIT_CALL_RET(0, hmR0VmxExitVmclear(pVCpu, pVmxTransient));
12473 case VMX_EXIT_VMLAUNCH: VMEXIT_CALL_RET(0, hmR0VmxExitVmlaunch(pVCpu, pVmxTransient));
12474 case VMX_EXIT_VMPTRLD: VMEXIT_CALL_RET(0, hmR0VmxExitVmptrld(pVCpu, pVmxTransient));
12475 case VMX_EXIT_VMPTRST: VMEXIT_CALL_RET(0, hmR0VmxExitVmptrst(pVCpu, pVmxTransient));
12476 case VMX_EXIT_VMREAD: VMEXIT_CALL_RET(0, hmR0VmxExitVmread(pVCpu, pVmxTransient));
12477 case VMX_EXIT_VMRESUME: VMEXIT_CALL_RET(0, hmR0VmxExitVmwrite(pVCpu, pVmxTransient));
12478 case VMX_EXIT_VMWRITE: VMEXIT_CALL_RET(0, hmR0VmxExitVmresume(pVCpu, pVmxTransient));
12479 case VMX_EXIT_VMXOFF: VMEXIT_CALL_RET(0, hmR0VmxExitVmxoff(pVCpu, pVmxTransient));
12480 case VMX_EXIT_VMXON: VMEXIT_CALL_RET(0, hmR0VmxExitVmxon(pVCpu, pVmxTransient));
12481 case VMX_EXIT_INVVPID: VMEXIT_CALL_RET(0, hmR0VmxExitInvvpid(pVCpu, pVmxTransient));
12482 case VMX_EXIT_INVEPT: VMEXIT_CALL_RET(0, hmR0VmxExitSetPendingXcptUD(pVCpu, pVmxTransient));
12483#else
12484 case VMX_EXIT_VMCLEAR:
12485 case VMX_EXIT_VMLAUNCH:
12486 case VMX_EXIT_VMPTRLD:
12487 case VMX_EXIT_VMPTRST:
12488 case VMX_EXIT_VMREAD:
12489 case VMX_EXIT_VMRESUME:
12490 case VMX_EXIT_VMWRITE:
12491 case VMX_EXIT_VMXOFF:
12492 case VMX_EXIT_VMXON:
12493 case VMX_EXIT_INVVPID:
12494 case VMX_EXIT_INVEPT:
12495 return hmR0VmxExitSetPendingXcptUD(pVCpu, pVmxTransient);
12496#endif
12497
12498 case VMX_EXIT_TRIPLE_FAULT: return hmR0VmxExitTripleFault(pVCpu, pVmxTransient);
12499 case VMX_EXIT_NMI_WINDOW: return hmR0VmxExitNmiWindow(pVCpu, pVmxTransient);
12500 case VMX_EXIT_ERR_INVALID_GUEST_STATE: return hmR0VmxExitErrInvalidGuestState(pVCpu, pVmxTransient);
12501
12502 case VMX_EXIT_INIT_SIGNAL:
12503 case VMX_EXIT_SIPI:
12504 case VMX_EXIT_IO_SMI:
12505 case VMX_EXIT_SMI:
12506 case VMX_EXIT_ERR_MSR_LOAD:
12507 case VMX_EXIT_ERR_MACHINE_CHECK:
12508 case VMX_EXIT_PML_FULL:
12509 case VMX_EXIT_VIRTUALIZED_EOI:
12510 case VMX_EXIT_GDTR_IDTR_ACCESS:
12511 case VMX_EXIT_LDTR_TR_ACCESS:
12512 case VMX_EXIT_APIC_WRITE:
12513 case VMX_EXIT_RDRAND:
12514 case VMX_EXIT_RSM:
12515 case VMX_EXIT_VMFUNC:
12516 case VMX_EXIT_ENCLS:
12517 case VMX_EXIT_RDSEED:
12518 case VMX_EXIT_XSAVES:
12519 case VMX_EXIT_XRSTORS:
12520 case VMX_EXIT_UMWAIT:
12521 case VMX_EXIT_TPAUSE:
12522 default:
12523 return hmR0VmxExitErrUnexpected(pVCpu, pVmxTransient);
12524 }
12525#undef VMEXIT_CALL_RET
12526}
12527#endif /* !HMVMX_USE_FUNCTION_TABLE */
12528
12529
12530#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
12531/**
12532 * Handles a nested-guest VM-exit from hardware-assisted VMX execution.
12533 *
12534 * @returns Strict VBox status code (i.e. informational status codes too).
12535 * @param pVCpu The cross context virtual CPU structure.
12536 * @param pVmxTransient The VMX-transient structure.
12537 */
12538DECLINLINE(VBOXSTRICTRC) hmR0VmxHandleExitNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
12539{
12540 /** @todo NSTVMX: Remove after debugging page-fault issue. */
12541#ifdef DEBUG_ramshankar
12542 hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, HMVMX_CPUMCTX_EXTRN_ALL);
12543 Log4Func(("cs:rip=%#04x:%#RX64 rsp=%#RX64 eflags=%#RX32 cr3=%#RX64\n", pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip,
12544 pVCpu->cpum.GstCtx.rsp, pVCpu->cpum.GstCtx.eflags.u32, pVCpu->cpum.GstCtx.cr3));
12545#endif
12546
12547 uint32_t const uExitReason = pVmxTransient->uExitReason;
12548 switch (uExitReason)
12549 {
12550 case VMX_EXIT_EPT_MISCONFIG: return hmR0VmxExitEptMisconfig(pVCpu, pVmxTransient);
12551 case VMX_EXIT_EPT_VIOLATION: return hmR0VmxExitEptViolation(pVCpu, pVmxTransient);
12552 case VMX_EXIT_XCPT_OR_NMI: return hmR0VmxExitXcptOrNmiNested(pVCpu, pVmxTransient);
12553 case VMX_EXIT_IO_INSTR: return hmR0VmxExitIoInstrNested(pVCpu, pVmxTransient);
12554 case VMX_EXIT_HLT: return hmR0VmxExitHltNested(pVCpu, pVmxTransient);
12555
12556 /*
12557 * We shouldn't direct host physical interrupts to the nested-guest.
12558 */
12559 case VMX_EXIT_EXT_INT:
12560 return hmR0VmxExitExtInt(pVCpu, pVmxTransient);
12561
12562 /*
12563 * Instructions that cause VM-exits unconditionally or the condition is
12564 * always is taken solely from the guest hypervisor (meaning if the VM-exit
12565 * happens, it's guaranteed to be a nested-guest VM-exit).
12566 *
12567 * - Provides VM-exit instruction length ONLY.
12568 */
12569 case VMX_EXIT_CPUID: /* Unconditional. */
12570 case VMX_EXIT_VMCALL:
12571 case VMX_EXIT_GETSEC:
12572 case VMX_EXIT_INVD:
12573 case VMX_EXIT_XSETBV:
12574 case VMX_EXIT_VMLAUNCH:
12575 case VMX_EXIT_VMRESUME:
12576 case VMX_EXIT_VMXOFF:
12577 case VMX_EXIT_ENCLS: /* Condition specified solely by guest hypervisor. */
12578 case VMX_EXIT_VMFUNC:
12579 return hmR0VmxExitInstrNested(pVCpu, pVmxTransient);
12580
12581 /*
12582 * Instructions that cause VM-exits unconditionally or the condition is
12583 * always is taken solely from the guest hypervisor (meaning if the VM-exit
12584 * happens, it's guaranteed to be a nested-guest VM-exit).
12585 *
12586 * - Provides VM-exit instruction length.
12587 * - Provides VM-exit information.
12588 * - Optionally provides Exit qualification.
12589 *
12590 * Since Exit qualification is 0 for all VM-exits where it is not
12591 * applicable, reading and passing it to the guest should produce
12592 * defined behavior.
12593 *
12594 * See Intel spec. 27.2.1 "Basic VM-Exit Information".
12595 */
12596 case VMX_EXIT_INVEPT: /* Unconditional. */
12597 case VMX_EXIT_INVVPID:
12598 case VMX_EXIT_VMCLEAR:
12599 case VMX_EXIT_VMPTRLD:
12600 case VMX_EXIT_VMPTRST:
12601 case VMX_EXIT_VMXON:
12602 case VMX_EXIT_GDTR_IDTR_ACCESS: /* Condition specified solely by guest hypervisor. */
12603 case VMX_EXIT_LDTR_TR_ACCESS:
12604 case VMX_EXIT_RDRAND:
12605 case VMX_EXIT_RDSEED:
12606 case VMX_EXIT_XSAVES:
12607 case VMX_EXIT_XRSTORS:
12608 case VMX_EXIT_UMWAIT:
12609 case VMX_EXIT_TPAUSE:
12610 return hmR0VmxExitInstrWithInfoNested(pVCpu, pVmxTransient);
12611
12612 case VMX_EXIT_RDTSC: return hmR0VmxExitRdtscNested(pVCpu, pVmxTransient);
12613 case VMX_EXIT_RDTSCP: return hmR0VmxExitRdtscpNested(pVCpu, pVmxTransient);
12614 case VMX_EXIT_RDMSR: return hmR0VmxExitRdmsrNested(pVCpu, pVmxTransient);
12615 case VMX_EXIT_WRMSR: return hmR0VmxExitWrmsrNested(pVCpu, pVmxTransient);
12616 case VMX_EXIT_INVLPG: return hmR0VmxExitInvlpgNested(pVCpu, pVmxTransient);
12617 case VMX_EXIT_INVPCID: return hmR0VmxExitInvpcidNested(pVCpu, pVmxTransient);
12618 case VMX_EXIT_TASK_SWITCH: return hmR0VmxExitTaskSwitchNested(pVCpu, pVmxTransient);
12619 case VMX_EXIT_WBINVD: return hmR0VmxExitWbinvdNested(pVCpu, pVmxTransient);
12620 case VMX_EXIT_MTF: return hmR0VmxExitMtfNested(pVCpu, pVmxTransient);
12621 case VMX_EXIT_APIC_ACCESS: return hmR0VmxExitApicAccessNested(pVCpu, pVmxTransient);
12622 case VMX_EXIT_APIC_WRITE: return hmR0VmxExitApicWriteNested(pVCpu, pVmxTransient);
12623 case VMX_EXIT_VIRTUALIZED_EOI: return hmR0VmxExitVirtEoiNested(pVCpu, pVmxTransient);
12624 case VMX_EXIT_MOV_CRX: return hmR0VmxExitMovCRxNested(pVCpu, pVmxTransient);
12625 case VMX_EXIT_INT_WINDOW: return hmR0VmxExitIntWindowNested(pVCpu, pVmxTransient);
12626 case VMX_EXIT_NMI_WINDOW: return hmR0VmxExitNmiWindowNested(pVCpu, pVmxTransient);
12627 case VMX_EXIT_TPR_BELOW_THRESHOLD: return hmR0VmxExitTprBelowThresholdNested(pVCpu, pVmxTransient);
12628 case VMX_EXIT_MWAIT: return hmR0VmxExitMwaitNested(pVCpu, pVmxTransient);
12629 case VMX_EXIT_MONITOR: return hmR0VmxExitMonitorNested(pVCpu, pVmxTransient);
12630 case VMX_EXIT_PAUSE: return hmR0VmxExitPauseNested(pVCpu, pVmxTransient);
12631
12632 case VMX_EXIT_PREEMPT_TIMER:
12633 {
12634 /** @todo NSTVMX: Preempt timer. */
12635 return hmR0VmxExitPreemptTimer(pVCpu, pVmxTransient);
12636 }
12637
12638 case VMX_EXIT_MOV_DRX: return hmR0VmxExitMovDRxNested(pVCpu, pVmxTransient);
12639 case VMX_EXIT_RDPMC: return hmR0VmxExitRdpmcNested(pVCpu, pVmxTransient);
12640
12641 case VMX_EXIT_VMREAD:
12642 case VMX_EXIT_VMWRITE: return hmR0VmxExitVmreadVmwriteNested(pVCpu, pVmxTransient);
12643
12644 case VMX_EXIT_TRIPLE_FAULT: return hmR0VmxExitTripleFaultNested(pVCpu, pVmxTransient);
12645 case VMX_EXIT_ERR_INVALID_GUEST_STATE: return hmR0VmxExitErrInvalidGuestStateNested(pVCpu, pVmxTransient);
12646
12647 case VMX_EXIT_INIT_SIGNAL:
12648 case VMX_EXIT_SIPI:
12649 case VMX_EXIT_IO_SMI:
12650 case VMX_EXIT_SMI:
12651 case VMX_EXIT_ERR_MSR_LOAD:
12652 case VMX_EXIT_ERR_MACHINE_CHECK:
12653 case VMX_EXIT_PML_FULL:
12654 case VMX_EXIT_RSM:
12655 default:
12656 return hmR0VmxExitErrUnexpected(pVCpu, pVmxTransient);
12657 }
12658}
12659#endif /* VBOX_WITH_NESTED_HWVIRT_VMX */
12660
12661
12662/** @name VM-exit helpers.
12663 * @{
12664 */
12665/* -=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= */
12666/* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= VM-exit helpers -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- */
12667/* -=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= */
12668
12669/** Macro for VM-exits called unexpectedly. */
12670#define HMVMX_UNEXPECTED_EXIT_RET(a_pVCpu, a_HmError) \
12671 do { \
12672 (a_pVCpu)->hm.s.u32HMError = (a_HmError); \
12673 return VERR_VMX_UNEXPECTED_EXIT; \
12674 } while (0)
12675
12676#ifdef VBOX_STRICT
12677/* Is there some generic IPRT define for this that are not in Runtime/internal/\* ?? */
12678# define HMVMX_ASSERT_PREEMPT_CPUID_VAR() \
12679 RTCPUID const idAssertCpu = RTThreadPreemptIsEnabled(NIL_RTTHREAD) ? NIL_RTCPUID : RTMpCpuId()
12680
12681# define HMVMX_ASSERT_PREEMPT_CPUID() \
12682 do { \
12683 RTCPUID const idAssertCpuNow = RTThreadPreemptIsEnabled(NIL_RTTHREAD) ? NIL_RTCPUID : RTMpCpuId(); \
12684 AssertMsg(idAssertCpu == idAssertCpuNow, ("VMX %#x, %#x\n", idAssertCpu, idAssertCpuNow)); \
12685 } while (0)
12686
12687# define HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(a_pVCpu, a_pVmxTransient) \
12688 do { \
12689 AssertPtr((a_pVCpu)); \
12690 AssertPtr((a_pVmxTransient)); \
12691 Assert((a_pVmxTransient)->fVMEntryFailed == false); \
12692 Assert((a_pVmxTransient)->pVmcsInfo); \
12693 Assert(ASMIntAreEnabled()); \
12694 HMVMX_ASSERT_PREEMPT_SAFE(a_pVCpu); \
12695 HMVMX_ASSERT_PREEMPT_CPUID_VAR(); \
12696 Log4Func(("vcpu[%RU32]\n", (a_pVCpu)->idCpu)); \
12697 HMVMX_ASSERT_PREEMPT_SAFE(a_pVCpu); \
12698 if (VMMR0IsLogFlushDisabled((a_pVCpu))) \
12699 HMVMX_ASSERT_PREEMPT_CPUID(); \
12700 HMVMX_STOP_EXIT_DISPATCH_PROF(); \
12701 } while (0)
12702
12703# define HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(a_pVCpu, a_pVmxTransient) \
12704 do { \
12705 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(a_pVCpu, a_pVmxTransient); \
12706 Assert((a_pVmxTransient)->fIsNestedGuest); \
12707 } while (0)
12708
12709# define HMVMX_VALIDATE_EXIT_XCPT_HANDLER_PARAMS(a_pVCpu, a_pVmxTransient) \
12710 do { \
12711 Log4Func(("\n")); \
12712 } while (0)
12713#else
12714# define HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(a_pVCpu, a_pVmxTransient) \
12715 do { \
12716 HMVMX_STOP_EXIT_DISPATCH_PROF(); \
12717 NOREF((a_pVCpu)); NOREF((a_pVmxTransient)); \
12718 } while (0)
12719
12720# define HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(a_pVCpu, a_pVmxTransient) \
12721 do { HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(a_pVCpu, a_pVmxTransient); } while (0)
12722
12723# define HMVMX_VALIDATE_EXIT_XCPT_HANDLER_PARAMS(a_pVCpu, a_pVmxTransient) do { } while (0)
12724#endif
12725
12726#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
12727/** Macro that does the necessary privilege checks and intercepted VM-exits for
12728 * guests that attempted to execute a VMX instruction. */
12729# define HMVMX_CHECK_EXIT_DUE_TO_VMX_INSTR(a_pVCpu, a_uExitReason) \
12730 do \
12731 { \
12732 VBOXSTRICTRC rcStrictTmp = hmR0VmxCheckExitDueToVmxInstr((a_pVCpu), (a_uExitReason)); \
12733 if (rcStrictTmp == VINF_SUCCESS) \
12734 { /* likely */ } \
12735 else if (rcStrictTmp == VINF_HM_PENDING_XCPT) \
12736 { \
12737 Assert((a_pVCpu)->hm.s.Event.fPending); \
12738 Log4Func(("Privilege checks failed -> %#x\n", VMX_ENTRY_INT_INFO_VECTOR((a_pVCpu)->hm.s.Event.u64IntInfo))); \
12739 return VINF_SUCCESS; \
12740 } \
12741 else \
12742 { \
12743 int rcTmp = VBOXSTRICTRC_VAL(rcStrictTmp); \
12744 AssertMsgFailedReturn(("Unexpected failure. rc=%Rrc", rcTmp), rcTmp); \
12745 } \
12746 } while (0)
12747
12748/** Macro that decodes a memory operand for an VM-exit caused by an instruction. */
12749# define HMVMX_DECODE_MEM_OPERAND(a_pVCpu, a_uExitInstrInfo, a_uExitQual, a_enmMemAccess, a_pGCPtrEffAddr) \
12750 do \
12751 { \
12752 VBOXSTRICTRC rcStrictTmp = hmR0VmxDecodeMemOperand((a_pVCpu), (a_uExitInstrInfo), (a_uExitQual), (a_enmMemAccess), \
12753 (a_pGCPtrEffAddr)); \
12754 if (rcStrictTmp == VINF_SUCCESS) \
12755 { /* likely */ } \
12756 else if (rcStrictTmp == VINF_HM_PENDING_XCPT) \
12757 { \
12758 uint8_t const uXcptTmp = VMX_ENTRY_INT_INFO_VECTOR((a_pVCpu)->hm.s.Event.u64IntInfo); \
12759 Log4Func(("Memory operand decoding failed, raising xcpt %#x\n", uXcptTmp)); \
12760 NOREF(uXcptTmp); \
12761 return VINF_SUCCESS; \
12762 } \
12763 else \
12764 { \
12765 Log4Func(("hmR0VmxDecodeMemOperand failed. rc=%Rrc\n", VBOXSTRICTRC_VAL(rcStrictTmp))); \
12766 return rcStrictTmp; \
12767 } \
12768 } while (0)
12769#endif /* VBOX_WITH_NESTED_HWVIRT_VMX */
12770
12771
12772/**
12773 * Advances the guest RIP by the specified number of bytes.
12774 *
12775 * @param pVCpu The cross context virtual CPU structure.
12776 * @param cbInstr Number of bytes to advance the RIP by.
12777 *
12778 * @remarks No-long-jump zone!!!
12779 */
12780DECLINLINE(void) hmR0VmxAdvanceGuestRipBy(PVMCPUCC pVCpu, uint32_t cbInstr)
12781{
12782 /* Advance the RIP. */
12783 pVCpu->cpum.GstCtx.rip += cbInstr;
12784 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP);
12785
12786 /* Update interrupt inhibition. */
12787 if ( VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS)
12788 && pVCpu->cpum.GstCtx.rip != EMGetInhibitInterruptsPC(pVCpu))
12789 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS);
12790}
12791
12792
12793/**
12794 * Advances the guest RIP after reading it from the VMCS.
12795 *
12796 * @returns VBox status code, no informational status codes.
12797 * @param pVCpu The cross context virtual CPU structure.
12798 * @param pVmxTransient The VMX-transient structure.
12799 *
12800 * @remarks No-long-jump zone!!!
12801 */
12802static int hmR0VmxAdvanceGuestRip(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
12803{
12804 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
12805 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, CPUMCTX_EXTRN_RIP | CPUMCTX_EXTRN_RFLAGS);
12806 AssertRCReturn(rc, rc);
12807
12808 hmR0VmxAdvanceGuestRipBy(pVCpu, pVmxTransient->cbExitInstr);
12809 return VINF_SUCCESS;
12810}
12811
12812
12813/**
12814 * Handle a condition that occurred while delivering an event through the guest or
12815 * nested-guest IDT.
12816 *
12817 * @returns Strict VBox status code (i.e. informational status codes too).
12818 * @retval VINF_SUCCESS if we should continue handling the VM-exit.
12819 * @retval VINF_HM_DOUBLE_FAULT if a \#DF condition was detected and we ought
12820 * to continue execution of the guest which will delivery the \#DF.
12821 * @retval VINF_EM_RESET if we detected a triple-fault condition.
12822 * @retval VERR_EM_GUEST_CPU_HANG if we detected a guest CPU hang.
12823 *
12824 * @param pVCpu The cross context virtual CPU structure.
12825 * @param pVmxTransient The VMX-transient structure.
12826 *
12827 * @remarks Requires all fields in HMVMX_READ_XCPT_INFO to be read from the VMCS.
12828 * Additionally, HMVMX_READ_EXIT_QUALIFICATION is required if the VM-exit
12829 * is due to an EPT violation, PML full or SPP-related event.
12830 *
12831 * @remarks No-long-jump zone!!!
12832 */
12833static VBOXSTRICTRC hmR0VmxCheckExitDueToEventDelivery(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
12834{
12835 Assert(!pVCpu->hm.s.Event.fPending);
12836 HMVMX_ASSERT_READ(pVmxTransient, HMVMX_READ_XCPT_INFO);
12837 if ( pVmxTransient->uExitReason == VMX_EXIT_EPT_VIOLATION
12838 || pVmxTransient->uExitReason == VMX_EXIT_PML_FULL
12839 || pVmxTransient->uExitReason == VMX_EXIT_SPP_EVENT)
12840 HMVMX_ASSERT_READ(pVmxTransient, HMVMX_READ_EXIT_QUALIFICATION);
12841
12842 VBOXSTRICTRC rcStrict = VINF_SUCCESS;
12843 PCVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
12844 uint32_t const uIdtVectorInfo = pVmxTransient->uIdtVectoringInfo;
12845 uint32_t const uExitIntInfo = pVmxTransient->uExitIntInfo;
12846 if (VMX_IDT_VECTORING_INFO_IS_VALID(uIdtVectorInfo))
12847 {
12848 uint32_t const uIdtVector = VMX_IDT_VECTORING_INFO_VECTOR(uIdtVectorInfo);
12849 uint32_t const uIdtVectorType = VMX_IDT_VECTORING_INFO_TYPE(uIdtVectorInfo);
12850
12851 /*
12852 * If the event was a software interrupt (generated with INT n) or a software exception
12853 * (generated by INT3/INTO) or a privileged software exception (generated by INT1), we
12854 * can handle the VM-exit and continue guest execution which will re-execute the
12855 * instruction rather than re-injecting the exception, as that can cause premature
12856 * trips to ring-3 before injection and involve TRPM which currently has no way of
12857 * storing that these exceptions were caused by these instructions (ICEBP's #DB poses
12858 * the problem).
12859 */
12860 IEMXCPTRAISE enmRaise;
12861 IEMXCPTRAISEINFO fRaiseInfo;
12862 if ( uIdtVectorType == VMX_IDT_VECTORING_INFO_TYPE_SW_INT
12863 || uIdtVectorType == VMX_IDT_VECTORING_INFO_TYPE_SW_XCPT
12864 || uIdtVectorType == VMX_IDT_VECTORING_INFO_TYPE_PRIV_SW_XCPT)
12865 {
12866 enmRaise = IEMXCPTRAISE_REEXEC_INSTR;
12867 fRaiseInfo = IEMXCPTRAISEINFO_NONE;
12868 }
12869 else if (VMX_EXIT_INT_INFO_IS_VALID(uExitIntInfo))
12870 {
12871 uint32_t const uExitVectorType = VMX_EXIT_INT_INFO_TYPE(uExitIntInfo);
12872 uint8_t const uExitVector = VMX_EXIT_INT_INFO_VECTOR(uExitIntInfo);
12873 Assert(uExitVectorType == VMX_EXIT_INT_INFO_TYPE_HW_XCPT);
12874
12875 uint32_t const fIdtVectorFlags = hmR0VmxGetIemXcptFlags(uIdtVector, uIdtVectorType);
12876 uint32_t const fExitVectorFlags = hmR0VmxGetIemXcptFlags(uExitVector, uExitVectorType);
12877
12878 enmRaise = IEMEvaluateRecursiveXcpt(pVCpu, fIdtVectorFlags, uIdtVector, fExitVectorFlags, uExitVector, &fRaiseInfo);
12879
12880 /* Determine a vectoring #PF condition, see comment in hmR0VmxExitXcptPF(). */
12881 if (fRaiseInfo & (IEMXCPTRAISEINFO_EXT_INT_PF | IEMXCPTRAISEINFO_NMI_PF))
12882 {
12883 pVmxTransient->fVectoringPF = true;
12884 enmRaise = IEMXCPTRAISE_PREV_EVENT;
12885 }
12886 }
12887 else
12888 {
12889 /*
12890 * If an exception or hardware interrupt delivery caused an EPT violation/misconfig or APIC access
12891 * VM-exit, then the VM-exit interruption-information will not be valid and we end up here.
12892 * It is sufficient to reflect the original event to the guest after handling the VM-exit.
12893 */
12894 Assert( uIdtVectorType == VMX_IDT_VECTORING_INFO_TYPE_HW_XCPT
12895 || uIdtVectorType == VMX_IDT_VECTORING_INFO_TYPE_NMI
12896 || uIdtVectorType == VMX_IDT_VECTORING_INFO_TYPE_EXT_INT);
12897 enmRaise = IEMXCPTRAISE_PREV_EVENT;
12898 fRaiseInfo = IEMXCPTRAISEINFO_NONE;
12899 }
12900
12901 /*
12902 * On CPUs that support Virtual NMIs, if this VM-exit (be it an exception or EPT violation/misconfig
12903 * etc.) occurred while delivering the NMI, we need to clear the block-by-NMI field in the guest
12904 * interruptibility-state before re-delivering the NMI after handling the VM-exit. Otherwise the
12905 * subsequent VM-entry would fail, see @bugref{7445}.
12906 *
12907 * See Intel spec. 30.7.1.2 "Resuming Guest Software after Handling an Exception".
12908 */
12909 if ( uIdtVectorType == VMX_IDT_VECTORING_INFO_TYPE_NMI
12910 && enmRaise == IEMXCPTRAISE_PREV_EVENT
12911 && (pVmcsInfo->u32PinCtls & VMX_PIN_CTLS_VIRT_NMI)
12912 && CPUMIsGuestNmiBlocking(pVCpu))
12913 {
12914 CPUMSetGuestNmiBlocking(pVCpu, false);
12915 }
12916
12917 switch (enmRaise)
12918 {
12919 case IEMXCPTRAISE_CURRENT_XCPT:
12920 {
12921 Log4Func(("IDT: Pending secondary Xcpt: idtinfo=%#RX64 exitinfo=%#RX64\n", uIdtVectorInfo, uExitIntInfo));
12922 Assert(rcStrict == VINF_SUCCESS);
12923 break;
12924 }
12925
12926 case IEMXCPTRAISE_PREV_EVENT:
12927 {
12928 uint32_t u32ErrCode;
12929 if (VMX_IDT_VECTORING_INFO_IS_ERROR_CODE_VALID(uIdtVectorInfo))
12930 u32ErrCode = pVmxTransient->uIdtVectoringErrorCode;
12931 else
12932 u32ErrCode = 0;
12933
12934 /* If uExitVector is #PF, CR2 value will be updated from the VMCS if it's a guest #PF, see hmR0VmxExitXcptPF(). */
12935 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectReflect);
12936 hmR0VmxSetPendingEvent(pVCpu, VMX_ENTRY_INT_INFO_FROM_EXIT_IDT_INFO(uIdtVectorInfo), 0 /* cbInstr */,
12937 u32ErrCode, pVCpu->cpum.GstCtx.cr2);
12938
12939 Log4Func(("IDT: Pending vectoring event %#RX64 Err=%#RX32\n", pVCpu->hm.s.Event.u64IntInfo,
12940 pVCpu->hm.s.Event.u32ErrCode));
12941 Assert(rcStrict == VINF_SUCCESS);
12942 break;
12943 }
12944
12945 case IEMXCPTRAISE_REEXEC_INSTR:
12946 Assert(rcStrict == VINF_SUCCESS);
12947 break;
12948
12949 case IEMXCPTRAISE_DOUBLE_FAULT:
12950 {
12951 /*
12952 * Determing a vectoring double #PF condition. Used later, when PGM evaluates the
12953 * second #PF as a guest #PF (and not a shadow #PF) and needs to be converted into a #DF.
12954 */
12955 if (fRaiseInfo & IEMXCPTRAISEINFO_PF_PF)
12956 {
12957 pVmxTransient->fVectoringDoublePF = true;
12958 Log4Func(("IDT: Vectoring double #PF %#RX64 cr2=%#RX64\n", pVCpu->hm.s.Event.u64IntInfo,
12959 pVCpu->cpum.GstCtx.cr2));
12960 rcStrict = VINF_SUCCESS;
12961 }
12962 else
12963 {
12964 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectConvertDF);
12965 hmR0VmxSetPendingXcptDF(pVCpu);
12966 Log4Func(("IDT: Pending vectoring #DF %#RX64 uIdtVector=%#x uExitVector=%#x\n", pVCpu->hm.s.Event.u64IntInfo,
12967 uIdtVector, VMX_EXIT_INT_INFO_VECTOR(uExitIntInfo)));
12968 rcStrict = VINF_HM_DOUBLE_FAULT;
12969 }
12970 break;
12971 }
12972
12973 case IEMXCPTRAISE_TRIPLE_FAULT:
12974 {
12975 Log4Func(("IDT: Pending vectoring triple-fault uIdt=%#x uExit=%#x\n", uIdtVector,
12976 VMX_EXIT_INT_INFO_VECTOR(uExitIntInfo)));
12977 rcStrict = VINF_EM_RESET;
12978 break;
12979 }
12980
12981 case IEMXCPTRAISE_CPU_HANG:
12982 {
12983 Log4Func(("IDT: Bad guest! Entering CPU hang. fRaiseInfo=%#x\n", fRaiseInfo));
12984 rcStrict = VERR_EM_GUEST_CPU_HANG;
12985 break;
12986 }
12987
12988 default:
12989 {
12990 AssertMsgFailed(("IDT: vcpu[%RU32] Unexpected/invalid value! enmRaise=%#x\n", pVCpu->idCpu, enmRaise));
12991 rcStrict = VERR_VMX_IPE_2;
12992 break;
12993 }
12994 }
12995 }
12996 else if ( (pVmcsInfo->u32PinCtls & VMX_PIN_CTLS_VIRT_NMI)
12997 && !CPUMIsGuestNmiBlocking(pVCpu))
12998 {
12999 if ( VMX_EXIT_INT_INFO_IS_VALID(uExitIntInfo)
13000 && VMX_EXIT_INT_INFO_VECTOR(uExitIntInfo) != X86_XCPT_DF
13001 && VMX_EXIT_INT_INFO_IS_NMI_UNBLOCK_IRET(uExitIntInfo))
13002 {
13003 /*
13004 * Execution of IRET caused a fault when NMI blocking was in effect (i.e we're in
13005 * the guest or nested-guest NMI handler). We need to set the block-by-NMI field so
13006 * that NMIs remain blocked until the IRET execution is completed.
13007 *
13008 * See Intel spec. 31.7.1.2 "Resuming Guest Software After Handling An Exception".
13009 */
13010 CPUMSetGuestNmiBlocking(pVCpu, true);
13011 Log4Func(("Set NMI blocking. uExitReason=%u\n", pVmxTransient->uExitReason));
13012 }
13013 else if ( pVmxTransient->uExitReason == VMX_EXIT_EPT_VIOLATION
13014 || pVmxTransient->uExitReason == VMX_EXIT_PML_FULL
13015 || pVmxTransient->uExitReason == VMX_EXIT_SPP_EVENT)
13016 {
13017 /*
13018 * Execution of IRET caused an EPT violation, page-modification log-full event or
13019 * SPP-related event VM-exit when NMI blocking was in effect (i.e. we're in the
13020 * guest or nested-guest NMI handler). We need to set the block-by-NMI field so
13021 * that NMIs remain blocked until the IRET execution is completed.
13022 *
13023 * See Intel spec. 27.2.3 "Information about NMI unblocking due to IRET"
13024 */
13025 if (VMX_EXIT_QUAL_EPT_IS_NMI_UNBLOCK_IRET(pVmxTransient->uExitQual))
13026 {
13027 CPUMSetGuestNmiBlocking(pVCpu, true);
13028 Log4Func(("Set NMI blocking. uExitReason=%u\n", pVmxTransient->uExitReason));
13029 }
13030 }
13031 }
13032
13033 Assert( rcStrict == VINF_SUCCESS || rcStrict == VINF_HM_DOUBLE_FAULT
13034 || rcStrict == VINF_EM_RESET || rcStrict == VERR_EM_GUEST_CPU_HANG);
13035 return rcStrict;
13036}
13037
13038
13039#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
13040/**
13041 * Perform the relevant VMX instruction checks for VM-exits that occurred due to the
13042 * guest attempting to execute a VMX instruction.
13043 *
13044 * @returns Strict VBox status code (i.e. informational status codes too).
13045 * @retval VINF_SUCCESS if we should continue handling the VM-exit.
13046 * @retval VINF_HM_PENDING_XCPT if an exception was raised.
13047 *
13048 * @param pVCpu The cross context virtual CPU structure.
13049 * @param uExitReason The VM-exit reason.
13050 *
13051 * @todo NSTVMX: Document other error codes when VM-exit is implemented.
13052 * @remarks No-long-jump zone!!!
13053 */
13054static VBOXSTRICTRC hmR0VmxCheckExitDueToVmxInstr(PVMCPUCC pVCpu, uint32_t uExitReason)
13055{
13056 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_CR0 | CPUMCTX_EXTRN_RFLAGS | CPUMCTX_EXTRN_SS
13057 | CPUMCTX_EXTRN_CS | CPUMCTX_EXTRN_EFER);
13058
13059 /*
13060 * The physical CPU would have already checked the CPU mode/code segment.
13061 * We shall just assert here for paranoia.
13062 * See Intel spec. 25.1.1 "Relative Priority of Faults and VM Exits".
13063 */
13064 Assert(!CPUMIsGuestInRealOrV86ModeEx(&pVCpu->cpum.GstCtx));
13065 Assert( !CPUMIsGuestInLongModeEx(&pVCpu->cpum.GstCtx)
13066 || CPUMIsGuestIn64BitCodeEx(&pVCpu->cpum.GstCtx));
13067
13068 if (uExitReason == VMX_EXIT_VMXON)
13069 {
13070 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_CR4);
13071
13072 /*
13073 * We check CR4.VMXE because it is required to be always set while in VMX operation
13074 * by physical CPUs and our CR4 read-shadow is only consulted when executing specific
13075 * instructions (CLTS, LMSW, MOV CR, and SMSW) and thus doesn't affect CPU operation
13076 * otherwise (i.e. physical CPU won't automatically #UD if Cr4Shadow.VMXE is 0).
13077 */
13078 if (!CPUMIsGuestVmxEnabled(&pVCpu->cpum.GstCtx))
13079 {
13080 Log4Func(("CR4.VMXE is not set -> #UD\n"));
13081 hmR0VmxSetPendingXcptUD(pVCpu);
13082 return VINF_HM_PENDING_XCPT;
13083 }
13084 }
13085 else if (!CPUMIsGuestInVmxRootMode(&pVCpu->cpum.GstCtx))
13086 {
13087 /*
13088 * The guest has not entered VMX operation but attempted to execute a VMX instruction
13089 * (other than VMXON), we need to raise a #UD.
13090 */
13091 Log4Func(("Not in VMX root mode -> #UD\n"));
13092 hmR0VmxSetPendingXcptUD(pVCpu);
13093 return VINF_HM_PENDING_XCPT;
13094 }
13095
13096 /* All other checks (including VM-exit intercepts) are handled by IEM instruction emulation. */
13097 return VINF_SUCCESS;
13098}
13099
13100
13101/**
13102 * Decodes the memory operand of an instruction that caused a VM-exit.
13103 *
13104 * The Exit qualification field provides the displacement field for memory
13105 * operand instructions, if any.
13106 *
13107 * @returns Strict VBox status code (i.e. informational status codes too).
13108 * @retval VINF_SUCCESS if the operand was successfully decoded.
13109 * @retval VINF_HM_PENDING_XCPT if an exception was raised while decoding the
13110 * operand.
13111 * @param pVCpu The cross context virtual CPU structure.
13112 * @param uExitInstrInfo The VM-exit instruction information field.
13113 * @param enmMemAccess The memory operand's access type (read or write).
13114 * @param GCPtrDisp The instruction displacement field, if any. For
13115 * RIP-relative addressing pass RIP + displacement here.
13116 * @param pGCPtrMem Where to store the effective destination memory address.
13117 *
13118 * @remarks Warning! This function ASSUMES the instruction cannot be used in real or
13119 * virtual-8086 mode hence skips those checks while verifying if the
13120 * segment is valid.
13121 */
13122static VBOXSTRICTRC hmR0VmxDecodeMemOperand(PVMCPUCC pVCpu, uint32_t uExitInstrInfo, RTGCPTR GCPtrDisp, VMXMEMACCESS enmMemAccess,
13123 PRTGCPTR pGCPtrMem)
13124{
13125 Assert(pGCPtrMem);
13126 Assert(!CPUMIsGuestInRealOrV86Mode(pVCpu));
13127 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_RIP | CPUMCTX_EXTRN_RSP | CPUMCTX_EXTRN_SREG_MASK | CPUMCTX_EXTRN_EFER
13128 | CPUMCTX_EXTRN_CR0);
13129
13130 static uint64_t const s_auAddrSizeMasks[] = { UINT64_C(0xffff), UINT64_C(0xffffffff), UINT64_C(0xffffffffffffffff) };
13131 static uint64_t const s_auAccessSizeMasks[] = { sizeof(uint16_t), sizeof(uint32_t), sizeof(uint64_t) };
13132 AssertCompile(RT_ELEMENTS(s_auAccessSizeMasks) == RT_ELEMENTS(s_auAddrSizeMasks));
13133
13134 VMXEXITINSTRINFO ExitInstrInfo;
13135 ExitInstrInfo.u = uExitInstrInfo;
13136 uint8_t const uAddrSize = ExitInstrInfo.All.u3AddrSize;
13137 uint8_t const iSegReg = ExitInstrInfo.All.iSegReg;
13138 bool const fIdxRegValid = !ExitInstrInfo.All.fIdxRegInvalid;
13139 uint8_t const iIdxReg = ExitInstrInfo.All.iIdxReg;
13140 uint8_t const uScale = ExitInstrInfo.All.u2Scaling;
13141 bool const fBaseRegValid = !ExitInstrInfo.All.fBaseRegInvalid;
13142 uint8_t const iBaseReg = ExitInstrInfo.All.iBaseReg;
13143 bool const fIsMemOperand = !ExitInstrInfo.All.fIsRegOperand;
13144 bool const fIsLongMode = CPUMIsGuestInLongModeEx(&pVCpu->cpum.GstCtx);
13145
13146 /*
13147 * Validate instruction information.
13148 * This shouldn't happen on real hardware but useful while testing our nested hardware-virtualization code.
13149 */
13150 AssertLogRelMsgReturn(uAddrSize < RT_ELEMENTS(s_auAddrSizeMasks),
13151 ("Invalid address size. ExitInstrInfo=%#RX32\n", ExitInstrInfo.u), VERR_VMX_IPE_1);
13152 AssertLogRelMsgReturn(iSegReg < X86_SREG_COUNT,
13153 ("Invalid segment register. ExitInstrInfo=%#RX32\n", ExitInstrInfo.u), VERR_VMX_IPE_2);
13154 AssertLogRelMsgReturn(fIsMemOperand,
13155 ("Expected memory operand. ExitInstrInfo=%#RX32\n", ExitInstrInfo.u), VERR_VMX_IPE_3);
13156
13157 /*
13158 * Compute the complete effective address.
13159 *
13160 * See AMD instruction spec. 1.4.2 "SIB Byte Format"
13161 * See AMD spec. 4.5.2 "Segment Registers".
13162 */
13163 RTGCPTR GCPtrMem = GCPtrDisp;
13164 if (fBaseRegValid)
13165 GCPtrMem += pVCpu->cpum.GstCtx.aGRegs[iBaseReg].u64;
13166 if (fIdxRegValid)
13167 GCPtrMem += pVCpu->cpum.GstCtx.aGRegs[iIdxReg].u64 << uScale;
13168
13169 RTGCPTR const GCPtrOff = GCPtrMem;
13170 if ( !fIsLongMode
13171 || iSegReg >= X86_SREG_FS)
13172 GCPtrMem += pVCpu->cpum.GstCtx.aSRegs[iSegReg].u64Base;
13173 GCPtrMem &= s_auAddrSizeMasks[uAddrSize];
13174
13175 /*
13176 * Validate effective address.
13177 * See AMD spec. 4.5.3 "Segment Registers in 64-Bit Mode".
13178 */
13179 uint8_t const cbAccess = s_auAccessSizeMasks[uAddrSize];
13180 Assert(cbAccess > 0);
13181 if (fIsLongMode)
13182 {
13183 if (X86_IS_CANONICAL(GCPtrMem))
13184 {
13185 *pGCPtrMem = GCPtrMem;
13186 return VINF_SUCCESS;
13187 }
13188
13189 /** @todo r=ramshankar: We should probably raise \#SS or \#GP. See AMD spec. 4.12.2
13190 * "Data Limit Checks in 64-bit Mode". */
13191 Log4Func(("Long mode effective address is not canonical GCPtrMem=%#RX64\n", GCPtrMem));
13192 hmR0VmxSetPendingXcptGP(pVCpu, 0);
13193 return VINF_HM_PENDING_XCPT;
13194 }
13195
13196 /*
13197 * This is a watered down version of iemMemApplySegment().
13198 * Parts that are not applicable for VMX instructions like real-or-v8086 mode
13199 * and segment CPL/DPL checks are skipped.
13200 */
13201 RTGCPTR32 const GCPtrFirst32 = (RTGCPTR32)GCPtrOff;
13202 RTGCPTR32 const GCPtrLast32 = GCPtrFirst32 + cbAccess - 1;
13203 PCCPUMSELREG pSel = &pVCpu->cpum.GstCtx.aSRegs[iSegReg];
13204
13205 /* Check if the segment is present and usable. */
13206 if ( pSel->Attr.n.u1Present
13207 && !pSel->Attr.n.u1Unusable)
13208 {
13209 Assert(pSel->Attr.n.u1DescType);
13210 if (!(pSel->Attr.n.u4Type & X86_SEL_TYPE_CODE))
13211 {
13212 /* Check permissions for the data segment. */
13213 if ( enmMemAccess == VMXMEMACCESS_WRITE
13214 && !(pSel->Attr.n.u4Type & X86_SEL_TYPE_WRITE))
13215 {
13216 Log4Func(("Data segment access invalid. iSegReg=%#x Attr=%#RX32\n", iSegReg, pSel->Attr.u));
13217 hmR0VmxSetPendingXcptGP(pVCpu, iSegReg);
13218 return VINF_HM_PENDING_XCPT;
13219 }
13220
13221 /* Check limits if it's a normal data segment. */
13222 if (!(pSel->Attr.n.u4Type & X86_SEL_TYPE_DOWN))
13223 {
13224 if ( GCPtrFirst32 > pSel->u32Limit
13225 || GCPtrLast32 > pSel->u32Limit)
13226 {
13227 Log4Func(("Data segment limit exceeded. "
13228 "iSegReg=%#x GCPtrFirst32=%#RX32 GCPtrLast32=%#RX32 u32Limit=%#RX32\n", iSegReg, GCPtrFirst32,
13229 GCPtrLast32, pSel->u32Limit));
13230 if (iSegReg == X86_SREG_SS)
13231 hmR0VmxSetPendingXcptSS(pVCpu, 0);
13232 else
13233 hmR0VmxSetPendingXcptGP(pVCpu, 0);
13234 return VINF_HM_PENDING_XCPT;
13235 }
13236 }
13237 else
13238 {
13239 /* Check limits if it's an expand-down data segment.
13240 Note! The upper boundary is defined by the B bit, not the G bit! */
13241 if ( GCPtrFirst32 < pSel->u32Limit + UINT32_C(1)
13242 || GCPtrLast32 > (pSel->Attr.n.u1DefBig ? UINT32_MAX : UINT32_C(0xffff)))
13243 {
13244 Log4Func(("Expand-down data segment limit exceeded. "
13245 "iSegReg=%#x GCPtrFirst32=%#RX32 GCPtrLast32=%#RX32 u32Limit=%#RX32\n", iSegReg, GCPtrFirst32,
13246 GCPtrLast32, pSel->u32Limit));
13247 if (iSegReg == X86_SREG_SS)
13248 hmR0VmxSetPendingXcptSS(pVCpu, 0);
13249 else
13250 hmR0VmxSetPendingXcptGP(pVCpu, 0);
13251 return VINF_HM_PENDING_XCPT;
13252 }
13253 }
13254 }
13255 else
13256 {
13257 /* Check permissions for the code segment. */
13258 if ( enmMemAccess == VMXMEMACCESS_WRITE
13259 || ( enmMemAccess == VMXMEMACCESS_READ
13260 && !(pSel->Attr.n.u4Type & X86_SEL_TYPE_READ)))
13261 {
13262 Log4Func(("Code segment access invalid. Attr=%#RX32\n", pSel->Attr.u));
13263 Assert(!CPUMIsGuestInRealOrV86ModeEx(&pVCpu->cpum.GstCtx));
13264 hmR0VmxSetPendingXcptGP(pVCpu, 0);
13265 return VINF_HM_PENDING_XCPT;
13266 }
13267
13268 /* Check limits for the code segment (normal/expand-down not applicable for code segments). */
13269 if ( GCPtrFirst32 > pSel->u32Limit
13270 || GCPtrLast32 > pSel->u32Limit)
13271 {
13272 Log4Func(("Code segment limit exceeded. GCPtrFirst32=%#RX32 GCPtrLast32=%#RX32 u32Limit=%#RX32\n",
13273 GCPtrFirst32, GCPtrLast32, pSel->u32Limit));
13274 if (iSegReg == X86_SREG_SS)
13275 hmR0VmxSetPendingXcptSS(pVCpu, 0);
13276 else
13277 hmR0VmxSetPendingXcptGP(pVCpu, 0);
13278 return VINF_HM_PENDING_XCPT;
13279 }
13280 }
13281 }
13282 else
13283 {
13284 Log4Func(("Not present or unusable segment. iSegReg=%#x Attr=%#RX32\n", iSegReg, pSel->Attr.u));
13285 hmR0VmxSetPendingXcptGP(pVCpu, 0);
13286 return VINF_HM_PENDING_XCPT;
13287 }
13288
13289 *pGCPtrMem = GCPtrMem;
13290 return VINF_SUCCESS;
13291}
13292#endif /* VBOX_WITH_NESTED_HWVIRT_VMX */
13293
13294
13295/**
13296 * VM-exit helper for LMSW.
13297 */
13298static VBOXSTRICTRC hmR0VmxExitLmsw(PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo, uint8_t cbInstr, uint16_t uMsw, RTGCPTR GCPtrEffDst)
13299{
13300 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, IEM_CPUMCTX_EXTRN_MUST_MASK);
13301 AssertRCReturn(rc, rc);
13302
13303 VBOXSTRICTRC rcStrict = IEMExecDecodedLmsw(pVCpu, cbInstr, uMsw, GCPtrEffDst);
13304 AssertMsg( rcStrict == VINF_SUCCESS
13305 || rcStrict == VINF_IEM_RAISED_XCPT, ("%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
13306
13307 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS | HM_CHANGED_GUEST_CR0);
13308 if (rcStrict == VINF_IEM_RAISED_XCPT)
13309 {
13310 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
13311 rcStrict = VINF_SUCCESS;
13312 }
13313
13314 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitLmsw);
13315 Log4Func(("rcStrict=%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
13316 return rcStrict;
13317}
13318
13319
13320/**
13321 * VM-exit helper for CLTS.
13322 */
13323static VBOXSTRICTRC hmR0VmxExitClts(PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo, uint8_t cbInstr)
13324{
13325 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, IEM_CPUMCTX_EXTRN_MUST_MASK);
13326 AssertRCReturn(rc, rc);
13327
13328 VBOXSTRICTRC rcStrict = IEMExecDecodedClts(pVCpu, cbInstr);
13329 AssertMsg( rcStrict == VINF_SUCCESS
13330 || rcStrict == VINF_IEM_RAISED_XCPT, ("%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
13331
13332 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS | HM_CHANGED_GUEST_CR0);
13333 if (rcStrict == VINF_IEM_RAISED_XCPT)
13334 {
13335 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
13336 rcStrict = VINF_SUCCESS;
13337 }
13338
13339 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitClts);
13340 Log4Func(("rcStrict=%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
13341 return rcStrict;
13342}
13343
13344
13345/**
13346 * VM-exit helper for MOV from CRx (CRx read).
13347 */
13348static VBOXSTRICTRC hmR0VmxExitMovFromCrX(PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo, uint8_t cbInstr, uint8_t iGReg, uint8_t iCrReg)
13349{
13350 Assert(iCrReg < 16);
13351 Assert(iGReg < RT_ELEMENTS(pVCpu->cpum.GstCtx.aGRegs));
13352
13353 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, IEM_CPUMCTX_EXTRN_MUST_MASK);
13354 AssertRCReturn(rc, rc);
13355
13356 VBOXSTRICTRC rcStrict = IEMExecDecodedMovCRxRead(pVCpu, cbInstr, iGReg, iCrReg);
13357 AssertMsg( rcStrict == VINF_SUCCESS
13358 || rcStrict == VINF_IEM_RAISED_XCPT, ("%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
13359
13360 if (iGReg == X86_GREG_xSP)
13361 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS | HM_CHANGED_GUEST_RSP);
13362 else
13363 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS);
13364#ifdef VBOX_WITH_STATISTICS
13365 switch (iCrReg)
13366 {
13367 case 0: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCR0Read); break;
13368 case 2: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCR2Read); break;
13369 case 3: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCR3Read); break;
13370 case 4: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCR4Read); break;
13371 case 8: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCR8Read); break;
13372 }
13373#endif
13374 Log4Func(("CR%d Read access rcStrict=%Rrc\n", iCrReg, VBOXSTRICTRC_VAL(rcStrict)));
13375 return rcStrict;
13376}
13377
13378
13379/**
13380 * VM-exit helper for MOV to CRx (CRx write).
13381 */
13382static VBOXSTRICTRC hmR0VmxExitMovToCrX(PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo, uint8_t cbInstr, uint8_t iGReg, uint8_t iCrReg)
13383{
13384 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, IEM_CPUMCTX_EXTRN_MUST_MASK);
13385 AssertRCReturn(rc, rc);
13386
13387 VBOXSTRICTRC rcStrict = IEMExecDecodedMovCRxWrite(pVCpu, cbInstr, iCrReg, iGReg);
13388 AssertMsg( rcStrict == VINF_SUCCESS
13389 || rcStrict == VINF_IEM_RAISED_XCPT
13390 || rcStrict == VINF_PGM_SYNC_CR3, ("%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
13391
13392 switch (iCrReg)
13393 {
13394 case 0:
13395 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS | HM_CHANGED_GUEST_CR0);
13396 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCR0Write);
13397 Log4Func(("CR0 write. rcStrict=%Rrc CR0=%#RX64\n", VBOXSTRICTRC_VAL(rcStrict), pVCpu->cpum.GstCtx.cr0));
13398 break;
13399
13400 case 2:
13401 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCR2Write);
13402 /* Nothing to do here, CR2 it's not part of the VMCS. */
13403 break;
13404
13405 case 3:
13406 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS | HM_CHANGED_GUEST_CR3);
13407 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCR3Write);
13408 Log4Func(("CR3 write. rcStrict=%Rrc CR3=%#RX64\n", VBOXSTRICTRC_VAL(rcStrict), pVCpu->cpum.GstCtx.cr3));
13409 break;
13410
13411 case 4:
13412 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS | HM_CHANGED_GUEST_CR4);
13413 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCR4Write);
13414 Log4Func(("CR4 write. rc=%Rrc CR4=%#RX64 fLoadSaveGuestXcr0=%u\n", VBOXSTRICTRC_VAL(rcStrict),
13415 pVCpu->cpum.GstCtx.cr4, pVCpu->hm.s.fLoadSaveGuestXcr0));
13416 break;
13417
13418 case 8:
13419 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged,
13420 HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS | HM_CHANGED_GUEST_APIC_TPR);
13421 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCR8Write);
13422 break;
13423
13424 default:
13425 AssertMsgFailed(("Invalid CRx register %#x\n", iCrReg));
13426 break;
13427 }
13428
13429 if (rcStrict == VINF_IEM_RAISED_XCPT)
13430 {
13431 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
13432 rcStrict = VINF_SUCCESS;
13433 }
13434 return rcStrict;
13435}
13436
13437
13438/**
13439 * VM-exit exception handler for \#PF (Page-fault exception).
13440 *
13441 * @remarks Requires all fields in HMVMX_READ_XCPT_INFO to be read from the VMCS.
13442 */
13443static VBOXSTRICTRC hmR0VmxExitXcptPF(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
13444{
13445 HMVMX_VALIDATE_EXIT_XCPT_HANDLER_PARAMS(pVCpu, pVmxTransient);
13446 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
13447 hmR0VmxReadExitQualVmcs(pVmxTransient);
13448
13449 if (!pVM->hm.s.fNestedPaging)
13450 { /* likely */ }
13451 else
13452 {
13453#if !defined(HMVMX_ALWAYS_TRAP_ALL_XCPTS) && !defined(HMVMX_ALWAYS_TRAP_PF)
13454 Assert(pVmxTransient->fIsNestedGuest || pVCpu->hm.s.fUsingDebugLoop);
13455#endif
13456 pVCpu->hm.s.Event.fPending = false; /* In case it's a contributory or vectoring #PF. */
13457 if (!pVmxTransient->fVectoringDoublePF)
13458 {
13459 hmR0VmxSetPendingEvent(pVCpu, VMX_ENTRY_INT_INFO_FROM_EXIT_INT_INFO(pVmxTransient->uExitIntInfo), 0 /* cbInstr */,
13460 pVmxTransient->uExitIntErrorCode, pVmxTransient->uExitQual);
13461 }
13462 else
13463 {
13464 /* A guest page-fault occurred during delivery of a page-fault. Inject #DF. */
13465 Assert(!pVmxTransient->fIsNestedGuest);
13466 hmR0VmxSetPendingXcptDF(pVCpu);
13467 Log4Func(("Pending #DF due to vectoring #PF w/ NestedPaging\n"));
13468 }
13469 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestPF);
13470 return VINF_SUCCESS;
13471 }
13472
13473 Assert(!pVmxTransient->fIsNestedGuest);
13474
13475 /* If it's a vectoring #PF, emulate injecting the original event injection as PGMTrap0eHandler() is incapable
13476 of differentiating between instruction emulation and event injection that caused a #PF. See @bugref{6607}. */
13477 if (pVmxTransient->fVectoringPF)
13478 {
13479 Assert(pVCpu->hm.s.Event.fPending);
13480 return VINF_EM_RAW_INJECT_TRPM_EVENT;
13481 }
13482
13483 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
13484 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, HMVMX_CPUMCTX_EXTRN_ALL);
13485 AssertRCReturn(rc, rc);
13486
13487 Log4Func(("#PF: cs:rip=%#04x:%#RX64 err_code=%#RX32 exit_qual=%#RX64 cr3=%#RX64\n", pCtx->cs.Sel, pCtx->rip,
13488 pVmxTransient->uExitIntErrorCode, pVmxTransient->uExitQual, pCtx->cr3));
13489
13490 TRPMAssertXcptPF(pVCpu, pVmxTransient->uExitQual, (RTGCUINT)pVmxTransient->uExitIntErrorCode);
13491 rc = PGMTrap0eHandler(pVCpu, pVmxTransient->uExitIntErrorCode, CPUMCTX2CORE(pCtx), (RTGCPTR)pVmxTransient->uExitQual);
13492
13493 Log4Func(("#PF: rc=%Rrc\n", rc));
13494 if (rc == VINF_SUCCESS)
13495 {
13496 /*
13497 * This is typically a shadow page table sync or a MMIO instruction. But we may have
13498 * emulated something like LTR or a far jump. Any part of the CPU context may have changed.
13499 */
13500 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_ALL_GUEST);
13501 TRPMResetTrap(pVCpu);
13502 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitShadowPF);
13503 return rc;
13504 }
13505
13506 if (rc == VINF_EM_RAW_GUEST_TRAP)
13507 {
13508 if (!pVmxTransient->fVectoringDoublePF)
13509 {
13510 /* It's a guest page fault and needs to be reflected to the guest. */
13511 uint32_t uGstErrorCode = TRPMGetErrorCode(pVCpu);
13512 TRPMResetTrap(pVCpu);
13513 pVCpu->hm.s.Event.fPending = false; /* In case it's a contributory #PF. */
13514 hmR0VmxSetPendingEvent(pVCpu, VMX_ENTRY_INT_INFO_FROM_EXIT_INT_INFO(pVmxTransient->uExitIntInfo), 0 /* cbInstr */,
13515 uGstErrorCode, pVmxTransient->uExitQual);
13516 }
13517 else
13518 {
13519 /* A guest page-fault occurred during delivery of a page-fault. Inject #DF. */
13520 TRPMResetTrap(pVCpu);
13521 pVCpu->hm.s.Event.fPending = false; /* Clear pending #PF to replace it with #DF. */
13522 hmR0VmxSetPendingXcptDF(pVCpu);
13523 Log4Func(("#PF: Pending #DF due to vectoring #PF\n"));
13524 }
13525
13526 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestPF);
13527 return VINF_SUCCESS;
13528 }
13529
13530 TRPMResetTrap(pVCpu);
13531 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitShadowPFEM);
13532 return rc;
13533}
13534
13535
13536/**
13537 * VM-exit exception handler for \#MF (Math Fault: floating point exception).
13538 *
13539 * @remarks Requires all fields in HMVMX_READ_XCPT_INFO to be read from the VMCS.
13540 */
13541static VBOXSTRICTRC hmR0VmxExitXcptMF(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
13542{
13543 HMVMX_VALIDATE_EXIT_XCPT_HANDLER_PARAMS(pVCpu, pVmxTransient);
13544 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestMF);
13545
13546 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, CPUMCTX_EXTRN_CR0);
13547 AssertRCReturn(rc, rc);
13548
13549 if (!(pVCpu->cpum.GstCtx.cr0 & X86_CR0_NE))
13550 {
13551 /* Convert a #MF into a FERR -> IRQ 13. See @bugref{6117}. */
13552 rc = PDMIsaSetIrq(pVCpu->CTX_SUFF(pVM), 13, 1, 0 /* uTagSrc */);
13553
13554 /** @todo r=ramshankar: The Intel spec. does -not- specify that this VM-exit
13555 * provides VM-exit instruction length. If this causes problem later,
13556 * disassemble the instruction like it's done on AMD-V. */
13557 int rc2 = hmR0VmxAdvanceGuestRip(pVCpu, pVmxTransient);
13558 AssertRCReturn(rc2, rc2);
13559 return rc;
13560 }
13561
13562 hmR0VmxSetPendingEvent(pVCpu, VMX_ENTRY_INT_INFO_FROM_EXIT_INT_INFO(pVmxTransient->uExitIntInfo), pVmxTransient->cbExitInstr,
13563 pVmxTransient->uExitIntErrorCode, 0 /* GCPtrFaultAddress */);
13564 return VINF_SUCCESS;
13565}
13566
13567
13568/**
13569 * VM-exit exception handler for \#BP (Breakpoint exception).
13570 *
13571 * @remarks Requires all fields in HMVMX_READ_XCPT_INFO to be read from the VMCS.
13572 */
13573static VBOXSTRICTRC hmR0VmxExitXcptBP(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
13574{
13575 HMVMX_VALIDATE_EXIT_XCPT_HANDLER_PARAMS(pVCpu, pVmxTransient);
13576 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestBP);
13577
13578 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, HMVMX_CPUMCTX_EXTRN_ALL);
13579 AssertRCReturn(rc, rc);
13580
13581 if (!pVmxTransient->fIsNestedGuest)
13582 rc = DBGFRZTrap03Handler(pVCpu->CTX_SUFF(pVM), pVCpu, CPUMCTX2CORE(&pVCpu->cpum.GstCtx));
13583 else
13584 rc = VINF_EM_RAW_GUEST_TRAP;
13585
13586 if (rc == VINF_EM_RAW_GUEST_TRAP)
13587 {
13588 hmR0VmxSetPendingEvent(pVCpu, VMX_ENTRY_INT_INFO_FROM_EXIT_INT_INFO(pVmxTransient->uExitIntInfo),
13589 pVmxTransient->cbExitInstr, pVmxTransient->uExitIntErrorCode, 0 /* GCPtrFaultAddress */);
13590 rc = VINF_SUCCESS;
13591 }
13592
13593 Assert(rc == VINF_SUCCESS || rc == VINF_EM_DBG_BREAKPOINT);
13594 return rc;
13595}
13596
13597
13598/**
13599 * VM-exit exception handler for \#AC (Alignment-check exception).
13600 *
13601 * @remarks Requires all fields in HMVMX_READ_XCPT_INFO to be read from the VMCS.
13602 */
13603static VBOXSTRICTRC hmR0VmxExitXcptAC(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
13604{
13605 HMVMX_VALIDATE_EXIT_XCPT_HANDLER_PARAMS(pVCpu, pVmxTransient);
13606 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestAC);
13607
13608 /* Re-inject it. We'll detect any nesting before getting here. */
13609 hmR0VmxSetPendingEvent(pVCpu, VMX_ENTRY_INT_INFO_FROM_EXIT_INT_INFO(pVmxTransient->uExitIntInfo),
13610 pVmxTransient->cbExitInstr, pVmxTransient->uExitIntErrorCode, 0 /* GCPtrFaultAddress */);
13611 return VINF_SUCCESS;
13612}
13613
13614
13615/**
13616 * VM-exit exception handler for \#DB (Debug exception).
13617 *
13618 * @remarks Requires all fields in HMVMX_READ_XCPT_INFO to be read from the VMCS.
13619 */
13620static VBOXSTRICTRC hmR0VmxExitXcptDB(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
13621{
13622 HMVMX_VALIDATE_EXIT_XCPT_HANDLER_PARAMS(pVCpu, pVmxTransient);
13623 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestDB);
13624
13625 /*
13626 * Get the DR6-like values from the Exit qualification and pass it to DBGF for processing.
13627 */
13628 hmR0VmxReadExitQualVmcs(pVmxTransient);
13629
13630 /* Refer Intel spec. Table 27-1. "Exit Qualifications for debug exceptions" for the format. */
13631 uint64_t const uDR6 = X86_DR6_INIT_VAL
13632 | (pVmxTransient->uExitQual & ( X86_DR6_B0 | X86_DR6_B1 | X86_DR6_B2 | X86_DR6_B3
13633 | X86_DR6_BD | X86_DR6_BS));
13634
13635 int rc;
13636 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
13637 if (!pVmxTransient->fIsNestedGuest)
13638 rc = DBGFRZTrap01Handler(pVCpu->CTX_SUFF(pVM), pVCpu, CPUMCTX2CORE(pCtx), uDR6, pVCpu->hm.s.fSingleInstruction);
13639 else
13640 rc = VINF_EM_RAW_GUEST_TRAP;
13641 Log6Func(("rc=%Rrc\n", rc));
13642 if (rc == VINF_EM_RAW_GUEST_TRAP)
13643 {
13644 /*
13645 * The exception was for the guest. Update DR6, DR7.GD and
13646 * IA32_DEBUGCTL.LBR before forwarding it.
13647 * See Intel spec. 27.1 "Architectural State before a VM-Exit".
13648 */
13649 VMMRZCallRing3Disable(pVCpu);
13650 HM_DISABLE_PREEMPT(pVCpu);
13651
13652 pCtx->dr[6] &= ~X86_DR6_B_MASK;
13653 pCtx->dr[6] |= uDR6;
13654 if (CPUMIsGuestDebugStateActive(pVCpu))
13655 ASMSetDR6(pCtx->dr[6]);
13656
13657 HM_RESTORE_PREEMPT();
13658 VMMRZCallRing3Enable(pVCpu);
13659
13660 rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, CPUMCTX_EXTRN_DR7);
13661 AssertRCReturn(rc, rc);
13662
13663 /* X86_DR7_GD will be cleared if DRx accesses should be trapped inside the guest. */
13664 pCtx->dr[7] &= ~(uint64_t)X86_DR7_GD;
13665
13666 /* Paranoia. */
13667 pCtx->dr[7] &= ~(uint64_t)X86_DR7_RAZ_MASK;
13668 pCtx->dr[7] |= X86_DR7_RA1_MASK;
13669
13670 rc = VMXWriteVmcsNw(VMX_VMCS_GUEST_DR7, pCtx->dr[7]);
13671 AssertRC(rc);
13672
13673 /*
13674 * Raise #DB in the guest.
13675 *
13676 * It is important to reflect exactly what the VM-exit gave us (preserving the
13677 * interruption-type) rather than use hmR0VmxSetPendingXcptDB() as the #DB could've
13678 * been raised while executing ICEBP (INT1) and not the regular #DB. Thus it may
13679 * trigger different handling in the CPU (like skipping DPL checks), see @bugref{6398}.
13680 *
13681 * Intel re-documented ICEBP/INT1 on May 2018 previously documented as part of
13682 * Intel 386, see Intel spec. 24.8.3 "VM-Entry Controls for Event Injection".
13683 */
13684 hmR0VmxSetPendingEvent(pVCpu, VMX_ENTRY_INT_INFO_FROM_EXIT_INT_INFO(pVmxTransient->uExitIntInfo),
13685 pVmxTransient->cbExitInstr, pVmxTransient->uExitIntErrorCode, 0 /* GCPtrFaultAddress */);
13686 return VINF_SUCCESS;
13687 }
13688
13689 /*
13690 * Not a guest trap, must be a hypervisor related debug event then.
13691 * Update DR6 in case someone is interested in it.
13692 */
13693 AssertMsg(rc == VINF_EM_DBG_STEPPED || rc == VINF_EM_DBG_BREAKPOINT, ("%Rrc\n", rc));
13694 AssertReturn(pVmxTransient->fWasHyperDebugStateActive, VERR_HM_IPE_5);
13695 CPUMSetHyperDR6(pVCpu, uDR6);
13696
13697 return rc;
13698}
13699
13700
13701/**
13702 * Hacks its way around the lovely mesa driver's backdoor accesses.
13703 *
13704 * @sa hmR0SvmHandleMesaDrvGp.
13705 */
13706static int hmR0VmxHandleMesaDrvGp(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient, PCPUMCTX pCtx)
13707{
13708 LogFunc(("cs:rip=%#04x:%#RX64 rcx=%#RX64 rbx=%#RX64\n", pCtx->cs.Sel, pCtx->rip, pCtx->rcx, pCtx->rbx));
13709 RT_NOREF(pCtx);
13710
13711 /* For now we'll just skip the instruction. */
13712 return hmR0VmxAdvanceGuestRip(pVCpu, pVmxTransient);
13713}
13714
13715
13716/**
13717 * Checks if the \#GP'ing instruction is the mesa driver doing it's lovely
13718 * backdoor logging w/o checking what it is running inside.
13719 *
13720 * This recognizes an "IN EAX,DX" instruction executed in flat ring-3, with the
13721 * backdoor port and magic numbers loaded in registers.
13722 *
13723 * @returns true if it is, false if it isn't.
13724 * @sa hmR0SvmIsMesaDrvGp.
13725 */
13726DECLINLINE(bool) hmR0VmxIsMesaDrvGp(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient, PCPUMCTX pCtx)
13727{
13728 /* 0xed: IN eAX,dx */
13729 uint8_t abInstr[1];
13730 if (pVmxTransient->cbExitInstr != sizeof(abInstr))
13731 return false;
13732
13733 /* Check that it is #GP(0). */
13734 if (pVmxTransient->uExitIntErrorCode != 0)
13735 return false;
13736
13737 /* Check magic and port. */
13738 Assert(!(pCtx->fExtrn & (CPUMCTX_EXTRN_RAX | CPUMCTX_EXTRN_RDX | CPUMCTX_EXTRN_RCX)));
13739 /*Log(("hmR0VmxIsMesaDrvGp: rax=%RX64 rdx=%RX64\n", pCtx->rax, pCtx->rdx));*/
13740 if (pCtx->rax != UINT32_C(0x564d5868))
13741 return false;
13742 if (pCtx->dx != UINT32_C(0x5658))
13743 return false;
13744
13745 /* Flat ring-3 CS. */
13746 AssertCompile(HMVMX_CPUMCTX_EXTRN_ALL & CPUMCTX_EXTRN_CS);
13747 Assert(!(pCtx->fExtrn & CPUMCTX_EXTRN_CS));
13748 /*Log(("hmR0VmxIsMesaDrvGp: cs.Attr.n.u2Dpl=%d base=%Rx64\n", pCtx->cs.Attr.n.u2Dpl, pCtx->cs.u64Base));*/
13749 if (pCtx->cs.Attr.n.u2Dpl != 3)
13750 return false;
13751 if (pCtx->cs.u64Base != 0)
13752 return false;
13753
13754 /* Check opcode. */
13755 AssertCompile(HMVMX_CPUMCTX_EXTRN_ALL & CPUMCTX_EXTRN_RIP);
13756 Assert(!(pCtx->fExtrn & CPUMCTX_EXTRN_RIP));
13757 int rc = PGMPhysSimpleReadGCPtr(pVCpu, abInstr, pCtx->rip, sizeof(abInstr));
13758 /*Log(("hmR0VmxIsMesaDrvGp: PGMPhysSimpleReadGCPtr -> %Rrc %#x\n", rc, abInstr[0]));*/
13759 if (RT_FAILURE(rc))
13760 return false;
13761 if (abInstr[0] != 0xed)
13762 return false;
13763
13764 return true;
13765}
13766
13767
13768/**
13769 * VM-exit exception handler for \#GP (General-protection exception).
13770 *
13771 * @remarks Requires all fields in HMVMX_READ_XCPT_INFO to be read from the VMCS.
13772 */
13773static VBOXSTRICTRC hmR0VmxExitXcptGP(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
13774{
13775 HMVMX_VALIDATE_EXIT_XCPT_HANDLER_PARAMS(pVCpu, pVmxTransient);
13776 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestGP);
13777
13778 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
13779 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
13780 if (pVmcsInfo->RealMode.fRealOnV86Active)
13781 { /* likely */ }
13782 else
13783 {
13784#ifndef HMVMX_ALWAYS_TRAP_ALL_XCPTS
13785 Assert(pVCpu->hm.s.fUsingDebugLoop || pVCpu->hm.s.fTrapXcptGpForLovelyMesaDrv || pVmxTransient->fIsNestedGuest);
13786#endif
13787 /*
13788 * If the guest is not in real-mode or we have unrestricted guest execution support, or if we are
13789 * executing a nested-guest, reflect #GP to the guest or nested-guest.
13790 */
13791 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, HMVMX_CPUMCTX_EXTRN_ALL);
13792 AssertRCReturn(rc, rc);
13793 Log4Func(("Gst: cs:rip=%#04x:%#RX64 ErrorCode=%#x cr0=%#RX64 cpl=%u tr=%#04x\n", pCtx->cs.Sel, pCtx->rip,
13794 pVmxTransient->uExitIntErrorCode, pCtx->cr0, CPUMGetGuestCPL(pVCpu), pCtx->tr.Sel));
13795
13796 if ( pVmxTransient->fIsNestedGuest
13797 || !pVCpu->hm.s.fTrapXcptGpForLovelyMesaDrv
13798 || !hmR0VmxIsMesaDrvGp(pVCpu, pVmxTransient, pCtx))
13799 hmR0VmxSetPendingEvent(pVCpu, VMX_ENTRY_INT_INFO_FROM_EXIT_INT_INFO(pVmxTransient->uExitIntInfo),
13800 pVmxTransient->cbExitInstr, pVmxTransient->uExitIntErrorCode, 0 /* GCPtrFaultAddress */);
13801 else
13802 rc = hmR0VmxHandleMesaDrvGp(pVCpu, pVmxTransient, pCtx);
13803 return rc;
13804 }
13805
13806 Assert(CPUMIsGuestInRealModeEx(pCtx));
13807 Assert(!pVCpu->CTX_SUFF(pVM)->hm.s.vmx.fUnrestrictedGuest);
13808 Assert(!pVmxTransient->fIsNestedGuest);
13809
13810 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, HMVMX_CPUMCTX_EXTRN_ALL);
13811 AssertRCReturn(rc, rc);
13812
13813 VBOXSTRICTRC rcStrict = IEMExecOne(pVCpu);
13814 if (rcStrict == VINF_SUCCESS)
13815 {
13816 if (!CPUMIsGuestInRealModeEx(pCtx))
13817 {
13818 /*
13819 * The guest is no longer in real-mode, check if we can continue executing the
13820 * guest using hardware-assisted VMX. Otherwise, fall back to emulation.
13821 */
13822 pVmcsInfo->RealMode.fRealOnV86Active = false;
13823 if (HMCanExecuteVmxGuest(pVCpu->pVMR0, pVCpu, pCtx))
13824 {
13825 Log4Func(("Mode changed but guest still suitable for executing using hardware-assisted VMX\n"));
13826 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_ALL_GUEST);
13827 }
13828 else
13829 {
13830 Log4Func(("Mode changed -> VINF_EM_RESCHEDULE\n"));
13831 rcStrict = VINF_EM_RESCHEDULE;
13832 }
13833 }
13834 else
13835 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_ALL_GUEST);
13836 }
13837 else if (rcStrict == VINF_IEM_RAISED_XCPT)
13838 {
13839 rcStrict = VINF_SUCCESS;
13840 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
13841 }
13842 return VBOXSTRICTRC_VAL(rcStrict);
13843}
13844
13845
13846/**
13847 * VM-exit exception handler wrapper for all other exceptions that are not handled
13848 * by a specific handler.
13849 *
13850 * This simply re-injects the exception back into the VM without any special
13851 * processing.
13852 *
13853 * @remarks Requires all fields in HMVMX_READ_XCPT_INFO to be read from the VMCS.
13854 */
13855static VBOXSTRICTRC hmR0VmxExitXcptOthers(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
13856{
13857 HMVMX_VALIDATE_EXIT_XCPT_HANDLER_PARAMS(pVCpu, pVmxTransient);
13858
13859#ifndef HMVMX_ALWAYS_TRAP_ALL_XCPTS
13860 PCVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
13861 AssertMsg(pVCpu->hm.s.fUsingDebugLoop || pVmcsInfo->RealMode.fRealOnV86Active || pVmxTransient->fIsNestedGuest,
13862 ("uVector=%#x u32XcptBitmap=%#X32\n",
13863 VMX_EXIT_INT_INFO_VECTOR(pVmxTransient->uExitIntInfo), pVmcsInfo->u32XcptBitmap));
13864 NOREF(pVmcsInfo);
13865#endif
13866
13867 /*
13868 * Re-inject the exception into the guest. This cannot be a double-fault condition which
13869 * would have been handled while checking exits due to event delivery.
13870 */
13871 uint8_t const uVector = VMX_EXIT_INT_INFO_VECTOR(pVmxTransient->uExitIntInfo);
13872
13873#ifdef HMVMX_ALWAYS_TRAP_ALL_XCPTS
13874 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, CPUMCTX_EXTRN_CS | CPUMCTX_EXTRN_RIP);
13875 AssertRCReturn(rc, rc);
13876 Log4Func(("Reinjecting Xcpt. uVector=%#x cs:rip=%#04x:%#RX64\n", uVector, pCtx->cs.Sel, pCtx->rip));
13877#endif
13878
13879#ifdef VBOX_WITH_STATISTICS
13880 switch (uVector)
13881 {
13882 case X86_XCPT_DE: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestDE); break;
13883 case X86_XCPT_DB: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestDB); break;
13884 case X86_XCPT_BP: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestBP); break;
13885 case X86_XCPT_OF: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestOF); break;
13886 case X86_XCPT_BR: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestBR); break;
13887 case X86_XCPT_UD: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestUD); break;
13888 case X86_XCPT_NM: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestOF); break;
13889 case X86_XCPT_DF: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestDF); break;
13890 case X86_XCPT_TS: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestTS); break;
13891 case X86_XCPT_NP: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestNP); break;
13892 case X86_XCPT_SS: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestSS); break;
13893 case X86_XCPT_GP: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestGP); break;
13894 case X86_XCPT_PF: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestPF); break;
13895 case X86_XCPT_MF: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestMF); break;
13896 case X86_XCPT_AC: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestAC); break;
13897 case X86_XCPT_XF: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestXF); break;
13898 default:
13899 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestXcpUnk);
13900 break;
13901 }
13902#endif
13903
13904 /* We should never call this function for a page-fault, we'd need to pass on the fault address below otherwise. */
13905 Assert(!VMX_EXIT_INT_INFO_IS_XCPT_PF(pVmxTransient->uExitIntInfo));
13906 NOREF(uVector);
13907
13908 /* Re-inject the original exception into the guest. */
13909 hmR0VmxSetPendingEvent(pVCpu, VMX_ENTRY_INT_INFO_FROM_EXIT_INT_INFO(pVmxTransient->uExitIntInfo),
13910 pVmxTransient->cbExitInstr, pVmxTransient->uExitIntErrorCode, 0 /* GCPtrFaultAddress */);
13911 return VINF_SUCCESS;
13912}
13913
13914
13915/**
13916 * VM-exit exception handler for all exceptions (except NMIs!).
13917 *
13918 * @remarks This may be called for both guests and nested-guests. Take care to not
13919 * make assumptions and avoid doing anything that is not relevant when
13920 * executing a nested-guest (e.g., Mesa driver hacks).
13921 */
13922static VBOXSTRICTRC hmR0VmxExitXcpt(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
13923{
13924 HMVMX_ASSERT_READ(pVmxTransient, HMVMX_READ_XCPT_INFO);
13925
13926 /*
13927 * If this VM-exit occurred while delivering an event through the guest IDT, take
13928 * action based on the return code and additional hints (e.g. for page-faults)
13929 * that will be updated in the VMX transient structure.
13930 */
13931 VBOXSTRICTRC rcStrict = hmR0VmxCheckExitDueToEventDelivery(pVCpu, pVmxTransient);
13932 if (rcStrict == VINF_SUCCESS)
13933 {
13934 /*
13935 * If an exception caused a VM-exit due to delivery of an event, the original
13936 * event may have to be re-injected into the guest. We shall reinject it and
13937 * continue guest execution. However, page-fault is a complicated case and
13938 * needs additional processing done in hmR0VmxExitXcptPF().
13939 */
13940 Assert(VMX_EXIT_INT_INFO_IS_VALID(pVmxTransient->uExitIntInfo));
13941 uint8_t const uVector = VMX_EXIT_INT_INFO_VECTOR(pVmxTransient->uExitIntInfo);
13942 if ( !pVCpu->hm.s.Event.fPending
13943 || uVector == X86_XCPT_PF)
13944 {
13945 switch (uVector)
13946 {
13947 case X86_XCPT_PF: return hmR0VmxExitXcptPF(pVCpu, pVmxTransient);
13948 case X86_XCPT_GP: return hmR0VmxExitXcptGP(pVCpu, pVmxTransient);
13949 case X86_XCPT_MF: return hmR0VmxExitXcptMF(pVCpu, pVmxTransient);
13950 case X86_XCPT_DB: return hmR0VmxExitXcptDB(pVCpu, pVmxTransient);
13951 case X86_XCPT_BP: return hmR0VmxExitXcptBP(pVCpu, pVmxTransient);
13952 case X86_XCPT_AC: return hmR0VmxExitXcptAC(pVCpu, pVmxTransient);
13953 default:
13954 return hmR0VmxExitXcptOthers(pVCpu, pVmxTransient);
13955 }
13956 }
13957 /* else: inject pending event before resuming guest execution. */
13958 }
13959 else if (rcStrict == VINF_HM_DOUBLE_FAULT)
13960 {
13961 Assert(pVCpu->hm.s.Event.fPending);
13962 rcStrict = VINF_SUCCESS;
13963 }
13964
13965 return rcStrict;
13966}
13967/** @} */
13968
13969
13970/** @name VM-exit handlers.
13971 * @{
13972 */
13973/* -=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= */
13974/* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- VM-exit handlers -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- */
13975/* -=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= */
13976
13977/**
13978 * VM-exit handler for external interrupts (VMX_EXIT_EXT_INT).
13979 */
13980HMVMX_EXIT_DECL hmR0VmxExitExtInt(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
13981{
13982 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
13983 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitExtInt);
13984 /* Windows hosts (32-bit and 64-bit) have DPC latency issues. See @bugref{6853}. */
13985 if (VMMR0ThreadCtxHookIsEnabled(pVCpu))
13986 return VINF_SUCCESS;
13987 return VINF_EM_RAW_INTERRUPT;
13988}
13989
13990
13991/**
13992 * VM-exit handler for exceptions or NMIs (VMX_EXIT_XCPT_OR_NMI). Conditional
13993 * VM-exit.
13994 */
13995HMVMX_EXIT_DECL hmR0VmxExitXcptOrNmi(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
13996{
13997 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
13998 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatExitXcptNmi, y3);
13999
14000 hmR0VmxReadExitIntInfoVmcs(pVmxTransient);
14001
14002 uint32_t const uExitIntType = VMX_EXIT_INT_INFO_TYPE(pVmxTransient->uExitIntInfo);
14003 uint8_t const uVector = VMX_EXIT_INT_INFO_VECTOR(pVmxTransient->uExitIntInfo);
14004 Assert(VMX_EXIT_INT_INFO_IS_VALID(pVmxTransient->uExitIntInfo));
14005
14006 PCVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
14007 Assert( !(pVmcsInfo->u32ExitCtls & VMX_EXIT_CTLS_ACK_EXT_INT)
14008 && uExitIntType != VMX_EXIT_INT_INFO_TYPE_EXT_INT);
14009 NOREF(pVmcsInfo);
14010
14011 VBOXSTRICTRC rcStrict;
14012 switch (uExitIntType)
14013 {
14014 /*
14015 * Host physical NMIs:
14016 * This cannot be a guest NMI as the only way for the guest to receive an NMI is if we
14017 * injected it ourselves and anything we inject is not going to cause a VM-exit directly
14018 * for the event being injected[1]. Go ahead and dispatch the NMI to the host[2].
14019 *
14020 * See Intel spec. 27.2.3 "Information for VM Exits During Event Delivery".
14021 * See Intel spec. 27.5.5 "Updating Non-Register State".
14022 */
14023 case VMX_EXIT_INT_INFO_TYPE_NMI:
14024 {
14025 rcStrict = hmR0VmxExitHostNmi(pVCpu, pVmcsInfo);
14026 break;
14027 }
14028
14029 /*
14030 * Privileged software exceptions (#DB from ICEBP),
14031 * Software exceptions (#BP and #OF),
14032 * Hardware exceptions:
14033 * Process the required exceptions and resume guest execution if possible.
14034 */
14035 case VMX_EXIT_INT_INFO_TYPE_PRIV_SW_XCPT:
14036 Assert(uVector == X86_XCPT_DB);
14037 RT_FALL_THRU();
14038 case VMX_EXIT_INT_INFO_TYPE_SW_XCPT:
14039 Assert(uVector == X86_XCPT_BP || uVector == X86_XCPT_OF || uExitIntType == VMX_EXIT_INT_INFO_TYPE_PRIV_SW_XCPT);
14040 RT_FALL_THRU();
14041 case VMX_EXIT_INT_INFO_TYPE_HW_XCPT:
14042 {
14043 NOREF(uVector);
14044 hmR0VmxReadExitIntErrorCodeVmcs(pVmxTransient);
14045 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
14046 hmR0VmxReadIdtVectoringInfoVmcs(pVmxTransient);
14047 hmR0VmxReadIdtVectoringErrorCodeVmcs(pVmxTransient);
14048
14049 rcStrict = hmR0VmxExitXcpt(pVCpu, pVmxTransient);
14050 break;
14051 }
14052
14053 default:
14054 {
14055 pVCpu->hm.s.u32HMError = pVmxTransient->uExitIntInfo;
14056 rcStrict = VERR_VMX_UNEXPECTED_INTERRUPTION_EXIT_TYPE;
14057 AssertMsgFailed(("Invalid/unexpected VM-exit interruption info %#x\n", pVmxTransient->uExitIntInfo));
14058 break;
14059 }
14060 }
14061
14062 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExitXcptNmi, y3);
14063 return rcStrict;
14064}
14065
14066
14067/**
14068 * VM-exit handler for interrupt-window exiting (VMX_EXIT_INT_WINDOW).
14069 */
14070HMVMX_EXIT_NSRC_DECL hmR0VmxExitIntWindow(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14071{
14072 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14073
14074 /* Indicate that we no longer need to VM-exit when the guest is ready to receive interrupts, it is now ready. */
14075 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
14076 hmR0VmxClearIntWindowExitVmcs(pVmcsInfo);
14077
14078 /* Evaluate and deliver pending events and resume guest execution. */
14079 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIntWindow);
14080 return VINF_SUCCESS;
14081}
14082
14083
14084/**
14085 * VM-exit handler for NMI-window exiting (VMX_EXIT_NMI_WINDOW).
14086 */
14087HMVMX_EXIT_NSRC_DECL hmR0VmxExitNmiWindow(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14088{
14089 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14090
14091 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
14092 if (RT_UNLIKELY(!(pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_NMI_WINDOW_EXIT))) /** @todo NSTVMX: Turn this into an assertion. */
14093 {
14094 AssertMsgFailed(("Unexpected NMI-window exit.\n"));
14095 HMVMX_UNEXPECTED_EXIT_RET(pVCpu, pVmxTransient->uExitReason);
14096 }
14097
14098 Assert(!CPUMIsGuestNmiBlocking(pVCpu));
14099
14100 /*
14101 * If block-by-STI is set when we get this VM-exit, it means the CPU doesn't block NMIs following STI.
14102 * It is therefore safe to unblock STI and deliver the NMI ourselves. See @bugref{7445}.
14103 */
14104 uint32_t fIntrState;
14105 int rc = VMXReadVmcs32(VMX_VMCS32_GUEST_INT_STATE, &fIntrState);
14106 AssertRC(rc);
14107 Assert(!(fIntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_MOVSS));
14108 if (fIntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_STI)
14109 {
14110 if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS))
14111 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS);
14112
14113 fIntrState &= ~VMX_VMCS_GUEST_INT_STATE_BLOCK_STI;
14114 rc = VMXWriteVmcs32(VMX_VMCS32_GUEST_INT_STATE, fIntrState);
14115 AssertRC(rc);
14116 }
14117
14118 /* Indicate that we no longer need to VM-exit when the guest is ready to receive NMIs, it is now ready */
14119 hmR0VmxClearNmiWindowExitVmcs(pVmcsInfo);
14120
14121 /* Evaluate and deliver pending events and resume guest execution. */
14122 return VINF_SUCCESS;
14123}
14124
14125
14126/**
14127 * VM-exit handler for WBINVD (VMX_EXIT_WBINVD). Conditional VM-exit.
14128 */
14129HMVMX_EXIT_NSRC_DECL hmR0VmxExitWbinvd(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14130{
14131 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14132 return hmR0VmxAdvanceGuestRip(pVCpu, pVmxTransient);
14133}
14134
14135
14136/**
14137 * VM-exit handler for INVD (VMX_EXIT_INVD). Unconditional VM-exit.
14138 */
14139HMVMX_EXIT_NSRC_DECL hmR0VmxExitInvd(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14140{
14141 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14142 return hmR0VmxAdvanceGuestRip(pVCpu, pVmxTransient);
14143}
14144
14145
14146/**
14147 * VM-exit handler for CPUID (VMX_EXIT_CPUID). Unconditional VM-exit.
14148 */
14149HMVMX_EXIT_DECL hmR0VmxExitCpuid(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14150{
14151 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14152
14153 /*
14154 * Get the state we need and update the exit history entry.
14155 */
14156 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
14157 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
14158
14159 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, IEM_CPUMCTX_EXTRN_EXEC_DECODED_NO_MEM_MASK);
14160 AssertRCReturn(rc, rc);
14161
14162 VBOXSTRICTRC rcStrict;
14163 PCEMEXITREC pExitRec = EMHistoryUpdateFlagsAndTypeAndPC(pVCpu,
14164 EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM | EMEXIT_F_HM, EMEXITTYPE_CPUID),
14165 pVCpu->cpum.GstCtx.rip + pVCpu->cpum.GstCtx.cs.u64Base);
14166 if (!pExitRec)
14167 {
14168 /*
14169 * Regular CPUID instruction execution.
14170 */
14171 rcStrict = IEMExecDecodedCpuid(pVCpu, pVmxTransient->cbExitInstr);
14172 if (rcStrict == VINF_SUCCESS)
14173 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS);
14174 else if (rcStrict == VINF_IEM_RAISED_XCPT)
14175 {
14176 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
14177 rcStrict = VINF_SUCCESS;
14178 }
14179 }
14180 else
14181 {
14182 /*
14183 * Frequent exit or something needing probing. Get state and call EMHistoryExec.
14184 */
14185 int rc2 = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, HMVMX_CPUMCTX_EXTRN_ALL);
14186 AssertRCReturn(rc2, rc2);
14187
14188 Log4(("CpuIdExit/%u: %04x:%08RX64: %#x/%#x -> EMHistoryExec\n",
14189 pVCpu->idCpu, pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip, pVCpu->cpum.GstCtx.eax, pVCpu->cpum.GstCtx.ecx));
14190
14191 rcStrict = EMHistoryExec(pVCpu, pExitRec, 0);
14192 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_ALL_GUEST);
14193
14194 Log4(("CpuIdExit/%u: %04x:%08RX64: EMHistoryExec -> %Rrc + %04x:%08RX64\n",
14195 pVCpu->idCpu, pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip,
14196 VBOXSTRICTRC_VAL(rcStrict), pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip));
14197 }
14198 return rcStrict;
14199}
14200
14201
14202/**
14203 * VM-exit handler for GETSEC (VMX_EXIT_GETSEC). Unconditional VM-exit.
14204 */
14205HMVMX_EXIT_DECL hmR0VmxExitGetsec(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14206{
14207 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14208
14209 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
14210 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, CPUMCTX_EXTRN_CR4);
14211 AssertRCReturn(rc, rc);
14212
14213 if (pVCpu->cpum.GstCtx.cr4 & X86_CR4_SMXE)
14214 return VINF_EM_RAW_EMULATE_INSTR;
14215
14216 AssertMsgFailed(("hmR0VmxExitGetsec: Unexpected VM-exit when CR4.SMXE is 0.\n"));
14217 HMVMX_UNEXPECTED_EXIT_RET(pVCpu, pVmxTransient->uExitReason);
14218}
14219
14220
14221/**
14222 * VM-exit handler for RDTSC (VMX_EXIT_RDTSC). Conditional VM-exit.
14223 */
14224HMVMX_EXIT_DECL hmR0VmxExitRdtsc(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14225{
14226 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14227
14228 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
14229 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
14230 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, IEM_CPUMCTX_EXTRN_MUST_MASK);
14231 AssertRCReturn(rc, rc);
14232
14233 VBOXSTRICTRC rcStrict = IEMExecDecodedRdtsc(pVCpu, pVmxTransient->cbExitInstr);
14234 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
14235 {
14236 /* If we get a spurious VM-exit when TSC offsetting is enabled,
14237 we must reset offsetting on VM-entry. See @bugref{6634}. */
14238 if (pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_USE_TSC_OFFSETTING)
14239 pVmxTransient->fUpdatedTscOffsettingAndPreemptTimer = false;
14240 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS);
14241 }
14242 else if (rcStrict == VINF_IEM_RAISED_XCPT)
14243 {
14244 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
14245 rcStrict = VINF_SUCCESS;
14246 }
14247 return rcStrict;
14248}
14249
14250
14251/**
14252 * VM-exit handler for RDTSCP (VMX_EXIT_RDTSCP). Conditional VM-exit.
14253 */
14254HMVMX_EXIT_DECL hmR0VmxExitRdtscp(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14255{
14256 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14257
14258 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
14259 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
14260 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, IEM_CPUMCTX_EXTRN_MUST_MASK | CPUMCTX_EXTRN_TSC_AUX);
14261 AssertRCReturn(rc, rc);
14262
14263 VBOXSTRICTRC rcStrict = IEMExecDecodedRdtscp(pVCpu, pVmxTransient->cbExitInstr);
14264 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
14265 {
14266 /* If we get a spurious VM-exit when TSC offsetting is enabled,
14267 we must reset offsetting on VM-reentry. See @bugref{6634}. */
14268 if (pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_USE_TSC_OFFSETTING)
14269 pVmxTransient->fUpdatedTscOffsettingAndPreemptTimer = false;
14270 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS);
14271 }
14272 else if (rcStrict == VINF_IEM_RAISED_XCPT)
14273 {
14274 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
14275 rcStrict = VINF_SUCCESS;
14276 }
14277 return rcStrict;
14278}
14279
14280
14281/**
14282 * VM-exit handler for RDPMC (VMX_EXIT_RDPMC). Conditional VM-exit.
14283 */
14284HMVMX_EXIT_DECL hmR0VmxExitRdpmc(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14285{
14286 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14287
14288 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
14289 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, CPUMCTX_EXTRN_CR4 | CPUMCTX_EXTRN_CR0
14290 | CPUMCTX_EXTRN_RFLAGS | CPUMCTX_EXTRN_SS);
14291 AssertRCReturn(rc, rc);
14292
14293 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
14294 rc = EMInterpretRdpmc(pVCpu->CTX_SUFF(pVM), pVCpu, CPUMCTX2CORE(pCtx));
14295 if (RT_LIKELY(rc == VINF_SUCCESS))
14296 {
14297 rc = hmR0VmxAdvanceGuestRip(pVCpu, pVmxTransient);
14298 Assert(pVmxTransient->cbExitInstr == 2);
14299 }
14300 else
14301 {
14302 AssertMsgFailed(("hmR0VmxExitRdpmc: EMInterpretRdpmc failed with %Rrc\n", rc));
14303 rc = VERR_EM_INTERPRETER;
14304 }
14305 return rc;
14306}
14307
14308
14309/**
14310 * VM-exit handler for VMCALL (VMX_EXIT_VMCALL). Unconditional VM-exit.
14311 */
14312HMVMX_EXIT_DECL hmR0VmxExitVmcall(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14313{
14314 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14315
14316 VBOXSTRICTRC rcStrict = VERR_VMX_IPE_3;
14317 if (EMAreHypercallInstructionsEnabled(pVCpu))
14318 {
14319 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
14320 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, CPUMCTX_EXTRN_RIP | CPUMCTX_EXTRN_RFLAGS | CPUMCTX_EXTRN_CR0
14321 | CPUMCTX_EXTRN_SS | CPUMCTX_EXTRN_CS | CPUMCTX_EXTRN_EFER);
14322 AssertRCReturn(rc, rc);
14323
14324 /* Perform the hypercall. */
14325 rcStrict = GIMHypercall(pVCpu, &pVCpu->cpum.GstCtx);
14326 if (rcStrict == VINF_SUCCESS)
14327 {
14328 rc = hmR0VmxAdvanceGuestRip(pVCpu, pVmxTransient);
14329 AssertRCReturn(rc, rc);
14330 }
14331 else
14332 Assert( rcStrict == VINF_GIM_R3_HYPERCALL
14333 || rcStrict == VINF_GIM_HYPERCALL_CONTINUING
14334 || RT_FAILURE(rcStrict));
14335
14336 /* If the hypercall changes anything other than guest's general-purpose registers,
14337 we would need to reload the guest changed bits here before VM-entry. */
14338 }
14339 else
14340 Log4Func(("Hypercalls not enabled\n"));
14341
14342 /* If hypercalls are disabled or the hypercall failed for some reason, raise #UD and continue. */
14343 if (RT_FAILURE(rcStrict))
14344 {
14345 hmR0VmxSetPendingXcptUD(pVCpu);
14346 rcStrict = VINF_SUCCESS;
14347 }
14348
14349 return rcStrict;
14350}
14351
14352
14353/**
14354 * VM-exit handler for INVLPG (VMX_EXIT_INVLPG). Conditional VM-exit.
14355 */
14356HMVMX_EXIT_DECL hmR0VmxExitInvlpg(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14357{
14358 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14359 Assert(!pVCpu->CTX_SUFF(pVM)->hm.s.fNestedPaging || pVCpu->hm.s.fUsingDebugLoop);
14360
14361 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
14362 hmR0VmxReadExitQualVmcs(pVmxTransient);
14363 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
14364 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, IEM_CPUMCTX_EXTRN_EXEC_DECODED_MEM_MASK);
14365 AssertRCReturn(rc, rc);
14366
14367 VBOXSTRICTRC rcStrict = IEMExecDecodedInvlpg(pVCpu, pVmxTransient->cbExitInstr, pVmxTransient->uExitQual);
14368
14369 if (rcStrict == VINF_SUCCESS || rcStrict == VINF_PGM_SYNC_CR3)
14370 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS);
14371 else if (rcStrict == VINF_IEM_RAISED_XCPT)
14372 {
14373 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
14374 rcStrict = VINF_SUCCESS;
14375 }
14376 else
14377 AssertMsgFailed(("Unexpected IEMExecDecodedInvlpg(%#RX64) status: %Rrc\n", pVmxTransient->uExitQual,
14378 VBOXSTRICTRC_VAL(rcStrict)));
14379 return rcStrict;
14380}
14381
14382
14383/**
14384 * VM-exit handler for MONITOR (VMX_EXIT_MONITOR). Conditional VM-exit.
14385 */
14386HMVMX_EXIT_DECL hmR0VmxExitMonitor(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14387{
14388 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14389
14390 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
14391 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
14392 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, IEM_CPUMCTX_EXTRN_EXEC_DECODED_MEM_MASK | CPUMCTX_EXTRN_DS);
14393 AssertRCReturn(rc, rc);
14394
14395 VBOXSTRICTRC rcStrict = IEMExecDecodedMonitor(pVCpu, pVmxTransient->cbExitInstr);
14396 if (rcStrict == VINF_SUCCESS)
14397 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS);
14398 else if (rcStrict == VINF_IEM_RAISED_XCPT)
14399 {
14400 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
14401 rcStrict = VINF_SUCCESS;
14402 }
14403
14404 return rcStrict;
14405}
14406
14407
14408/**
14409 * VM-exit handler for MWAIT (VMX_EXIT_MWAIT). Conditional VM-exit.
14410 */
14411HMVMX_EXIT_DECL hmR0VmxExitMwait(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14412{
14413 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14414
14415 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
14416 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
14417 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, IEM_CPUMCTX_EXTRN_EXEC_DECODED_NO_MEM_MASK);
14418 AssertRCReturn(rc, rc);
14419
14420 VBOXSTRICTRC rcStrict = IEMExecDecodedMwait(pVCpu, pVmxTransient->cbExitInstr);
14421 if (RT_SUCCESS(rcStrict))
14422 {
14423 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS);
14424 if (EMMonitorWaitShouldContinue(pVCpu, &pVCpu->cpum.GstCtx))
14425 rcStrict = VINF_SUCCESS;
14426 }
14427
14428 return rcStrict;
14429}
14430
14431
14432/**
14433 * VM-exit handler for triple faults (VMX_EXIT_TRIPLE_FAULT). Unconditional
14434 * VM-exit.
14435 */
14436HMVMX_EXIT_DECL hmR0VmxExitTripleFault(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14437{
14438 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14439 return VINF_EM_RESET;
14440}
14441
14442
14443/**
14444 * VM-exit handler for HLT (VMX_EXIT_HLT). Conditional VM-exit.
14445 */
14446HMVMX_EXIT_DECL hmR0VmxExitHlt(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14447{
14448 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14449
14450 int rc = hmR0VmxAdvanceGuestRip(pVCpu, pVmxTransient);
14451 AssertRCReturn(rc, rc);
14452
14453 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_RFLAGS); /* Advancing the RIP above should've imported eflags. */
14454 if (EMShouldContinueAfterHalt(pVCpu, &pVCpu->cpum.GstCtx)) /* Requires eflags. */
14455 rc = VINF_SUCCESS;
14456 else
14457 rc = VINF_EM_HALT;
14458
14459 if (rc != VINF_SUCCESS)
14460 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchHltToR3);
14461 return rc;
14462}
14463
14464
14465/**
14466 * VM-exit handler for instructions that result in a \#UD exception delivered to
14467 * the guest.
14468 */
14469HMVMX_EXIT_NSRC_DECL hmR0VmxExitSetPendingXcptUD(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14470{
14471 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14472 hmR0VmxSetPendingXcptUD(pVCpu);
14473 return VINF_SUCCESS;
14474}
14475
14476
14477/**
14478 * VM-exit handler for expiry of the VMX-preemption timer.
14479 */
14480HMVMX_EXIT_DECL hmR0VmxExitPreemptTimer(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14481{
14482 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14483
14484 /* If the VMX-preemption timer has expired, reinitialize the preemption timer on next VM-entry. */
14485 pVmxTransient->fUpdatedTscOffsettingAndPreemptTimer = false;
14486
14487 /* If there are any timer events pending, fall back to ring-3, otherwise resume guest execution. */
14488 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
14489 bool fTimersPending = TMTimerPollBool(pVM, pVCpu);
14490 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitPreemptTimer);
14491 return fTimersPending ? VINF_EM_RAW_TIMER_PENDING : VINF_SUCCESS;
14492}
14493
14494
14495/**
14496 * VM-exit handler for XSETBV (VMX_EXIT_XSETBV). Unconditional VM-exit.
14497 */
14498HMVMX_EXIT_DECL hmR0VmxExitXsetbv(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14499{
14500 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14501
14502 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
14503 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
14504 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, IEM_CPUMCTX_EXTRN_MUST_MASK | CPUMCTX_EXTRN_CR4);
14505 AssertRCReturn(rc, rc);
14506
14507 VBOXSTRICTRC rcStrict = IEMExecDecodedXsetbv(pVCpu, pVmxTransient->cbExitInstr);
14508 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, rcStrict != VINF_IEM_RAISED_XCPT ? HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS
14509 : HM_CHANGED_RAISED_XCPT_MASK);
14510
14511 PCCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
14512 pVCpu->hm.s.fLoadSaveGuestXcr0 = (pCtx->cr4 & X86_CR4_OSXSAVE) && pCtx->aXcr[0] != ASMGetXcr0();
14513
14514 return rcStrict;
14515}
14516
14517
14518/**
14519 * VM-exit handler for INVPCID (VMX_EXIT_INVPCID). Conditional VM-exit.
14520 */
14521HMVMX_EXIT_DECL hmR0VmxExitInvpcid(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14522{
14523 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14524 /** @todo Use VM-exit instruction information. */
14525 return VERR_EM_INTERPRETER;
14526}
14527
14528
14529/**
14530 * VM-exit handler for invalid-guest-state (VMX_EXIT_ERR_INVALID_GUEST_STATE). Error
14531 * VM-exit.
14532 */
14533HMVMX_EXIT_NSRC_DECL hmR0VmxExitErrInvalidGuestState(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14534{
14535 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
14536 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, HMVMX_CPUMCTX_EXTRN_ALL);
14537 AssertRCReturn(rc, rc);
14538
14539 rc = hmR0VmxCheckVmcsCtls(pVCpu, pVmcsInfo, pVmxTransient->fIsNestedGuest);
14540 if (RT_FAILURE(rc))
14541 return rc;
14542
14543 uint32_t const uInvalidReason = hmR0VmxCheckGuestState(pVCpu, pVmcsInfo);
14544 NOREF(uInvalidReason);
14545
14546#ifdef VBOX_STRICT
14547 uint32_t fIntrState;
14548 uint64_t u64Val;
14549 hmR0VmxReadEntryIntInfoVmcs(pVmxTransient);
14550 hmR0VmxReadEntryXcptErrorCodeVmcs(pVmxTransient);
14551 hmR0VmxReadEntryInstrLenVmcs(pVmxTransient);
14552
14553 Log4(("uInvalidReason %u\n", uInvalidReason));
14554 Log4(("VMX_VMCS32_CTRL_ENTRY_INTERRUPTION_INFO %#RX32\n", pVmxTransient->uEntryIntInfo));
14555 Log4(("VMX_VMCS32_CTRL_ENTRY_EXCEPTION_ERRCODE %#RX32\n", pVmxTransient->uEntryXcptErrorCode));
14556 Log4(("VMX_VMCS32_CTRL_ENTRY_INSTR_LENGTH %#RX32\n", pVmxTransient->cbEntryInstr));
14557
14558 rc = VMXReadVmcs32(VMX_VMCS32_GUEST_INT_STATE, &fIntrState); AssertRC(rc);
14559 Log4(("VMX_VMCS32_GUEST_INT_STATE %#RX32\n", fIntrState));
14560 rc = VMXReadVmcsNw(VMX_VMCS_GUEST_CR0, &u64Val); AssertRC(rc);
14561 Log4(("VMX_VMCS_GUEST_CR0 %#RX64\n", u64Val));
14562 rc = VMXReadVmcsNw(VMX_VMCS_CTRL_CR0_MASK, &u64Val); AssertRC(rc);
14563 Log4(("VMX_VMCS_CTRL_CR0_MASK %#RX64\n", u64Val));
14564 rc = VMXReadVmcsNw(VMX_VMCS_CTRL_CR0_READ_SHADOW, &u64Val); AssertRC(rc);
14565 Log4(("VMX_VMCS_CTRL_CR4_READ_SHADOW %#RX64\n", u64Val));
14566 rc = VMXReadVmcsNw(VMX_VMCS_CTRL_CR4_MASK, &u64Val); AssertRC(rc);
14567 Log4(("VMX_VMCS_CTRL_CR4_MASK %#RX64\n", u64Val));
14568 rc = VMXReadVmcsNw(VMX_VMCS_CTRL_CR4_READ_SHADOW, &u64Val); AssertRC(rc);
14569 Log4(("VMX_VMCS_CTRL_CR4_READ_SHADOW %#RX64\n", u64Val));
14570 if (pVCpu->CTX_SUFF(pVM)->hm.s.fNestedPaging)
14571 {
14572 rc = VMXReadVmcs64(VMX_VMCS64_CTRL_EPTP_FULL, &u64Val); AssertRC(rc);
14573 Log4(("VMX_VMCS64_CTRL_EPTP_FULL %#RX64\n", u64Val));
14574 }
14575 hmR0DumpRegs(pVCpu, HM_DUMP_REG_FLAGS_ALL);
14576#endif
14577
14578 return VERR_VMX_INVALID_GUEST_STATE;
14579}
14580
14581/**
14582 * VM-exit handler for all undefined/unexpected reasons. Should never happen.
14583 */
14584HMVMX_EXIT_NSRC_DECL hmR0VmxExitErrUnexpected(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14585{
14586 /*
14587 * Cummulative notes of all recognized but unexpected VM-exits.
14588 *
14589 * 1. This does -not- cover scenarios like like a page-fault VM-exit occurring when
14590 * nested-paging is used.
14591 *
14592 * 2. Any instruction that causes a VM-exit unconditionally (for e.g. VMXON) must be
14593 * emulated or a #UD must be raised in the guest. Therefore, we should -not- be using
14594 * this function (and thereby stop VM execution) for handling such instructions.
14595 *
14596 *
14597 * VMX_EXIT_INIT_SIGNAL:
14598 * INIT signals are blocked in VMX root operation by VMXON and by SMI in SMM.
14599 * It is -NOT- blocked in VMX non-root operation so we can, in theory, still get these
14600 * VM-exits. However, we should not receive INIT signals VM-exit while executing a VM.
14601 *
14602 * See Intel spec. 33.14.1 Default Treatment of SMI Delivery"
14603 * See Intel spec. 29.3 "VMX Instructions" for "VMXON".
14604 * See Intel spec. "23.8 Restrictions on VMX operation".
14605 *
14606 * VMX_EXIT_SIPI:
14607 * SIPI exits can only occur in VMX non-root operation when the "wait-for-SIPI" guest
14608 * activity state is used. We don't make use of it as our guests don't have direct
14609 * access to the host local APIC.
14610 *
14611 * See Intel spec. 25.3 "Other Causes of VM-exits".
14612 *
14613 * VMX_EXIT_IO_SMI:
14614 * VMX_EXIT_SMI:
14615 * This can only happen if we support dual-monitor treatment of SMI, which can be
14616 * activated by executing VMCALL in VMX root operation. Only an STM (SMM transfer
14617 * monitor) would get this VM-exit when we (the executive monitor) execute a VMCALL in
14618 * VMX root mode or receive an SMI. If we get here, something funny is going on.
14619 *
14620 * See Intel spec. 33.15.6 "Activating the Dual-Monitor Treatment"
14621 * See Intel spec. 25.3 "Other Causes of VM-Exits"
14622 *
14623 * VMX_EXIT_ERR_MSR_LOAD:
14624 * Failures while loading MSRs are part of the VM-entry MSR-load area are unexpected
14625 * and typically indicates a bug in the hypervisor code. We thus cannot not resume
14626 * execution.
14627 *
14628 * See Intel spec. 26.7 "VM-Entry Failures During Or After Loading Guest State".
14629 *
14630 * VMX_EXIT_ERR_MACHINE_CHECK:
14631 * Machine check exceptions indicates a fatal/unrecoverable hardware condition
14632 * including but not limited to system bus, ECC, parity, cache and TLB errors. A
14633 * #MC exception abort class exception is raised. We thus cannot assume a
14634 * reasonable chance of continuing any sort of execution and we bail.
14635 *
14636 * See Intel spec. 15.1 "Machine-check Architecture".
14637 * See Intel spec. 27.1 "Architectural State Before A VM Exit".
14638 *
14639 * VMX_EXIT_PML_FULL:
14640 * VMX_EXIT_VIRTUALIZED_EOI:
14641 * VMX_EXIT_APIC_WRITE:
14642 * We do not currently support any of these features and thus they are all unexpected
14643 * VM-exits.
14644 *
14645 * VMX_EXIT_GDTR_IDTR_ACCESS:
14646 * VMX_EXIT_LDTR_TR_ACCESS:
14647 * VMX_EXIT_RDRAND:
14648 * VMX_EXIT_RSM:
14649 * VMX_EXIT_VMFUNC:
14650 * VMX_EXIT_ENCLS:
14651 * VMX_EXIT_RDSEED:
14652 * VMX_EXIT_XSAVES:
14653 * VMX_EXIT_XRSTORS:
14654 * VMX_EXIT_UMWAIT:
14655 * VMX_EXIT_TPAUSE:
14656 * These VM-exits are -not- caused unconditionally by execution of the corresponding
14657 * instruction. Any VM-exit for these instructions indicate a hardware problem,
14658 * unsupported CPU modes (like SMM) or potentially corrupt VMCS controls.
14659 *
14660 * See Intel spec. 25.1.3 "Instructions That Cause VM Exits Conditionally".
14661 */
14662 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14663 AssertMsgFailed(("Unexpected VM-exit %u\n", pVmxTransient->uExitReason));
14664 HMVMX_UNEXPECTED_EXIT_RET(pVCpu, pVmxTransient->uExitReason);
14665}
14666
14667
14668/**
14669 * VM-exit handler for RDMSR (VMX_EXIT_RDMSR).
14670 */
14671HMVMX_EXIT_DECL hmR0VmxExitRdmsr(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14672{
14673 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14674
14675 /** @todo Optimize this: We currently drag in in the whole MSR state
14676 * (CPUMCTX_EXTRN_ALL_MSRS) here. We should optimize this to only get
14677 * MSRs required. That would require changes to IEM and possibly CPUM too.
14678 * (Should probably do it lazy fashion from CPUMAllMsrs.cpp). */
14679 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
14680 uint32_t const idMsr = pVCpu->cpum.GstCtx.ecx;
14681 uint64_t fImport = IEM_CPUMCTX_EXTRN_EXEC_DECODED_NO_MEM_MASK | CPUMCTX_EXTRN_ALL_MSRS;
14682 switch (idMsr)
14683 {
14684 case MSR_K8_FS_BASE: fImport |= CPUMCTX_EXTRN_FS; break;
14685 case MSR_K8_GS_BASE: fImport |= CPUMCTX_EXTRN_GS; break;
14686 }
14687
14688 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
14689 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, fImport);
14690 AssertRCReturn(rc, rc);
14691
14692 Log4Func(("ecx=%#RX32\n", idMsr));
14693
14694#ifdef VBOX_STRICT
14695 Assert(!pVmxTransient->fIsNestedGuest);
14696 if (pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_USE_MSR_BITMAPS)
14697 {
14698 if ( hmR0VmxIsAutoLoadGuestMsr(pVmcsInfo, idMsr)
14699 && idMsr != MSR_K6_EFER)
14700 {
14701 AssertMsgFailed(("Unexpected RDMSR for an MSR in the auto-load/store area in the VMCS. ecx=%#RX32\n", idMsr));
14702 HMVMX_UNEXPECTED_EXIT_RET(pVCpu, idMsr);
14703 }
14704 if (hmR0VmxIsLazyGuestMsr(pVCpu, idMsr))
14705 {
14706 Assert(pVmcsInfo->pvMsrBitmap);
14707 uint32_t fMsrpm = CPUMGetVmxMsrPermission(pVmcsInfo->pvMsrBitmap, idMsr);
14708 if (fMsrpm & VMXMSRPM_ALLOW_RD)
14709 {
14710 AssertMsgFailed(("Unexpected RDMSR for a passthru lazy-restore MSR. ecx=%#RX32\n", idMsr));
14711 HMVMX_UNEXPECTED_EXIT_RET(pVCpu, idMsr);
14712 }
14713 }
14714 }
14715#endif
14716
14717 VBOXSTRICTRC rcStrict = IEMExecDecodedRdmsr(pVCpu, pVmxTransient->cbExitInstr);
14718 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitRdmsr);
14719 if (rcStrict == VINF_SUCCESS)
14720 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS
14721 | HM_CHANGED_GUEST_RAX | HM_CHANGED_GUEST_RDX);
14722 else if (rcStrict == VINF_IEM_RAISED_XCPT)
14723 {
14724 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
14725 rcStrict = VINF_SUCCESS;
14726 }
14727 else
14728 AssertMsg(rcStrict == VINF_CPUM_R3_MSR_READ, ("Unexpected IEMExecDecodedRdmsr rc (%Rrc)\n", VBOXSTRICTRC_VAL(rcStrict)));
14729
14730 return rcStrict;
14731}
14732
14733
14734/**
14735 * VM-exit handler for WRMSR (VMX_EXIT_WRMSR).
14736 */
14737HMVMX_EXIT_DECL hmR0VmxExitWrmsr(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14738{
14739 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14740
14741 /** @todo Optimize this: We currently drag in in the whole MSR state
14742 * (CPUMCTX_EXTRN_ALL_MSRS) here. We should optimize this to only get
14743 * MSRs required. That would require changes to IEM and possibly CPUM too.
14744 * (Should probably do it lazy fashion from CPUMAllMsrs.cpp). */
14745 uint32_t const idMsr = pVCpu->cpum.GstCtx.ecx;
14746 uint64_t fImport = IEM_CPUMCTX_EXTRN_EXEC_DECODED_NO_MEM_MASK | CPUMCTX_EXTRN_ALL_MSRS;
14747
14748 /*
14749 * The FS and GS base MSRs are not part of the above all-MSRs mask.
14750 * Although we don't need to fetch the base as it will be overwritten shortly, while
14751 * loading guest-state we would also load the entire segment register including limit
14752 * and attributes and thus we need to load them here.
14753 */
14754 switch (idMsr)
14755 {
14756 case MSR_K8_FS_BASE: fImport |= CPUMCTX_EXTRN_FS; break;
14757 case MSR_K8_GS_BASE: fImport |= CPUMCTX_EXTRN_GS; break;
14758 }
14759
14760 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
14761 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
14762 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, fImport);
14763 AssertRCReturn(rc, rc);
14764
14765 Log4Func(("ecx=%#RX32 edx:eax=%#RX32:%#RX32\n", idMsr, pVCpu->cpum.GstCtx.edx, pVCpu->cpum.GstCtx.eax));
14766
14767 VBOXSTRICTRC rcStrict = IEMExecDecodedWrmsr(pVCpu, pVmxTransient->cbExitInstr);
14768 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitWrmsr);
14769
14770 if (rcStrict == VINF_SUCCESS)
14771 {
14772 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS);
14773
14774 /* If this is an X2APIC WRMSR access, update the APIC state as well. */
14775 if ( idMsr == MSR_IA32_APICBASE
14776 || ( idMsr >= MSR_IA32_X2APIC_START
14777 && idMsr <= MSR_IA32_X2APIC_END))
14778 {
14779 /*
14780 * We've already saved the APIC related guest-state (TPR) in post-run phase.
14781 * When full APIC register virtualization is implemented we'll have to make
14782 * sure APIC state is saved from the VMCS before IEM changes it.
14783 */
14784 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_APIC_TPR);
14785 }
14786 else if (idMsr == MSR_IA32_TSC) /* Windows 7 does this during bootup. See @bugref{6398}. */
14787 pVmxTransient->fUpdatedTscOffsettingAndPreemptTimer = false;
14788 else if (idMsr == MSR_K6_EFER)
14789 {
14790 /*
14791 * If the guest touches the EFER MSR we need to update the VM-Entry and VM-Exit controls
14792 * as well, even if it is -not- touching bits that cause paging mode changes (LMA/LME).
14793 * We care about the other bits as well, SCE and NXE. See @bugref{7368}.
14794 */
14795 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_EFER_MSR | HM_CHANGED_VMX_ENTRY_EXIT_CTLS);
14796 }
14797
14798 /* Update MSRs that are part of the VMCS and auto-load/store area when MSR-bitmaps are not used. */
14799 if (!(pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_USE_MSR_BITMAPS))
14800 {
14801 switch (idMsr)
14802 {
14803 case MSR_IA32_SYSENTER_CS: ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_SYSENTER_CS_MSR); break;
14804 case MSR_IA32_SYSENTER_EIP: ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_SYSENTER_EIP_MSR); break;
14805 case MSR_IA32_SYSENTER_ESP: ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_SYSENTER_ESP_MSR); break;
14806 case MSR_K8_FS_BASE: ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_FS); break;
14807 case MSR_K8_GS_BASE: ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_GS); break;
14808 case MSR_K6_EFER: /* Nothing to do, already handled above. */ break;
14809 default:
14810 {
14811 if (hmR0VmxIsLazyGuestMsr(pVCpu, idMsr))
14812 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_VMX_GUEST_LAZY_MSRS);
14813 else if (hmR0VmxIsAutoLoadGuestMsr(pVmcsInfo, idMsr))
14814 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_VMX_GUEST_AUTO_MSRS);
14815 break;
14816 }
14817 }
14818 }
14819#ifdef VBOX_STRICT
14820 else
14821 {
14822 /* Paranoia. Validate that MSRs in the MSR-bitmaps with write-passthru are not intercepted. */
14823 switch (idMsr)
14824 {
14825 case MSR_IA32_SYSENTER_CS:
14826 case MSR_IA32_SYSENTER_EIP:
14827 case MSR_IA32_SYSENTER_ESP:
14828 case MSR_K8_FS_BASE:
14829 case MSR_K8_GS_BASE:
14830 {
14831 AssertMsgFailed(("Unexpected WRMSR for an MSR in the VMCS. ecx=%#RX32\n", idMsr));
14832 HMVMX_UNEXPECTED_EXIT_RET(pVCpu, idMsr);
14833 }
14834
14835 /* Writes to MSRs in auto-load/store area/swapped MSRs, shouldn't cause VM-exits with MSR-bitmaps. */
14836 default:
14837 {
14838 if (hmR0VmxIsAutoLoadGuestMsr(pVmcsInfo, idMsr))
14839 {
14840 /* EFER MSR writes are always intercepted. */
14841 if (idMsr != MSR_K6_EFER)
14842 {
14843 AssertMsgFailed(("Unexpected WRMSR for an MSR in the auto-load/store area in the VMCS. ecx=%#RX32\n",
14844 idMsr));
14845 HMVMX_UNEXPECTED_EXIT_RET(pVCpu, idMsr);
14846 }
14847 }
14848
14849 if (hmR0VmxIsLazyGuestMsr(pVCpu, idMsr))
14850 {
14851 Assert(pVmcsInfo->pvMsrBitmap);
14852 uint32_t fMsrpm = CPUMGetVmxMsrPermission(pVmcsInfo->pvMsrBitmap, idMsr);
14853 if (fMsrpm & VMXMSRPM_ALLOW_WR)
14854 {
14855 AssertMsgFailed(("Unexpected WRMSR for passthru, lazy-restore MSR. ecx=%#RX32\n", idMsr));
14856 HMVMX_UNEXPECTED_EXIT_RET(pVCpu, idMsr);
14857 }
14858 }
14859 break;
14860 }
14861 }
14862 }
14863#endif /* VBOX_STRICT */
14864 }
14865 else if (rcStrict == VINF_IEM_RAISED_XCPT)
14866 {
14867 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
14868 rcStrict = VINF_SUCCESS;
14869 }
14870 else
14871 AssertMsg(rcStrict == VINF_CPUM_R3_MSR_WRITE, ("Unexpected IEMExecDecodedWrmsr rc (%Rrc)\n", VBOXSTRICTRC_VAL(rcStrict)));
14872
14873 return rcStrict;
14874}
14875
14876
14877/**
14878 * VM-exit handler for PAUSE (VMX_EXIT_PAUSE). Conditional VM-exit.
14879 */
14880HMVMX_EXIT_DECL hmR0VmxExitPause(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14881{
14882 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14883
14884 /** @todo The guest has likely hit a contended spinlock. We might want to
14885 * poke a schedule different guest VCPU. */
14886 int rc = hmR0VmxAdvanceGuestRip(pVCpu, pVmxTransient);
14887 if (RT_SUCCESS(rc))
14888 return VINF_EM_RAW_INTERRUPT;
14889
14890 AssertMsgFailed(("hmR0VmxExitPause: Failed to increment RIP. rc=%Rrc\n", rc));
14891 return rc;
14892}
14893
14894
14895/**
14896 * VM-exit handler for when the TPR value is lowered below the specified
14897 * threshold (VMX_EXIT_TPR_BELOW_THRESHOLD). Conditional VM-exit.
14898 */
14899HMVMX_EXIT_NSRC_DECL hmR0VmxExitTprBelowThreshold(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14900{
14901 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14902 Assert(pVmxTransient->pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_USE_TPR_SHADOW);
14903
14904 /*
14905 * The TPR shadow would've been synced with the APIC TPR in the post-run phase.
14906 * We'll re-evaluate pending interrupts and inject them before the next VM
14907 * entry so we can just continue execution here.
14908 */
14909 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitTprBelowThreshold);
14910 return VINF_SUCCESS;
14911}
14912
14913
14914/**
14915 * VM-exit handler for control-register accesses (VMX_EXIT_MOV_CRX). Conditional
14916 * VM-exit.
14917 *
14918 * @retval VINF_SUCCESS when guest execution can continue.
14919 * @retval VINF_PGM_SYNC_CR3 CR3 sync is required, back to ring-3.
14920 * @retval VERR_EM_RESCHEDULE_REM when we need to return to ring-3 due to
14921 * incompatible guest state for VMX execution (real-on-v86 case).
14922 */
14923HMVMX_EXIT_DECL hmR0VmxExitMovCRx(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14924{
14925 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14926 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatExitMovCRx, y2);
14927
14928 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
14929 hmR0VmxReadExitQualVmcs(pVmxTransient);
14930 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
14931
14932 VBOXSTRICTRC rcStrict;
14933 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
14934 uint64_t const uExitQual = pVmxTransient->uExitQual;
14935 uint32_t const uAccessType = VMX_EXIT_QUAL_CRX_ACCESS(uExitQual);
14936 switch (uAccessType)
14937 {
14938 /*
14939 * MOV to CRx.
14940 */
14941 case VMX_EXIT_QUAL_CRX_ACCESS_WRITE:
14942 {
14943 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, IEM_CPUMCTX_EXTRN_MUST_MASK);
14944 AssertRCReturn(rc, rc);
14945
14946 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_CR0);
14947 uint32_t const uOldCr0 = pVCpu->cpum.GstCtx.cr0;
14948 uint8_t const iGReg = VMX_EXIT_QUAL_CRX_GENREG(uExitQual);
14949 uint8_t const iCrReg = VMX_EXIT_QUAL_CRX_REGISTER(uExitQual);
14950
14951 /*
14952 * MOV to CR3 only cause a VM-exit when one or more of the following are true:
14953 * - When nested paging isn't used.
14954 * - If the guest doesn't have paging enabled (intercept CR3 to update shadow page tables).
14955 * - We are executing in the VM debug loop.
14956 */
14957 Assert( iCrReg != 3
14958 || !pVM->hm.s.fNestedPaging
14959 || !CPUMIsGuestPagingEnabledEx(&pVCpu->cpum.GstCtx)
14960 || pVCpu->hm.s.fUsingDebugLoop);
14961
14962 /* MOV to CR8 writes only cause VM-exits when TPR shadow is not used. */
14963 Assert( iCrReg != 8
14964 || !(pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_USE_TPR_SHADOW));
14965
14966 rcStrict = hmR0VmxExitMovToCrX(pVCpu, pVmcsInfo, pVmxTransient->cbExitInstr, iGReg, iCrReg);
14967 AssertMsg( rcStrict == VINF_SUCCESS
14968 || rcStrict == VINF_PGM_SYNC_CR3, ("%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
14969
14970 /*
14971 * This is a kludge for handling switches back to real mode when we try to use
14972 * V86 mode to run real mode code directly. Problem is that V86 mode cannot
14973 * deal with special selector values, so we have to return to ring-3 and run
14974 * there till the selector values are V86 mode compatible.
14975 *
14976 * Note! Using VINF_EM_RESCHEDULE_REM here rather than VINF_EM_RESCHEDULE since the
14977 * latter is an alias for VINF_IEM_RAISED_XCPT which is asserted at the end of
14978 * this function.
14979 */
14980 if ( iCrReg == 0
14981 && rcStrict == VINF_SUCCESS
14982 && !pVM->hm.s.vmx.fUnrestrictedGuest
14983 && CPUMIsGuestInRealModeEx(&pVCpu->cpum.GstCtx)
14984 && (uOldCr0 & X86_CR0_PE)
14985 && !(pVCpu->cpum.GstCtx.cr0 & X86_CR0_PE))
14986 {
14987 /** @todo Check selectors rather than returning all the time. */
14988 Assert(!pVmxTransient->fIsNestedGuest);
14989 Log4Func(("CR0 write, back to real mode -> VINF_EM_RESCHEDULE_REM\n"));
14990 rcStrict = VINF_EM_RESCHEDULE_REM;
14991 }
14992 break;
14993 }
14994
14995 /*
14996 * MOV from CRx.
14997 */
14998 case VMX_EXIT_QUAL_CRX_ACCESS_READ:
14999 {
15000 uint8_t const iGReg = VMX_EXIT_QUAL_CRX_GENREG(uExitQual);
15001 uint8_t const iCrReg = VMX_EXIT_QUAL_CRX_REGISTER(uExitQual);
15002
15003 /*
15004 * MOV from CR3 only cause a VM-exit when one or more of the following are true:
15005 * - When nested paging isn't used.
15006 * - If the guest doesn't have paging enabled (pass guest's CR3 rather than our identity mapped CR3).
15007 * - We are executing in the VM debug loop.
15008 */
15009 Assert( iCrReg != 3
15010 || !pVM->hm.s.fNestedPaging
15011 || !CPUMIsGuestPagingEnabledEx(&pVCpu->cpum.GstCtx)
15012 || pVCpu->hm.s.fUsingDebugLoop);
15013
15014 /* MOV from CR8 reads only cause a VM-exit when the TPR shadow feature isn't enabled. */
15015 Assert( iCrReg != 8
15016 || !(pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_USE_TPR_SHADOW));
15017
15018 rcStrict = hmR0VmxExitMovFromCrX(pVCpu, pVmcsInfo, pVmxTransient->cbExitInstr, iGReg, iCrReg);
15019 break;
15020 }
15021
15022 /*
15023 * CLTS (Clear Task-Switch Flag in CR0).
15024 */
15025 case VMX_EXIT_QUAL_CRX_ACCESS_CLTS:
15026 {
15027 rcStrict = hmR0VmxExitClts(pVCpu, pVmcsInfo, pVmxTransient->cbExitInstr);
15028 break;
15029 }
15030
15031 /*
15032 * LMSW (Load Machine-Status Word into CR0).
15033 * LMSW cannot clear CR0.PE, so no fRealOnV86Active kludge needed here.
15034 */
15035 case VMX_EXIT_QUAL_CRX_ACCESS_LMSW:
15036 {
15037 RTGCPTR GCPtrEffDst;
15038 uint8_t const cbInstr = pVmxTransient->cbExitInstr;
15039 uint16_t const uMsw = VMX_EXIT_QUAL_CRX_LMSW_DATA(uExitQual);
15040 bool const fMemOperand = VMX_EXIT_QUAL_CRX_LMSW_OP_MEM(uExitQual);
15041 if (fMemOperand)
15042 {
15043 hmR0VmxReadGuestLinearAddrVmcs(pVmxTransient);
15044 GCPtrEffDst = pVmxTransient->uGuestLinearAddr;
15045 }
15046 else
15047 GCPtrEffDst = NIL_RTGCPTR;
15048 rcStrict = hmR0VmxExitLmsw(pVCpu, pVmcsInfo, cbInstr, uMsw, GCPtrEffDst);
15049 break;
15050 }
15051
15052 default:
15053 {
15054 AssertMsgFailed(("Unrecognized Mov CRX access type %#x\n", uAccessType));
15055 HMVMX_UNEXPECTED_EXIT_RET(pVCpu, uAccessType);
15056 }
15057 }
15058
15059 Assert((pVCpu->hm.s.fCtxChanged & (HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS))
15060 == (HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS));
15061 Assert(rcStrict != VINF_IEM_RAISED_XCPT);
15062
15063 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExitMovCRx, y2);
15064 NOREF(pVM);
15065 return rcStrict;
15066}
15067
15068
15069/**
15070 * VM-exit handler for I/O instructions (VMX_EXIT_IO_INSTR). Conditional
15071 * VM-exit.
15072 */
15073HMVMX_EXIT_DECL hmR0VmxExitIoInstr(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
15074{
15075 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
15076 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatExitIO, y1);
15077
15078 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
15079 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
15080 hmR0VmxReadExitQualVmcs(pVmxTransient);
15081 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
15082 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, IEM_CPUMCTX_EXTRN_MUST_MASK | CPUMCTX_EXTRN_SREG_MASK
15083 | CPUMCTX_EXTRN_EFER);
15084 /* EFER MSR also required for longmode checks in EMInterpretDisasCurrent(), but it's always up-to-date. */
15085 AssertRCReturn(rc, rc);
15086
15087 /* Refer Intel spec. 27-5. "Exit Qualifications for I/O Instructions" for the format. */
15088 uint32_t const uIOPort = VMX_EXIT_QUAL_IO_PORT(pVmxTransient->uExitQual);
15089 uint8_t const uIOSize = VMX_EXIT_QUAL_IO_SIZE(pVmxTransient->uExitQual);
15090 bool const fIOWrite = (VMX_EXIT_QUAL_IO_DIRECTION(pVmxTransient->uExitQual) == VMX_EXIT_QUAL_IO_DIRECTION_OUT);
15091 bool const fIOString = VMX_EXIT_QUAL_IO_IS_STRING(pVmxTransient->uExitQual);
15092 bool const fGstStepping = RT_BOOL(pCtx->eflags.Bits.u1TF);
15093 bool const fDbgStepping = pVCpu->hm.s.fSingleInstruction;
15094 AssertReturn(uIOSize <= 3 && uIOSize != 2, VERR_VMX_IPE_1);
15095
15096 /*
15097 * Update exit history to see if this exit can be optimized.
15098 */
15099 VBOXSTRICTRC rcStrict;
15100 PCEMEXITREC pExitRec = NULL;
15101 if ( !fGstStepping
15102 && !fDbgStepping)
15103 pExitRec = EMHistoryUpdateFlagsAndTypeAndPC(pVCpu,
15104 !fIOString
15105 ? !fIOWrite
15106 ? EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM | EMEXIT_F_HM, EMEXITTYPE_IO_PORT_READ)
15107 : EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM | EMEXIT_F_HM, EMEXITTYPE_IO_PORT_WRITE)
15108 : !fIOWrite
15109 ? EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM | EMEXIT_F_HM, EMEXITTYPE_IO_PORT_STR_READ)
15110 : EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM | EMEXIT_F_HM, EMEXITTYPE_IO_PORT_STR_WRITE),
15111 pVCpu->cpum.GstCtx.rip + pVCpu->cpum.GstCtx.cs.u64Base);
15112 if (!pExitRec)
15113 {
15114 static uint32_t const s_aIOSizes[4] = { 1, 2, 0, 4 }; /* Size of the I/O accesses in bytes. */
15115 static uint32_t const s_aIOOpAnd[4] = { 0xff, 0xffff, 0, 0xffffffff }; /* AND masks for saving result in AL/AX/EAX. */
15116
15117 uint32_t const cbValue = s_aIOSizes[uIOSize];
15118 uint32_t const cbInstr = pVmxTransient->cbExitInstr;
15119 bool fUpdateRipAlready = false; /* ugly hack, should be temporary. */
15120 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
15121 if (fIOString)
15122 {
15123 /*
15124 * INS/OUTS - I/O String instruction.
15125 *
15126 * Use instruction-information if available, otherwise fall back on
15127 * interpreting the instruction.
15128 */
15129 Log4Func(("cs:rip=%#04x:%#RX64 %#06x/%u %c str\n", pCtx->cs.Sel, pCtx->rip, uIOPort, cbValue, fIOWrite ? 'w' : 'r'));
15130 AssertReturn(pCtx->dx == uIOPort, VERR_VMX_IPE_2);
15131 bool const fInsOutsInfo = RT_BF_GET(pVM->hm.s.vmx.Msrs.u64Basic, VMX_BF_BASIC_VMCS_INS_OUTS);
15132 if (fInsOutsInfo)
15133 {
15134 hmR0VmxReadExitInstrInfoVmcs(pVmxTransient);
15135 AssertReturn(pVmxTransient->ExitInstrInfo.StrIo.u3AddrSize <= 2, VERR_VMX_IPE_3);
15136 AssertCompile(IEMMODE_16BIT == 0 && IEMMODE_32BIT == 1 && IEMMODE_64BIT == 2);
15137 IEMMODE const enmAddrMode = (IEMMODE)pVmxTransient->ExitInstrInfo.StrIo.u3AddrSize;
15138 bool const fRep = VMX_EXIT_QUAL_IO_IS_REP(pVmxTransient->uExitQual);
15139 if (fIOWrite)
15140 rcStrict = IEMExecStringIoWrite(pVCpu, cbValue, enmAddrMode, fRep, cbInstr,
15141 pVmxTransient->ExitInstrInfo.StrIo.iSegReg, true /*fIoChecked*/);
15142 else
15143 {
15144 /*
15145 * The segment prefix for INS cannot be overridden and is always ES. We can safely assume X86_SREG_ES.
15146 * Hence "iSegReg" field is undefined in the instruction-information field in VT-x for INS.
15147 * See Intel Instruction spec. for "INS".
15148 * See Intel spec. Table 27-8 "Format of the VM-Exit Instruction-Information Field as Used for INS and OUTS".
15149 */
15150 rcStrict = IEMExecStringIoRead(pVCpu, cbValue, enmAddrMode, fRep, cbInstr, true /*fIoChecked*/);
15151 }
15152 }
15153 else
15154 rcStrict = IEMExecOne(pVCpu);
15155
15156 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP);
15157 fUpdateRipAlready = true;
15158 }
15159 else
15160 {
15161 /*
15162 * IN/OUT - I/O instruction.
15163 */
15164 Log4Func(("cs:rip=%04x:%08RX64 %#06x/%u %c\n", pCtx->cs.Sel, pCtx->rip, uIOPort, cbValue, fIOWrite ? 'w' : 'r'));
15165 uint32_t const uAndVal = s_aIOOpAnd[uIOSize];
15166 Assert(!VMX_EXIT_QUAL_IO_IS_REP(pVmxTransient->uExitQual));
15167 if (fIOWrite)
15168 {
15169 rcStrict = IOMIOPortWrite(pVM, pVCpu, uIOPort, pCtx->eax & uAndVal, cbValue);
15170 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIOWrite);
15171 if ( rcStrict == VINF_IOM_R3_IOPORT_WRITE
15172 && !pCtx->eflags.Bits.u1TF)
15173 rcStrict = EMRZSetPendingIoPortWrite(pVCpu, uIOPort, cbInstr, cbValue, pCtx->eax & uAndVal);
15174 }
15175 else
15176 {
15177 uint32_t u32Result = 0;
15178 rcStrict = IOMIOPortRead(pVM, pVCpu, uIOPort, &u32Result, cbValue);
15179 if (IOM_SUCCESS(rcStrict))
15180 {
15181 /* Save result of I/O IN instr. in AL/AX/EAX. */
15182 pCtx->eax = (pCtx->eax & ~uAndVal) | (u32Result & uAndVal);
15183 }
15184 if ( rcStrict == VINF_IOM_R3_IOPORT_READ
15185 && !pCtx->eflags.Bits.u1TF)
15186 rcStrict = EMRZSetPendingIoPortRead(pVCpu, uIOPort, cbInstr, cbValue);
15187 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIORead);
15188 }
15189 }
15190
15191 if (IOM_SUCCESS(rcStrict))
15192 {
15193 if (!fUpdateRipAlready)
15194 {
15195 hmR0VmxAdvanceGuestRipBy(pVCpu, cbInstr);
15196 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP);
15197 }
15198
15199 /*
15200 * INS/OUTS with REP prefix updates RFLAGS, can be observed with triple-fault guru
15201 * while booting Fedora 17 64-bit guest.
15202 *
15203 * See Intel Instruction reference for REP/REPE/REPZ/REPNE/REPNZ.
15204 */
15205 if (fIOString)
15206 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RFLAGS);
15207
15208 /*
15209 * If any I/O breakpoints are armed, we need to check if one triggered
15210 * and take appropriate action.
15211 * Note that the I/O breakpoint type is undefined if CR4.DE is 0.
15212 */
15213 rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, CPUMCTX_EXTRN_DR7);
15214 AssertRCReturn(rc, rc);
15215
15216 /** @todo Optimize away the DBGFBpIsHwIoArmed call by having DBGF tell the
15217 * execution engines about whether hyper BPs and such are pending. */
15218 uint32_t const uDr7 = pCtx->dr[7];
15219 if (RT_UNLIKELY( ( (uDr7 & X86_DR7_ENABLED_MASK)
15220 && X86_DR7_ANY_RW_IO(uDr7)
15221 && (pCtx->cr4 & X86_CR4_DE))
15222 || DBGFBpIsHwIoArmed(pVM)))
15223 {
15224 STAM_COUNTER_INC(&pVCpu->hm.s.StatDRxIoCheck);
15225
15226 /* We're playing with the host CPU state here, make sure we don't preempt or longjmp. */
15227 VMMRZCallRing3Disable(pVCpu);
15228 HM_DISABLE_PREEMPT(pVCpu);
15229
15230 bool fIsGuestDbgActive = CPUMR0DebugStateMaybeSaveGuest(pVCpu, true /* fDr6 */);
15231
15232 VBOXSTRICTRC rcStrict2 = DBGFBpCheckIo(pVM, pVCpu, pCtx, uIOPort, cbValue);
15233 if (rcStrict2 == VINF_EM_RAW_GUEST_TRAP)
15234 {
15235 /* Raise #DB. */
15236 if (fIsGuestDbgActive)
15237 ASMSetDR6(pCtx->dr[6]);
15238 if (pCtx->dr[7] != uDr7)
15239 pVCpu->hm.s.fCtxChanged |= HM_CHANGED_GUEST_DR7;
15240
15241 hmR0VmxSetPendingXcptDB(pVCpu);
15242 }
15243 /* rcStrict is VINF_SUCCESS, VINF_IOM_R3_IOPORT_COMMIT_WRITE, or in [VINF_EM_FIRST..VINF_EM_LAST],
15244 however we can ditch VINF_IOM_R3_IOPORT_COMMIT_WRITE as it has VMCPU_FF_IOM as backup. */
15245 else if ( rcStrict2 != VINF_SUCCESS
15246 && (rcStrict == VINF_SUCCESS || rcStrict2 < rcStrict))
15247 rcStrict = rcStrict2;
15248 AssertCompile(VINF_EM_LAST < VINF_IOM_R3_IOPORT_COMMIT_WRITE);
15249
15250 HM_RESTORE_PREEMPT();
15251 VMMRZCallRing3Enable(pVCpu);
15252 }
15253 }
15254
15255#ifdef VBOX_STRICT
15256 if ( rcStrict == VINF_IOM_R3_IOPORT_READ
15257 || rcStrict == VINF_EM_PENDING_R3_IOPORT_READ)
15258 Assert(!fIOWrite);
15259 else if ( rcStrict == VINF_IOM_R3_IOPORT_WRITE
15260 || rcStrict == VINF_IOM_R3_IOPORT_COMMIT_WRITE
15261 || rcStrict == VINF_EM_PENDING_R3_IOPORT_WRITE)
15262 Assert(fIOWrite);
15263 else
15264 {
15265# if 0 /** @todo r=bird: This is missing a bunch of VINF_EM_FIRST..VINF_EM_LAST
15266 * statuses, that the VMM device and some others may return. See
15267 * IOM_SUCCESS() for guidance. */
15268 AssertMsg( RT_FAILURE(rcStrict)
15269 || rcStrict == VINF_SUCCESS
15270 || rcStrict == VINF_EM_RAW_EMULATE_INSTR
15271 || rcStrict == VINF_EM_DBG_BREAKPOINT
15272 || rcStrict == VINF_EM_RAW_GUEST_TRAP
15273 || rcStrict == VINF_EM_RAW_TO_R3
15274 || rcStrict == VINF_TRPM_XCPT_DISPATCHED, ("%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
15275# endif
15276 }
15277#endif
15278 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExitIO, y1);
15279 }
15280 else
15281 {
15282 /*
15283 * Frequent exit or something needing probing. Get state and call EMHistoryExec.
15284 */
15285 int rc2 = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, HMVMX_CPUMCTX_EXTRN_ALL);
15286 AssertRCReturn(rc2, rc2);
15287 STAM_COUNTER_INC(!fIOString ? fIOWrite ? &pVCpu->hm.s.StatExitIOWrite : &pVCpu->hm.s.StatExitIORead
15288 : fIOWrite ? &pVCpu->hm.s.StatExitIOStringWrite : &pVCpu->hm.s.StatExitIOStringRead);
15289 Log4(("IOExit/%u: %04x:%08RX64: %s%s%s %#x LB %u -> EMHistoryExec\n",
15290 pVCpu->idCpu, pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip,
15291 VMX_EXIT_QUAL_IO_IS_REP(pVmxTransient->uExitQual) ? "REP " : "",
15292 fIOWrite ? "OUT" : "IN", fIOString ? "S" : "", uIOPort, uIOSize));
15293
15294 rcStrict = EMHistoryExec(pVCpu, pExitRec, 0);
15295 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_ALL_GUEST);
15296
15297 Log4(("IOExit/%u: %04x:%08RX64: EMHistoryExec -> %Rrc + %04x:%08RX64\n",
15298 pVCpu->idCpu, pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip,
15299 VBOXSTRICTRC_VAL(rcStrict), pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip));
15300 }
15301 return rcStrict;
15302}
15303
15304
15305/**
15306 * VM-exit handler for task switches (VMX_EXIT_TASK_SWITCH). Unconditional
15307 * VM-exit.
15308 */
15309HMVMX_EXIT_DECL hmR0VmxExitTaskSwitch(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
15310{
15311 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
15312
15313 /* Check if this task-switch occurred while delivery an event through the guest IDT. */
15314 hmR0VmxReadExitQualVmcs(pVmxTransient);
15315 if (VMX_EXIT_QUAL_TASK_SWITCH_TYPE(pVmxTransient->uExitQual) == VMX_EXIT_QUAL_TASK_SWITCH_TYPE_IDT)
15316 {
15317 hmR0VmxReadIdtVectoringInfoVmcs(pVmxTransient);
15318 if (VMX_IDT_VECTORING_INFO_IS_VALID(pVmxTransient->uIdtVectoringInfo))
15319 {
15320 uint32_t uErrCode;
15321 if (VMX_IDT_VECTORING_INFO_IS_ERROR_CODE_VALID(pVmxTransient->uIdtVectoringInfo))
15322 {
15323 hmR0VmxReadIdtVectoringErrorCodeVmcs(pVmxTransient);
15324 uErrCode = pVmxTransient->uIdtVectoringErrorCode;
15325 }
15326 else
15327 uErrCode = 0;
15328
15329 RTGCUINTPTR GCPtrFaultAddress;
15330 if (VMX_IDT_VECTORING_INFO_IS_XCPT_PF(pVmxTransient->uIdtVectoringInfo))
15331 GCPtrFaultAddress = pVCpu->cpum.GstCtx.cr2;
15332 else
15333 GCPtrFaultAddress = 0;
15334
15335 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
15336
15337 hmR0VmxSetPendingEvent(pVCpu, VMX_ENTRY_INT_INFO_FROM_EXIT_IDT_INFO(pVmxTransient->uIdtVectoringInfo),
15338 pVmxTransient->cbExitInstr, uErrCode, GCPtrFaultAddress);
15339
15340 Log4Func(("Pending event. uIntType=%#x uVector=%#x\n", VMX_IDT_VECTORING_INFO_TYPE(pVmxTransient->uIdtVectoringInfo),
15341 VMX_IDT_VECTORING_INFO_VECTOR(pVmxTransient->uIdtVectoringInfo)));
15342 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitTaskSwitch);
15343 return VINF_EM_RAW_INJECT_TRPM_EVENT;
15344 }
15345 }
15346
15347 /* Fall back to the interpreter to emulate the task-switch. */
15348 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitTaskSwitch);
15349 return VERR_EM_INTERPRETER;
15350}
15351
15352
15353/**
15354 * VM-exit handler for monitor-trap-flag (VMX_EXIT_MTF). Conditional VM-exit.
15355 */
15356HMVMX_EXIT_DECL hmR0VmxExitMtf(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
15357{
15358 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
15359
15360 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
15361 pVmcsInfo->u32ProcCtls &= ~VMX_PROC_CTLS_MONITOR_TRAP_FLAG;
15362 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, pVmcsInfo->u32ProcCtls);
15363 AssertRC(rc);
15364 return VINF_EM_DBG_STEPPED;
15365}
15366
15367
15368/**
15369 * VM-exit handler for APIC access (VMX_EXIT_APIC_ACCESS). Conditional VM-exit.
15370 */
15371HMVMX_EXIT_DECL hmR0VmxExitApicAccess(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
15372{
15373 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
15374 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitApicAccess);
15375
15376 hmR0VmxReadExitIntInfoVmcs(pVmxTransient);
15377 hmR0VmxReadExitIntErrorCodeVmcs(pVmxTransient);
15378 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
15379 hmR0VmxReadIdtVectoringInfoVmcs(pVmxTransient);
15380 hmR0VmxReadIdtVectoringErrorCodeVmcs(pVmxTransient);
15381
15382 /*
15383 * If this VM-exit occurred while delivering an event through the guest IDT, handle it accordingly.
15384 */
15385 VBOXSTRICTRC rcStrict = hmR0VmxCheckExitDueToEventDelivery(pVCpu, pVmxTransient);
15386 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
15387 {
15388 /* For some crazy guest, if an event delivery causes an APIC-access VM-exit, go to instruction emulation. */
15389 if (RT_UNLIKELY(pVCpu->hm.s.Event.fPending))
15390 {
15391 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectInterpret);
15392 return VINF_EM_RAW_INJECT_TRPM_EVENT;
15393 }
15394 }
15395 else
15396 {
15397 Assert(rcStrict != VINF_HM_DOUBLE_FAULT);
15398 return rcStrict;
15399 }
15400
15401 /* IOMMIOPhysHandler() below may call into IEM, save the necessary state. */
15402 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
15403 hmR0VmxReadExitQualVmcs(pVmxTransient);
15404 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, IEM_CPUMCTX_EXTRN_MUST_MASK);
15405 AssertRCReturn(rc, rc);
15406
15407 /* See Intel spec. 27-6 "Exit Qualifications for APIC-access VM-exits from Linear Accesses & Guest-Phyiscal Addresses" */
15408 uint32_t const uAccessType = VMX_EXIT_QUAL_APIC_ACCESS_TYPE(pVmxTransient->uExitQual);
15409 switch (uAccessType)
15410 {
15411 case VMX_APIC_ACCESS_TYPE_LINEAR_WRITE:
15412 case VMX_APIC_ACCESS_TYPE_LINEAR_READ:
15413 {
15414 AssertMsg( !(pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_USE_TPR_SHADOW)
15415 || VMX_EXIT_QUAL_APIC_ACCESS_OFFSET(pVmxTransient->uExitQual) != XAPIC_OFF_TPR,
15416 ("hmR0VmxExitApicAccess: can't access TPR offset while using TPR shadowing.\n"));
15417
15418 RTGCPHYS GCPhys = pVCpu->hm.s.vmx.u64GstMsrApicBase; /* Always up-to-date, as it is not part of the VMCS. */
15419 GCPhys &= PAGE_BASE_GC_MASK;
15420 GCPhys += VMX_EXIT_QUAL_APIC_ACCESS_OFFSET(pVmxTransient->uExitQual);
15421 Log4Func(("Linear access uAccessType=%#x GCPhys=%#RGp Off=%#x\n", uAccessType, GCPhys,
15422 VMX_EXIT_QUAL_APIC_ACCESS_OFFSET(pVmxTransient->uExitQual)));
15423
15424 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
15425 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
15426 rcStrict = IOMMMIOPhysHandler(pVM, pVCpu,
15427 uAccessType == VMX_APIC_ACCESS_TYPE_LINEAR_READ ? 0 : X86_TRAP_PF_RW,
15428 CPUMCTX2CORE(pCtx), GCPhys);
15429 Log4Func(("IOMMMIOPhysHandler returned %Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
15430 if ( rcStrict == VINF_SUCCESS
15431 || rcStrict == VERR_PAGE_TABLE_NOT_PRESENT
15432 || rcStrict == VERR_PAGE_NOT_PRESENT)
15433 {
15434 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RSP | HM_CHANGED_GUEST_RFLAGS
15435 | HM_CHANGED_GUEST_APIC_TPR);
15436 rcStrict = VINF_SUCCESS;
15437 }
15438 break;
15439 }
15440
15441 default:
15442 {
15443 Log4Func(("uAccessType=%#x\n", uAccessType));
15444 rcStrict = VINF_EM_RAW_EMULATE_INSTR;
15445 break;
15446 }
15447 }
15448
15449 if (rcStrict != VINF_SUCCESS)
15450 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchApicAccessToR3);
15451 return rcStrict;
15452}
15453
15454
15455/**
15456 * VM-exit handler for debug-register accesses (VMX_EXIT_MOV_DRX). Conditional
15457 * VM-exit.
15458 */
15459HMVMX_EXIT_DECL hmR0VmxExitMovDRx(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
15460{
15461 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
15462 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
15463
15464 /* We might get this VM-exit if the nested-guest is not intercepting MOV DRx accesses. */
15465 if (!pVmxTransient->fIsNestedGuest)
15466 {
15467 /* We should -not- get this VM-exit if the guest's debug registers were active. */
15468 if (pVmxTransient->fWasGuestDebugStateActive)
15469 {
15470 AssertMsgFailed(("Unexpected MOV DRx exit\n"));
15471 HMVMX_UNEXPECTED_EXIT_RET(pVCpu, pVmxTransient->uExitReason);
15472 }
15473
15474 if ( !pVCpu->hm.s.fSingleInstruction
15475 && !pVmxTransient->fWasHyperDebugStateActive)
15476 {
15477 Assert(!DBGFIsStepping(pVCpu));
15478 Assert(pVmcsInfo->u32XcptBitmap & RT_BIT(X86_XCPT_DB));
15479
15480 /* Don't intercept MOV DRx any more. */
15481 pVmcsInfo->u32ProcCtls &= ~VMX_PROC_CTLS_MOV_DR_EXIT;
15482 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, pVmcsInfo->u32ProcCtls);
15483 AssertRC(rc);
15484
15485 /* We're playing with the host CPU state here, make sure we can't preempt or longjmp. */
15486 VMMRZCallRing3Disable(pVCpu);
15487 HM_DISABLE_PREEMPT(pVCpu);
15488
15489 /* Save the host & load the guest debug state, restart execution of the MOV DRx instruction. */
15490 CPUMR0LoadGuestDebugState(pVCpu, true /* include DR6 */);
15491 Assert(CPUMIsGuestDebugStateActive(pVCpu));
15492
15493 HM_RESTORE_PREEMPT();
15494 VMMRZCallRing3Enable(pVCpu);
15495
15496#ifdef VBOX_WITH_STATISTICS
15497 hmR0VmxReadExitQualVmcs(pVmxTransient);
15498 if (VMX_EXIT_QUAL_DRX_DIRECTION(pVmxTransient->uExitQual) == VMX_EXIT_QUAL_DRX_DIRECTION_WRITE)
15499 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitDRxWrite);
15500 else
15501 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitDRxRead);
15502#endif
15503 STAM_COUNTER_INC(&pVCpu->hm.s.StatDRxContextSwitch);
15504 return VINF_SUCCESS;
15505 }
15506 }
15507
15508 /*
15509 * EMInterpretDRx[Write|Read]() calls CPUMIsGuestIn64BitCode() which requires EFER MSR, CS.
15510 * The EFER MSR is always up-to-date.
15511 * Update the segment registers and DR7 from the CPU.
15512 */
15513 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
15514 hmR0VmxReadExitQualVmcs(pVmxTransient);
15515 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, CPUMCTX_EXTRN_SREG_MASK | CPUMCTX_EXTRN_DR7);
15516 AssertRCReturn(rc, rc);
15517 Log4Func(("cs:rip=%#04x:%#RX64\n", pCtx->cs.Sel, pCtx->rip));
15518
15519 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
15520 if (VMX_EXIT_QUAL_DRX_DIRECTION(pVmxTransient->uExitQual) == VMX_EXIT_QUAL_DRX_DIRECTION_WRITE)
15521 {
15522 rc = EMInterpretDRxWrite(pVM, pVCpu, CPUMCTX2CORE(pCtx),
15523 VMX_EXIT_QUAL_DRX_REGISTER(pVmxTransient->uExitQual),
15524 VMX_EXIT_QUAL_DRX_GENREG(pVmxTransient->uExitQual));
15525 if (RT_SUCCESS(rc))
15526 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_DR7);
15527 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitDRxWrite);
15528 }
15529 else
15530 {
15531 rc = EMInterpretDRxRead(pVM, pVCpu, CPUMCTX2CORE(pCtx),
15532 VMX_EXIT_QUAL_DRX_GENREG(pVmxTransient->uExitQual),
15533 VMX_EXIT_QUAL_DRX_REGISTER(pVmxTransient->uExitQual));
15534 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitDRxRead);
15535 }
15536
15537 Assert(rc == VINF_SUCCESS || rc == VERR_EM_INTERPRETER);
15538 if (RT_SUCCESS(rc))
15539 {
15540 int rc2 = hmR0VmxAdvanceGuestRip(pVCpu, pVmxTransient);
15541 AssertRCReturn(rc2, rc2);
15542 return VINF_SUCCESS;
15543 }
15544 return rc;
15545}
15546
15547
15548/**
15549 * VM-exit handler for EPT misconfiguration (VMX_EXIT_EPT_MISCONFIG).
15550 * Conditional VM-exit.
15551 */
15552HMVMX_EXIT_DECL hmR0VmxExitEptMisconfig(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
15553{
15554 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
15555 Assert(pVCpu->CTX_SUFF(pVM)->hm.s.fNestedPaging);
15556
15557 hmR0VmxReadExitIntInfoVmcs(pVmxTransient);
15558 hmR0VmxReadExitIntErrorCodeVmcs(pVmxTransient);
15559 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
15560 hmR0VmxReadIdtVectoringInfoVmcs(pVmxTransient);
15561 hmR0VmxReadIdtVectoringErrorCodeVmcs(pVmxTransient);
15562
15563 /*
15564 * If this VM-exit occurred while delivering an event through the guest IDT, handle it accordingly.
15565 */
15566 VBOXSTRICTRC rcStrict = hmR0VmxCheckExitDueToEventDelivery(pVCpu, pVmxTransient);
15567 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
15568 {
15569 /*
15570 * In the unlikely case where delivering an event causes an EPT misconfig (MMIO), go back to
15571 * instruction emulation to inject the original event. Otherwise, injecting the original event
15572 * using hardware-assisted VMX would would trigger the same EPT misconfig VM-exit again.
15573 */
15574 if (!pVCpu->hm.s.Event.fPending)
15575 { /* likely */ }
15576 else
15577 {
15578 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectInterpret);
15579#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
15580 /** @todo NSTVMX: Think about how this should be handled. */
15581 if (pVmxTransient->fIsNestedGuest)
15582 return VERR_VMX_IPE_3;
15583#endif
15584 return VINF_EM_RAW_INJECT_TRPM_EVENT;
15585 }
15586 }
15587 else
15588 {
15589 Assert(rcStrict != VINF_HM_DOUBLE_FAULT);
15590 return rcStrict;
15591 }
15592
15593 /*
15594 * Get sufficent state and update the exit history entry.
15595 */
15596 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
15597 hmR0VmxReadGuestPhysicalAddrVmcs(pVmxTransient);
15598 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, IEM_CPUMCTX_EXTRN_MUST_MASK);
15599 AssertRCReturn(rc, rc);
15600
15601 RTGCPHYS const GCPhys = pVmxTransient->uGuestPhysicalAddr;
15602 PCEMEXITREC pExitRec = EMHistoryUpdateFlagsAndTypeAndPC(pVCpu,
15603 EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM | EMEXIT_F_HM, EMEXITTYPE_MMIO),
15604 pVCpu->cpum.GstCtx.rip + pVCpu->cpum.GstCtx.cs.u64Base);
15605 if (!pExitRec)
15606 {
15607 /*
15608 * If we succeed, resume guest execution.
15609 * If we fail in interpreting the instruction because we couldn't get the guest physical address
15610 * of the page containing the instruction via the guest's page tables (we would invalidate the guest page
15611 * in the host TLB), resume execution which would cause a guest page fault to let the guest handle this
15612 * weird case. See @bugref{6043}.
15613 */
15614 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
15615 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
15616 rcStrict = PGMR0Trap0eHandlerNPMisconfig(pVM, pVCpu, PGMMODE_EPT, CPUMCTX2CORE(pCtx), GCPhys, UINT32_MAX);
15617 Log4Func(("At %#RGp RIP=%#RX64 rc=%Rrc\n", GCPhys, pCtx->rip, VBOXSTRICTRC_VAL(rcStrict)));
15618 if ( rcStrict == VINF_SUCCESS
15619 || rcStrict == VERR_PAGE_TABLE_NOT_PRESENT
15620 || rcStrict == VERR_PAGE_NOT_PRESENT)
15621 {
15622 /* Successfully handled MMIO operation. */
15623 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RSP | HM_CHANGED_GUEST_RFLAGS
15624 | HM_CHANGED_GUEST_APIC_TPR);
15625 rcStrict = VINF_SUCCESS;
15626 }
15627 }
15628 else
15629 {
15630 /*
15631 * Frequent exit or something needing probing. Call EMHistoryExec.
15632 */
15633 Log4(("EptMisscfgExit/%u: %04x:%08RX64: %RGp -> EMHistoryExec\n",
15634 pVCpu->idCpu, pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip, GCPhys));
15635
15636 rcStrict = EMHistoryExec(pVCpu, pExitRec, 0);
15637 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_ALL_GUEST);
15638
15639 Log4(("EptMisscfgExit/%u: %04x:%08RX64: EMHistoryExec -> %Rrc + %04x:%08RX64\n",
15640 pVCpu->idCpu, pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip,
15641 VBOXSTRICTRC_VAL(rcStrict), pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip));
15642 }
15643 return rcStrict;
15644}
15645
15646
15647/**
15648 * VM-exit handler for EPT violation (VMX_EXIT_EPT_VIOLATION). Conditional
15649 * VM-exit.
15650 */
15651HMVMX_EXIT_DECL hmR0VmxExitEptViolation(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
15652{
15653 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
15654 Assert(pVCpu->CTX_SUFF(pVM)->hm.s.fNestedPaging);
15655
15656 hmR0VmxReadExitQualVmcs(pVmxTransient);
15657 hmR0VmxReadExitIntInfoVmcs(pVmxTransient);
15658 hmR0VmxReadExitIntErrorCodeVmcs(pVmxTransient);
15659 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
15660 hmR0VmxReadIdtVectoringInfoVmcs(pVmxTransient);
15661 hmR0VmxReadIdtVectoringErrorCodeVmcs(pVmxTransient);
15662
15663 /*
15664 * If this VM-exit occurred while delivering an event through the guest IDT, handle it accordingly.
15665 */
15666 VBOXSTRICTRC rcStrict = hmR0VmxCheckExitDueToEventDelivery(pVCpu, pVmxTransient);
15667 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
15668 {
15669 /*
15670 * If delivery of an event causes an EPT violation (true nested #PF and not MMIO),
15671 * we shall resolve the nested #PF and re-inject the original event.
15672 */
15673 if (pVCpu->hm.s.Event.fPending)
15674 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectReflectNPF);
15675 }
15676 else
15677 {
15678 Assert(rcStrict != VINF_HM_DOUBLE_FAULT);
15679 return rcStrict;
15680 }
15681
15682 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
15683 hmR0VmxReadGuestPhysicalAddrVmcs(pVmxTransient);
15684 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, IEM_CPUMCTX_EXTRN_MUST_MASK);
15685 AssertRCReturn(rc, rc);
15686
15687 RTGCPHYS const GCPhys = pVmxTransient->uGuestPhysicalAddr;
15688 uint64_t const uExitQual = pVmxTransient->uExitQual;
15689 AssertMsg(((pVmxTransient->uExitQual >> 7) & 3) != 2, ("%#RX64", uExitQual));
15690
15691 RTGCUINT uErrorCode = 0;
15692 if (uExitQual & VMX_EXIT_QUAL_EPT_INSTR_FETCH)
15693 uErrorCode |= X86_TRAP_PF_ID;
15694 if (uExitQual & VMX_EXIT_QUAL_EPT_DATA_WRITE)
15695 uErrorCode |= X86_TRAP_PF_RW;
15696 if (uExitQual & VMX_EXIT_QUAL_EPT_ENTRY_PRESENT)
15697 uErrorCode |= X86_TRAP_PF_P;
15698
15699 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
15700 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
15701 Log4Func(("at %#RX64 (%#RX64 errcode=%#x) cs:rip=%#04x:%#RX64\n", GCPhys, uExitQual, uErrorCode, pCtx->cs.Sel, pCtx->rip));
15702
15703 /*
15704 * Handle the pagefault trap for the nested shadow table.
15705 */
15706 TRPMAssertXcptPF(pVCpu, GCPhys, uErrorCode);
15707 rcStrict = PGMR0Trap0eHandlerNestedPaging(pVM, pVCpu, PGMMODE_EPT, uErrorCode, CPUMCTX2CORE(pCtx), GCPhys);
15708 TRPMResetTrap(pVCpu);
15709
15710 /* Same case as PGMR0Trap0eHandlerNPMisconfig(). See comment above, @bugref{6043}. */
15711 if ( rcStrict == VINF_SUCCESS
15712 || rcStrict == VERR_PAGE_TABLE_NOT_PRESENT
15713 || rcStrict == VERR_PAGE_NOT_PRESENT)
15714 {
15715 /* Successfully synced our nested page tables. */
15716 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitReasonNpf);
15717 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RSP | HM_CHANGED_GUEST_RFLAGS);
15718 return VINF_SUCCESS;
15719 }
15720
15721 Log4Func(("EPT return to ring-3 rcStrict2=%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
15722 return rcStrict;
15723}
15724
15725
15726#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
15727/**
15728 * VM-exit handler for VMCLEAR (VMX_EXIT_VMCLEAR). Unconditional VM-exit.
15729 */
15730HMVMX_EXIT_DECL hmR0VmxExitVmclear(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
15731{
15732 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
15733
15734 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
15735 hmR0VmxReadExitInstrInfoVmcs(pVmxTransient);
15736 hmR0VmxReadExitQualVmcs(pVmxTransient);
15737 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, CPUMCTX_EXTRN_RSP | CPUMCTX_EXTRN_SREG_MASK
15738 | CPUMCTX_EXTRN_HWVIRT
15739 | IEM_CPUMCTX_EXTRN_EXEC_DECODED_MEM_MASK);
15740 AssertRCReturn(rc, rc);
15741
15742 HMVMX_CHECK_EXIT_DUE_TO_VMX_INSTR(pVCpu, pVmxTransient->uExitReason);
15743
15744 VMXVEXITINFO ExitInfo;
15745 RT_ZERO(ExitInfo);
15746 ExitInfo.uReason = pVmxTransient->uExitReason;
15747 ExitInfo.u64Qual = pVmxTransient->uExitQual;
15748 ExitInfo.InstrInfo.u = pVmxTransient->ExitInstrInfo.u;
15749 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
15750 HMVMX_DECODE_MEM_OPERAND(pVCpu, ExitInfo.InstrInfo.u, ExitInfo.u64Qual, VMXMEMACCESS_READ, &ExitInfo.GCPtrEffAddr);
15751
15752 VBOXSTRICTRC rcStrict = IEMExecDecodedVmclear(pVCpu, &ExitInfo);
15753 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
15754 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS | HM_CHANGED_GUEST_HWVIRT);
15755 else if (rcStrict == VINF_IEM_RAISED_XCPT)
15756 {
15757 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
15758 rcStrict = VINF_SUCCESS;
15759 }
15760 return rcStrict;
15761}
15762
15763
15764/**
15765 * VM-exit handler for VMLAUNCH (VMX_EXIT_VMLAUNCH). Unconditional VM-exit.
15766 */
15767HMVMX_EXIT_DECL hmR0VmxExitVmlaunch(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
15768{
15769 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
15770
15771 /* Import the entire VMCS state for now as we would be switching VMCS on successful VMLAUNCH,
15772 otherwise we could import just IEM_CPUMCTX_EXTRN_VMX_VMENTRY_MASK. */
15773 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
15774 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, HMVMX_CPUMCTX_EXTRN_ALL);
15775 AssertRCReturn(rc, rc);
15776
15777 HMVMX_CHECK_EXIT_DUE_TO_VMX_INSTR(pVCpu, pVmxTransient->uExitReason);
15778
15779 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatExitVmentry, z);
15780 VBOXSTRICTRC rcStrict = IEMExecDecodedVmlaunchVmresume(pVCpu, pVmxTransient->cbExitInstr, VMXINSTRID_VMLAUNCH);
15781 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExitVmentry, z);
15782 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
15783 {
15784 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_ALL_GUEST);
15785 if (CPUMIsGuestInVmxNonRootMode(&pVCpu->cpum.GstCtx))
15786 rcStrict = VINF_VMX_VMLAUNCH_VMRESUME;
15787 }
15788 Assert(rcStrict != VINF_IEM_RAISED_XCPT);
15789 return rcStrict;
15790}
15791
15792
15793/**
15794 * VM-exit handler for VMPTRLD (VMX_EXIT_VMPTRLD). Unconditional VM-exit.
15795 */
15796HMVMX_EXIT_DECL hmR0VmxExitVmptrld(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
15797{
15798 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
15799
15800 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
15801 hmR0VmxReadExitInstrInfoVmcs(pVmxTransient);
15802 hmR0VmxReadExitQualVmcs(pVmxTransient);
15803 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, CPUMCTX_EXTRN_RSP | CPUMCTX_EXTRN_SREG_MASK
15804 | CPUMCTX_EXTRN_HWVIRT
15805 | IEM_CPUMCTX_EXTRN_EXEC_DECODED_MEM_MASK);
15806 AssertRCReturn(rc, rc);
15807
15808 HMVMX_CHECK_EXIT_DUE_TO_VMX_INSTR(pVCpu, pVmxTransient->uExitReason);
15809
15810 VMXVEXITINFO ExitInfo;
15811 RT_ZERO(ExitInfo);
15812 ExitInfo.uReason = pVmxTransient->uExitReason;
15813 ExitInfo.u64Qual = pVmxTransient->uExitQual;
15814 ExitInfo.InstrInfo.u = pVmxTransient->ExitInstrInfo.u;
15815 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
15816 HMVMX_DECODE_MEM_OPERAND(pVCpu, ExitInfo.InstrInfo.u, ExitInfo.u64Qual, VMXMEMACCESS_READ, &ExitInfo.GCPtrEffAddr);
15817
15818 VBOXSTRICTRC rcStrict = IEMExecDecodedVmptrld(pVCpu, &ExitInfo);
15819 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
15820 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS | HM_CHANGED_GUEST_HWVIRT);
15821 else if (rcStrict == VINF_IEM_RAISED_XCPT)
15822 {
15823 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
15824 rcStrict = VINF_SUCCESS;
15825 }
15826 return rcStrict;
15827}
15828
15829
15830/**
15831 * VM-exit handler for VMPTRST (VMX_EXIT_VMPTRST). Unconditional VM-exit.
15832 */
15833HMVMX_EXIT_DECL hmR0VmxExitVmptrst(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
15834{
15835 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
15836
15837 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
15838 hmR0VmxReadExitInstrInfoVmcs(pVmxTransient);
15839 hmR0VmxReadExitQualVmcs(pVmxTransient);
15840 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, CPUMCTX_EXTRN_RSP | CPUMCTX_EXTRN_SREG_MASK
15841 | CPUMCTX_EXTRN_HWVIRT
15842 | IEM_CPUMCTX_EXTRN_EXEC_DECODED_MEM_MASK);
15843 AssertRCReturn(rc, rc);
15844
15845 HMVMX_CHECK_EXIT_DUE_TO_VMX_INSTR(pVCpu, pVmxTransient->uExitReason);
15846
15847 VMXVEXITINFO ExitInfo;
15848 RT_ZERO(ExitInfo);
15849 ExitInfo.uReason = pVmxTransient->uExitReason;
15850 ExitInfo.u64Qual = pVmxTransient->uExitQual;
15851 ExitInfo.InstrInfo.u = pVmxTransient->ExitInstrInfo.u;
15852 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
15853 HMVMX_DECODE_MEM_OPERAND(pVCpu, ExitInfo.InstrInfo.u, ExitInfo.u64Qual, VMXMEMACCESS_WRITE, &ExitInfo.GCPtrEffAddr);
15854
15855 VBOXSTRICTRC rcStrict = IEMExecDecodedVmptrst(pVCpu, &ExitInfo);
15856 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
15857 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS);
15858 else if (rcStrict == VINF_IEM_RAISED_XCPT)
15859 {
15860 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
15861 rcStrict = VINF_SUCCESS;
15862 }
15863 return rcStrict;
15864}
15865
15866
15867/**
15868 * VM-exit handler for VMREAD (VMX_EXIT_VMREAD). Conditional VM-exit.
15869 */
15870HMVMX_EXIT_DECL hmR0VmxExitVmread(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
15871{
15872 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
15873
15874 /*
15875 * Strictly speaking we should not get VMREAD VM-exits for shadow VMCS fields and
15876 * thus might not need to import the shadow VMCS state, it's safer just in case
15877 * code elsewhere dares look at unsynced VMCS fields.
15878 */
15879 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
15880 hmR0VmxReadExitInstrInfoVmcs(pVmxTransient);
15881 hmR0VmxReadExitQualVmcs(pVmxTransient);
15882 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, CPUMCTX_EXTRN_RSP | CPUMCTX_EXTRN_SREG_MASK
15883 | CPUMCTX_EXTRN_HWVIRT
15884 | IEM_CPUMCTX_EXTRN_EXEC_DECODED_MEM_MASK);
15885 AssertRCReturn(rc, rc);
15886
15887 HMVMX_CHECK_EXIT_DUE_TO_VMX_INSTR(pVCpu, pVmxTransient->uExitReason);
15888
15889 VMXVEXITINFO ExitInfo;
15890 RT_ZERO(ExitInfo);
15891 ExitInfo.uReason = pVmxTransient->uExitReason;
15892 ExitInfo.u64Qual = pVmxTransient->uExitQual;
15893 ExitInfo.InstrInfo.u = pVmxTransient->ExitInstrInfo.u;
15894 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
15895 if (!ExitInfo.InstrInfo.VmreadVmwrite.fIsRegOperand)
15896 HMVMX_DECODE_MEM_OPERAND(pVCpu, ExitInfo.InstrInfo.u, ExitInfo.u64Qual, VMXMEMACCESS_WRITE, &ExitInfo.GCPtrEffAddr);
15897
15898 VBOXSTRICTRC rcStrict = IEMExecDecodedVmread(pVCpu, &ExitInfo);
15899 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
15900 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS);
15901 else if (rcStrict == VINF_IEM_RAISED_XCPT)
15902 {
15903 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
15904 rcStrict = VINF_SUCCESS;
15905 }
15906 return rcStrict;
15907}
15908
15909
15910/**
15911 * VM-exit handler for VMRESUME (VMX_EXIT_VMRESUME). Unconditional VM-exit.
15912 */
15913HMVMX_EXIT_DECL hmR0VmxExitVmresume(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
15914{
15915 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
15916
15917 /* Import the entire VMCS state for now as we would be switching VMCS on successful VMRESUME,
15918 otherwise we could import just IEM_CPUMCTX_EXTRN_VMX_VMENTRY_MASK. */
15919 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
15920 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, HMVMX_CPUMCTX_EXTRN_ALL);
15921 AssertRCReturn(rc, rc);
15922
15923 HMVMX_CHECK_EXIT_DUE_TO_VMX_INSTR(pVCpu, pVmxTransient->uExitReason);
15924
15925 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatExitVmentry, z);
15926 VBOXSTRICTRC rcStrict = IEMExecDecodedVmlaunchVmresume(pVCpu, pVmxTransient->cbExitInstr, VMXINSTRID_VMRESUME);
15927 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExitVmentry, z);
15928 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
15929 {
15930 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_ALL_GUEST);
15931 if (CPUMIsGuestInVmxNonRootMode(&pVCpu->cpum.GstCtx))
15932 rcStrict = VINF_VMX_VMLAUNCH_VMRESUME;
15933 }
15934 Assert(rcStrict != VINF_IEM_RAISED_XCPT);
15935 return rcStrict;
15936}
15937
15938
15939/**
15940 * VM-exit handler for VMWRITE (VMX_EXIT_VMWRITE). Conditional VM-exit.
15941 */
15942HMVMX_EXIT_DECL hmR0VmxExitVmwrite(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
15943{
15944 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
15945
15946 /*
15947 * Although we should not get VMWRITE VM-exits for shadow VMCS fields, since our HM hook
15948 * gets invoked when IEM's VMWRITE instruction emulation modifies the current VMCS and it
15949 * flags re-loading the entire shadow VMCS, we should save the entire shadow VMCS here.
15950 */
15951 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
15952 hmR0VmxReadExitInstrInfoVmcs(pVmxTransient);
15953 hmR0VmxReadExitQualVmcs(pVmxTransient);
15954 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, CPUMCTX_EXTRN_RSP | CPUMCTX_EXTRN_SREG_MASK
15955 | CPUMCTX_EXTRN_HWVIRT
15956 | IEM_CPUMCTX_EXTRN_EXEC_DECODED_MEM_MASK);
15957 AssertRCReturn(rc, rc);
15958
15959 HMVMX_CHECK_EXIT_DUE_TO_VMX_INSTR(pVCpu, pVmxTransient->uExitReason);
15960
15961 VMXVEXITINFO ExitInfo;
15962 RT_ZERO(ExitInfo);
15963 ExitInfo.uReason = pVmxTransient->uExitReason;
15964 ExitInfo.u64Qual = pVmxTransient->uExitQual;
15965 ExitInfo.InstrInfo.u = pVmxTransient->ExitInstrInfo.u;
15966 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
15967 if (!ExitInfo.InstrInfo.VmreadVmwrite.fIsRegOperand)
15968 HMVMX_DECODE_MEM_OPERAND(pVCpu, ExitInfo.InstrInfo.u, ExitInfo.u64Qual, VMXMEMACCESS_READ, &ExitInfo.GCPtrEffAddr);
15969
15970 VBOXSTRICTRC rcStrict = IEMExecDecodedVmwrite(pVCpu, &ExitInfo);
15971 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
15972 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS | HM_CHANGED_GUEST_HWVIRT);
15973 else if (rcStrict == VINF_IEM_RAISED_XCPT)
15974 {
15975 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
15976 rcStrict = VINF_SUCCESS;
15977 }
15978 return rcStrict;
15979}
15980
15981
15982/**
15983 * VM-exit handler for VMXOFF (VMX_EXIT_VMXOFF). Unconditional VM-exit.
15984 */
15985HMVMX_EXIT_DECL hmR0VmxExitVmxoff(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
15986{
15987 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
15988
15989 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
15990 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, CPUMCTX_EXTRN_CR4
15991 | CPUMCTX_EXTRN_HWVIRT
15992 | IEM_CPUMCTX_EXTRN_EXEC_DECODED_NO_MEM_MASK);
15993 AssertRCReturn(rc, rc);
15994
15995 HMVMX_CHECK_EXIT_DUE_TO_VMX_INSTR(pVCpu, pVmxTransient->uExitReason);
15996
15997 VBOXSTRICTRC rcStrict = IEMExecDecodedVmxoff(pVCpu, pVmxTransient->cbExitInstr);
15998 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
15999 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_HWVIRT);
16000 else if (rcStrict == VINF_IEM_RAISED_XCPT)
16001 {
16002 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
16003 rcStrict = VINF_SUCCESS;
16004 }
16005 return rcStrict;
16006}
16007
16008
16009/**
16010 * VM-exit handler for VMXON (VMX_EXIT_VMXON). Unconditional VM-exit.
16011 */
16012HMVMX_EXIT_DECL hmR0VmxExitVmxon(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16013{
16014 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16015
16016 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16017 hmR0VmxReadExitInstrInfoVmcs(pVmxTransient);
16018 hmR0VmxReadExitQualVmcs(pVmxTransient);
16019 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, CPUMCTX_EXTRN_RSP | CPUMCTX_EXTRN_SREG_MASK
16020 | CPUMCTX_EXTRN_HWVIRT
16021 | IEM_CPUMCTX_EXTRN_EXEC_DECODED_MEM_MASK);
16022 AssertRCReturn(rc, rc);
16023
16024 HMVMX_CHECK_EXIT_DUE_TO_VMX_INSTR(pVCpu, pVmxTransient->uExitReason);
16025
16026 VMXVEXITINFO ExitInfo;
16027 RT_ZERO(ExitInfo);
16028 ExitInfo.uReason = pVmxTransient->uExitReason;
16029 ExitInfo.u64Qual = pVmxTransient->uExitQual;
16030 ExitInfo.InstrInfo.u = pVmxTransient->ExitInstrInfo.u;
16031 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
16032 HMVMX_DECODE_MEM_OPERAND(pVCpu, ExitInfo.InstrInfo.u, ExitInfo.u64Qual, VMXMEMACCESS_READ, &ExitInfo.GCPtrEffAddr);
16033
16034 VBOXSTRICTRC rcStrict = IEMExecDecodedVmxon(pVCpu, &ExitInfo);
16035 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
16036 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS | HM_CHANGED_GUEST_HWVIRT);
16037 else if (rcStrict == VINF_IEM_RAISED_XCPT)
16038 {
16039 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
16040 rcStrict = VINF_SUCCESS;
16041 }
16042 return rcStrict;
16043}
16044
16045
16046/**
16047 * VM-exit handler for INVVPID (VMX_EXIT_INVVPID). Unconditional VM-exit.
16048 */
16049HMVMX_EXIT_DECL hmR0VmxExitInvvpid(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16050{
16051 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16052
16053 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16054 hmR0VmxReadExitInstrInfoVmcs(pVmxTransient);
16055 hmR0VmxReadExitQualVmcs(pVmxTransient);
16056 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, CPUMCTX_EXTRN_RSP | CPUMCTX_EXTRN_SREG_MASK
16057 | IEM_CPUMCTX_EXTRN_EXEC_DECODED_MEM_MASK);
16058 AssertRCReturn(rc, rc);
16059
16060 HMVMX_CHECK_EXIT_DUE_TO_VMX_INSTR(pVCpu, pVmxTransient->uExitReason);
16061
16062 VMXVEXITINFO ExitInfo;
16063 RT_ZERO(ExitInfo);
16064 ExitInfo.uReason = pVmxTransient->uExitReason;
16065 ExitInfo.u64Qual = pVmxTransient->uExitQual;
16066 ExitInfo.InstrInfo.u = pVmxTransient->ExitInstrInfo.u;
16067 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
16068 HMVMX_DECODE_MEM_OPERAND(pVCpu, ExitInfo.InstrInfo.u, ExitInfo.u64Qual, VMXMEMACCESS_READ, &ExitInfo.GCPtrEffAddr);
16069
16070 VBOXSTRICTRC rcStrict = IEMExecDecodedInvvpid(pVCpu, &ExitInfo);
16071 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
16072 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS);
16073 else if (rcStrict == VINF_IEM_RAISED_XCPT)
16074 {
16075 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
16076 rcStrict = VINF_SUCCESS;
16077 }
16078 return rcStrict;
16079}
16080#endif /* VBOX_WITH_NESTED_HWVIRT_VMX */
16081/** @} */
16082
16083
16084#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
16085/** @name Nested-guest VM-exit handlers.
16086 * @{
16087 */
16088/* -=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= */
16089/* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- Nested-guest VM-exit handlers -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= */
16090/* -=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= */
16091
16092/**
16093 * Nested-guest VM-exit handler for exceptions or NMIs (VMX_EXIT_XCPT_OR_NMI).
16094 * Conditional VM-exit.
16095 */
16096HMVMX_EXIT_DECL hmR0VmxExitXcptOrNmiNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16097{
16098 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16099
16100 hmR0VmxReadExitIntInfoVmcs(pVmxTransient);
16101
16102 uint64_t const uExitIntInfo = pVmxTransient->uExitIntInfo;
16103 uint32_t const uExitIntType = VMX_EXIT_INT_INFO_TYPE(uExitIntInfo);
16104 Assert(VMX_EXIT_INT_INFO_IS_VALID(uExitIntInfo));
16105
16106 switch (uExitIntType)
16107 {
16108 /*
16109 * Physical NMIs:
16110 * We shouldn't direct host physical NMIs to the nested-guest. Dispatch it to the host.
16111 */
16112 case VMX_EXIT_INT_INFO_TYPE_NMI:
16113 return hmR0VmxExitHostNmi(pVCpu, pVmxTransient->pVmcsInfo);
16114
16115 /*
16116 * Hardware exceptions,
16117 * Software exceptions,
16118 * Privileged software exceptions:
16119 * Figure out if the exception must be delivered to the guest or the nested-guest.
16120 */
16121 case VMX_EXIT_INT_INFO_TYPE_SW_XCPT:
16122 case VMX_EXIT_INT_INFO_TYPE_PRIV_SW_XCPT:
16123 case VMX_EXIT_INT_INFO_TYPE_HW_XCPT:
16124 {
16125 hmR0VmxReadExitIntErrorCodeVmcs(pVmxTransient);
16126 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16127 hmR0VmxReadIdtVectoringInfoVmcs(pVmxTransient);
16128 hmR0VmxReadIdtVectoringErrorCodeVmcs(pVmxTransient);
16129
16130 PCCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
16131 bool const fIntercept = CPUMIsGuestVmxXcptInterceptSet(pVCpu, pCtx, VMX_EXIT_INT_INFO_VECTOR(uExitIntInfo),
16132 pVmxTransient->uExitIntErrorCode);
16133 if (fIntercept)
16134 {
16135 /* Exit qualification is required for debug and page-fault exceptions. */
16136 hmR0VmxReadExitQualVmcs(pVmxTransient);
16137
16138 /*
16139 * For VM-exits due to software exceptions (those generated by INT3 or INTO) and privileged
16140 * software exceptions (those generated by INT1/ICEBP) we need to supply the VM-exit instruction
16141 * length. However, if delivery of a software interrupt, software exception or privileged
16142 * software exception causes a VM-exit, that too provides the VM-exit instruction length.
16143 */
16144 VMXVEXITINFO ExitInfo;
16145 RT_ZERO(ExitInfo);
16146 ExitInfo.uReason = pVmxTransient->uExitReason;
16147 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
16148 ExitInfo.u64Qual = pVmxTransient->uExitQual;
16149
16150 VMXVEXITEVENTINFO ExitEventInfo;
16151 RT_ZERO(ExitEventInfo);
16152 ExitEventInfo.uExitIntInfo = pVmxTransient->uExitIntInfo;
16153 ExitEventInfo.uExitIntErrCode = pVmxTransient->uExitIntErrorCode;
16154 ExitEventInfo.uIdtVectoringInfo = pVmxTransient->uIdtVectoringInfo;
16155 ExitEventInfo.uIdtVectoringErrCode = pVmxTransient->uIdtVectoringErrorCode;
16156
16157#ifdef DEBUG_ramshankar
16158 hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, HMVMX_CPUMCTX_EXTRN_ALL);
16159 Log4Func(("exit_int_info=%#RX32 err_code=%#RX32 exit_qual=%#RX64\n", pVmxTransient->uExitIntInfo,
16160 pVmxTransient->uExitIntErrorCode, pVmxTransient->uExitQual));
16161 if (VMX_IDT_VECTORING_INFO_IS_VALID(pVmxTransient->uIdtVectoringInfo))
16162 {
16163 Log4Func(("idt_info=%#RX32 idt_errcode=%#RX32 cr2=%#RX64\n", pVmxTransient->uIdtVectoringInfo,
16164 pVmxTransient->uIdtVectoringErrorCode, pCtx->cr2));
16165 }
16166#endif
16167 return IEMExecVmxVmexitXcpt(pVCpu, &ExitInfo, &ExitEventInfo);
16168 }
16169
16170 /* Nested paging is currently a requirement, otherwise we would need to handle shadow #PFs in hmR0VmxExitXcptPF. */
16171 Assert(pVCpu->CTX_SUFF(pVM)->hm.s.fNestedPaging);
16172 return hmR0VmxExitXcpt(pVCpu, pVmxTransient);
16173 }
16174
16175 /*
16176 * Software interrupts:
16177 * VM-exits cannot be caused by software interrupts.
16178 *
16179 * External interrupts:
16180 * This should only happen when "acknowledge external interrupts on VM-exit"
16181 * control is set. However, we never set this when executing a guest or
16182 * nested-guest. For nested-guests it is emulated while injecting interrupts into
16183 * the guest.
16184 */
16185 case VMX_EXIT_INT_INFO_TYPE_SW_INT:
16186 case VMX_EXIT_INT_INFO_TYPE_EXT_INT:
16187 default:
16188 {
16189 pVCpu->hm.s.u32HMError = pVmxTransient->uExitIntInfo;
16190 return VERR_VMX_UNEXPECTED_INTERRUPTION_EXIT_TYPE;
16191 }
16192 }
16193}
16194
16195
16196/**
16197 * Nested-guest VM-exit handler for triple faults (VMX_EXIT_TRIPLE_FAULT).
16198 * Unconditional VM-exit.
16199 */
16200HMVMX_EXIT_DECL hmR0VmxExitTripleFaultNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16201{
16202 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16203 return IEMExecVmxVmexitTripleFault(pVCpu);
16204}
16205
16206
16207/**
16208 * Nested-guest VM-exit handler for interrupt-window exiting (VMX_EXIT_INT_WINDOW).
16209 */
16210HMVMX_EXIT_NSRC_DECL hmR0VmxExitIntWindowNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16211{
16212 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16213
16214 if (CPUMIsGuestVmxProcCtlsSet(pVCpu, &pVCpu->cpum.GstCtx, VMX_PROC_CTLS_INT_WINDOW_EXIT))
16215 return IEMExecVmxVmexit(pVCpu, pVmxTransient->uExitReason, 0 /* uExitQual */);
16216 return hmR0VmxExitIntWindow(pVCpu, pVmxTransient);
16217}
16218
16219
16220/**
16221 * Nested-guest VM-exit handler for NMI-window exiting (VMX_EXIT_NMI_WINDOW).
16222 */
16223HMVMX_EXIT_NSRC_DECL hmR0VmxExitNmiWindowNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16224{
16225 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16226
16227 if (CPUMIsGuestVmxProcCtlsSet(pVCpu, &pVCpu->cpum.GstCtx, VMX_PROC_CTLS_NMI_WINDOW_EXIT))
16228 return IEMExecVmxVmexit(pVCpu, pVmxTransient->uExitReason, 0 /* uExitQual */);
16229 return hmR0VmxExitIntWindow(pVCpu, pVmxTransient);
16230}
16231
16232
16233/**
16234 * Nested-guest VM-exit handler for task switches (VMX_EXIT_TASK_SWITCH).
16235 * Unconditional VM-exit.
16236 */
16237HMVMX_EXIT_DECL hmR0VmxExitTaskSwitchNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16238{
16239 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16240
16241 hmR0VmxReadExitQualVmcs(pVmxTransient);
16242 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16243 hmR0VmxReadIdtVectoringInfoVmcs(pVmxTransient);
16244 hmR0VmxReadIdtVectoringErrorCodeVmcs(pVmxTransient);
16245
16246 VMXVEXITINFO ExitInfo;
16247 RT_ZERO(ExitInfo);
16248 ExitInfo.uReason = pVmxTransient->uExitReason;
16249 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
16250 ExitInfo.u64Qual = pVmxTransient->uExitQual;
16251
16252 VMXVEXITEVENTINFO ExitEventInfo;
16253 RT_ZERO(ExitEventInfo);
16254 ExitEventInfo.uIdtVectoringInfo = pVmxTransient->uIdtVectoringInfo;
16255 ExitEventInfo.uIdtVectoringErrCode = pVmxTransient->uIdtVectoringErrorCode;
16256 return IEMExecVmxVmexitTaskSwitch(pVCpu, &ExitInfo, &ExitEventInfo);
16257}
16258
16259
16260/**
16261 * Nested-guest VM-exit handler for HLT (VMX_EXIT_HLT). Conditional VM-exit.
16262 */
16263HMVMX_EXIT_DECL hmR0VmxExitHltNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16264{
16265 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16266
16267 if (CPUMIsGuestVmxProcCtlsSet(pVCpu, &pVCpu->cpum.GstCtx, VMX_PROC_CTLS_HLT_EXIT))
16268 {
16269 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16270 return IEMExecVmxVmexitInstr(pVCpu, pVmxTransient->uExitReason, pVmxTransient->cbExitInstr);
16271 }
16272 return hmR0VmxExitHlt(pVCpu, pVmxTransient);
16273}
16274
16275
16276/**
16277 * Nested-guest VM-exit handler for INVLPG (VMX_EXIT_INVLPG). Conditional VM-exit.
16278 */
16279HMVMX_EXIT_DECL hmR0VmxExitInvlpgNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16280{
16281 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16282
16283 if (CPUMIsGuestVmxProcCtlsSet(pVCpu, &pVCpu->cpum.GstCtx, VMX_PROC_CTLS_INVLPG_EXIT))
16284 {
16285 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16286 hmR0VmxReadExitQualVmcs(pVmxTransient);
16287
16288 VMXVEXITINFO ExitInfo;
16289 RT_ZERO(ExitInfo);
16290 ExitInfo.uReason = pVmxTransient->uExitReason;
16291 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
16292 ExitInfo.u64Qual = pVmxTransient->uExitQual;
16293 return IEMExecVmxVmexitInstrWithInfo(pVCpu, &ExitInfo);
16294 }
16295 return hmR0VmxExitInvlpg(pVCpu, pVmxTransient);
16296}
16297
16298
16299/**
16300 * Nested-guest VM-exit handler for RDPMC (VMX_EXIT_RDPMC). Conditional VM-exit.
16301 */
16302HMVMX_EXIT_DECL hmR0VmxExitRdpmcNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16303{
16304 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16305
16306 if (CPUMIsGuestVmxProcCtlsSet(pVCpu, &pVCpu->cpum.GstCtx, VMX_PROC_CTLS_RDPMC_EXIT))
16307 {
16308 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16309 return IEMExecVmxVmexitInstr(pVCpu, pVmxTransient->uExitReason, pVmxTransient->cbExitInstr);
16310 }
16311 return hmR0VmxExitRdpmc(pVCpu, pVmxTransient);
16312}
16313
16314
16315/**
16316 * Nested-guest VM-exit handler for VMREAD (VMX_EXIT_VMREAD) and VMWRITE
16317 * (VMX_EXIT_VMWRITE). Conditional VM-exit.
16318 */
16319HMVMX_EXIT_DECL hmR0VmxExitVmreadVmwriteNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16320{
16321 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16322
16323 Assert( pVmxTransient->uExitReason == VMX_EXIT_VMREAD
16324 || pVmxTransient->uExitReason == VMX_EXIT_VMWRITE);
16325
16326 hmR0VmxReadExitInstrInfoVmcs(pVmxTransient);
16327
16328 uint8_t const iGReg = pVmxTransient->ExitInstrInfo.VmreadVmwrite.iReg2;
16329 Assert(iGReg < RT_ELEMENTS(pVCpu->cpum.GstCtx.aGRegs));
16330 uint64_t u64VmcsField = pVCpu->cpum.GstCtx.aGRegs[iGReg].u64;
16331
16332 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_EFER);
16333 if (!CPUMIsGuestInLongModeEx(&pVCpu->cpum.GstCtx))
16334 u64VmcsField &= UINT64_C(0xffffffff);
16335
16336 if (CPUMIsGuestVmxVmreadVmwriteInterceptSet(pVCpu, pVmxTransient->uExitReason, u64VmcsField))
16337 {
16338 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16339 hmR0VmxReadExitQualVmcs(pVmxTransient);
16340
16341 VMXVEXITINFO ExitInfo;
16342 RT_ZERO(ExitInfo);
16343 ExitInfo.uReason = pVmxTransient->uExitReason;
16344 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
16345 ExitInfo.u64Qual = pVmxTransient->uExitQual;
16346 ExitInfo.InstrInfo = pVmxTransient->ExitInstrInfo;
16347 return IEMExecVmxVmexitInstrWithInfo(pVCpu, &ExitInfo);
16348 }
16349
16350 if (pVmxTransient->uExitReason == VMX_EXIT_VMREAD)
16351 return hmR0VmxExitVmread(pVCpu, pVmxTransient);
16352 return hmR0VmxExitVmwrite(pVCpu, pVmxTransient);
16353}
16354
16355
16356/**
16357 * Nested-guest VM-exit handler for RDTSC (VMX_EXIT_RDTSC). Conditional VM-exit.
16358 */
16359HMVMX_EXIT_DECL hmR0VmxExitRdtscNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16360{
16361 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16362
16363 if (CPUMIsGuestVmxProcCtlsSet(pVCpu, &pVCpu->cpum.GstCtx, VMX_PROC_CTLS_RDTSC_EXIT))
16364 {
16365 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16366 return IEMExecVmxVmexitInstr(pVCpu, pVmxTransient->uExitReason, pVmxTransient->cbExitInstr);
16367 }
16368
16369 return hmR0VmxExitRdtsc(pVCpu, pVmxTransient);
16370}
16371
16372
16373/**
16374 * Nested-guest VM-exit handler for control-register accesses (VMX_EXIT_MOV_CRX).
16375 * Conditional VM-exit.
16376 */
16377HMVMX_EXIT_DECL hmR0VmxExitMovCRxNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16378{
16379 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16380
16381 hmR0VmxReadExitQualVmcs(pVmxTransient);
16382 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16383
16384 VBOXSTRICTRC rcStrict;
16385 uint32_t const uAccessType = VMX_EXIT_QUAL_CRX_ACCESS(pVmxTransient->uExitQual);
16386 switch (uAccessType)
16387 {
16388 case VMX_EXIT_QUAL_CRX_ACCESS_WRITE:
16389 {
16390 uint8_t const iCrReg = VMX_EXIT_QUAL_CRX_REGISTER(pVmxTransient->uExitQual);
16391 uint8_t const iGReg = VMX_EXIT_QUAL_CRX_GENREG(pVmxTransient->uExitQual);
16392 Assert(iGReg < RT_ELEMENTS(pVCpu->cpum.GstCtx.aGRegs));
16393 uint64_t const uNewCrX = pVCpu->cpum.GstCtx.aGRegs[iGReg].u64;
16394
16395 bool fIntercept;
16396 switch (iCrReg)
16397 {
16398 case 0:
16399 case 4:
16400 fIntercept = CPUMIsGuestVmxMovToCr0Cr4InterceptSet(pVCpu, &pVCpu->cpum.GstCtx, iCrReg, uNewCrX);
16401 break;
16402
16403 case 3:
16404 fIntercept = CPUMIsGuestVmxMovToCr3InterceptSet(pVCpu, uNewCrX);
16405 break;
16406
16407 case 8:
16408 fIntercept = CPUMIsGuestVmxProcCtlsSet(pVCpu, &pVCpu->cpum.GstCtx, VMX_PROC_CTLS_CR8_LOAD_EXIT);
16409 break;
16410
16411 default:
16412 fIntercept = false;
16413 break;
16414 }
16415 if (fIntercept)
16416 {
16417 VMXVEXITINFO ExitInfo;
16418 RT_ZERO(ExitInfo);
16419 ExitInfo.uReason = pVmxTransient->uExitReason;
16420 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
16421 ExitInfo.u64Qual = pVmxTransient->uExitQual;
16422 rcStrict = IEMExecVmxVmexitInstrWithInfo(pVCpu, &ExitInfo);
16423 }
16424 else
16425 rcStrict = hmR0VmxExitMovToCrX(pVCpu, pVmxTransient->pVmcsInfo, pVmxTransient->cbExitInstr, iGReg, iCrReg);
16426 break;
16427 }
16428
16429 case VMX_EXIT_QUAL_CRX_ACCESS_READ:
16430 {
16431 /*
16432 * CR0/CR4 reads do not cause VM-exits, the read-shadow is used (subject to masking).
16433 * CR2 reads do not cause a VM-exit.
16434 * CR3 reads cause a VM-exit depending on the "CR3 store exiting" control.
16435 * CR8 reads cause a VM-exit depending on the "CR8 store exiting" control.
16436 */
16437 uint8_t const iCrReg = VMX_EXIT_QUAL_CRX_REGISTER(pVmxTransient->uExitQual);
16438 if ( iCrReg == 3
16439 || iCrReg == 8)
16440 {
16441 static const uint32_t s_auCrXReadIntercepts[] = { 0, 0, 0, VMX_PROC_CTLS_CR3_STORE_EXIT, 0,
16442 0, 0, 0, VMX_PROC_CTLS_CR8_STORE_EXIT };
16443 uint32_t const uIntercept = s_auCrXReadIntercepts[iCrReg];
16444 if (CPUMIsGuestVmxProcCtlsSet(pVCpu, &pVCpu->cpum.GstCtx, uIntercept))
16445 {
16446 VMXVEXITINFO ExitInfo;
16447 RT_ZERO(ExitInfo);
16448 ExitInfo.uReason = pVmxTransient->uExitReason;
16449 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
16450 ExitInfo.u64Qual = pVmxTransient->uExitQual;
16451 rcStrict = IEMExecVmxVmexitInstrWithInfo(pVCpu, &ExitInfo);
16452 }
16453 else
16454 {
16455 uint8_t const iGReg = VMX_EXIT_QUAL_CRX_GENREG(pVmxTransient->uExitQual);
16456 rcStrict = hmR0VmxExitMovFromCrX(pVCpu, pVmxTransient->pVmcsInfo, pVmxTransient->cbExitInstr, iGReg, iCrReg);
16457 }
16458 }
16459 else
16460 {
16461 AssertMsgFailed(("MOV from CR%d VM-exit must not happen\n", iCrReg));
16462 HMVMX_UNEXPECTED_EXIT_RET(pVCpu, iCrReg);
16463 }
16464 break;
16465 }
16466
16467 case VMX_EXIT_QUAL_CRX_ACCESS_CLTS:
16468 {
16469 PCVMXVVMCS pVmcsNstGst = pVCpu->cpum.GstCtx.hwvirt.vmx.CTX_SUFF(pVmcs);
16470 Assert(pVmcsNstGst);
16471 uint64_t const uGstHostMask = pVmcsNstGst->u64Cr0Mask.u;
16472 uint64_t const uReadShadow = pVmcsNstGst->u64Cr0ReadShadow.u;
16473 if ( (uGstHostMask & X86_CR0_TS)
16474 && (uReadShadow & X86_CR0_TS))
16475 {
16476 VMXVEXITINFO ExitInfo;
16477 RT_ZERO(ExitInfo);
16478 ExitInfo.uReason = pVmxTransient->uExitReason;
16479 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
16480 ExitInfo.u64Qual = pVmxTransient->uExitQual;
16481 rcStrict = IEMExecVmxVmexitInstrWithInfo(pVCpu, &ExitInfo);
16482 }
16483 else
16484 rcStrict = hmR0VmxExitClts(pVCpu, pVmxTransient->pVmcsInfo, pVmxTransient->cbExitInstr);
16485 break;
16486 }
16487
16488 case VMX_EXIT_QUAL_CRX_ACCESS_LMSW: /* LMSW (Load Machine-Status Word into CR0) */
16489 {
16490 RTGCPTR GCPtrEffDst;
16491 uint16_t const uNewMsw = VMX_EXIT_QUAL_CRX_LMSW_DATA(pVmxTransient->uExitQual);
16492 bool const fMemOperand = VMX_EXIT_QUAL_CRX_LMSW_OP_MEM(pVmxTransient->uExitQual);
16493 if (fMemOperand)
16494 {
16495 hmR0VmxReadGuestLinearAddrVmcs(pVmxTransient);
16496 GCPtrEffDst = pVmxTransient->uGuestLinearAddr;
16497 }
16498 else
16499 GCPtrEffDst = NIL_RTGCPTR;
16500
16501 if (CPUMIsGuestVmxLmswInterceptSet(pVCpu, &pVCpu->cpum.GstCtx, uNewMsw))
16502 {
16503 VMXVEXITINFO ExitInfo;
16504 RT_ZERO(ExitInfo);
16505 ExitInfo.uReason = pVmxTransient->uExitReason;
16506 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
16507 ExitInfo.u64GuestLinearAddr = GCPtrEffDst;
16508 ExitInfo.u64Qual = pVmxTransient->uExitQual;
16509 rcStrict = IEMExecVmxVmexitInstrWithInfo(pVCpu, &ExitInfo);
16510 }
16511 else
16512 rcStrict = hmR0VmxExitLmsw(pVCpu, pVmxTransient->pVmcsInfo, pVmxTransient->cbExitInstr, uNewMsw, GCPtrEffDst);
16513 break;
16514 }
16515
16516 default:
16517 {
16518 AssertMsgFailed(("Unrecognized Mov CRX access type %#x\n", uAccessType));
16519 HMVMX_UNEXPECTED_EXIT_RET(pVCpu, uAccessType);
16520 }
16521 }
16522
16523 if (rcStrict == VINF_IEM_RAISED_XCPT)
16524 {
16525 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
16526 rcStrict = VINF_SUCCESS;
16527 }
16528 return rcStrict;
16529}
16530
16531
16532/**
16533 * Nested-guest VM-exit handler for debug-register accesses (VMX_EXIT_MOV_DRX).
16534 * Conditional VM-exit.
16535 */
16536HMVMX_EXIT_DECL hmR0VmxExitMovDRxNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16537{
16538 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16539
16540 if (CPUMIsGuestVmxProcCtlsSet(pVCpu, &pVCpu->cpum.GstCtx, VMX_PROC_CTLS_MOV_DR_EXIT))
16541 {
16542 hmR0VmxReadExitQualVmcs(pVmxTransient);
16543 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16544
16545 VMXVEXITINFO ExitInfo;
16546 RT_ZERO(ExitInfo);
16547 ExitInfo.uReason = pVmxTransient->uExitReason;
16548 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
16549 ExitInfo.u64Qual = pVmxTransient->uExitQual;
16550 return IEMExecVmxVmexitInstrWithInfo(pVCpu, &ExitInfo);
16551 }
16552 return hmR0VmxExitMovDRx(pVCpu, pVmxTransient);
16553}
16554
16555
16556/**
16557 * Nested-guest VM-exit handler for I/O instructions (VMX_EXIT_IO_INSTR).
16558 * Conditional VM-exit.
16559 */
16560HMVMX_EXIT_DECL hmR0VmxExitIoInstrNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16561{
16562 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16563
16564 hmR0VmxReadExitQualVmcs(pVmxTransient);
16565
16566 uint32_t const uIOPort = VMX_EXIT_QUAL_IO_PORT(pVmxTransient->uExitQual);
16567 uint8_t const uIOSize = VMX_EXIT_QUAL_IO_SIZE(pVmxTransient->uExitQual);
16568 AssertReturn(uIOSize <= 3 && uIOSize != 2, VERR_VMX_IPE_1);
16569
16570 static uint32_t const s_aIOSizes[4] = { 1, 2, 0, 4 }; /* Size of the I/O accesses in bytes. */
16571 uint8_t const cbAccess = s_aIOSizes[uIOSize];
16572 if (CPUMIsGuestVmxIoInterceptSet(pVCpu, uIOPort, cbAccess))
16573 {
16574 /*
16575 * IN/OUT instruction:
16576 * - Provides VM-exit instruction length.
16577 *
16578 * INS/OUTS instruction:
16579 * - Provides VM-exit instruction length.
16580 * - Provides Guest-linear address.
16581 * - Optionally provides VM-exit instruction info (depends on CPU feature).
16582 */
16583 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
16584 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16585
16586 /* Make sure we don't use stale/uninitialized VMX-transient info. below. */
16587 pVmxTransient->ExitInstrInfo.u = 0;
16588 pVmxTransient->uGuestLinearAddr = 0;
16589
16590 bool const fVmxInsOutsInfo = pVM->cpum.ro.GuestFeatures.fVmxInsOutInfo;
16591 bool const fIOString = VMX_EXIT_QUAL_IO_IS_STRING(pVmxTransient->uExitQual);
16592 if (fIOString)
16593 {
16594 hmR0VmxReadGuestLinearAddrVmcs(pVmxTransient);
16595 if (fVmxInsOutsInfo)
16596 {
16597 Assert(RT_BF_GET(pVM->hm.s.vmx.Msrs.u64Basic, VMX_BF_BASIC_VMCS_INS_OUTS)); /* Paranoia. */
16598 hmR0VmxReadExitInstrInfoVmcs(pVmxTransient);
16599 }
16600 }
16601
16602 VMXVEXITINFO ExitInfo;
16603 RT_ZERO(ExitInfo);
16604 ExitInfo.uReason = pVmxTransient->uExitReason;
16605 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
16606 ExitInfo.u64Qual = pVmxTransient->uExitQual;
16607 ExitInfo.InstrInfo = pVmxTransient->ExitInstrInfo;
16608 ExitInfo.u64GuestLinearAddr = pVmxTransient->uGuestLinearAddr;
16609 return IEMExecVmxVmexitInstrWithInfo(pVCpu, &ExitInfo);
16610 }
16611 return hmR0VmxExitIoInstr(pVCpu, pVmxTransient);
16612}
16613
16614
16615/**
16616 * Nested-guest VM-exit handler for RDMSR (VMX_EXIT_RDMSR).
16617 */
16618HMVMX_EXIT_DECL hmR0VmxExitRdmsrNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16619{
16620 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16621
16622 uint32_t fMsrpm;
16623 if (CPUMIsGuestVmxProcCtlsSet(pVCpu, &pVCpu->cpum.GstCtx, VMX_PROC_CTLS_USE_MSR_BITMAPS))
16624 fMsrpm = CPUMGetVmxMsrPermission(pVCpu->cpum.GstCtx.hwvirt.vmx.CTX_SUFF(pvMsrBitmap), pVCpu->cpum.GstCtx.ecx);
16625 else
16626 fMsrpm = VMXMSRPM_EXIT_RD;
16627
16628 if (fMsrpm & VMXMSRPM_EXIT_RD)
16629 {
16630 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16631 return IEMExecVmxVmexitInstr(pVCpu, pVmxTransient->uExitReason, pVmxTransient->cbExitInstr);
16632 }
16633 return hmR0VmxExitRdmsr(pVCpu, pVmxTransient);
16634}
16635
16636
16637/**
16638 * Nested-guest VM-exit handler for WRMSR (VMX_EXIT_WRMSR).
16639 */
16640HMVMX_EXIT_DECL hmR0VmxExitWrmsrNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16641{
16642 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16643
16644 uint32_t fMsrpm;
16645 if (CPUMIsGuestVmxProcCtlsSet(pVCpu, &pVCpu->cpum.GstCtx, VMX_PROC_CTLS_USE_MSR_BITMAPS))
16646 fMsrpm = CPUMGetVmxMsrPermission(pVCpu->cpum.GstCtx.hwvirt.vmx.CTX_SUFF(pvMsrBitmap), pVCpu->cpum.GstCtx.ecx);
16647 else
16648 fMsrpm = VMXMSRPM_EXIT_WR;
16649
16650 if (fMsrpm & VMXMSRPM_EXIT_WR)
16651 {
16652 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16653 return IEMExecVmxVmexitInstr(pVCpu, pVmxTransient->uExitReason, pVmxTransient->cbExitInstr);
16654 }
16655 return hmR0VmxExitWrmsr(pVCpu, pVmxTransient);
16656}
16657
16658
16659/**
16660 * Nested-guest VM-exit handler for MWAIT (VMX_EXIT_MWAIT). Conditional VM-exit.
16661 */
16662HMVMX_EXIT_DECL hmR0VmxExitMwaitNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16663{
16664 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16665
16666 if (CPUMIsGuestVmxProcCtlsSet(pVCpu, &pVCpu->cpum.GstCtx, VMX_PROC_CTLS_MWAIT_EXIT))
16667 {
16668 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16669 return IEMExecVmxVmexitInstr(pVCpu, pVmxTransient->uExitReason, pVmxTransient->cbExitInstr);
16670 }
16671 return hmR0VmxExitMwait(pVCpu, pVmxTransient);
16672}
16673
16674
16675/**
16676 * Nested-guest VM-exit handler for monitor-trap-flag (VMX_EXIT_MTF). Conditional
16677 * VM-exit.
16678 */
16679HMVMX_EXIT_DECL hmR0VmxExitMtfNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16680{
16681 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16682
16683 /** @todo NSTVMX: Should consider debugging nested-guests using VM debugger. */
16684 hmR0VmxReadGuestPendingDbgXctps(pVmxTransient);
16685 VMXVEXITINFO ExitInfo;
16686 RT_ZERO(ExitInfo);
16687 ExitInfo.uReason = pVmxTransient->uExitReason;
16688 ExitInfo.u64GuestPendingDbgXcpts = pVmxTransient->uGuestPendingDbgXcpts;
16689 return IEMExecVmxVmexitTrapLike(pVCpu, &ExitInfo);
16690}
16691
16692
16693/**
16694 * Nested-guest VM-exit handler for MONITOR (VMX_EXIT_MONITOR). Conditional VM-exit.
16695 */
16696HMVMX_EXIT_DECL hmR0VmxExitMonitorNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16697{
16698 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16699
16700 if (CPUMIsGuestVmxProcCtlsSet(pVCpu, &pVCpu->cpum.GstCtx, VMX_PROC_CTLS_MONITOR_EXIT))
16701 {
16702 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16703 return IEMExecVmxVmexitInstr(pVCpu, pVmxTransient->uExitReason, pVmxTransient->cbExitInstr);
16704 }
16705 return hmR0VmxExitMonitor(pVCpu, pVmxTransient);
16706}
16707
16708
16709/**
16710 * Nested-guest VM-exit handler for PAUSE (VMX_EXIT_PAUSE). Conditional VM-exit.
16711 */
16712HMVMX_EXIT_DECL hmR0VmxExitPauseNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16713{
16714 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16715
16716 /** @todo NSTVMX: Think about this more. Does the outer guest need to intercept
16717 * PAUSE when executing a nested-guest? If it does not, we would not need
16718 * to check for the intercepts here. Just call VM-exit... */
16719
16720 /* The CPU would have already performed the necessary CPL checks for PAUSE-loop exiting. */
16721 if ( CPUMIsGuestVmxProcCtlsSet(pVCpu, &pVCpu->cpum.GstCtx, VMX_PROC_CTLS_PAUSE_EXIT)
16722 || CPUMIsGuestVmxProcCtls2Set(pVCpu, &pVCpu->cpum.GstCtx, VMX_PROC_CTLS2_PAUSE_LOOP_EXIT))
16723 {
16724 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16725 return IEMExecVmxVmexitInstr(pVCpu, pVmxTransient->uExitReason, pVmxTransient->cbExitInstr);
16726 }
16727 return hmR0VmxExitPause(pVCpu, pVmxTransient);
16728}
16729
16730
16731/**
16732 * Nested-guest VM-exit handler for when the TPR value is lowered below the
16733 * specified threshold (VMX_EXIT_TPR_BELOW_THRESHOLD). Conditional VM-exit.
16734 */
16735HMVMX_EXIT_NSRC_DECL hmR0VmxExitTprBelowThresholdNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16736{
16737 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16738
16739 if (CPUMIsGuestVmxProcCtlsSet(pVCpu, &pVCpu->cpum.GstCtx, VMX_PROC_CTLS_USE_TPR_SHADOW))
16740 {
16741 hmR0VmxReadGuestPendingDbgXctps(pVmxTransient);
16742 VMXVEXITINFO ExitInfo;
16743 RT_ZERO(ExitInfo);
16744 ExitInfo.uReason = pVmxTransient->uExitReason;
16745 ExitInfo.u64GuestPendingDbgXcpts = pVmxTransient->uGuestPendingDbgXcpts;
16746 return IEMExecVmxVmexitTrapLike(pVCpu, &ExitInfo);
16747 }
16748 return hmR0VmxExitTprBelowThreshold(pVCpu, pVmxTransient);
16749}
16750
16751
16752/**
16753 * Nested-guest VM-exit handler for APIC access (VMX_EXIT_APIC_ACCESS). Conditional
16754 * VM-exit.
16755 */
16756HMVMX_EXIT_DECL hmR0VmxExitApicAccessNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16757{
16758 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16759
16760 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16761 hmR0VmxReadIdtVectoringInfoVmcs(pVmxTransient);
16762 hmR0VmxReadIdtVectoringErrorCodeVmcs(pVmxTransient);
16763 hmR0VmxReadExitQualVmcs(pVmxTransient);
16764
16765 Assert(CPUMIsGuestVmxProcCtls2Set(pVCpu, &pVCpu->cpum.GstCtx, VMX_PROC_CTLS2_VIRT_APIC_ACCESS));
16766
16767 Log4Func(("at offset %#x type=%u\n", VMX_EXIT_QUAL_APIC_ACCESS_OFFSET(pVmxTransient->uExitQual),
16768 VMX_EXIT_QUAL_APIC_ACCESS_TYPE(pVmxTransient->uExitQual)));
16769
16770 VMXVEXITINFO ExitInfo;
16771 RT_ZERO(ExitInfo);
16772 ExitInfo.uReason = pVmxTransient->uExitReason;
16773 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
16774 ExitInfo.u64Qual = pVmxTransient->uExitQual;
16775
16776 VMXVEXITEVENTINFO ExitEventInfo;
16777 RT_ZERO(ExitEventInfo);
16778 ExitEventInfo.uIdtVectoringInfo = pVmxTransient->uIdtVectoringInfo;
16779 ExitEventInfo.uIdtVectoringErrCode = pVmxTransient->uIdtVectoringErrorCode;
16780 return IEMExecVmxVmexitApicAccess(pVCpu, &ExitInfo, &ExitEventInfo);
16781}
16782
16783
16784/**
16785 * Nested-guest VM-exit handler for APIC write emulation (VMX_EXIT_APIC_WRITE).
16786 * Conditional VM-exit.
16787 */
16788HMVMX_EXIT_DECL hmR0VmxExitApicWriteNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16789{
16790 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16791
16792 Assert(CPUMIsGuestVmxProcCtls2Set(pVCpu, &pVCpu->cpum.GstCtx, VMX_PROC_CTLS2_APIC_REG_VIRT));
16793 hmR0VmxReadExitQualVmcs(pVmxTransient);
16794 return IEMExecVmxVmexit(pVCpu, pVmxTransient->uExitReason, pVmxTransient->uExitQual);
16795}
16796
16797
16798/**
16799 * Nested-guest VM-exit handler for virtualized EOI (VMX_EXIT_VIRTUALIZED_EOI).
16800 * Conditional VM-exit.
16801 */
16802HMVMX_EXIT_DECL hmR0VmxExitVirtEoiNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16803{
16804 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16805
16806 Assert(CPUMIsGuestVmxProcCtls2Set(pVCpu, &pVCpu->cpum.GstCtx, VMX_PROC_CTLS2_VIRT_INT_DELIVERY));
16807 hmR0VmxReadExitQualVmcs(pVmxTransient);
16808 return IEMExecVmxVmexit(pVCpu, pVmxTransient->uExitReason, pVmxTransient->uExitQual);
16809}
16810
16811
16812/**
16813 * Nested-guest VM-exit handler for RDTSCP (VMX_EXIT_RDTSCP). Conditional VM-exit.
16814 */
16815HMVMX_EXIT_DECL hmR0VmxExitRdtscpNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16816{
16817 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16818
16819 if (CPUMIsGuestVmxProcCtlsSet(pVCpu, &pVCpu->cpum.GstCtx, VMX_PROC_CTLS_RDTSC_EXIT))
16820 {
16821 Assert(CPUMIsGuestVmxProcCtls2Set(pVCpu, &pVCpu->cpum.GstCtx, VMX_PROC_CTLS2_RDTSCP));
16822 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16823 return IEMExecVmxVmexitInstr(pVCpu, pVmxTransient->uExitReason, pVmxTransient->cbExitInstr);
16824 }
16825 return hmR0VmxExitRdtscp(pVCpu, pVmxTransient);
16826}
16827
16828
16829/**
16830 * Nested-guest VM-exit handler for WBINVD (VMX_EXIT_WBINVD). Conditional VM-exit.
16831 */
16832HMVMX_EXIT_NSRC_DECL hmR0VmxExitWbinvdNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16833{
16834 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16835
16836 if (CPUMIsGuestVmxProcCtls2Set(pVCpu, &pVCpu->cpum.GstCtx, VMX_PROC_CTLS2_WBINVD_EXIT))
16837 {
16838 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16839 return IEMExecVmxVmexitInstr(pVCpu, pVmxTransient->uExitReason, pVmxTransient->cbExitInstr);
16840 }
16841 return hmR0VmxExitWbinvd(pVCpu, pVmxTransient);
16842}
16843
16844
16845/**
16846 * Nested-guest VM-exit handler for INVPCID (VMX_EXIT_INVPCID). Conditional VM-exit.
16847 */
16848HMVMX_EXIT_DECL hmR0VmxExitInvpcidNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16849{
16850 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16851
16852 if (CPUMIsGuestVmxProcCtlsSet(pVCpu, &pVCpu->cpum.GstCtx, VMX_PROC_CTLS_INVLPG_EXIT))
16853 {
16854 Assert(CPUMIsGuestVmxProcCtls2Set(pVCpu, &pVCpu->cpum.GstCtx, VMX_PROC_CTLS2_INVPCID));
16855 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16856 hmR0VmxReadExitQualVmcs(pVmxTransient);
16857 hmR0VmxReadExitInstrInfoVmcs(pVmxTransient);
16858
16859 VMXVEXITINFO ExitInfo;
16860 RT_ZERO(ExitInfo);
16861 ExitInfo.uReason = pVmxTransient->uExitReason;
16862 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
16863 ExitInfo.u64Qual = pVmxTransient->uExitQual;
16864 ExitInfo.InstrInfo = pVmxTransient->ExitInstrInfo;
16865 return IEMExecVmxVmexitInstrWithInfo(pVCpu, &ExitInfo);
16866 }
16867 return hmR0VmxExitInvpcid(pVCpu, pVmxTransient);
16868}
16869
16870
16871/**
16872 * Nested-guest VM-exit handler for invalid-guest state
16873 * (VMX_EXIT_ERR_INVALID_GUEST_STATE). Error VM-exit.
16874 */
16875HMVMX_EXIT_DECL hmR0VmxExitErrInvalidGuestStateNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16876{
16877 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16878
16879 /*
16880 * Currently this should never happen because we fully emulate VMLAUNCH/VMRESUME in IEM.
16881 * So if it does happen, it indicates a bug possibly in the hardware-assisted VMX code.
16882 * Handle it like it's in an invalid guest state of the outer guest.
16883 *
16884 * When the fast path is implemented, this should be changed to cause the corresponding
16885 * nested-guest VM-exit.
16886 */
16887 return hmR0VmxExitErrInvalidGuestState(pVCpu, pVmxTransient);
16888}
16889
16890
16891/**
16892 * Nested-guest VM-exit handler for instructions that cause VM-exits uncondtionally
16893 * and only provide the instruction length.
16894 *
16895 * Unconditional VM-exit.
16896 */
16897HMVMX_EXIT_DECL hmR0VmxExitInstrNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16898{
16899 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16900
16901#ifdef VBOX_STRICT
16902 PCCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
16903 switch (pVmxTransient->uExitReason)
16904 {
16905 case VMX_EXIT_ENCLS:
16906 Assert(CPUMIsGuestVmxProcCtls2Set(pVCpu, pCtx, VMX_PROC_CTLS2_ENCLS_EXIT));
16907 break;
16908
16909 case VMX_EXIT_VMFUNC:
16910 Assert(CPUMIsGuestVmxProcCtls2Set(pVCpu, pCtx, VMX_PROC_CTLS2_VMFUNC));
16911 break;
16912 }
16913#endif
16914
16915 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16916 return IEMExecVmxVmexitInstr(pVCpu, pVmxTransient->uExitReason, pVmxTransient->cbExitInstr);
16917}
16918
16919
16920/**
16921 * Nested-guest VM-exit handler for instructions that provide instruction length as
16922 * well as more information.
16923 *
16924 * Unconditional VM-exit.
16925 */
16926HMVMX_EXIT_DECL hmR0VmxExitInstrWithInfoNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16927{
16928 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16929
16930#ifdef VBOX_STRICT
16931 PCCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
16932 switch (pVmxTransient->uExitReason)
16933 {
16934 case VMX_EXIT_GDTR_IDTR_ACCESS:
16935 case VMX_EXIT_LDTR_TR_ACCESS:
16936 Assert(CPUMIsGuestVmxProcCtls2Set(pVCpu, pCtx, VMX_PROC_CTLS2_DESC_TABLE_EXIT));
16937 break;
16938
16939 case VMX_EXIT_RDRAND:
16940 Assert(CPUMIsGuestVmxProcCtls2Set(pVCpu, pCtx, VMX_PROC_CTLS2_RDRAND_EXIT));
16941 break;
16942
16943 case VMX_EXIT_RDSEED:
16944 Assert(CPUMIsGuestVmxProcCtls2Set(pVCpu, pCtx, VMX_PROC_CTLS2_RDSEED_EXIT));
16945 break;
16946
16947 case VMX_EXIT_XSAVES:
16948 case VMX_EXIT_XRSTORS:
16949 /** @todo NSTVMX: Verify XSS-bitmap. */
16950 Assert(CPUMIsGuestVmxProcCtls2Set(pVCpu, pCtx, VMX_PROC_CTLS2_XSAVES_XRSTORS));
16951 break;
16952
16953 case VMX_EXIT_UMWAIT:
16954 case VMX_EXIT_TPAUSE:
16955 Assert(CPUMIsGuestVmxProcCtlsSet(pVCpu, pCtx, VMX_PROC_CTLS_RDTSC_EXIT));
16956 Assert(CPUMIsGuestVmxProcCtls2Set(pVCpu, pCtx, VMX_PROC_CTLS2_USER_WAIT_PAUSE));
16957 break;
16958 }
16959#endif
16960
16961 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16962 hmR0VmxReadExitQualVmcs(pVmxTransient);
16963 hmR0VmxReadExitInstrInfoVmcs(pVmxTransient);
16964
16965 VMXVEXITINFO ExitInfo;
16966 RT_ZERO(ExitInfo);
16967 ExitInfo.uReason = pVmxTransient->uExitReason;
16968 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
16969 ExitInfo.u64Qual = pVmxTransient->uExitQual;
16970 ExitInfo.InstrInfo = pVmxTransient->ExitInstrInfo;
16971 return IEMExecVmxVmexitInstrWithInfo(pVCpu, &ExitInfo);
16972}
16973
16974/** @} */
16975#endif /* VBOX_WITH_NESTED_HWVIRT_VMX */
16976
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