VirtualBox

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

Last change on this file since 80706 was 80690, checked in by vboxsync, 6 years ago

VMM/HMVMXR0: Nested VMX: bugref:9180 space nit.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 708.1 KB
Line 
1/* $Id: HMVMXR0.cpp 80690 2019-09-10 09:52:40Z 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
3919 /* Paranoia - We've not yet initialized these, they shall be done while merging the VMCS. */
3920 Assert(!pVmcsInfo->u64Cr0Mask);
3921 Assert(!pVmcsInfo->u64Cr4Mask);
3922 return VINF_SUCCESS;
3923 }
3924 else
3925 LogRelFunc(("Failed to set up the VMCS link pointer in the nested-guest VMCS. rc=%Rrc\n", rc));
3926 return rc;
3927}
3928#endif
3929
3930
3931/**
3932 * Sets up the VMCS for executing a guest (or nested-guest) using hardware-assisted
3933 * VMX.
3934 *
3935 * @returns VBox status code.
3936 * @param pVCpu The cross context virtual CPU structure.
3937 * @param pVmcsInfo The VMCS info. object.
3938 * @param fIsNstGstVmcs Whether this is a nested-guest VMCS.
3939 */
3940static int hmR0VmxSetupVmcs(PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo, bool fIsNstGstVmcs)
3941{
3942 Assert(pVmcsInfo->pvVmcs);
3943 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
3944
3945 /* Set the CPU specified revision identifier at the beginning of the VMCS structure. */
3946 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
3947 *(uint32_t *)pVmcsInfo->pvVmcs = RT_BF_GET(pVM->hm.s.vmx.Msrs.u64Basic, VMX_BF_BASIC_VMCS_ID);
3948 const char * const pszVmcs = fIsNstGstVmcs ? "nested-guest VMCS" : "guest VMCS";
3949
3950 LogFlowFunc(("\n"));
3951
3952 /*
3953 * Initialize the VMCS using VMCLEAR before loading the VMCS.
3954 * See Intel spec. 31.6 "Preparation And Launching A Virtual Machine".
3955 */
3956 int rc = hmR0VmxClearVmcs(pVmcsInfo);
3957 if (RT_SUCCESS(rc))
3958 {
3959 rc = hmR0VmxLoadVmcs(pVmcsInfo);
3960 if (RT_SUCCESS(rc))
3961 {
3962 if (!fIsNstGstVmcs)
3963 {
3964 rc = hmR0VmxSetupVmcsPinCtls(pVCpu, pVmcsInfo);
3965 if (RT_SUCCESS(rc))
3966 {
3967 rc = hmR0VmxSetupVmcsProcCtls(pVCpu, pVmcsInfo);
3968 if (RT_SUCCESS(rc))
3969 {
3970 rc = hmR0VmxSetupVmcsMiscCtls(pVCpu, pVmcsInfo);
3971 if (RT_SUCCESS(rc))
3972 {
3973 hmR0VmxSetupVmcsXcptBitmap(pVCpu, pVmcsInfo);
3974#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
3975 /*
3976 * If a shadow VMCS is allocated for the VMCS info. object, initialize the
3977 * VMCS revision ID and shadow VMCS indicator bit. Also, clear the VMCS
3978 * making it fit for use when VMCS shadowing is later enabled.
3979 */
3980 if (pVmcsInfo->pvShadowVmcs)
3981 {
3982 VMXVMCSREVID VmcsRevId;
3983 VmcsRevId.u = RT_BF_GET(pVM->hm.s.vmx.Msrs.u64Basic, VMX_BF_BASIC_VMCS_ID);
3984 VmcsRevId.n.fIsShadowVmcs = 1;
3985 *(uint32_t *)pVmcsInfo->pvShadowVmcs = VmcsRevId.u;
3986 rc = hmR0VmxClearShadowVmcs(pVmcsInfo);
3987 if (RT_SUCCESS(rc))
3988 { /* likely */ }
3989 else
3990 LogRelFunc(("Failed to initialize shadow VMCS. rc=%Rrc\n", rc));
3991 }
3992#endif
3993 }
3994 else
3995 LogRelFunc(("Failed to setup miscellaneous controls. rc=%Rrc\n", rc));
3996 }
3997 else
3998 LogRelFunc(("Failed to setup processor-based VM-execution controls. rc=%Rrc\n", rc));
3999 }
4000 else
4001 LogRelFunc(("Failed to setup pin-based controls. rc=%Rrc\n", rc));
4002 }
4003 else
4004 {
4005#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
4006 rc = hmR0VmxSetupVmcsCtlsNested(pVCpu, pVmcsInfo);
4007 if (RT_SUCCESS(rc))
4008 { /* likely */ }
4009 else
4010 LogRelFunc(("Failed to initialize nested-guest VMCS. rc=%Rrc\n", rc));
4011#else
4012 AssertFailed();
4013#endif
4014 }
4015 }
4016 else
4017 LogRelFunc(("Failed to load the %s. rc=%Rrc\n", rc, pszVmcs));
4018 }
4019 else
4020 LogRelFunc(("Failed to clear the %s. rc=%Rrc\n", rc, pszVmcs));
4021
4022 /* Sync any CPU internal VMCS data back into our VMCS in memory. */
4023 if (RT_SUCCESS(rc))
4024 {
4025 rc = hmR0VmxClearVmcs(pVmcsInfo);
4026 if (RT_SUCCESS(rc))
4027 { /* likely */ }
4028 else
4029 LogRelFunc(("Failed to clear the %s post setup. rc=%Rrc\n", rc, pszVmcs));
4030 }
4031
4032 /*
4033 * Update the last-error record both for failures and success, so we
4034 * can propagate the status code back to ring-3 for diagnostics.
4035 */
4036 hmR0VmxUpdateErrorRecord(pVCpu, rc);
4037 NOREF(pszVmcs);
4038 return rc;
4039}
4040
4041
4042/**
4043 * Does global VT-x initialization (called during module initialization).
4044 *
4045 * @returns VBox status code.
4046 */
4047VMMR0DECL(int) VMXR0GlobalInit(void)
4048{
4049#ifdef HMVMX_USE_FUNCTION_TABLE
4050 AssertCompile(VMX_EXIT_MAX + 1 == RT_ELEMENTS(g_apfnVMExitHandlers));
4051# ifdef VBOX_STRICT
4052 for (unsigned i = 0; i < RT_ELEMENTS(g_apfnVMExitHandlers); i++)
4053 Assert(g_apfnVMExitHandlers[i]);
4054# endif
4055#endif
4056 return VINF_SUCCESS;
4057}
4058
4059
4060/**
4061 * Does global VT-x termination (called during module termination).
4062 */
4063VMMR0DECL(void) VMXR0GlobalTerm()
4064{
4065 /* Nothing to do currently. */
4066}
4067
4068
4069/**
4070 * Sets up and activates VT-x on the current CPU.
4071 *
4072 * @returns VBox status code.
4073 * @param pHostCpu The HM physical-CPU structure.
4074 * @param pVM The cross context VM structure. Can be
4075 * NULL after a host resume operation.
4076 * @param pvCpuPage Pointer to the VMXON region (can be NULL if @a
4077 * fEnabledByHost is @c true).
4078 * @param HCPhysCpuPage Physical address of the VMXON region (can be 0 if
4079 * @a fEnabledByHost is @c true).
4080 * @param fEnabledByHost Set if SUPR0EnableVTx() or similar was used to
4081 * enable VT-x on the host.
4082 * @param pHwvirtMsrs Pointer to the hardware-virtualization MSRs.
4083 */
4084VMMR0DECL(int) VMXR0EnableCpu(PHMPHYSCPU pHostCpu, PVMCC pVM, void *pvCpuPage, RTHCPHYS HCPhysCpuPage, bool fEnabledByHost,
4085 PCSUPHWVIRTMSRS pHwvirtMsrs)
4086{
4087 AssertPtr(pHostCpu);
4088 AssertPtr(pHwvirtMsrs);
4089 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
4090
4091 /* Enable VT-x if it's not already enabled by the host. */
4092 if (!fEnabledByHost)
4093 {
4094 int rc = hmR0VmxEnterRootMode(pVM, HCPhysCpuPage, pvCpuPage);
4095 if (RT_FAILURE(rc))
4096 return rc;
4097 }
4098
4099 /*
4100 * Flush all EPT tagged-TLB entries (in case VirtualBox or any other hypervisor have been
4101 * using EPTPs) so we don't retain any stale guest-physical mappings which won't get
4102 * invalidated when flushing by VPID.
4103 */
4104 if (pHwvirtMsrs->u.vmx.u64EptVpidCaps & MSR_IA32_VMX_EPT_VPID_CAP_INVEPT_ALL_CONTEXTS)
4105 {
4106 hmR0VmxFlushEpt(NULL /* pVCpu */, NULL /* pVmcsInfo */, VMXTLBFLUSHEPT_ALL_CONTEXTS);
4107 pHostCpu->fFlushAsidBeforeUse = false;
4108 }
4109 else
4110 pHostCpu->fFlushAsidBeforeUse = true;
4111
4112 /* Ensure each VCPU scheduled on this CPU gets a new VPID on resume. See @bugref{6255}. */
4113 ++pHostCpu->cTlbFlushes;
4114
4115 return VINF_SUCCESS;
4116}
4117
4118
4119/**
4120 * Deactivates VT-x on the current CPU.
4121 *
4122 * @returns VBox status code.
4123 * @param pvCpuPage Pointer to the VMXON region.
4124 * @param HCPhysCpuPage Physical address of the VMXON region.
4125 *
4126 * @remarks This function should never be called when SUPR0EnableVTx() or
4127 * similar was used to enable VT-x on the host.
4128 */
4129VMMR0DECL(int) VMXR0DisableCpu(void *pvCpuPage, RTHCPHYS HCPhysCpuPage)
4130{
4131 RT_NOREF2(pvCpuPage, HCPhysCpuPage);
4132
4133 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
4134 return hmR0VmxLeaveRootMode();
4135}
4136
4137
4138/**
4139 * Does per-VM VT-x initialization.
4140 *
4141 * @returns VBox status code.
4142 * @param pVM The cross context VM structure.
4143 */
4144VMMR0DECL(int) VMXR0InitVM(PVMCC pVM)
4145{
4146 AssertPtr(pVM);
4147 LogFlowFunc(("pVM=%p\n", pVM));
4148
4149 int rc = hmR0VmxStructsAlloc(pVM);
4150 if (RT_FAILURE(rc))
4151 {
4152 LogRelFunc(("Failed to allocated VMX structures. rc=%Rrc\n", rc));
4153 return rc;
4154 }
4155
4156 return VINF_SUCCESS;
4157}
4158
4159
4160/**
4161 * Does per-VM VT-x termination.
4162 *
4163 * @returns VBox status code.
4164 * @param pVM The cross context VM structure.
4165 */
4166VMMR0DECL(int) VMXR0TermVM(PVMCC pVM)
4167{
4168 AssertPtr(pVM);
4169 LogFlowFunc(("pVM=%p\n", pVM));
4170
4171#ifdef VBOX_WITH_CRASHDUMP_MAGIC
4172 if (pVM->hm.s.vmx.hMemObjScratch != NIL_RTR0MEMOBJ)
4173 {
4174 Assert(pVM->hm.s.vmx.pvScratch);
4175 ASMMemZero32(pVM->hm.s.vmx.pvScratch, X86_PAGE_4K_SIZE);
4176 }
4177#endif
4178 hmR0VmxStructsFree(pVM);
4179 return VINF_SUCCESS;
4180}
4181
4182
4183/**
4184 * Sets up the VM for execution using hardware-assisted VMX.
4185 * This function is only called once per-VM during initialization.
4186 *
4187 * @returns VBox status code.
4188 * @param pVM The cross context VM structure.
4189 */
4190VMMR0DECL(int) VMXR0SetupVM(PVMCC pVM)
4191{
4192 AssertPtr(pVM);
4193 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
4194
4195 LogFlowFunc(("pVM=%p\n", pVM));
4196
4197 /*
4198 * At least verify if VMX is enabled, since we can't check if we're in VMX root mode or not
4199 * without causing a #GP.
4200 */
4201 RTCCUINTREG const uHostCr4 = ASMGetCR4();
4202 if (RT_LIKELY(uHostCr4 & X86_CR4_VMXE))
4203 { /* likely */ }
4204 else
4205 return VERR_VMX_NOT_IN_VMX_ROOT_MODE;
4206
4207 /*
4208 * Without unrestricted guest execution, pRealModeTSS and pNonPagingModeEPTPageTable *must*
4209 * always be allocated. We no longer support the highly unlikely case of unrestricted guest
4210 * without pRealModeTSS, see hmR3InitFinalizeR0Intel().
4211 */
4212 if ( !pVM->hm.s.vmx.fUnrestrictedGuest
4213 && ( !pVM->hm.s.vmx.pNonPagingModeEPTPageTable
4214 || !pVM->hm.s.vmx.pRealModeTSS))
4215 {
4216 LogRelFunc(("Invalid real-on-v86 state.\n"));
4217 return VERR_INTERNAL_ERROR;
4218 }
4219
4220 /* Initialize these always, see hmR3InitFinalizeR0().*/
4221 pVM->hm.s.vmx.enmTlbFlushEpt = VMXTLBFLUSHEPT_NONE;
4222 pVM->hm.s.vmx.enmTlbFlushVpid = VMXTLBFLUSHVPID_NONE;
4223
4224 /* Setup the tagged-TLB flush handlers. */
4225 int rc = hmR0VmxSetupTaggedTlb(pVM);
4226 if (RT_FAILURE(rc))
4227 {
4228 LogRelFunc(("Failed to setup tagged TLB. rc=%Rrc\n", rc));
4229 return rc;
4230 }
4231
4232#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
4233 /* Setup the shadow VMCS fields array and VMREAD/VMWRITE bitmaps. */
4234 if (pVM->hm.s.vmx.fUseVmcsShadowing)
4235 {
4236 rc = hmR0VmxSetupShadowVmcsFieldsArrays(pVM);
4237 if (RT_SUCCESS(rc))
4238 hmR0VmxSetupVmreadVmwriteBitmaps(pVM);
4239 else
4240 {
4241 LogRelFunc(("Failed to setup shadow VMCS fields arrays. rc=%Rrc\n", rc));
4242 return rc;
4243 }
4244 }
4245#endif
4246
4247 for (VMCPUID idCpu = 0; idCpu < pVM->cCpus; idCpu++)
4248 {
4249 PVMCPUCC pVCpu = VMCC_GET_CPU(pVM, idCpu);
4250 Log4Func(("pVCpu=%p idCpu=%RU32\n", pVCpu, pVCpu->idCpu));
4251
4252 rc = hmR0VmxSetupVmcs(pVCpu, &pVCpu->hm.s.vmx.VmcsInfo, false /* fIsNstGstVmcs */);
4253 if (RT_SUCCESS(rc))
4254 {
4255#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
4256 if (pVM->cpum.ro.GuestFeatures.fVmx)
4257 {
4258 rc = hmR0VmxSetupVmcs(pVCpu, &pVCpu->hm.s.vmx.VmcsInfoNstGst, true /* fIsNstGstVmcs */);
4259 if (RT_SUCCESS(rc))
4260 { /* likely */ }
4261 else
4262 {
4263 LogRelFunc(("Nested-guest VMCS setup failed. rc=%Rrc\n", rc));
4264 return rc;
4265 }
4266 }
4267#endif
4268 }
4269 else
4270 {
4271 LogRelFunc(("VMCS setup failed. rc=%Rrc\n", rc));
4272 return rc;
4273 }
4274 }
4275
4276 return VINF_SUCCESS;
4277}
4278
4279
4280/**
4281 * Saves the host control registers (CR0, CR3, CR4) into the host-state area in
4282 * the VMCS.
4283 */
4284static void hmR0VmxExportHostControlRegs(void)
4285{
4286 int rc = VMXWriteVmcsNw(VMX_VMCS_HOST_CR0, ASMGetCR0()); AssertRC(rc);
4287 rc = VMXWriteVmcsNw(VMX_VMCS_HOST_CR3, ASMGetCR3()); AssertRC(rc);
4288 rc = VMXWriteVmcsNw(VMX_VMCS_HOST_CR4, ASMGetCR4()); AssertRC(rc);
4289}
4290
4291
4292/**
4293 * Saves the host segment registers and GDTR, IDTR, (TR, GS and FS bases) into
4294 * the host-state area in the VMCS.
4295 *
4296 * @returns VBox status code.
4297 * @param pVCpu The cross context virtual CPU structure.
4298 */
4299static int hmR0VmxExportHostSegmentRegs(PVMCPUCC pVCpu)
4300{
4301/**
4302 * Macro for adjusting host segment selectors to satisfy VT-x's VM-entry
4303 * requirements. See hmR0VmxExportHostSegmentRegs().
4304 */
4305#define VMXLOCAL_ADJUST_HOST_SEG(a_Seg, a_selValue) \
4306 if ((a_selValue) & (X86_SEL_RPL | X86_SEL_LDT)) \
4307 { \
4308 bool fValidSelector = true; \
4309 if ((a_selValue) & X86_SEL_LDT) \
4310 { \
4311 uint32_t const uAttr = ASMGetSegAttr(a_selValue); \
4312 fValidSelector = RT_BOOL(uAttr != UINT32_MAX && (uAttr & X86_DESC_P)); \
4313 } \
4314 if (fValidSelector) \
4315 { \
4316 pVCpu->hm.s.vmx.fRestoreHostFlags |= VMX_RESTORE_HOST_SEL_##a_Seg; \
4317 pVCpu->hm.s.vmx.RestoreHost.uHostSel##a_Seg = (a_selValue); \
4318 } \
4319 (a_selValue) = 0; \
4320 }
4321
4322 /*
4323 * If we've executed guest code using hardware-assisted VMX, the host-state bits
4324 * will be messed up. We should -not- save the messed up state without restoring
4325 * the original host-state, see @bugref{7240}.
4326 *
4327 * This apparently can happen (most likely the FPU changes), deal with it rather than
4328 * asserting. Was observed booting Solaris 10u10 32-bit guest.
4329 */
4330 if ( (pVCpu->hm.s.vmx.fRestoreHostFlags & VMX_RESTORE_HOST_REQUIRED)
4331 && (pVCpu->hm.s.vmx.fRestoreHostFlags & ~VMX_RESTORE_HOST_REQUIRED))
4332 {
4333 Log4Func(("Restoring Host State: fRestoreHostFlags=%#RX32 HostCpuId=%u\n", pVCpu->hm.s.vmx.fRestoreHostFlags,
4334 pVCpu->idCpu));
4335 VMXRestoreHostState(pVCpu->hm.s.vmx.fRestoreHostFlags, &pVCpu->hm.s.vmx.RestoreHost);
4336 }
4337 pVCpu->hm.s.vmx.fRestoreHostFlags = 0;
4338
4339 /*
4340 * Host segment registers.
4341 */
4342 RTSEL uSelES = ASMGetES();
4343 RTSEL uSelCS = ASMGetCS();
4344 RTSEL uSelSS = ASMGetSS();
4345 RTSEL uSelDS = ASMGetDS();
4346 RTSEL uSelFS = ASMGetFS();
4347 RTSEL uSelGS = ASMGetGS();
4348 RTSEL uSelTR = ASMGetTR();
4349
4350 /*
4351 * Determine if the host segment registers are suitable for VT-x. Otherwise use zero to
4352 * gain VM-entry and restore them before we get preempted.
4353 *
4354 * See Intel spec. 26.2.3 "Checks on Host Segment and Descriptor-Table Registers".
4355 */
4356 VMXLOCAL_ADJUST_HOST_SEG(DS, uSelDS);
4357 VMXLOCAL_ADJUST_HOST_SEG(ES, uSelES);
4358 VMXLOCAL_ADJUST_HOST_SEG(FS, uSelFS);
4359 VMXLOCAL_ADJUST_HOST_SEG(GS, uSelGS);
4360
4361 /* Verification based on Intel spec. 26.2.3 "Checks on Host Segment and Descriptor-Table Registers" */
4362 Assert(!(uSelCS & X86_SEL_RPL)); Assert(!(uSelCS & X86_SEL_LDT));
4363 Assert(!(uSelSS & X86_SEL_RPL)); Assert(!(uSelSS & X86_SEL_LDT));
4364 Assert(!(uSelDS & X86_SEL_RPL)); Assert(!(uSelDS & X86_SEL_LDT));
4365 Assert(!(uSelES & X86_SEL_RPL)); Assert(!(uSelES & X86_SEL_LDT));
4366 Assert(!(uSelFS & X86_SEL_RPL)); Assert(!(uSelFS & X86_SEL_LDT));
4367 Assert(!(uSelGS & X86_SEL_RPL)); Assert(!(uSelGS & X86_SEL_LDT));
4368 Assert(!(uSelTR & X86_SEL_RPL)); Assert(!(uSelTR & X86_SEL_LDT));
4369 Assert(uSelCS);
4370 Assert(uSelTR);
4371
4372 /* Write these host selector fields into the host-state area in the VMCS. */
4373 int rc = VMXWriteVmcs16(VMX_VMCS16_HOST_CS_SEL, uSelCS); AssertRC(rc);
4374 rc = VMXWriteVmcs16(VMX_VMCS16_HOST_SS_SEL, uSelSS); AssertRC(rc);
4375 rc = VMXWriteVmcs16(VMX_VMCS16_HOST_DS_SEL, uSelDS); AssertRC(rc);
4376 rc = VMXWriteVmcs16(VMX_VMCS16_HOST_ES_SEL, uSelES); AssertRC(rc);
4377 rc = VMXWriteVmcs16(VMX_VMCS16_HOST_FS_SEL, uSelFS); AssertRC(rc);
4378 rc = VMXWriteVmcs16(VMX_VMCS16_HOST_GS_SEL, uSelGS); AssertRC(rc);
4379 rc = VMXWriteVmcs16(VMX_VMCS16_HOST_TR_SEL, uSelTR); AssertRC(rc);
4380
4381 /*
4382 * Host GDTR and IDTR.
4383 */
4384 RTGDTR Gdtr;
4385 RTIDTR Idtr;
4386 RT_ZERO(Gdtr);
4387 RT_ZERO(Idtr);
4388 ASMGetGDTR(&Gdtr);
4389 ASMGetIDTR(&Idtr);
4390 rc = VMXWriteVmcsNw(VMX_VMCS_HOST_GDTR_BASE, Gdtr.pGdt); AssertRC(rc);
4391 rc = VMXWriteVmcsNw(VMX_VMCS_HOST_IDTR_BASE, Idtr.pIdt); AssertRC(rc);
4392
4393 /*
4394 * Determine if we need to manually need to restore the GDTR and IDTR limits as VT-x zaps
4395 * them to the maximum limit (0xffff) on every VM-exit.
4396 */
4397 if (Gdtr.cbGdt != 0xffff)
4398 pVCpu->hm.s.vmx.fRestoreHostFlags |= VMX_RESTORE_HOST_GDTR;
4399
4400 /*
4401 * IDT limit is effectively capped at 0xfff. (See Intel spec. 6.14.1 "64-Bit Mode IDT" and
4402 * Intel spec. 6.2 "Exception and Interrupt Vectors".) Therefore if the host has the limit
4403 * as 0xfff, VT-x bloating the limit to 0xffff shouldn't cause any different CPU behavior.
4404 * However, several hosts either insists on 0xfff being the limit (Windows Patch Guard) or
4405 * uses the limit for other purposes (darwin puts the CPU ID in there but botches sidt
4406 * alignment in at least one consumer). So, we're only allowing the IDTR.LIMIT to be left
4407 * at 0xffff on hosts where we are sure it won't cause trouble.
4408 */
4409#if defined(RT_OS_LINUX) || defined(RT_OS_SOLARIS)
4410 if (Idtr.cbIdt < 0x0fff)
4411#else
4412 if (Idtr.cbIdt != 0xffff)
4413#endif
4414 {
4415 pVCpu->hm.s.vmx.fRestoreHostFlags |= VMX_RESTORE_HOST_IDTR;
4416 AssertCompile(sizeof(Idtr) == sizeof(X86XDTR64));
4417 memcpy(&pVCpu->hm.s.vmx.RestoreHost.HostIdtr, &Idtr, sizeof(X86XDTR64));
4418 }
4419
4420 /*
4421 * Host TR base. Verify that TR selector doesn't point past the GDT. Masking off the TI
4422 * and RPL bits is effectively what the CPU does for "scaling by 8". TI is always 0 and
4423 * RPL should be too in most cases.
4424 */
4425 AssertMsgReturn((uSelTR | X86_SEL_RPL_LDT) <= Gdtr.cbGdt,
4426 ("TR selector exceeds limit. TR=%RTsel cbGdt=%#x\n", uSelTR, Gdtr.cbGdt), VERR_VMX_INVALID_HOST_STATE);
4427
4428 PCX86DESCHC pDesc = (PCX86DESCHC)(Gdtr.pGdt + (uSelTR & X86_SEL_MASK));
4429 uintptr_t const uTRBase = X86DESC64_BASE(pDesc);
4430
4431 /*
4432 * VT-x unconditionally restores the TR limit to 0x67 and type to 11 (32-bit busy TSS) on
4433 * all VM-exits. The type is the same for 64-bit busy TSS[1]. The limit needs manual
4434 * restoration if the host has something else. Task switching is not supported in 64-bit
4435 * mode[2], but the limit still matters as IOPM is supported in 64-bit mode. Restoring the
4436 * limit lazily while returning to ring-3 is safe because IOPM is not applicable in ring-0.
4437 *
4438 * [1] See Intel spec. 3.5 "System Descriptor Types".
4439 * [2] See Intel spec. 7.2.3 "TSS Descriptor in 64-bit mode".
4440 */
4441 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
4442 Assert(pDesc->System.u4Type == 11);
4443 if ( pDesc->System.u16LimitLow != 0x67
4444 || pDesc->System.u4LimitHigh)
4445 {
4446 pVCpu->hm.s.vmx.fRestoreHostFlags |= VMX_RESTORE_HOST_SEL_TR;
4447 /* If the host has made GDT read-only, we would need to temporarily toggle CR0.WP before writing the GDT. */
4448 if (pVM->hm.s.fHostKernelFeatures & SUPKERNELFEATURES_GDT_READ_ONLY)
4449 pVCpu->hm.s.vmx.fRestoreHostFlags |= VMX_RESTORE_HOST_GDT_READ_ONLY;
4450 pVCpu->hm.s.vmx.RestoreHost.uHostSelTR = uSelTR;
4451 }
4452
4453 /*
4454 * Store the GDTR as we need it when restoring the GDT and while restoring the TR.
4455 */
4456 if (pVCpu->hm.s.vmx.fRestoreHostFlags & (VMX_RESTORE_HOST_GDTR | VMX_RESTORE_HOST_SEL_TR))
4457 {
4458 AssertCompile(sizeof(Gdtr) == sizeof(X86XDTR64));
4459 memcpy(&pVCpu->hm.s.vmx.RestoreHost.HostGdtr, &Gdtr, sizeof(X86XDTR64));
4460 if (pVM->hm.s.fHostKernelFeatures & SUPKERNELFEATURES_GDT_NEED_WRITABLE)
4461 {
4462 /* The GDT is read-only but the writable GDT is available. */
4463 pVCpu->hm.s.vmx.fRestoreHostFlags |= VMX_RESTORE_HOST_GDT_NEED_WRITABLE;
4464 pVCpu->hm.s.vmx.RestoreHost.HostGdtrRw.cb = Gdtr.cbGdt;
4465 rc = SUPR0GetCurrentGdtRw(&pVCpu->hm.s.vmx.RestoreHost.HostGdtrRw.uAddr);
4466 AssertRCReturn(rc, rc);
4467 }
4468 }
4469
4470 rc = VMXWriteVmcsNw(VMX_VMCS_HOST_TR_BASE, uTRBase);
4471 AssertRC(rc);
4472
4473 /*
4474 * Host FS base and GS base.
4475 */
4476 uint64_t const u64FSBase = ASMRdMsr(MSR_K8_FS_BASE);
4477 uint64_t const u64GSBase = ASMRdMsr(MSR_K8_GS_BASE);
4478 rc = VMXWriteVmcsNw(VMX_VMCS_HOST_FS_BASE, u64FSBase); AssertRC(rc);
4479 rc = VMXWriteVmcsNw(VMX_VMCS_HOST_GS_BASE, u64GSBase); AssertRC(rc);
4480
4481 /* Store the base if we have to restore FS or GS manually as we need to restore the base as well. */
4482 if (pVCpu->hm.s.vmx.fRestoreHostFlags & VMX_RESTORE_HOST_SEL_FS)
4483 pVCpu->hm.s.vmx.RestoreHost.uHostFSBase = u64FSBase;
4484 if (pVCpu->hm.s.vmx.fRestoreHostFlags & VMX_RESTORE_HOST_SEL_GS)
4485 pVCpu->hm.s.vmx.RestoreHost.uHostGSBase = u64GSBase;
4486
4487 return VINF_SUCCESS;
4488#undef VMXLOCAL_ADJUST_HOST_SEG
4489}
4490
4491
4492/**
4493 * Exports certain host MSRs in the VM-exit MSR-load area and some in the
4494 * host-state area of the VMCS.
4495 *
4496 * These MSRs will be automatically restored on the host after every successful
4497 * VM-exit.
4498 *
4499 * @param pVCpu The cross context virtual CPU structure.
4500 *
4501 * @remarks No-long-jump zone!!!
4502 */
4503static void hmR0VmxExportHostMsrs(PVMCPUCC pVCpu)
4504{
4505 AssertPtr(pVCpu);
4506
4507 /*
4508 * Save MSRs that we restore lazily (due to preemption or transition to ring-3)
4509 * rather than swapping them on every VM-entry.
4510 */
4511 hmR0VmxLazySaveHostMsrs(pVCpu);
4512
4513 /*
4514 * Host Sysenter MSRs.
4515 */
4516 int rc = VMXWriteVmcs32(VMX_VMCS32_HOST_SYSENTER_CS, ASMRdMsr_Low(MSR_IA32_SYSENTER_CS)); AssertRC(rc);
4517 rc = VMXWriteVmcsNw(VMX_VMCS_HOST_SYSENTER_ESP, ASMRdMsr(MSR_IA32_SYSENTER_ESP)); AssertRC(rc);
4518 rc = VMXWriteVmcsNw(VMX_VMCS_HOST_SYSENTER_EIP, ASMRdMsr(MSR_IA32_SYSENTER_EIP)); AssertRC(rc);
4519
4520 /*
4521 * Host EFER MSR.
4522 *
4523 * If the CPU supports the newer VMCS controls for managing EFER, use it. Otherwise it's
4524 * done as part of auto-load/store MSR area in the VMCS, see hmR0VmxExportGuestMsrs().
4525 */
4526 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
4527 if (pVM->hm.s.vmx.fSupportsVmcsEfer)
4528 {
4529 rc = VMXWriteVmcs64(VMX_VMCS64_HOST_EFER_FULL, pVM->hm.s.vmx.u64HostMsrEfer);
4530 AssertRC(rc);
4531 }
4532
4533 /** @todo IA32_PERF_GLOBALCTRL, IA32_PAT also see
4534 * hmR0VmxExportGuestEntryExitCtls(). */
4535}
4536
4537
4538/**
4539 * Figures out if we need to swap the EFER MSR which is particularly expensive.
4540 *
4541 * We check all relevant bits. For now, that's everything besides LMA/LME, as
4542 * these two bits are handled by VM-entry, see hmR0VMxExportGuestEntryExitCtls().
4543 *
4544 * @returns true if we need to load guest EFER, false otherwise.
4545 * @param pVCpu The cross context virtual CPU structure.
4546 * @param pVmxTransient The VMX-transient structure.
4547 *
4548 * @remarks Requires EFER, CR4.
4549 * @remarks No-long-jump zone!!!
4550 */
4551static bool hmR0VmxShouldSwapEferMsr(PCVMCPUCC pVCpu, PCVMXTRANSIENT pVmxTransient)
4552{
4553#ifdef HMVMX_ALWAYS_SWAP_EFER
4554 RT_NOREF2(pVCpu, pVmxTransient);
4555 return true;
4556#else
4557 PCCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
4558 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
4559 uint64_t const u64HostEfer = pVM->hm.s.vmx.u64HostMsrEfer;
4560 uint64_t const u64GuestEfer = pCtx->msrEFER;
4561
4562# ifdef VBOX_WITH_NESTED_HWVIRT_VMX
4563 /*
4564 * For nested-guests, we shall honor swapping the EFER MSR when requested by
4565 * the nested-guest.
4566 */
4567 if ( pVmxTransient->fIsNestedGuest
4568 && ( CPUMIsGuestVmxEntryCtlsSet(pVCpu, pCtx, VMX_ENTRY_CTLS_LOAD_EFER_MSR)
4569 || CPUMIsGuestVmxExitCtlsSet(pVCpu, pCtx, VMX_EXIT_CTLS_SAVE_EFER_MSR)
4570 || CPUMIsGuestVmxExitCtlsSet(pVCpu, pCtx, VMX_EXIT_CTLS_LOAD_EFER_MSR)))
4571 return true;
4572# else
4573 RT_NOREF(pVmxTransient);
4574#endif
4575
4576 /*
4577 * For 64-bit guests, if EFER.SCE bit differs, we need to swap the EFER MSR
4578 * to ensure that the guest's SYSCALL behaviour isn't broken, see @bugref{7386}.
4579 */
4580 if ( CPUMIsGuestInLongModeEx(pCtx)
4581 && (u64GuestEfer & MSR_K6_EFER_SCE) != (u64HostEfer & MSR_K6_EFER_SCE))
4582 return true;
4583
4584 /*
4585 * If the guest uses PAE and EFER.NXE bit differs, we need to swap the EFER MSR
4586 * as it affects guest paging. 64-bit paging implies CR4.PAE as well.
4587 *
4588 * See Intel spec. 4.5 "IA-32e Paging".
4589 * See Intel spec. 4.1.1 "Three Paging Modes".
4590 *
4591 * Verify that we always intercept CR4.PAE and CR0.PG bits, so we don't need to
4592 * import CR4 and CR0 from the VMCS here as those bits are always up to date.
4593 */
4594 Assert(hmR0VmxGetFixedCr4Mask(pVCpu) & X86_CR4_PAE);
4595 Assert(hmR0VmxGetFixedCr0Mask(pVCpu) & X86_CR0_PG);
4596 if ( (pCtx->cr4 & X86_CR4_PAE)
4597 && (pCtx->cr0 & X86_CR0_PG))
4598 {
4599 /*
4600 * If nested paging is not used, verify that the guest paging mode matches the
4601 * shadow paging mode which is/will be placed in the VMCS (which is what will
4602 * actually be used while executing the guest and not the CR4 shadow value).
4603 */
4604 AssertMsg(pVM->hm.s.fNestedPaging || ( pVCpu->hm.s.enmShadowMode == PGMMODE_PAE
4605 || pVCpu->hm.s.enmShadowMode == PGMMODE_PAE_NX
4606 || pVCpu->hm.s.enmShadowMode == PGMMODE_AMD64
4607 || pVCpu->hm.s.enmShadowMode == PGMMODE_AMD64_NX),
4608 ("enmShadowMode=%u\n", pVCpu->hm.s.enmShadowMode));
4609 if ((u64GuestEfer & MSR_K6_EFER_NXE) != (u64HostEfer & MSR_K6_EFER_NXE))
4610 {
4611 /* Verify that the host is NX capable. */
4612 Assert(pVCpu->CTX_SUFF(pVM)->cpum.ro.HostFeatures.fNoExecute);
4613 return true;
4614 }
4615 }
4616
4617 return false;
4618#endif
4619}
4620
4621
4622/**
4623 * Exports the guest state with appropriate VM-entry and VM-exit controls in the
4624 * VMCS.
4625 *
4626 * This is typically required when the guest changes paging mode.
4627 *
4628 * @returns VBox status code.
4629 * @param pVCpu The cross context virtual CPU structure.
4630 * @param pVmxTransient The VMX-transient structure.
4631 *
4632 * @remarks Requires EFER.
4633 * @remarks No-long-jump zone!!!
4634 */
4635static int hmR0VmxExportGuestEntryExitCtls(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
4636{
4637 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_VMX_ENTRY_EXIT_CTLS)
4638 {
4639 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
4640 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
4641
4642 /*
4643 * VM-entry controls.
4644 */
4645 {
4646 uint32_t fVal = pVM->hm.s.vmx.Msrs.EntryCtls.n.allowed0; /* Bits set here must be set in the VMCS. */
4647 uint32_t const fZap = pVM->hm.s.vmx.Msrs.EntryCtls.n.allowed1; /* Bits cleared here must be cleared in the VMCS. */
4648
4649 /*
4650 * Load the guest debug controls (DR7 and IA32_DEBUGCTL MSR) on VM-entry.
4651 * The first VT-x capable CPUs only supported the 1-setting of this bit.
4652 *
4653 * For nested-guests, this is a mandatory VM-entry control. It's also
4654 * required because we do not want to leak host bits to the nested-guest.
4655 */
4656 fVal |= VMX_ENTRY_CTLS_LOAD_DEBUG;
4657
4658 /*
4659 * Set if the guest is in long mode. This will set/clear the EFER.LMA bit on VM-entry.
4660 *
4661 * For nested-guests, the "IA-32e mode guest" control we initialize with what is
4662 * required to get the nested-guest working with hardware-assisted VMX execution.
4663 * It depends on the nested-guest's IA32_EFER.LMA bit. Remember, a guest hypervisor
4664 * can skip intercepting changes to the EFER MSR. This is why it it needs to be done
4665 * here rather than while merging the guest VMCS controls.
4666 */
4667 if (CPUMIsGuestInLongModeEx(&pVCpu->cpum.GstCtx))
4668 {
4669 Assert(pVCpu->cpum.GstCtx.msrEFER & MSR_K6_EFER_LME);
4670 fVal |= VMX_ENTRY_CTLS_IA32E_MODE_GUEST;
4671 }
4672 else
4673 Assert(!(fVal & VMX_ENTRY_CTLS_IA32E_MODE_GUEST));
4674
4675 /*
4676 * If the CPU supports the newer VMCS controls for managing guest/host EFER, use it.
4677 *
4678 * For nested-guests, we use the "load IA32_EFER" if the hardware supports it,
4679 * regardless of whether the nested-guest VMCS specifies it because we are free to
4680 * load whatever MSRs we require and we do not need to modify the guest visible copy
4681 * of the VM-entry MSR load area.
4682 */
4683 if ( pVM->hm.s.vmx.fSupportsVmcsEfer
4684 && hmR0VmxShouldSwapEferMsr(pVCpu, pVmxTransient))
4685 fVal |= VMX_ENTRY_CTLS_LOAD_EFER_MSR;
4686 else
4687 Assert(!(fVal & VMX_ENTRY_CTLS_LOAD_EFER_MSR));
4688
4689 /*
4690 * The following should -not- be set (since we're not in SMM mode):
4691 * - VMX_ENTRY_CTLS_ENTRY_TO_SMM
4692 * - VMX_ENTRY_CTLS_DEACTIVATE_DUAL_MON
4693 */
4694
4695 /** @todo VMX_ENTRY_CTLS_LOAD_PERF_MSR,
4696 * VMX_ENTRY_CTLS_LOAD_PAT_MSR. */
4697
4698 if ((fVal & fZap) == fVal)
4699 { /* likely */ }
4700 else
4701 {
4702 Log4Func(("Invalid VM-entry controls combo! Cpu=%#RX32 fVal=%#RX32 fZap=%#RX32\n",
4703 pVM->hm.s.vmx.Msrs.EntryCtls.n.allowed0, fVal, fZap));
4704 pVCpu->hm.s.u32HMError = VMX_UFC_CTRL_ENTRY;
4705 return VERR_HM_UNSUPPORTED_CPU_FEATURE_COMBO;
4706 }
4707
4708 /* Commit it to the VMCS. */
4709 if (pVmcsInfo->u32EntryCtls != fVal)
4710 {
4711 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_ENTRY, fVal);
4712 AssertRC(rc);
4713 pVmcsInfo->u32EntryCtls = fVal;
4714 }
4715 }
4716
4717 /*
4718 * VM-exit controls.
4719 */
4720 {
4721 uint32_t fVal = pVM->hm.s.vmx.Msrs.ExitCtls.n.allowed0; /* Bits set here must be set in the VMCS. */
4722 uint32_t const fZap = pVM->hm.s.vmx.Msrs.ExitCtls.n.allowed1; /* Bits cleared here must be cleared in the VMCS. */
4723
4724 /*
4725 * Save debug controls (DR7 & IA32_DEBUGCTL_MSR). The first VT-x CPUs only
4726 * supported the 1-setting of this bit.
4727 *
4728 * For nested-guests, we set the "save debug controls" as the converse
4729 * "load debug controls" is mandatory for nested-guests anyway.
4730 */
4731 fVal |= VMX_EXIT_CTLS_SAVE_DEBUG;
4732
4733 /*
4734 * Set the host long mode active (EFER.LMA) bit (which Intel calls
4735 * "Host address-space size") if necessary. On VM-exit, VT-x sets both the
4736 * host EFER.LMA and EFER.LME bit to this value. See assertion in
4737 * hmR0VmxExportHostMsrs().
4738 *
4739 * For nested-guests, we always set this bit as we do not support 32-bit
4740 * hosts.
4741 */
4742 fVal |= VMX_EXIT_CTLS_HOST_ADDR_SPACE_SIZE;
4743
4744 /*
4745 * If the VMCS EFER MSR fields are supported by the hardware, we use it.
4746 *
4747 * For nested-guests, we should use the "save IA32_EFER" control if we also
4748 * used the "load IA32_EFER" control while exporting VM-entry controls.
4749 */
4750 if ( pVM->hm.s.vmx.fSupportsVmcsEfer
4751 && hmR0VmxShouldSwapEferMsr(pVCpu, pVmxTransient))
4752 {
4753 fVal |= VMX_EXIT_CTLS_SAVE_EFER_MSR
4754 | VMX_EXIT_CTLS_LOAD_EFER_MSR;
4755 }
4756
4757 /*
4758 * Enable saving of the VMX-preemption timer value on VM-exit.
4759 * For nested-guests, currently not exposed/used.
4760 */
4761 if ( pVM->hm.s.vmx.fUsePreemptTimer
4762 && (pVM->hm.s.vmx.Msrs.ExitCtls.n.allowed1 & VMX_EXIT_CTLS_SAVE_PREEMPT_TIMER))
4763 fVal |= VMX_EXIT_CTLS_SAVE_PREEMPT_TIMER;
4764
4765 /* Don't acknowledge external interrupts on VM-exit. We want to let the host do that. */
4766 Assert(!(fVal & VMX_EXIT_CTLS_ACK_EXT_INT));
4767
4768 /** @todo VMX_EXIT_CTLS_LOAD_PERF_MSR,
4769 * VMX_EXIT_CTLS_SAVE_PAT_MSR,
4770 * VMX_EXIT_CTLS_LOAD_PAT_MSR. */
4771
4772 if ((fVal & fZap) == fVal)
4773 { /* likely */ }
4774 else
4775 {
4776 Log4Func(("Invalid VM-exit controls combo! cpu=%#RX32 fVal=%#RX32 fZap=%R#X32\n",
4777 pVM->hm.s.vmx.Msrs.ExitCtls.n.allowed0, fVal, fZap));
4778 pVCpu->hm.s.u32HMError = VMX_UFC_CTRL_EXIT;
4779 return VERR_HM_UNSUPPORTED_CPU_FEATURE_COMBO;
4780 }
4781
4782 /* Commit it to the VMCS. */
4783 if (pVmcsInfo->u32ExitCtls != fVal)
4784 {
4785 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_EXIT, fVal);
4786 AssertRC(rc);
4787 pVmcsInfo->u32ExitCtls = fVal;
4788 }
4789 }
4790
4791 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_VMX_ENTRY_EXIT_CTLS);
4792 }
4793 return VINF_SUCCESS;
4794}
4795
4796
4797/**
4798 * Sets the TPR threshold in the VMCS.
4799 *
4800 * @param pVmcsInfo The VMCS info. object.
4801 * @param u32TprThreshold The TPR threshold (task-priority class only).
4802 */
4803DECLINLINE(void) hmR0VmxApicSetTprThreshold(PVMXVMCSINFO pVmcsInfo, uint32_t u32TprThreshold)
4804{
4805 Assert(!(u32TprThreshold & ~VMX_TPR_THRESHOLD_MASK)); /* Bits 31:4 MBZ. */
4806 Assert(pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_USE_TPR_SHADOW);
4807 RT_NOREF(pVmcsInfo);
4808 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_TPR_THRESHOLD, u32TprThreshold);
4809 AssertRC(rc);
4810}
4811
4812
4813/**
4814 * Exports the guest APIC TPR state into the VMCS.
4815 *
4816 * @returns VBox status code.
4817 * @param pVCpu The cross context virtual CPU structure.
4818 * @param pVmxTransient The VMX-transient structure.
4819 *
4820 * @remarks No-long-jump zone!!!
4821 */
4822static int hmR0VmxExportGuestApicTpr(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
4823{
4824 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_APIC_TPR)
4825 {
4826 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_APIC_TPR);
4827
4828 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
4829 if (!pVmxTransient->fIsNestedGuest)
4830 {
4831 if ( PDMHasApic(pVCpu->CTX_SUFF(pVM))
4832 && APICIsEnabled(pVCpu))
4833 {
4834 /*
4835 * Setup TPR shadowing.
4836 */
4837 if (pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_USE_TPR_SHADOW)
4838 {
4839 bool fPendingIntr = false;
4840 uint8_t u8Tpr = 0;
4841 uint8_t u8PendingIntr = 0;
4842 int rc = APICGetTpr(pVCpu, &u8Tpr, &fPendingIntr, &u8PendingIntr);
4843 AssertRCReturn(rc, rc);
4844
4845 /*
4846 * If there are interrupts pending but masked by the TPR, instruct VT-x to
4847 * cause a TPR-below-threshold VM-exit when the guest lowers its TPR below the
4848 * priority of the pending interrupt so we can deliver the interrupt. If there
4849 * are no interrupts pending, set threshold to 0 to not cause any
4850 * TPR-below-threshold VM-exits.
4851 */
4852 uint32_t u32TprThreshold = 0;
4853 if (fPendingIntr)
4854 {
4855 /* Bits 3:0 of the TPR threshold field correspond to bits 7:4 of the TPR
4856 (which is the Task-Priority Class). */
4857 const uint8_t u8PendingPriority = u8PendingIntr >> 4;
4858 const uint8_t u8TprPriority = u8Tpr >> 4;
4859 if (u8PendingPriority <= u8TprPriority)
4860 u32TprThreshold = u8PendingPriority;
4861 }
4862
4863 hmR0VmxApicSetTprThreshold(pVmcsInfo, u32TprThreshold);
4864 }
4865 }
4866 }
4867 /* else: the TPR threshold has already been updated while merging the nested-guest VMCS. */
4868 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_APIC_TPR);
4869 }
4870 return VINF_SUCCESS;
4871}
4872
4873
4874/**
4875 * Gets the guest interruptibility-state.
4876 *
4877 * @returns Guest's interruptibility-state.
4878 * @param pVCpu The cross context virtual CPU structure.
4879 * @param pVmxTransient The VMX-transient structure.
4880 *
4881 * @remarks No-long-jump zone!!!
4882 */
4883static uint32_t hmR0VmxGetGuestIntrState(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
4884{
4885 /*
4886 * Check if we should inhibit interrupt delivery due to instructions like STI and MOV SS.
4887 */
4888 uint32_t fIntrState = 0;
4889 if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS))
4890 {
4891 /* If inhibition is active, RIP and RFLAGS should've been imported from the VMCS already. */
4892 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_RIP | CPUMCTX_EXTRN_RFLAGS);
4893
4894 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
4895 if (pCtx->rip == EMGetInhibitInterruptsPC(pVCpu))
4896 {
4897 if (pCtx->eflags.Bits.u1IF)
4898 fIntrState = VMX_VMCS_GUEST_INT_STATE_BLOCK_STI;
4899 else
4900 fIntrState = VMX_VMCS_GUEST_INT_STATE_BLOCK_MOVSS;
4901 }
4902 else if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS))
4903 {
4904 /*
4905 * We can clear the inhibit force flag as even if we go back to the recompiler
4906 * without executing guest code in VT-x, the flag's condition to be cleared is
4907 * met and thus the cleared state is correct.
4908 */
4909 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS);
4910 }
4911 }
4912
4913 /*
4914 * NMIs to the guest are blocked after an NMI is injected until the guest executes an IRET. We only
4915 * bother with virtual-NMI blocking when we have support for virtual NMIs in the CPU, otherwise
4916 * setting this would block host-NMIs and IRET will not clear the blocking.
4917 *
4918 * We always set NMI-exiting so when the host receives an NMI we get a VM-exit.
4919 *
4920 * See Intel spec. 26.6.1 "Interruptibility state". See @bugref{7445}.
4921 */
4922 PCVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
4923 if ( (pVmcsInfo->u32PinCtls & VMX_PIN_CTLS_VIRT_NMI)
4924 && CPUMIsGuestNmiBlocking(pVCpu))
4925 fIntrState |= VMX_VMCS_GUEST_INT_STATE_BLOCK_NMI;
4926
4927 return fIntrState;
4928}
4929
4930
4931/**
4932 * Exports the exception intercepts required for guest execution in the VMCS.
4933 *
4934 * @returns VBox status code.
4935 * @param pVCpu The cross context virtual CPU structure.
4936 * @param pVmxTransient The VMX-transient structure.
4937 *
4938 * @remarks No-long-jump zone!!!
4939 */
4940static int hmR0VmxExportGuestXcptIntercepts(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
4941{
4942 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_VMX_XCPT_INTERCEPTS)
4943 {
4944 /* When executing a nested-guest, we do not need to trap GIM hypercalls by intercepting #UD. */
4945 if ( !pVmxTransient->fIsNestedGuest
4946 && pVCpu->hm.s.fGIMTrapXcptUD)
4947 hmR0VmxAddXcptIntercept(pVmxTransient, X86_XCPT_UD);
4948 else
4949 hmR0VmxRemoveXcptIntercept(pVCpu, pVmxTransient, X86_XCPT_UD);
4950
4951 /* Other exception intercepts are handled elsewhere, e.g. while exporting guest CR0. */
4952 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_VMX_XCPT_INTERCEPTS);
4953 }
4954 return VINF_SUCCESS;
4955}
4956
4957
4958/**
4959 * Exports the guest's RIP into the guest-state area in the VMCS.
4960 *
4961 * @returns VBox status code.
4962 * @param pVCpu The cross context virtual CPU structure.
4963 *
4964 * @remarks No-long-jump zone!!!
4965 */
4966static int hmR0VmxExportGuestRip(PVMCPUCC pVCpu)
4967{
4968 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_RIP)
4969 {
4970 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_RIP);
4971
4972 int rc = VMXWriteVmcsNw(VMX_VMCS_GUEST_RIP, pVCpu->cpum.GstCtx.rip);
4973 AssertRC(rc);
4974
4975 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_RIP);
4976 Log4Func(("rip=%#RX64\n", pVCpu->cpum.GstCtx.rip));
4977 }
4978 return VINF_SUCCESS;
4979}
4980
4981
4982/**
4983 * Exports the guest's RSP into the guest-state area in the VMCS.
4984 *
4985 * @returns VBox status code.
4986 * @param pVCpu The cross context virtual CPU structure.
4987 *
4988 * @remarks No-long-jump zone!!!
4989 */
4990static int hmR0VmxExportGuestRsp(PVMCPUCC pVCpu)
4991{
4992 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_RSP)
4993 {
4994 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_RSP);
4995
4996 int rc = VMXWriteVmcsNw(VMX_VMCS_GUEST_RSP, pVCpu->cpum.GstCtx.rsp);
4997 AssertRC(rc);
4998
4999 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_RSP);
5000 Log4Func(("rsp=%#RX64\n", pVCpu->cpum.GstCtx.rsp));
5001 }
5002 return VINF_SUCCESS;
5003}
5004
5005
5006/**
5007 * Exports the guest's RFLAGS into the guest-state area in the VMCS.
5008 *
5009 * @returns VBox status code.
5010 * @param pVCpu The cross context virtual CPU structure.
5011 * @param pVmxTransient The VMX-transient structure.
5012 *
5013 * @remarks No-long-jump zone!!!
5014 */
5015static int hmR0VmxExportGuestRflags(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
5016{
5017 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_RFLAGS)
5018 {
5019 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_RFLAGS);
5020
5021 /* Intel spec. 2.3.1 "System Flags and Fields in IA-32e Mode" claims the upper 32-bits of RFLAGS are reserved (MBZ).
5022 Let us assert it as such and use 32-bit VMWRITE. */
5023 Assert(!RT_HI_U32(pVCpu->cpum.GstCtx.rflags.u64));
5024 X86EFLAGS fEFlags = pVCpu->cpum.GstCtx.eflags;
5025 Assert(fEFlags.u32 & X86_EFL_RA1_MASK);
5026 Assert(!(fEFlags.u32 & ~(X86_EFL_1 | X86_EFL_LIVE_MASK)));
5027
5028 /*
5029 * If we're emulating real-mode using Virtual 8086 mode, save the real-mode eflags so
5030 * we can restore them on VM-exit. Modify the real-mode guest's eflags so that VT-x
5031 * can run the real-mode guest code under Virtual 8086 mode.
5032 */
5033 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
5034 if (pVmcsInfo->RealMode.fRealOnV86Active)
5035 {
5036 Assert(pVCpu->CTX_SUFF(pVM)->hm.s.vmx.pRealModeTSS);
5037 Assert(PDMVmmDevHeapIsEnabled(pVCpu->CTX_SUFF(pVM)));
5038 Assert(!pVmxTransient->fIsNestedGuest);
5039 pVmcsInfo->RealMode.Eflags.u32 = fEFlags.u32; /* Save the original eflags of the real-mode guest. */
5040 fEFlags.Bits.u1VM = 1; /* Set the Virtual 8086 mode bit. */
5041 fEFlags.Bits.u2IOPL = 0; /* Change IOPL to 0, otherwise certain instructions won't fault. */
5042 }
5043
5044 int rc = VMXWriteVmcsNw(VMX_VMCS_GUEST_RFLAGS, fEFlags.u32);
5045 AssertRC(rc);
5046
5047 /*
5048 * Setup pending debug exceptions if the guest is single-stepping using EFLAGS.TF.
5049 *
5050 * We must avoid setting any automatic debug exceptions delivery when single-stepping
5051 * through the hypervisor debugger using EFLAGS.TF.
5052 */
5053 if ( !pVmxTransient->fIsNestedGuest
5054 && !pVCpu->hm.s.fSingleInstruction
5055 && fEFlags.Bits.u1TF)
5056 {
5057 /** @todo r=ramshankar: Warning!! We ASSUME EFLAGS.TF will not cleared on
5058 * premature trips to ring-3 esp since IEM does not yet handle it. */
5059 rc = VMXWriteVmcsNw(VMX_VMCS_GUEST_PENDING_DEBUG_XCPTS, VMX_VMCS_GUEST_PENDING_DEBUG_XCPT_BS);
5060 AssertRC(rc);
5061 }
5062 /* else: for nested-guest currently handling while merging controls. */
5063
5064 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_RFLAGS);
5065 Log4Func(("eflags=%#RX32\n", fEFlags.u32));
5066 }
5067 return VINF_SUCCESS;
5068}
5069
5070
5071#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
5072/**
5073 * Copies the nested-guest VMCS to the shadow VMCS.
5074 *
5075 * @returns VBox status code.
5076 * @param pVCpu The cross context virtual CPU structure.
5077 * @param pVmcsInfo The VMCS info. object.
5078 *
5079 * @remarks No-long-jump zone!!!
5080 */
5081static int hmR0VmxCopyNstGstToShadowVmcs(PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo)
5082{
5083 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
5084 PCVMXVVMCS pVmcsNstGst = pVCpu->cpum.GstCtx.hwvirt.vmx.CTX_SUFF(pVmcs);
5085
5086 /*
5087 * Disable interrupts so we don't get preempted while the shadow VMCS is the
5088 * current VMCS, as we may try saving guest lazy MSRs.
5089 *
5090 * Strictly speaking the lazy MSRs are not in the VMCS, but I'd rather not risk
5091 * calling the import VMCS code which is currently performing the guest MSR reads
5092 * (on 64-bit hosts) and accessing the auto-load/store MSR area on 32-bit hosts
5093 * and the rest of the VMX leave session machinery.
5094 */
5095 RTCCUINTREG const fEFlags = ASMIntDisableFlags();
5096
5097 int rc = hmR0VmxLoadShadowVmcs(pVmcsInfo);
5098 if (RT_SUCCESS(rc))
5099 {
5100 /*
5101 * Copy all guest read/write VMCS fields.
5102 *
5103 * We don't check for VMWRITE failures here for performance reasons and
5104 * because they are not expected to fail, barring irrecoverable conditions
5105 * like hardware errors.
5106 */
5107 uint32_t const cShadowVmcsFields = pVM->hm.s.vmx.cShadowVmcsFields;
5108 for (uint32_t i = 0; i < cShadowVmcsFields; i++)
5109 {
5110 uint64_t u64Val;
5111 uint32_t const uVmcsField = pVM->hm.s.vmx.paShadowVmcsFields[i];
5112 IEMReadVmxVmcsField(pVmcsNstGst, uVmcsField, &u64Val);
5113 VMXWriteVmcs64(uVmcsField, u64Val);
5114 }
5115
5116 /*
5117 * If the host CPU supports writing all VMCS fields, copy the guest read-only
5118 * VMCS fields, so the guest can VMREAD them without causing a VM-exit.
5119 */
5120 if (pVM->hm.s.vmx.Msrs.u64Misc & VMX_MISC_VMWRITE_ALL)
5121 {
5122 uint32_t const cShadowVmcsRoFields = pVM->hm.s.vmx.cShadowVmcsRoFields;
5123 for (uint32_t i = 0; i < cShadowVmcsRoFields; i++)
5124 {
5125 uint64_t u64Val;
5126 uint32_t const uVmcsField = pVM->hm.s.vmx.paShadowVmcsRoFields[i];
5127 IEMReadVmxVmcsField(pVmcsNstGst, uVmcsField, &u64Val);
5128 VMXWriteVmcs64(uVmcsField, u64Val);
5129 }
5130 }
5131
5132 rc = hmR0VmxClearShadowVmcs(pVmcsInfo);
5133 rc |= hmR0VmxLoadVmcs(pVmcsInfo);
5134 }
5135
5136 ASMSetFlags(fEFlags);
5137 return rc;
5138}
5139
5140
5141/**
5142 * Copies the shadow VMCS to the nested-guest VMCS.
5143 *
5144 * @returns VBox status code.
5145 * @param pVCpu The cross context virtual CPU structure.
5146 * @param pVmcsInfo The VMCS info. object.
5147 *
5148 * @remarks Called with interrupts disabled.
5149 */
5150static int hmR0VmxCopyShadowToNstGstVmcs(PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo)
5151{
5152 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
5153 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
5154 PVMXVVMCS pVmcsNstGst = pVCpu->cpum.GstCtx.hwvirt.vmx.CTX_SUFF(pVmcs);
5155
5156 int rc = hmR0VmxLoadShadowVmcs(pVmcsInfo);
5157 if (RT_SUCCESS(rc))
5158 {
5159 /*
5160 * Copy guest read/write fields from the shadow VMCS.
5161 * Guest read-only fields cannot be modified, so no need to copy them.
5162 *
5163 * We don't check for VMREAD failures here for performance reasons and
5164 * because they are not expected to fail, barring irrecoverable conditions
5165 * like hardware errors.
5166 */
5167 uint32_t const cShadowVmcsFields = pVM->hm.s.vmx.cShadowVmcsFields;
5168 for (uint32_t i = 0; i < cShadowVmcsFields; i++)
5169 {
5170 uint64_t u64Val;
5171 uint32_t const uVmcsField = pVM->hm.s.vmx.paShadowVmcsFields[i];
5172 VMXReadVmcs64(uVmcsField, &u64Val);
5173 IEMWriteVmxVmcsField(pVmcsNstGst, uVmcsField, u64Val);
5174 }
5175
5176 rc = hmR0VmxClearShadowVmcs(pVmcsInfo);
5177 rc |= hmR0VmxLoadVmcs(pVmcsInfo);
5178 }
5179 return rc;
5180}
5181
5182
5183/**
5184 * Enables VMCS shadowing for the given VMCS info. object.
5185 *
5186 * @param pVmcsInfo The VMCS info. object.
5187 *
5188 * @remarks No-long-jump zone!!!
5189 */
5190static void hmR0VmxEnableVmcsShadowing(PVMXVMCSINFO pVmcsInfo)
5191{
5192 uint32_t uProcCtls2 = pVmcsInfo->u32ProcCtls2;
5193 if (!(uProcCtls2 & VMX_PROC_CTLS2_VMCS_SHADOWING))
5194 {
5195 Assert(pVmcsInfo->HCPhysShadowVmcs != 0 && pVmcsInfo->HCPhysShadowVmcs != NIL_RTHCPHYS);
5196 uProcCtls2 |= VMX_PROC_CTLS2_VMCS_SHADOWING;
5197 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC2, uProcCtls2); AssertRC(rc);
5198 rc = VMXWriteVmcs64(VMX_VMCS64_GUEST_VMCS_LINK_PTR_FULL, pVmcsInfo->HCPhysShadowVmcs); AssertRC(rc);
5199 pVmcsInfo->u32ProcCtls2 = uProcCtls2;
5200 pVmcsInfo->u64VmcsLinkPtr = pVmcsInfo->HCPhysShadowVmcs;
5201 Log4Func(("Enabled\n"));
5202 }
5203}
5204
5205
5206/**
5207 * Disables VMCS shadowing for the given VMCS info. object.
5208 *
5209 * @param pVmcsInfo The VMCS info. object.
5210 *
5211 * @remarks No-long-jump zone!!!
5212 */
5213static void hmR0VmxDisableVmcsShadowing(PVMXVMCSINFO pVmcsInfo)
5214{
5215 /*
5216 * We want all VMREAD and VMWRITE instructions to cause VM-exits, so we clear the
5217 * VMCS shadowing control. However, VM-entry requires the shadow VMCS indicator bit
5218 * to match the VMCS shadowing control if the VMCS link pointer is not NIL_RTHCPHYS.
5219 * Hence, we must also reset the VMCS link pointer to ensure VM-entry does not fail.
5220 *
5221 * See Intel spec. 26.2.1.1 "VM-Execution Control Fields".
5222 * See Intel spec. 26.3.1.5 "Checks on Guest Non-Register State".
5223 */
5224 uint32_t uProcCtls2 = pVmcsInfo->u32ProcCtls2;
5225 if (uProcCtls2 & VMX_PROC_CTLS2_VMCS_SHADOWING)
5226 {
5227 uProcCtls2 &= ~VMX_PROC_CTLS2_VMCS_SHADOWING;
5228 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC2, uProcCtls2); AssertRC(rc);
5229 rc = VMXWriteVmcs64(VMX_VMCS64_GUEST_VMCS_LINK_PTR_FULL, NIL_RTHCPHYS); AssertRC(rc);
5230 pVmcsInfo->u32ProcCtls2 = uProcCtls2;
5231 pVmcsInfo->u64VmcsLinkPtr = NIL_RTHCPHYS;
5232 Log4Func(("Disabled\n"));
5233 }
5234}
5235#endif
5236
5237
5238/**
5239 * Exports the guest hardware-virtualization state.
5240 *
5241 * @returns VBox status code.
5242 * @param pVCpu The cross context virtual CPU structure.
5243 * @param pVmxTransient The VMX-transient structure.
5244 *
5245 * @remarks No-long-jump zone!!!
5246 */
5247static int hmR0VmxExportGuestHwvirtState(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
5248{
5249 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_HWVIRT)
5250 {
5251#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
5252 /*
5253 * Check if the VMX feature is exposed to the guest and if the host CPU supports
5254 * VMCS shadowing.
5255 */
5256 if (pVCpu->CTX_SUFF(pVM)->hm.s.vmx.fUseVmcsShadowing)
5257 {
5258 /*
5259 * If the guest hypervisor has loaded a current VMCS and is in VMX root mode,
5260 * copy the guest hypervisor's current VMCS into the shadow VMCS and enable
5261 * VMCS shadowing to skip intercepting some or all VMREAD/VMWRITE VM-exits.
5262 *
5263 * We check for VMX root mode here in case the guest executes VMXOFF without
5264 * clearing the current VMCS pointer and our VMXOFF instruction emulation does
5265 * not clear the current VMCS pointer.
5266 */
5267 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
5268 if ( CPUMIsGuestInVmxRootMode(&pVCpu->cpum.GstCtx)
5269 && !CPUMIsGuestInVmxNonRootMode(&pVCpu->cpum.GstCtx)
5270 && CPUMIsGuestVmxCurrentVmcsValid(pVCpu, &pVCpu->cpum.GstCtx))
5271 {
5272 /* Paranoia. */
5273 Assert(!pVmxTransient->fIsNestedGuest);
5274
5275 /*
5276 * For performance reasons, also check if the guest hypervisor's current VMCS
5277 * was newly loaded or modified before copying it to the shadow VMCS.
5278 */
5279 if (!pVCpu->hm.s.vmx.fCopiedNstGstToShadowVmcs)
5280 {
5281 int rc = hmR0VmxCopyNstGstToShadowVmcs(pVCpu, pVmcsInfo);
5282 AssertRCReturn(rc, rc);
5283 pVCpu->hm.s.vmx.fCopiedNstGstToShadowVmcs = true;
5284 }
5285 hmR0VmxEnableVmcsShadowing(pVmcsInfo);
5286 }
5287 else
5288 hmR0VmxDisableVmcsShadowing(pVmcsInfo);
5289 }
5290#else
5291 NOREF(pVmxTransient);
5292#endif
5293 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_HWVIRT);
5294 }
5295 return VINF_SUCCESS;
5296}
5297
5298
5299/**
5300 * Exports the guest CR0 control register into the guest-state area in the VMCS.
5301 *
5302 * The guest FPU state is always pre-loaded hence we don't need to bother about
5303 * sharing FPU related CR0 bits between the guest and host.
5304 *
5305 * @returns VBox status code.
5306 * @param pVCpu The cross context virtual CPU structure.
5307 * @param pVmxTransient The VMX-transient structure.
5308 *
5309 * @remarks No-long-jump zone!!!
5310 */
5311static int hmR0VmxExportGuestCR0(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
5312{
5313 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_CR0)
5314 {
5315 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
5316 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
5317
5318 /*
5319 * Figure out fixed CR0 bits in VMX operation.
5320 */
5321 uint64_t fSetCr0 = pVM->hm.s.vmx.Msrs.u64Cr0Fixed0;
5322 uint64_t const fZapCr0 = pVM->hm.s.vmx.Msrs.u64Cr0Fixed1;
5323 if (pVM->hm.s.vmx.fUnrestrictedGuest)
5324 fSetCr0 &= ~(uint64_t)(X86_CR0_PE | X86_CR0_PG);
5325 else
5326 Assert((fSetCr0 & (X86_CR0_PE | X86_CR0_PG)) == (X86_CR0_PE | X86_CR0_PG));
5327
5328 if (!pVmxTransient->fIsNestedGuest)
5329 {
5330 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_CR0);
5331 uint64_t u64GuestCr0 = pVCpu->cpum.GstCtx.cr0;
5332 uint64_t const u64ShadowCr0 = u64GuestCr0;
5333 Assert(!RT_HI_U32(u64GuestCr0));
5334
5335 /*
5336 * Setup VT-x's view of the guest CR0.
5337 */
5338 uint32_t uProcCtls = pVmcsInfo->u32ProcCtls;
5339 if (pVM->hm.s.fNestedPaging)
5340 {
5341 if (CPUMIsGuestPagingEnabled(pVCpu))
5342 {
5343 /* The guest has paging enabled, let it access CR3 without causing a VM-exit if supported. */
5344 uProcCtls &= ~( VMX_PROC_CTLS_CR3_LOAD_EXIT
5345 | VMX_PROC_CTLS_CR3_STORE_EXIT);
5346 }
5347 else
5348 {
5349 /* The guest doesn't have paging enabled, make CR3 access cause a VM-exit to update our shadow. */
5350 uProcCtls |= VMX_PROC_CTLS_CR3_LOAD_EXIT
5351 | VMX_PROC_CTLS_CR3_STORE_EXIT;
5352 }
5353
5354 /* If we have unrestricted guest execution, we never have to intercept CR3 reads. */
5355 if (pVM->hm.s.vmx.fUnrestrictedGuest)
5356 uProcCtls &= ~VMX_PROC_CTLS_CR3_STORE_EXIT;
5357 }
5358 else
5359 {
5360 /* Guest CPL 0 writes to its read-only pages should cause a #PF VM-exit. */
5361 u64GuestCr0 |= X86_CR0_WP;
5362 }
5363
5364 /*
5365 * Guest FPU bits.
5366 *
5367 * Since we pre-load the guest FPU always before VM-entry there is no need to track lazy state
5368 * using CR0.TS.
5369 *
5370 * Intel spec. 23.8 "Restrictions on VMX operation" mentions that CR0.NE bit must always be
5371 * set on the first CPUs to support VT-x and no mention of with regards to UX in VM-entry checks.
5372 */
5373 u64GuestCr0 |= X86_CR0_NE;
5374
5375 /* If CR0.NE isn't set, we need to intercept #MF exceptions and report them to the guest differently. */
5376 bool const fInterceptMF = !(u64ShadowCr0 & X86_CR0_NE);
5377
5378 /*
5379 * Update exception intercepts.
5380 */
5381 uint32_t uXcptBitmap = pVmcsInfo->u32XcptBitmap;
5382 if (pVmcsInfo->RealMode.fRealOnV86Active)
5383 {
5384 Assert(PDMVmmDevHeapIsEnabled(pVM));
5385 Assert(pVM->hm.s.vmx.pRealModeTSS);
5386 uXcptBitmap |= HMVMX_REAL_MODE_XCPT_MASK;
5387 }
5388 else
5389 {
5390 /* For now, cleared here as mode-switches can happen outside HM/VT-x. See @bugref{7626#c11}. */
5391 uXcptBitmap &= ~HMVMX_REAL_MODE_XCPT_MASK;
5392 if (fInterceptMF)
5393 uXcptBitmap |= RT_BIT(X86_XCPT_MF);
5394 }
5395
5396 /* Additional intercepts for debugging, define these yourself explicitly. */
5397#ifdef HMVMX_ALWAYS_TRAP_ALL_XCPTS
5398 uXcptBitmap |= 0
5399 | RT_BIT(X86_XCPT_BP)
5400 | RT_BIT(X86_XCPT_DE)
5401 | RT_BIT(X86_XCPT_NM)
5402 | RT_BIT(X86_XCPT_TS)
5403 | RT_BIT(X86_XCPT_UD)
5404 | RT_BIT(X86_XCPT_NP)
5405 | RT_BIT(X86_XCPT_SS)
5406 | RT_BIT(X86_XCPT_GP)
5407 | RT_BIT(X86_XCPT_PF)
5408 | RT_BIT(X86_XCPT_MF)
5409 ;
5410#elif defined(HMVMX_ALWAYS_TRAP_PF)
5411 uXcptBitmap |= RT_BIT(X86_XCPT_PF);
5412#endif
5413 if (pVCpu->hm.s.fTrapXcptGpForLovelyMesaDrv)
5414 uXcptBitmap |= RT_BIT(X86_XCPT_GP);
5415 Assert(pVM->hm.s.fNestedPaging || (uXcptBitmap & RT_BIT(X86_XCPT_PF)));
5416
5417 /* Apply the hardware specified fixed CR0 bits and enable caching. */
5418 u64GuestCr0 |= fSetCr0;
5419 u64GuestCr0 &= fZapCr0;
5420 u64GuestCr0 &= ~(uint64_t)(X86_CR0_CD | X86_CR0_NW);
5421
5422 /* Commit the CR0 and related fields to the guest VMCS. */
5423 int rc = VMXWriteVmcsNw(VMX_VMCS_GUEST_CR0, u64GuestCr0); AssertRC(rc);
5424 rc = VMXWriteVmcsNw(VMX_VMCS_CTRL_CR0_READ_SHADOW, u64ShadowCr0); AssertRC(rc);
5425 if (uProcCtls != pVmcsInfo->u32ProcCtls)
5426 {
5427 rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, uProcCtls);
5428 AssertRC(rc);
5429 }
5430 if (uXcptBitmap != pVmcsInfo->u32XcptBitmap)
5431 {
5432 rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_EXCEPTION_BITMAP, uXcptBitmap);
5433 AssertRC(rc);
5434 }
5435
5436 /* Update our caches. */
5437 pVmcsInfo->u32ProcCtls = uProcCtls;
5438 pVmcsInfo->u32XcptBitmap = uXcptBitmap;
5439
5440 Log4Func(("cr0=%#RX64 shadow=%#RX64 set=%#RX64 zap=%#RX64\n", u64GuestCr0, u64ShadowCr0, fSetCr0, fZapCr0));
5441 }
5442 else
5443 {
5444 /*
5445 * With nested-guests, we may have extended the guest/host mask here since we
5446 * merged in the outer guest's mask. Thus, the merged mask can include more bits
5447 * (to read from the nested-guest CR0 read-shadow) than the guest hypervisor
5448 * originally supplied. We must copy those bits from the nested-guest CR0 into
5449 * the nested-guest CR0 read-shadow.
5450 */
5451 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_CR0);
5452 uint64_t u64GuestCr0 = pVCpu->cpum.GstCtx.cr0;
5453 uint64_t const u64ShadowCr0 = CPUMGetGuestVmxMaskedCr0(pVCpu, &pVCpu->cpum.GstCtx, pVmcsInfo->u64Cr0Mask);
5454 Assert(!RT_HI_U32(u64GuestCr0));
5455 Assert(u64GuestCr0 & X86_CR0_NE);
5456
5457 /* Apply the hardware specified fixed CR0 bits and enable caching. */
5458 u64GuestCr0 |= fSetCr0;
5459 u64GuestCr0 &= fZapCr0;
5460 u64GuestCr0 &= ~(uint64_t)(X86_CR0_CD | X86_CR0_NW);
5461
5462 /* Commit the CR0 and CR0 read-shadow to the nested-guest VMCS. */
5463 int rc = VMXWriteVmcsNw(VMX_VMCS_GUEST_CR0, u64GuestCr0); AssertRC(rc);
5464 rc = VMXWriteVmcsNw(VMX_VMCS_CTRL_CR0_READ_SHADOW, u64ShadowCr0); AssertRC(rc);
5465
5466 Log4Func(("cr0=%#RX64 shadow=%#RX64 (set=%#RX64 zap=%#RX64)\n", u64GuestCr0, u64ShadowCr0, fSetCr0, fZapCr0));
5467 }
5468
5469 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_CR0);
5470 }
5471
5472 return VINF_SUCCESS;
5473}
5474
5475
5476/**
5477 * Exports the guest control registers (CR3, CR4) into the guest-state area
5478 * in the VMCS.
5479 *
5480 * @returns VBox strict status code.
5481 * @retval VINF_EM_RESCHEDULE_REM if we try to emulate non-paged guest code
5482 * without unrestricted guest access and the VMMDev is not presently
5483 * mapped (e.g. EFI32).
5484 *
5485 * @param pVCpu The cross context virtual CPU structure.
5486 * @param pVmxTransient The VMX-transient structure.
5487 *
5488 * @remarks No-long-jump zone!!!
5489 */
5490static VBOXSTRICTRC hmR0VmxExportGuestCR3AndCR4(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
5491{
5492 int rc = VINF_SUCCESS;
5493 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
5494
5495 /*
5496 * Guest CR2.
5497 * It's always loaded in the assembler code. Nothing to do here.
5498 */
5499
5500 /*
5501 * Guest CR3.
5502 */
5503 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_CR3)
5504 {
5505 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_CR3);
5506
5507 if (pVM->hm.s.fNestedPaging)
5508 {
5509 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
5510 pVmcsInfo->HCPhysEPTP = PGMGetHyperCR3(pVCpu);
5511
5512 /* Validate. See Intel spec. 28.2.2 "EPT Translation Mechanism" and 24.6.11 "Extended-Page-Table Pointer (EPTP)" */
5513 Assert(pVmcsInfo->HCPhysEPTP != NIL_RTHCPHYS);
5514 Assert(!(pVmcsInfo->HCPhysEPTP & UINT64_C(0xfff0000000000000)));
5515 Assert(!(pVmcsInfo->HCPhysEPTP & 0xfff));
5516
5517 /* VMX_EPT_MEMTYPE_WB support is already checked in hmR0VmxSetupTaggedTlb(). */
5518 pVmcsInfo->HCPhysEPTP |= VMX_EPT_MEMTYPE_WB
5519 | (VMX_EPT_PAGE_WALK_LENGTH_DEFAULT << VMX_EPT_PAGE_WALK_LENGTH_SHIFT);
5520
5521 /* Validate. See Intel spec. 26.2.1 "Checks on VMX Controls" */
5522 AssertMsg( ((pVmcsInfo->HCPhysEPTP >> 3) & 0x07) == 3 /* Bits 3:5 (EPT page walk length - 1) must be 3. */
5523 && ((pVmcsInfo->HCPhysEPTP >> 7) & 0x1f) == 0, /* Bits 7:11 MBZ. */
5524 ("EPTP %#RX64\n", pVmcsInfo->HCPhysEPTP));
5525 AssertMsg( !((pVmcsInfo->HCPhysEPTP >> 6) & 0x01) /* Bit 6 (EPT accessed & dirty bit). */
5526 || (pVM->hm.s.vmx.Msrs.u64EptVpidCaps & MSR_IA32_VMX_EPT_VPID_CAP_EPT_ACCESS_DIRTY),
5527 ("EPTP accessed/dirty bit not supported by CPU but set %#RX64\n", pVmcsInfo->HCPhysEPTP));
5528
5529 rc = VMXWriteVmcs64(VMX_VMCS64_CTRL_EPTP_FULL, pVmcsInfo->HCPhysEPTP);
5530 AssertRC(rc);
5531
5532 uint64_t u64GuestCr3;
5533 PCCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
5534 if ( pVM->hm.s.vmx.fUnrestrictedGuest
5535 || CPUMIsGuestPagingEnabledEx(pCtx))
5536 {
5537 /* If the guest is in PAE mode, pass the PDPEs to VT-x using the VMCS fields. */
5538 if (CPUMIsGuestInPAEModeEx(pCtx))
5539 {
5540 rc = PGMGstGetPaePdpes(pVCpu, &pVCpu->hm.s.aPdpes[0]);
5541 AssertRC(rc);
5542 rc = VMXWriteVmcs64(VMX_VMCS64_GUEST_PDPTE0_FULL, pVCpu->hm.s.aPdpes[0].u); AssertRC(rc);
5543 rc = VMXWriteVmcs64(VMX_VMCS64_GUEST_PDPTE1_FULL, pVCpu->hm.s.aPdpes[1].u); AssertRC(rc);
5544 rc = VMXWriteVmcs64(VMX_VMCS64_GUEST_PDPTE2_FULL, pVCpu->hm.s.aPdpes[2].u); AssertRC(rc);
5545 rc = VMXWriteVmcs64(VMX_VMCS64_GUEST_PDPTE3_FULL, pVCpu->hm.s.aPdpes[3].u); AssertRC(rc);
5546 }
5547
5548 /*
5549 * The guest's view of its CR3 is unblemished with nested paging when the
5550 * guest is using paging or we have unrestricted guest execution to handle
5551 * the guest when it's not using paging.
5552 */
5553 u64GuestCr3 = pCtx->cr3;
5554 }
5555 else
5556 {
5557 /*
5558 * The guest is not using paging, but the CPU (VT-x) has to. While the guest
5559 * thinks it accesses physical memory directly, we use our identity-mapped
5560 * page table to map guest-linear to guest-physical addresses. EPT takes care
5561 * of translating it to host-physical addresses.
5562 */
5563 RTGCPHYS GCPhys;
5564 Assert(pVM->hm.s.vmx.pNonPagingModeEPTPageTable);
5565
5566 /* We obtain it here every time as the guest could have relocated this PCI region. */
5567 rc = PDMVmmDevHeapR3ToGCPhys(pVM, pVM->hm.s.vmx.pNonPagingModeEPTPageTable, &GCPhys);
5568 if (RT_SUCCESS(rc))
5569 { /* likely */ }
5570 else if (rc == VERR_PDM_DEV_HEAP_R3_TO_GCPHYS)
5571 {
5572 Log4Func(("VERR_PDM_DEV_HEAP_R3_TO_GCPHYS -> VINF_EM_RESCHEDULE_REM\n"));
5573 return VINF_EM_RESCHEDULE_REM; /* We cannot execute now, switch to REM/IEM till the guest maps in VMMDev. */
5574 }
5575 else
5576 AssertMsgFailedReturn(("%Rrc\n", rc), rc);
5577
5578 u64GuestCr3 = GCPhys;
5579 }
5580
5581 Log4Func(("guest_cr3=%#RX64 (GstN)\n", u64GuestCr3));
5582 rc = VMXWriteVmcsNw(VMX_VMCS_GUEST_CR3, u64GuestCr3);
5583 AssertRC(rc);
5584 }
5585 else
5586 {
5587 Assert(!pVmxTransient->fIsNestedGuest);
5588 /* Non-nested paging case, just use the hypervisor's CR3. */
5589 RTHCPHYS const HCPhysGuestCr3 = PGMGetHyperCR3(pVCpu);
5590
5591 Log4Func(("guest_cr3=%#RX64 (HstN)\n", HCPhysGuestCr3));
5592 rc = VMXWriteVmcsNw(VMX_VMCS_GUEST_CR3, HCPhysGuestCr3);
5593 AssertRC(rc);
5594 }
5595
5596 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_CR3);
5597 }
5598
5599 /*
5600 * Guest CR4.
5601 * ASSUMES this is done everytime we get in from ring-3! (XCR0)
5602 */
5603 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_CR4)
5604 {
5605 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
5606 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
5607
5608 /*
5609 * Figure out fixed CR4 bits in VMX operation.
5610 */
5611 uint64_t const fSetCr4 = pVM->hm.s.vmx.Msrs.u64Cr4Fixed0;
5612 uint64_t const fZapCr4 = pVM->hm.s.vmx.Msrs.u64Cr4Fixed1;
5613
5614 /*
5615 * With nested-guests, we may have extended the guest/host mask here (since we
5616 * merged in the outer guest's mask, see hmR0VmxMergeVmcsNested). This means, the
5617 * mask can include more bits (to read from the nested-guest CR4 read-shadow) than
5618 * the guest hypervisor originally supplied. Thus, we should, in essence, copy
5619 * those bits from the nested-guest CR4 into the nested-guest CR4 read-shadow.
5620 */
5621 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_CR4);
5622 uint64_t u64GuestCr4 = pCtx->cr4;
5623 uint64_t const u64ShadowCr4 = !pVmxTransient->fIsNestedGuest
5624 ? pCtx->cr4
5625 : CPUMGetGuestVmxMaskedCr4(pVCpu, pCtx, pVmcsInfo->u64Cr4Mask);
5626 Assert(!RT_HI_U32(u64GuestCr4));
5627
5628 /*
5629 * Setup VT-x's view of the guest CR4.
5630 *
5631 * If we're emulating real-mode using virtual-8086 mode, we want to redirect software
5632 * interrupts to the 8086 program interrupt handler. Clear the VME bit (the interrupt
5633 * redirection bitmap is already all 0, see hmR3InitFinalizeR0())
5634 *
5635 * See Intel spec. 20.2 "Software Interrupt Handling Methods While in Virtual-8086 Mode".
5636 */
5637 if (pVmcsInfo->RealMode.fRealOnV86Active)
5638 {
5639 Assert(pVM->hm.s.vmx.pRealModeTSS);
5640 Assert(PDMVmmDevHeapIsEnabled(pVM));
5641 u64GuestCr4 &= ~(uint64_t)X86_CR4_VME;
5642 }
5643
5644 if (pVM->hm.s.fNestedPaging)
5645 {
5646 if ( !CPUMIsGuestPagingEnabledEx(pCtx)
5647 && !pVM->hm.s.vmx.fUnrestrictedGuest)
5648 {
5649 /* We use 4 MB pages in our identity mapping page table when the guest doesn't have paging. */
5650 u64GuestCr4 |= X86_CR4_PSE;
5651 /* Our identity mapping is a 32-bit page directory. */
5652 u64GuestCr4 &= ~(uint64_t)X86_CR4_PAE;
5653 }
5654 /* else use guest CR4.*/
5655 }
5656 else
5657 {
5658 Assert(!pVmxTransient->fIsNestedGuest);
5659
5660 /*
5661 * The shadow paging modes and guest paging modes are different, the shadow is in accordance with the host
5662 * paging mode and thus we need to adjust VT-x's view of CR4 depending on our shadow page tables.
5663 */
5664 switch (pVCpu->hm.s.enmShadowMode)
5665 {
5666 case PGMMODE_REAL: /* Real-mode. */
5667 case PGMMODE_PROTECTED: /* Protected mode without paging. */
5668 case PGMMODE_32_BIT: /* 32-bit paging. */
5669 {
5670 u64GuestCr4 &= ~(uint64_t)X86_CR4_PAE;
5671 break;
5672 }
5673
5674 case PGMMODE_PAE: /* PAE paging. */
5675 case PGMMODE_PAE_NX: /* PAE paging with NX. */
5676 {
5677 u64GuestCr4 |= X86_CR4_PAE;
5678 break;
5679 }
5680
5681 case PGMMODE_AMD64: /* 64-bit AMD paging (long mode). */
5682 case PGMMODE_AMD64_NX: /* 64-bit AMD paging (long mode) with NX enabled. */
5683 {
5684#ifdef VBOX_WITH_64_BITS_GUESTS
5685 /* For our assumption in hmR0VmxShouldSwapEferMsr. */
5686 Assert(u64GuestCr4 & X86_CR4_PAE);
5687 break;
5688#endif
5689 }
5690 default:
5691 AssertFailed();
5692 return VERR_PGM_UNSUPPORTED_SHADOW_PAGING_MODE;
5693 }
5694 }
5695
5696 /* Apply the hardware specified fixed CR4 bits (mainly CR4.VMXE). */
5697 u64GuestCr4 |= fSetCr4;
5698 u64GuestCr4 &= fZapCr4;
5699
5700 /* Commit the CR4 and CR4 read-shadow to the guest VMCS. */
5701 rc = VMXWriteVmcsNw(VMX_VMCS_GUEST_CR4, u64GuestCr4); AssertRC(rc);
5702 rc = VMXWriteVmcsNw(VMX_VMCS_CTRL_CR4_READ_SHADOW, u64ShadowCr4); AssertRC(rc);
5703
5704 /* Whether to save/load/restore XCR0 during world switch depends on CR4.OSXSAVE and host+guest XCR0. */
5705 pVCpu->hm.s.fLoadSaveGuestXcr0 = (pCtx->cr4 & X86_CR4_OSXSAVE) && pCtx->aXcr[0] != ASMGetXcr0();
5706
5707 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_CR4);
5708
5709 Log4Func(("cr4=%#RX64 shadow=%#RX64 (set=%#RX64 zap=%#RX64)\n", u64GuestCr4, u64ShadowCr4, fSetCr4, fZapCr4));
5710 }
5711 return rc;
5712}
5713
5714
5715/**
5716 * Exports the guest debug registers into the guest-state area in the VMCS.
5717 * The guest debug bits are partially shared with the host (e.g. DR6, DR0-3).
5718 *
5719 * This also sets up whether \#DB and MOV DRx accesses cause VM-exits.
5720 *
5721 * @returns VBox status code.
5722 * @param pVCpu The cross context virtual CPU structure.
5723 * @param pVmxTransient The VMX-transient structure.
5724 *
5725 * @remarks No-long-jump zone!!!
5726 */
5727static int hmR0VmxExportSharedDebugState(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
5728{
5729 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
5730
5731 /** @todo NSTVMX: Figure out what we want to do with nested-guest instruction
5732 * stepping. */
5733 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
5734 if (pVmxTransient->fIsNestedGuest)
5735 {
5736 int rc = VMXWriteVmcsNw(VMX_VMCS_GUEST_DR7, CPUMGetGuestDR7(pVCpu));
5737 AssertRC(rc);
5738
5739 /* Always intercept Mov DRx accesses for the nested-guest for now. */
5740 pVmcsInfo->u32ProcCtls |= VMX_PROC_CTLS_MOV_DR_EXIT;
5741 rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, pVmcsInfo->u32ProcCtls);
5742 AssertRC(rc);
5743 return VINF_SUCCESS;
5744 }
5745
5746#ifdef VBOX_STRICT
5747 /* Validate. Intel spec. 26.3.1.1 "Checks on Guest Controls Registers, Debug Registers, MSRs" */
5748 if (pVmcsInfo->u32EntryCtls & VMX_ENTRY_CTLS_LOAD_DEBUG)
5749 {
5750 /* Validate. Intel spec. 17.2 "Debug Registers", recompiler paranoia checks. */
5751 Assert((pVCpu->cpum.GstCtx.dr[7] & (X86_DR7_MBZ_MASK | X86_DR7_RAZ_MASK)) == 0);
5752 Assert((pVCpu->cpum.GstCtx.dr[7] & X86_DR7_RA1_MASK) == X86_DR7_RA1_MASK);
5753 }
5754#endif
5755
5756 bool fSteppingDB = false;
5757 bool fInterceptMovDRx = false;
5758 uint32_t uProcCtls = pVmcsInfo->u32ProcCtls;
5759 if (pVCpu->hm.s.fSingleInstruction)
5760 {
5761 /* If the CPU supports the monitor trap flag, use it for single stepping in DBGF and avoid intercepting #DB. */
5762 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
5763 if (pVM->hm.s.vmx.Msrs.ProcCtls.n.allowed1 & VMX_PROC_CTLS_MONITOR_TRAP_FLAG)
5764 {
5765 uProcCtls |= VMX_PROC_CTLS_MONITOR_TRAP_FLAG;
5766 Assert(fSteppingDB == false);
5767 }
5768 else
5769 {
5770 pVCpu->cpum.GstCtx.eflags.u32 |= X86_EFL_TF;
5771 pVCpu->hm.s.fCtxChanged |= HM_CHANGED_GUEST_RFLAGS;
5772 pVCpu->hm.s.fClearTrapFlag = true;
5773 fSteppingDB = true;
5774 }
5775 }
5776
5777 uint64_t u64GuestDr7;
5778 if ( fSteppingDB
5779 || (CPUMGetHyperDR7(pVCpu) & X86_DR7_ENABLED_MASK))
5780 {
5781 /*
5782 * Use the combined guest and host DRx values found in the hypervisor register set
5783 * because the hypervisor debugger has breakpoints active or someone is single stepping
5784 * on the host side without a monitor trap flag.
5785 *
5786 * Note! DBGF expects a clean DR6 state before executing guest code.
5787 */
5788 if (!CPUMIsHyperDebugStateActive(pVCpu))
5789 {
5790 CPUMR0LoadHyperDebugState(pVCpu, true /* include DR6 */);
5791 Assert(CPUMIsHyperDebugStateActive(pVCpu));
5792 Assert(!CPUMIsGuestDebugStateActive(pVCpu));
5793 }
5794
5795 /* Update DR7 with the hypervisor value (other DRx registers are handled by CPUM one way or another). */
5796 u64GuestDr7 = CPUMGetHyperDR7(pVCpu);
5797 pVCpu->hm.s.fUsingHyperDR7 = true;
5798 fInterceptMovDRx = true;
5799 }
5800 else
5801 {
5802 /*
5803 * If the guest has enabled debug registers, we need to load them prior to
5804 * executing guest code so they'll trigger at the right time.
5805 */
5806 if (pVCpu->cpum.GstCtx.dr[7] & (X86_DR7_ENABLED_MASK | X86_DR7_GD))
5807 {
5808 if (!CPUMIsGuestDebugStateActive(pVCpu))
5809 {
5810 CPUMR0LoadGuestDebugState(pVCpu, true /* include DR6 */);
5811 Assert(CPUMIsGuestDebugStateActive(pVCpu));
5812 Assert(!CPUMIsHyperDebugStateActive(pVCpu));
5813 STAM_COUNTER_INC(&pVCpu->hm.s.StatDRxArmed);
5814 }
5815 Assert(!fInterceptMovDRx);
5816 }
5817 else if (!CPUMIsGuestDebugStateActive(pVCpu))
5818 {
5819 /*
5820 * If no debugging enabled, we'll lazy load DR0-3. Unlike on AMD-V, we
5821 * must intercept #DB in order to maintain a correct DR6 guest value, and
5822 * because we need to intercept it to prevent nested #DBs from hanging the
5823 * CPU, we end up always having to intercept it. See hmR0VmxSetupVmcsXcptBitmap().
5824 */
5825 fInterceptMovDRx = true;
5826 }
5827
5828 /* Update DR7 with the actual guest value. */
5829 u64GuestDr7 = pVCpu->cpum.GstCtx.dr[7];
5830 pVCpu->hm.s.fUsingHyperDR7 = false;
5831 }
5832
5833 if (fInterceptMovDRx)
5834 uProcCtls |= VMX_PROC_CTLS_MOV_DR_EXIT;
5835 else
5836 uProcCtls &= ~VMX_PROC_CTLS_MOV_DR_EXIT;
5837
5838 /*
5839 * Update the processor-based VM-execution controls with the MOV-DRx intercepts and the
5840 * monitor-trap flag and update our cache.
5841 */
5842 if (uProcCtls != pVmcsInfo->u32ProcCtls)
5843 {
5844 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, uProcCtls);
5845 AssertRC(rc);
5846 pVmcsInfo->u32ProcCtls = uProcCtls;
5847 }
5848
5849 /*
5850 * Update guest DR7.
5851 */
5852 int rc = VMXWriteVmcsNw(VMX_VMCS_GUEST_DR7, u64GuestDr7);
5853 AssertRC(rc);
5854
5855 /*
5856 * If we have forced EFLAGS.TF to be set because we're single-stepping in the hypervisor debugger,
5857 * we need to clear interrupt inhibition if any as otherwise it causes a VM-entry failure.
5858 *
5859 * See Intel spec. 26.3.1.5 "Checks on Guest Non-Register State".
5860 */
5861 if (fSteppingDB)
5862 {
5863 Assert(pVCpu->hm.s.fSingleInstruction);
5864 Assert(pVCpu->cpum.GstCtx.eflags.Bits.u1TF);
5865
5866 uint32_t fIntrState = 0;
5867 rc = VMXReadVmcs32(VMX_VMCS32_GUEST_INT_STATE, &fIntrState);
5868 AssertRC(rc);
5869
5870 if (fIntrState & (VMX_VMCS_GUEST_INT_STATE_BLOCK_STI | VMX_VMCS_GUEST_INT_STATE_BLOCK_MOVSS))
5871 {
5872 fIntrState &= ~(VMX_VMCS_GUEST_INT_STATE_BLOCK_STI | VMX_VMCS_GUEST_INT_STATE_BLOCK_MOVSS);
5873 rc = VMXWriteVmcs32(VMX_VMCS32_GUEST_INT_STATE, fIntrState);
5874 AssertRC(rc);
5875 }
5876 }
5877
5878 return VINF_SUCCESS;
5879}
5880
5881
5882#ifdef VBOX_STRICT
5883/**
5884 * Strict function to validate segment registers.
5885 *
5886 * @param pVCpu The cross context virtual CPU structure.
5887 * @param pVmcsInfo The VMCS info. object.
5888 *
5889 * @remarks Will import guest CR0 on strict builds during validation of
5890 * segments.
5891 */
5892static void hmR0VmxValidateSegmentRegs(PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo)
5893{
5894 /*
5895 * Validate segment registers. See Intel spec. 26.3.1.2 "Checks on Guest Segment Registers".
5896 *
5897 * The reason we check for attribute value 0 in this function and not just the unusable bit is
5898 * because hmR0VmxExportGuestSegReg() only updates the VMCS' copy of the value with the
5899 * unusable bit and doesn't change the guest-context value.
5900 */
5901 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
5902 PCCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
5903 hmR0VmxImportGuestState(pVCpu, pVmcsInfo, CPUMCTX_EXTRN_CR0);
5904 if ( !pVM->hm.s.vmx.fUnrestrictedGuest
5905 && ( !CPUMIsGuestInRealModeEx(pCtx)
5906 && !CPUMIsGuestInV86ModeEx(pCtx)))
5907 {
5908 /* Protected mode checks */
5909 /* CS */
5910 Assert(pCtx->cs.Attr.n.u1Present);
5911 Assert(!(pCtx->cs.Attr.u & 0xf00));
5912 Assert(!(pCtx->cs.Attr.u & 0xfffe0000));
5913 Assert( (pCtx->cs.u32Limit & 0xfff) == 0xfff
5914 || !(pCtx->cs.Attr.n.u1Granularity));
5915 Assert( !(pCtx->cs.u32Limit & 0xfff00000)
5916 || (pCtx->cs.Attr.n.u1Granularity));
5917 /* CS cannot be loaded with NULL in protected mode. */
5918 Assert(pCtx->cs.Attr.u && !(pCtx->cs.Attr.u & X86DESCATTR_UNUSABLE)); /** @todo is this really true even for 64-bit CS? */
5919 if (pCtx->cs.Attr.n.u4Type == 9 || pCtx->cs.Attr.n.u4Type == 11)
5920 Assert(pCtx->cs.Attr.n.u2Dpl == pCtx->ss.Attr.n.u2Dpl);
5921 else if (pCtx->cs.Attr.n.u4Type == 13 || pCtx->cs.Attr.n.u4Type == 15)
5922 Assert(pCtx->cs.Attr.n.u2Dpl <= pCtx->ss.Attr.n.u2Dpl);
5923 else
5924 AssertMsgFailed(("Invalid CS Type %#x\n", pCtx->cs.Attr.n.u2Dpl));
5925 /* SS */
5926 Assert((pCtx->ss.Sel & X86_SEL_RPL) == (pCtx->cs.Sel & X86_SEL_RPL));
5927 Assert(pCtx->ss.Attr.n.u2Dpl == (pCtx->ss.Sel & X86_SEL_RPL));
5928 if ( !(pCtx->cr0 & X86_CR0_PE)
5929 || pCtx->cs.Attr.n.u4Type == 3)
5930 {
5931 Assert(!pCtx->ss.Attr.n.u2Dpl);
5932 }
5933 if (pCtx->ss.Attr.u && !(pCtx->ss.Attr.u & X86DESCATTR_UNUSABLE))
5934 {
5935 Assert((pCtx->ss.Sel & X86_SEL_RPL) == (pCtx->cs.Sel & X86_SEL_RPL));
5936 Assert(pCtx->ss.Attr.n.u4Type == 3 || pCtx->ss.Attr.n.u4Type == 7);
5937 Assert(pCtx->ss.Attr.n.u1Present);
5938 Assert(!(pCtx->ss.Attr.u & 0xf00));
5939 Assert(!(pCtx->ss.Attr.u & 0xfffe0000));
5940 Assert( (pCtx->ss.u32Limit & 0xfff) == 0xfff
5941 || !(pCtx->ss.Attr.n.u1Granularity));
5942 Assert( !(pCtx->ss.u32Limit & 0xfff00000)
5943 || (pCtx->ss.Attr.n.u1Granularity));
5944 }
5945 /* DS, ES, FS, GS - only check for usable selectors, see hmR0VmxExportGuestSegReg(). */
5946 if (pCtx->ds.Attr.u && !(pCtx->ds.Attr.u & X86DESCATTR_UNUSABLE))
5947 {
5948 Assert(pCtx->ds.Attr.n.u4Type & X86_SEL_TYPE_ACCESSED);
5949 Assert(pCtx->ds.Attr.n.u1Present);
5950 Assert(pCtx->ds.Attr.n.u4Type > 11 || pCtx->ds.Attr.n.u2Dpl >= (pCtx->ds.Sel & X86_SEL_RPL));
5951 Assert(!(pCtx->ds.Attr.u & 0xf00));
5952 Assert(!(pCtx->ds.Attr.u & 0xfffe0000));
5953 Assert( (pCtx->ds.u32Limit & 0xfff) == 0xfff
5954 || !(pCtx->ds.Attr.n.u1Granularity));
5955 Assert( !(pCtx->ds.u32Limit & 0xfff00000)
5956 || (pCtx->ds.Attr.n.u1Granularity));
5957 Assert( !(pCtx->ds.Attr.n.u4Type & X86_SEL_TYPE_CODE)
5958 || (pCtx->ds.Attr.n.u4Type & X86_SEL_TYPE_READ));
5959 }
5960 if (pCtx->es.Attr.u && !(pCtx->es.Attr.u & X86DESCATTR_UNUSABLE))
5961 {
5962 Assert(pCtx->es.Attr.n.u4Type & X86_SEL_TYPE_ACCESSED);
5963 Assert(pCtx->es.Attr.n.u1Present);
5964 Assert(pCtx->es.Attr.n.u4Type > 11 || pCtx->es.Attr.n.u2Dpl >= (pCtx->es.Sel & X86_SEL_RPL));
5965 Assert(!(pCtx->es.Attr.u & 0xf00));
5966 Assert(!(pCtx->es.Attr.u & 0xfffe0000));
5967 Assert( (pCtx->es.u32Limit & 0xfff) == 0xfff
5968 || !(pCtx->es.Attr.n.u1Granularity));
5969 Assert( !(pCtx->es.u32Limit & 0xfff00000)
5970 || (pCtx->es.Attr.n.u1Granularity));
5971 Assert( !(pCtx->es.Attr.n.u4Type & X86_SEL_TYPE_CODE)
5972 || (pCtx->es.Attr.n.u4Type & X86_SEL_TYPE_READ));
5973 }
5974 if (pCtx->fs.Attr.u && !(pCtx->fs.Attr.u & X86DESCATTR_UNUSABLE))
5975 {
5976 Assert(pCtx->fs.Attr.n.u4Type & X86_SEL_TYPE_ACCESSED);
5977 Assert(pCtx->fs.Attr.n.u1Present);
5978 Assert(pCtx->fs.Attr.n.u4Type > 11 || pCtx->fs.Attr.n.u2Dpl >= (pCtx->fs.Sel & X86_SEL_RPL));
5979 Assert(!(pCtx->fs.Attr.u & 0xf00));
5980 Assert(!(pCtx->fs.Attr.u & 0xfffe0000));
5981 Assert( (pCtx->fs.u32Limit & 0xfff) == 0xfff
5982 || !(pCtx->fs.Attr.n.u1Granularity));
5983 Assert( !(pCtx->fs.u32Limit & 0xfff00000)
5984 || (pCtx->fs.Attr.n.u1Granularity));
5985 Assert( !(pCtx->fs.Attr.n.u4Type & X86_SEL_TYPE_CODE)
5986 || (pCtx->fs.Attr.n.u4Type & X86_SEL_TYPE_READ));
5987 }
5988 if (pCtx->gs.Attr.u && !(pCtx->gs.Attr.u & X86DESCATTR_UNUSABLE))
5989 {
5990 Assert(pCtx->gs.Attr.n.u4Type & X86_SEL_TYPE_ACCESSED);
5991 Assert(pCtx->gs.Attr.n.u1Present);
5992 Assert(pCtx->gs.Attr.n.u4Type > 11 || pCtx->gs.Attr.n.u2Dpl >= (pCtx->gs.Sel & X86_SEL_RPL));
5993 Assert(!(pCtx->gs.Attr.u & 0xf00));
5994 Assert(!(pCtx->gs.Attr.u & 0xfffe0000));
5995 Assert( (pCtx->gs.u32Limit & 0xfff) == 0xfff
5996 || !(pCtx->gs.Attr.n.u1Granularity));
5997 Assert( !(pCtx->gs.u32Limit & 0xfff00000)
5998 || (pCtx->gs.Attr.n.u1Granularity));
5999 Assert( !(pCtx->gs.Attr.n.u4Type & X86_SEL_TYPE_CODE)
6000 || (pCtx->gs.Attr.n.u4Type & X86_SEL_TYPE_READ));
6001 }
6002 /* 64-bit capable CPUs. */
6003 Assert(!RT_HI_U32(pCtx->cs.u64Base));
6004 Assert(!pCtx->ss.Attr.u || !RT_HI_U32(pCtx->ss.u64Base));
6005 Assert(!pCtx->ds.Attr.u || !RT_HI_U32(pCtx->ds.u64Base));
6006 Assert(!pCtx->es.Attr.u || !RT_HI_U32(pCtx->es.u64Base));
6007 }
6008 else if ( CPUMIsGuestInV86ModeEx(pCtx)
6009 || ( CPUMIsGuestInRealModeEx(pCtx)
6010 && !pVM->hm.s.vmx.fUnrestrictedGuest))
6011 {
6012 /* Real and v86 mode checks. */
6013 /* hmR0VmxExportGuestSegReg() writes the modified in VMCS. We want what we're feeding to VT-x. */
6014 uint32_t u32CSAttr, u32SSAttr, u32DSAttr, u32ESAttr, u32FSAttr, u32GSAttr;
6015 if (pVmcsInfo->RealMode.fRealOnV86Active)
6016 {
6017 u32CSAttr = 0xf3; u32SSAttr = 0xf3; u32DSAttr = 0xf3;
6018 u32ESAttr = 0xf3; u32FSAttr = 0xf3; u32GSAttr = 0xf3;
6019 }
6020 else
6021 {
6022 u32CSAttr = pCtx->cs.Attr.u; u32SSAttr = pCtx->ss.Attr.u; u32DSAttr = pCtx->ds.Attr.u;
6023 u32ESAttr = pCtx->es.Attr.u; u32FSAttr = pCtx->fs.Attr.u; u32GSAttr = pCtx->gs.Attr.u;
6024 }
6025
6026 /* CS */
6027 AssertMsg((pCtx->cs.u64Base == (uint64_t)pCtx->cs.Sel << 4), ("CS base %#x %#x\n", pCtx->cs.u64Base, pCtx->cs.Sel));
6028 Assert(pCtx->cs.u32Limit == 0xffff);
6029 Assert(u32CSAttr == 0xf3);
6030 /* SS */
6031 Assert(pCtx->ss.u64Base == (uint64_t)pCtx->ss.Sel << 4);
6032 Assert(pCtx->ss.u32Limit == 0xffff);
6033 Assert(u32SSAttr == 0xf3);
6034 /* DS */
6035 Assert(pCtx->ds.u64Base == (uint64_t)pCtx->ds.Sel << 4);
6036 Assert(pCtx->ds.u32Limit == 0xffff);
6037 Assert(u32DSAttr == 0xf3);
6038 /* ES */
6039 Assert(pCtx->es.u64Base == (uint64_t)pCtx->es.Sel << 4);
6040 Assert(pCtx->es.u32Limit == 0xffff);
6041 Assert(u32ESAttr == 0xf3);
6042 /* FS */
6043 Assert(pCtx->fs.u64Base == (uint64_t)pCtx->fs.Sel << 4);
6044 Assert(pCtx->fs.u32Limit == 0xffff);
6045 Assert(u32FSAttr == 0xf3);
6046 /* GS */
6047 Assert(pCtx->gs.u64Base == (uint64_t)pCtx->gs.Sel << 4);
6048 Assert(pCtx->gs.u32Limit == 0xffff);
6049 Assert(u32GSAttr == 0xf3);
6050 /* 64-bit capable CPUs. */
6051 Assert(!RT_HI_U32(pCtx->cs.u64Base));
6052 Assert(!u32SSAttr || !RT_HI_U32(pCtx->ss.u64Base));
6053 Assert(!u32DSAttr || !RT_HI_U32(pCtx->ds.u64Base));
6054 Assert(!u32ESAttr || !RT_HI_U32(pCtx->es.u64Base));
6055 }
6056}
6057#endif /* VBOX_STRICT */
6058
6059
6060/**
6061 * Exports a guest segment register into the guest-state area in the VMCS.
6062 *
6063 * @returns VBox status code.
6064 * @param pVCpu The cross context virtual CPU structure.
6065 * @param pVmcsInfo The VMCS info. object.
6066 * @param iSegReg The segment register number (X86_SREG_XXX).
6067 * @param pSelReg Pointer to the segment selector.
6068 *
6069 * @remarks No-long-jump zone!!!
6070 */
6071static int hmR0VmxExportGuestSegReg(PVMCPUCC pVCpu, PCVMXVMCSINFO pVmcsInfo, uint8_t iSegReg, PCCPUMSELREG pSelReg)
6072{
6073 Assert(iSegReg < X86_SREG_COUNT);
6074 uint32_t const idxSel = g_aVmcsSegSel[iSegReg];
6075 uint32_t const idxLimit = g_aVmcsSegLimit[iSegReg];
6076 uint32_t const idxBase = g_aVmcsSegBase[iSegReg];
6077 uint32_t const idxAttr = g_aVmcsSegAttr[iSegReg];
6078
6079 uint32_t u32Access = pSelReg->Attr.u;
6080 if (pVmcsInfo->RealMode.fRealOnV86Active)
6081 {
6082 /* VT-x requires our real-using-v86 mode hack to override the segment access-right bits. */
6083 u32Access = 0xf3;
6084 Assert(pVCpu->CTX_SUFF(pVM)->hm.s.vmx.pRealModeTSS);
6085 Assert(PDMVmmDevHeapIsEnabled(pVCpu->CTX_SUFF(pVM)));
6086 RT_NOREF_PV(pVCpu);
6087 }
6088 else
6089 {
6090 /*
6091 * The way to differentiate between whether this is really a null selector or was just
6092 * a selector loaded with 0 in real-mode is using the segment attributes. A selector
6093 * loaded in real-mode with the value 0 is valid and usable in protected-mode and we
6094 * should -not- mark it as an unusable segment. Both the recompiler & VT-x ensures
6095 * NULL selectors loaded in protected-mode have their attribute as 0.
6096 */
6097 if (!u32Access)
6098 u32Access = X86DESCATTR_UNUSABLE;
6099 }
6100
6101 /* Validate segment access rights. Refer to Intel spec. "26.3.1.2 Checks on Guest Segment Registers". */
6102 AssertMsg((u32Access & X86DESCATTR_UNUSABLE) || (u32Access & X86_SEL_TYPE_ACCESSED),
6103 ("Access bit not set for usable segment. idx=%#x sel=%#x attr %#x\n", idxBase, pSelReg, pSelReg->Attr.u));
6104
6105 /*
6106 * Commit it to the VMCS.
6107 */
6108 int rc = VMXWriteVmcs32(idxSel, pSelReg->Sel); AssertRC(rc);
6109 rc = VMXWriteVmcs32(idxLimit, pSelReg->u32Limit); AssertRC(rc);
6110 rc = VMXWriteVmcsNw(idxBase, pSelReg->u64Base); AssertRC(rc);
6111 rc = VMXWriteVmcs32(idxAttr, u32Access); AssertRC(rc);
6112 return VINF_SUCCESS;
6113}
6114
6115
6116/**
6117 * Exports the guest segment registers, GDTR, IDTR, LDTR, TR into the guest-state
6118 * area in the VMCS.
6119 *
6120 * @returns VBox status code.
6121 * @param pVCpu The cross context virtual CPU structure.
6122 * @param pVmxTransient The VMX-transient structure.
6123 *
6124 * @remarks Will import guest CR0 on strict builds during validation of
6125 * segments.
6126 * @remarks No-long-jump zone!!!
6127 */
6128static int hmR0VmxExportGuestSegRegsXdtr(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
6129{
6130 int rc = VERR_INTERNAL_ERROR_5;
6131 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
6132 PCCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
6133 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
6134
6135 /*
6136 * Guest Segment registers: CS, SS, DS, ES, FS, GS.
6137 */
6138 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_SREG_MASK)
6139 {
6140#ifdef VBOX_WITH_REM
6141 if (!pVM->hm.s.vmx.fUnrestrictedGuest)
6142 {
6143 Assert(!pVmxTransient->fIsNestedGuest);
6144 Assert(pVM->hm.s.vmx.pRealModeTSS);
6145 AssertCompile(PGMMODE_REAL < PGMMODE_PROTECTED);
6146 if ( pVmcsInfo->fWasInRealMode
6147 && PGMGetGuestMode(pVCpu) >= PGMMODE_PROTECTED)
6148 {
6149 /*
6150 * Notify the recompiler must flush its code-cache as the guest -may-
6151 * rewrite code it in real-mode (e.g. OpenBSD 4.0).
6152 */
6153 REMFlushTBs(pVM);
6154 Log4Func(("Switch to protected mode detected!\n"));
6155 pVmcsInfo->fWasInRealMode = false;
6156 }
6157 }
6158#endif
6159 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_CS)
6160 {
6161 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_CS);
6162 if (pVmcsInfo->RealMode.fRealOnV86Active)
6163 pVmcsInfo->RealMode.AttrCS.u = pCtx->cs.Attr.u;
6164 rc = hmR0VmxExportGuestSegReg(pVCpu, pVmcsInfo, X86_SREG_CS, &pCtx->cs);
6165 AssertRC(rc);
6166 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_CS);
6167 }
6168
6169 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_SS)
6170 {
6171 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_SS);
6172 if (pVmcsInfo->RealMode.fRealOnV86Active)
6173 pVmcsInfo->RealMode.AttrSS.u = pCtx->ss.Attr.u;
6174 rc = hmR0VmxExportGuestSegReg(pVCpu, pVmcsInfo, X86_SREG_SS, &pCtx->ss);
6175 AssertRC(rc);
6176 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_SS);
6177 }
6178
6179 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_DS)
6180 {
6181 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_DS);
6182 if (pVmcsInfo->RealMode.fRealOnV86Active)
6183 pVmcsInfo->RealMode.AttrDS.u = pCtx->ds.Attr.u;
6184 rc = hmR0VmxExportGuestSegReg(pVCpu, pVmcsInfo, X86_SREG_DS, &pCtx->ds);
6185 AssertRC(rc);
6186 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_DS);
6187 }
6188
6189 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_ES)
6190 {
6191 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_ES);
6192 if (pVmcsInfo->RealMode.fRealOnV86Active)
6193 pVmcsInfo->RealMode.AttrES.u = pCtx->es.Attr.u;
6194 rc = hmR0VmxExportGuestSegReg(pVCpu, pVmcsInfo, X86_SREG_ES, &pCtx->es);
6195 AssertRC(rc);
6196 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_ES);
6197 }
6198
6199 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_FS)
6200 {
6201 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_FS);
6202 if (pVmcsInfo->RealMode.fRealOnV86Active)
6203 pVmcsInfo->RealMode.AttrFS.u = pCtx->fs.Attr.u;
6204 rc = hmR0VmxExportGuestSegReg(pVCpu, pVmcsInfo, X86_SREG_FS, &pCtx->fs);
6205 AssertRC(rc);
6206 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_FS);
6207 }
6208
6209 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_GS)
6210 {
6211 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_GS);
6212 if (pVmcsInfo->RealMode.fRealOnV86Active)
6213 pVmcsInfo->RealMode.AttrGS.u = pCtx->gs.Attr.u;
6214 rc = hmR0VmxExportGuestSegReg(pVCpu, pVmcsInfo, X86_SREG_GS, &pCtx->gs);
6215 AssertRC(rc);
6216 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_GS);
6217 }
6218
6219#ifdef VBOX_STRICT
6220 hmR0VmxValidateSegmentRegs(pVCpu, pVmcsInfo);
6221#endif
6222 Log4Func(("cs={%#04x base=%#RX64 limit=%#RX32 attr=%#RX32}\n", pCtx->cs.Sel, pCtx->cs.u64Base, pCtx->cs.u32Limit,
6223 pCtx->cs.Attr.u));
6224 }
6225
6226 /*
6227 * Guest TR.
6228 */
6229 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_TR)
6230 {
6231 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_TR);
6232
6233 /*
6234 * Real-mode emulation using virtual-8086 mode with CR4.VME. Interrupt redirection is
6235 * achieved using the interrupt redirection bitmap (all bits cleared to let the guest
6236 * handle INT-n's) in the TSS. See hmR3InitFinalizeR0() to see how pRealModeTSS is setup.
6237 */
6238 uint16_t u16Sel;
6239 uint32_t u32Limit;
6240 uint64_t u64Base;
6241 uint32_t u32AccessRights;
6242 if (!pVmcsInfo->RealMode.fRealOnV86Active)
6243 {
6244 u16Sel = pCtx->tr.Sel;
6245 u32Limit = pCtx->tr.u32Limit;
6246 u64Base = pCtx->tr.u64Base;
6247 u32AccessRights = pCtx->tr.Attr.u;
6248 }
6249 else
6250 {
6251 Assert(!pVmxTransient->fIsNestedGuest);
6252 Assert(pVM->hm.s.vmx.pRealModeTSS);
6253 Assert(PDMVmmDevHeapIsEnabled(pVM)); /* Guaranteed by HMCanExecuteGuest() -XXX- what about inner loop changes? */
6254
6255 /* We obtain it here every time as PCI regions could be reconfigured in the guest, changing the VMMDev base. */
6256 RTGCPHYS GCPhys;
6257 rc = PDMVmmDevHeapR3ToGCPhys(pVM, pVM->hm.s.vmx.pRealModeTSS, &GCPhys);
6258 AssertRCReturn(rc, rc);
6259
6260 X86DESCATTR DescAttr;
6261 DescAttr.u = 0;
6262 DescAttr.n.u1Present = 1;
6263 DescAttr.n.u4Type = X86_SEL_TYPE_SYS_386_TSS_BUSY;
6264
6265 u16Sel = 0;
6266 u32Limit = HM_VTX_TSS_SIZE;
6267 u64Base = GCPhys;
6268 u32AccessRights = DescAttr.u;
6269 }
6270
6271 /* Validate. */
6272 Assert(!(u16Sel & RT_BIT(2)));
6273 AssertMsg( (u32AccessRights & 0xf) == X86_SEL_TYPE_SYS_386_TSS_BUSY
6274 || (u32AccessRights & 0xf) == X86_SEL_TYPE_SYS_286_TSS_BUSY, ("TSS is not busy!? %#x\n", u32AccessRights));
6275 AssertMsg(!(u32AccessRights & X86DESCATTR_UNUSABLE), ("TR unusable bit is not clear!? %#x\n", u32AccessRights));
6276 Assert(!(u32AccessRights & RT_BIT(4))); /* System MBZ.*/
6277 Assert(u32AccessRights & RT_BIT(7)); /* Present MB1.*/
6278 Assert(!(u32AccessRights & 0xf00)); /* 11:8 MBZ. */
6279 Assert(!(u32AccessRights & 0xfffe0000)); /* 31:17 MBZ. */
6280 Assert( (u32Limit & 0xfff) == 0xfff
6281 || !(u32AccessRights & RT_BIT(15))); /* Granularity MBZ. */
6282 Assert( !(pCtx->tr.u32Limit & 0xfff00000)
6283 || (u32AccessRights & RT_BIT(15))); /* Granularity MB1. */
6284
6285 rc = VMXWriteVmcs16(VMX_VMCS16_GUEST_TR_SEL, u16Sel); AssertRC(rc);
6286 rc = VMXWriteVmcs32(VMX_VMCS32_GUEST_TR_LIMIT, u32Limit); AssertRC(rc);
6287 rc = VMXWriteVmcs32(VMX_VMCS32_GUEST_TR_ACCESS_RIGHTS, u32AccessRights); AssertRC(rc);
6288 rc = VMXWriteVmcsNw(VMX_VMCS_GUEST_TR_BASE, u64Base); AssertRC(rc);
6289
6290 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_TR);
6291 Log4Func(("tr base=%#RX64 limit=%#RX32\n", pCtx->tr.u64Base, pCtx->tr.u32Limit));
6292 }
6293
6294 /*
6295 * Guest GDTR.
6296 */
6297 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_GDTR)
6298 {
6299 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_GDTR);
6300
6301 rc = VMXWriteVmcs32(VMX_VMCS32_GUEST_GDTR_LIMIT, pCtx->gdtr.cbGdt); AssertRC(rc);
6302 rc = VMXWriteVmcsNw(VMX_VMCS_GUEST_GDTR_BASE, pCtx->gdtr.pGdt); AssertRC(rc);
6303
6304 /* Validate. */
6305 Assert(!(pCtx->gdtr.cbGdt & 0xffff0000)); /* Bits 31:16 MBZ. */
6306
6307 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_GDTR);
6308 Log4Func(("gdtr base=%#RX64 limit=%#RX32\n", pCtx->gdtr.pGdt, pCtx->gdtr.cbGdt));
6309 }
6310
6311 /*
6312 * Guest LDTR.
6313 */
6314 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_LDTR)
6315 {
6316 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_LDTR);
6317
6318 /* The unusable bit is specific to VT-x, if it's a null selector mark it as an unusable segment. */
6319 uint32_t u32Access;
6320 if ( !pVmxTransient->fIsNestedGuest
6321 && !pCtx->ldtr.Attr.u)
6322 u32Access = X86DESCATTR_UNUSABLE;
6323 else
6324 u32Access = pCtx->ldtr.Attr.u;
6325
6326 rc = VMXWriteVmcs16(VMX_VMCS16_GUEST_LDTR_SEL, pCtx->ldtr.Sel); AssertRC(rc);
6327 rc = VMXWriteVmcs32(VMX_VMCS32_GUEST_LDTR_LIMIT, pCtx->ldtr.u32Limit); AssertRC(rc);
6328 rc = VMXWriteVmcs32(VMX_VMCS32_GUEST_LDTR_ACCESS_RIGHTS, u32Access); AssertRC(rc);
6329 rc = VMXWriteVmcsNw(VMX_VMCS_GUEST_LDTR_BASE, pCtx->ldtr.u64Base); AssertRC(rc);
6330
6331 /* Validate. */
6332 if (!(u32Access & X86DESCATTR_UNUSABLE))
6333 {
6334 Assert(!(pCtx->ldtr.Sel & RT_BIT(2))); /* TI MBZ. */
6335 Assert(pCtx->ldtr.Attr.n.u4Type == 2); /* Type MB2 (LDT). */
6336 Assert(!pCtx->ldtr.Attr.n.u1DescType); /* System MBZ. */
6337 Assert(pCtx->ldtr.Attr.n.u1Present == 1); /* Present MB1. */
6338 Assert(!pCtx->ldtr.Attr.n.u4LimitHigh); /* 11:8 MBZ. */
6339 Assert(!(pCtx->ldtr.Attr.u & 0xfffe0000)); /* 31:17 MBZ. */
6340 Assert( (pCtx->ldtr.u32Limit & 0xfff) == 0xfff
6341 || !pCtx->ldtr.Attr.n.u1Granularity); /* Granularity MBZ. */
6342 Assert( !(pCtx->ldtr.u32Limit & 0xfff00000)
6343 || pCtx->ldtr.Attr.n.u1Granularity); /* Granularity MB1. */
6344 }
6345
6346 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_LDTR);
6347 Log4Func(("ldtr base=%#RX64 limit=%#RX32\n", pCtx->ldtr.u64Base, pCtx->ldtr.u32Limit));
6348 }
6349
6350 /*
6351 * Guest IDTR.
6352 */
6353 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_IDTR)
6354 {
6355 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_IDTR);
6356
6357 rc = VMXWriteVmcs32(VMX_VMCS32_GUEST_IDTR_LIMIT, pCtx->idtr.cbIdt); AssertRC(rc);
6358 rc = VMXWriteVmcsNw(VMX_VMCS_GUEST_IDTR_BASE, pCtx->idtr.pIdt); AssertRC(rc);
6359
6360 /* Validate. */
6361 Assert(!(pCtx->idtr.cbIdt & 0xffff0000)); /* Bits 31:16 MBZ. */
6362
6363 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_IDTR);
6364 Log4Func(("idtr base=%#RX64 limit=%#RX32\n", pCtx->idtr.pIdt, pCtx->idtr.cbIdt));
6365 }
6366
6367 return VINF_SUCCESS;
6368}
6369
6370
6371/**
6372 * Exports certain guest MSRs into the VM-entry MSR-load and VM-exit MSR-store
6373 * areas.
6374 *
6375 * These MSRs will automatically be loaded to the host CPU on every successful
6376 * VM-entry and stored from the host CPU on every successful VM-exit.
6377 *
6378 * We creates/updates MSR slots for the host MSRs in the VM-exit MSR-load area. The
6379 * actual host MSR values are not- updated here for performance reasons. See
6380 * hmR0VmxExportHostMsrs().
6381 *
6382 * We also exports the guest sysenter MSRs into the guest-state area in the VMCS.
6383 *
6384 * @returns VBox status code.
6385 * @param pVCpu The cross context virtual CPU structure.
6386 * @param pVmxTransient The VMX-transient structure.
6387 *
6388 * @remarks No-long-jump zone!!!
6389 */
6390static int hmR0VmxExportGuestMsrs(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
6391{
6392 AssertPtr(pVCpu);
6393 AssertPtr(pVmxTransient);
6394
6395 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
6396 PCCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
6397
6398 /*
6399 * MSRs that we use the auto-load/store MSR area in the VMCS.
6400 * For 64-bit hosts, we load/restore them lazily, see hmR0VmxLazyLoadGuestMsrs(),
6401 * nothing to do here. The host MSR values are updated when it's safe in
6402 * hmR0VmxLazySaveHostMsrs().
6403 *
6404 * For nested-guests, the guests MSRs from the VM-entry MSR-load area are already
6405 * loaded (into the guest-CPU context) by the VMLAUNCH/VMRESUME instruction
6406 * emulation. The merged MSR permission bitmap will ensure that we get VM-exits
6407 * for any MSR that are not part of the lazy MSRs so we do not need to place
6408 * those MSRs into the auto-load/store MSR area. Nothing to do here.
6409 */
6410 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_VMX_GUEST_AUTO_MSRS)
6411 {
6412 /* No auto-load/store MSRs currently. */
6413 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_VMX_GUEST_AUTO_MSRS);
6414 }
6415
6416 /*
6417 * Guest Sysenter MSRs.
6418 */
6419 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_SYSENTER_MSR_MASK)
6420 {
6421 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_SYSENTER_MSRS);
6422
6423 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_SYSENTER_CS_MSR)
6424 {
6425 int rc = VMXWriteVmcs32(VMX_VMCS32_GUEST_SYSENTER_CS, pCtx->SysEnter.cs);
6426 AssertRC(rc);
6427 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_SYSENTER_CS_MSR);
6428 }
6429
6430 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_SYSENTER_EIP_MSR)
6431 {
6432 int rc = VMXWriteVmcsNw(VMX_VMCS_GUEST_SYSENTER_EIP, pCtx->SysEnter.eip);
6433 AssertRC(rc);
6434 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_SYSENTER_EIP_MSR);
6435 }
6436
6437 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_SYSENTER_ESP_MSR)
6438 {
6439 int rc = VMXWriteVmcsNw(VMX_VMCS_GUEST_SYSENTER_ESP, pCtx->SysEnter.esp);
6440 AssertRC(rc);
6441 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_SYSENTER_ESP_MSR);
6442 }
6443 }
6444
6445 /*
6446 * Guest/host EFER MSR.
6447 */
6448 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_EFER_MSR)
6449 {
6450 /* Whether we are using the VMCS to swap the EFER MSR must have been
6451 determined earlier while exporting VM-entry/VM-exit controls. */
6452 Assert(!(ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_VMX_ENTRY_EXIT_CTLS));
6453 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_EFER);
6454
6455 if (hmR0VmxShouldSwapEferMsr(pVCpu, pVmxTransient))
6456 {
6457 /*
6458 * EFER.LME is written by software, while EFER.LMA is set by the CPU to (CR0.PG & EFER.LME).
6459 * This means a guest can set EFER.LME=1 while CR0.PG=0 and EFER.LMA can remain 0.
6460 * VT-x requires that "IA-32e mode guest" VM-entry control must be identical to EFER.LMA
6461 * and to CR0.PG. Without unrestricted execution, CR0.PG (used for VT-x, not the shadow)
6462 * must always be 1. This forces us to effectively clear both EFER.LMA and EFER.LME until
6463 * the guest has also set CR0.PG=1. Otherwise, we would run into an invalid-guest state
6464 * during VM-entry.
6465 */
6466 uint64_t uGuestEferMsr = pCtx->msrEFER;
6467 if (!pVM->hm.s.vmx.fUnrestrictedGuest)
6468 {
6469 if (!(pCtx->msrEFER & MSR_K6_EFER_LMA))
6470 uGuestEferMsr &= ~MSR_K6_EFER_LME;
6471 else
6472 Assert((pCtx->msrEFER & (MSR_K6_EFER_LMA | MSR_K6_EFER_LME)) == (MSR_K6_EFER_LMA | MSR_K6_EFER_LME));
6473 }
6474
6475 /*
6476 * If the CPU supports VMCS controls for swapping EFER, use it. Otherwise, we have no option
6477 * but to use the auto-load store MSR area in the VMCS for swapping EFER. See @bugref{7368}.
6478 */
6479 if (pVM->hm.s.vmx.fSupportsVmcsEfer)
6480 {
6481 int rc = VMXWriteVmcs64(VMX_VMCS64_GUEST_EFER_FULL, uGuestEferMsr);
6482 AssertRC(rc);
6483 }
6484 else
6485 {
6486 /*
6487 * We shall use the auto-load/store MSR area only for loading the EFER MSR but we must
6488 * continue to intercept guest read and write accesses to it, see @bugref{7386#c16}.
6489 */
6490 int rc = hmR0VmxAddAutoLoadStoreMsr(pVCpu, pVmxTransient, MSR_K6_EFER, uGuestEferMsr,
6491 false /* fSetReadWrite */, false /* fUpdateHostMsr */);
6492 AssertRCReturn(rc, rc);
6493 }
6494
6495 Log4Func(("efer=%#RX64 shadow=%#RX64\n", uGuestEferMsr, pCtx->msrEFER));
6496 }
6497 else if (!pVM->hm.s.vmx.fSupportsVmcsEfer)
6498 hmR0VmxRemoveAutoLoadStoreMsr(pVCpu, pVmxTransient, MSR_K6_EFER);
6499
6500 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_EFER_MSR);
6501 }
6502
6503 /*
6504 * Other MSRs.
6505 * Speculation Control (R/W).
6506 */
6507 if (ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged) & HM_CHANGED_GUEST_OTHER_MSRS)
6508 {
6509 HMVMX_CPUMCTX_ASSERT(pVCpu, HM_CHANGED_GUEST_OTHER_MSRS);
6510 if (pVM->cpum.ro.GuestFeatures.fIbrs)
6511 {
6512 int rc = hmR0VmxAddAutoLoadStoreMsr(pVCpu, pVmxTransient, MSR_IA32_SPEC_CTRL, CPUMGetGuestSpecCtrl(pVCpu),
6513 false /* fSetReadWrite */, false /* fUpdateHostMsr */);
6514 AssertRCReturn(rc, rc);
6515 }
6516 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~HM_CHANGED_GUEST_OTHER_MSRS);
6517 }
6518
6519 return VINF_SUCCESS;
6520}
6521
6522
6523/**
6524 * Selects up the appropriate function to run guest code.
6525 *
6526 * @returns VBox status code.
6527 * @param pVCpu The cross context virtual CPU structure.
6528 * @param pVmxTransient The VMX-transient structure.
6529 *
6530 * @remarks No-long-jump zone!!!
6531 */
6532static int hmR0VmxSelectVMRunHandler(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
6533{
6534 PCCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
6535 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
6536
6537 if (CPUMIsGuestInLongModeEx(pCtx))
6538 {
6539#ifndef VBOX_WITH_64_BITS_GUESTS
6540 return VERR_PGM_UNSUPPORTED_SHADOW_PAGING_MODE;
6541#else
6542 Assert(pVCpu->CTX_SUFF(pVM)->hm.s.fAllow64BitGuests); /* Guaranteed by hmR3InitFinalizeR0(). */
6543 /* Guest is in long mode, use the 64-bit handler (host is 64-bit). */
6544 pVmcsInfo->pfnStartVM = VMXR0StartVM64;
6545#endif
6546 }
6547 else
6548 {
6549 /* Guest is not in long mode, use the 32-bit handler. */
6550 pVmcsInfo->pfnStartVM = VMXR0StartVM32;
6551 }
6552 Assert(pVmcsInfo->pfnStartVM);
6553 return VINF_SUCCESS;
6554}
6555
6556
6557/**
6558 * Wrapper for running the guest code in VT-x.
6559 *
6560 * @returns VBox status code, no informational status codes.
6561 * @param pVCpu The cross context virtual CPU structure.
6562 * @param pVmxTransient The VMX-transient structure.
6563 *
6564 * @remarks No-long-jump zone!!!
6565 */
6566DECLINLINE(int) hmR0VmxRunGuest(PVMCPUCC pVCpu, PCVMXTRANSIENT pVmxTransient)
6567{
6568 /* Mark that HM is the keeper of all guest-CPU registers now that we're going to execute guest code. */
6569 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
6570 pCtx->fExtrn |= HMVMX_CPUMCTX_EXTRN_ALL | CPUMCTX_EXTRN_KEEPER_HM;
6571
6572 /** @todo Add stats for VMRESUME vs VMLAUNCH. */
6573
6574 /*
6575 * 64-bit Windows uses XMM registers in the kernel as the Microsoft compiler expresses
6576 * floating-point operations using SSE instructions. Some XMM registers (XMM6-XMM15) are
6577 * callee-saved and thus the need for this XMM wrapper.
6578 *
6579 * See MSDN "Configuring Programs for 64-bit/x64 Software Conventions / Register Usage".
6580 */
6581 PCVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
6582 bool const fResumeVM = RT_BOOL(pVmcsInfo->fVmcsState & VMX_V_VMCS_LAUNCH_STATE_LAUNCHED);
6583 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
6584#ifdef VBOX_WITH_KERNEL_USING_XMM
6585 int rc = hmR0VMXStartVMWrapXMM(fResumeVM, pCtx, NULL /*pvUnused*/, pVM, pVCpu, pVmcsInfo->pfnStartVM);
6586#else
6587 int rc = pVmcsInfo->pfnStartVM(fResumeVM, pCtx, NULL /*pvUnused*/, pVM, pVCpu);
6588#endif
6589 AssertMsg(rc <= VINF_SUCCESS, ("%Rrc\n", rc));
6590 return rc;
6591}
6592
6593
6594/**
6595 * Reports world-switch error and dumps some useful debug info.
6596 *
6597 * @param pVCpu The cross context virtual CPU structure.
6598 * @param rcVMRun The return code from VMLAUNCH/VMRESUME.
6599 * @param pVmxTransient The VMX-transient structure (only
6600 * exitReason updated).
6601 */
6602static void hmR0VmxReportWorldSwitchError(PVMCPUCC pVCpu, int rcVMRun, PVMXTRANSIENT pVmxTransient)
6603{
6604 Assert(pVCpu);
6605 Assert(pVmxTransient);
6606 HMVMX_ASSERT_PREEMPT_SAFE(pVCpu);
6607
6608 Log4Func(("VM-entry failure: %Rrc\n", rcVMRun));
6609 switch (rcVMRun)
6610 {
6611 case VERR_VMX_INVALID_VMXON_PTR:
6612 AssertFailed();
6613 break;
6614 case VINF_SUCCESS: /* VMLAUNCH/VMRESUME succeeded but VM-entry failed... yeah, true story. */
6615 case VERR_VMX_UNABLE_TO_START_VM: /* VMLAUNCH/VMRESUME itself failed. */
6616 {
6617 int rc = VMXReadVmcs32(VMX_VMCS32_RO_EXIT_REASON, &pVCpu->hm.s.vmx.LastError.u32ExitReason);
6618 rc |= VMXReadVmcs32(VMX_VMCS32_RO_VM_INSTR_ERROR, &pVCpu->hm.s.vmx.LastError.u32InstrError);
6619 AssertRC(rc);
6620 hmR0VmxReadExitQualVmcs(pVmxTransient);
6621
6622 pVCpu->hm.s.vmx.LastError.idEnteredCpu = pVCpu->hm.s.idEnteredCpu;
6623 /* LastError.idCurrentCpu was already updated in hmR0VmxPreRunGuestCommitted().
6624 Cannot do it here as we may have been long preempted. */
6625
6626#ifdef VBOX_STRICT
6627 PVMXVMCSINFO pVmcsInfo = hmGetVmxActiveVmcsInfo(pVCpu);
6628 Log4(("uExitReason %#RX32 (VmxTransient %#RX16)\n", pVCpu->hm.s.vmx.LastError.u32ExitReason,
6629 pVmxTransient->uExitReason));
6630 Log4(("Exit Qualification %#RX64\n", pVmxTransient->uExitQual));
6631 Log4(("InstrError %#RX32\n", pVCpu->hm.s.vmx.LastError.u32InstrError));
6632 if (pVCpu->hm.s.vmx.LastError.u32InstrError <= HMVMX_INSTR_ERROR_MAX)
6633 Log4(("InstrError Desc. \"%s\"\n", g_apszVmxInstrErrors[pVCpu->hm.s.vmx.LastError.u32InstrError]));
6634 else
6635 Log4(("InstrError Desc. Range exceeded %u\n", HMVMX_INSTR_ERROR_MAX));
6636 Log4(("Entered host CPU %u\n", pVCpu->hm.s.vmx.LastError.idEnteredCpu));
6637 Log4(("Current host CPU %u\n", pVCpu->hm.s.vmx.LastError.idCurrentCpu));
6638
6639 static struct
6640 {
6641 /** Name of the field to log. */
6642 const char *pszName;
6643 /** The VMCS field. */
6644 uint32_t uVmcsField;
6645 /** Whether host support of this field needs to be checked. */
6646 bool fCheckSupport;
6647 } const s_aVmcsFields[] =
6648 {
6649 { "VMX_VMCS32_CTRL_PIN_EXEC", VMX_VMCS32_CTRL_PIN_EXEC, false },
6650 { "VMX_VMCS32_CTRL_PROC_EXEC", VMX_VMCS32_CTRL_PROC_EXEC, false },
6651 { "VMX_VMCS32_CTRL_PROC_EXEC2", VMX_VMCS32_CTRL_PROC_EXEC2, true },
6652 { "VMX_VMCS32_CTRL_ENTRY", VMX_VMCS32_CTRL_ENTRY, false },
6653 { "VMX_VMCS32_CTRL_EXIT", VMX_VMCS32_CTRL_EXIT, false },
6654 { "VMX_VMCS32_CTRL_CR3_TARGET_COUNT", VMX_VMCS32_CTRL_CR3_TARGET_COUNT, false },
6655 { "VMX_VMCS32_CTRL_ENTRY_INTERRUPTION_INFO", VMX_VMCS32_CTRL_ENTRY_INTERRUPTION_INFO, false },
6656 { "VMX_VMCS32_CTRL_ENTRY_EXCEPTION_ERRCODE", VMX_VMCS32_CTRL_ENTRY_EXCEPTION_ERRCODE, false },
6657 { "VMX_VMCS32_CTRL_ENTRY_INSTR_LENGTH", VMX_VMCS32_CTRL_ENTRY_INSTR_LENGTH, false },
6658 { "VMX_VMCS32_CTRL_TPR_THRESHOLD", VMX_VMCS32_CTRL_TPR_THRESHOLD, false },
6659 { "VMX_VMCS32_CTRL_EXIT_MSR_STORE_COUNT", VMX_VMCS32_CTRL_EXIT_MSR_STORE_COUNT, false },
6660 { "VMX_VMCS32_CTRL_EXIT_MSR_LOAD_COUNT", VMX_VMCS32_CTRL_EXIT_MSR_LOAD_COUNT, false },
6661 { "VMX_VMCS32_CTRL_ENTRY_MSR_LOAD_COUNT", VMX_VMCS32_CTRL_ENTRY_MSR_LOAD_COUNT, false },
6662 { "VMX_VMCS32_CTRL_EXCEPTION_BITMAP", VMX_VMCS32_CTRL_EXCEPTION_BITMAP, false },
6663 { "VMX_VMCS32_CTRL_PAGEFAULT_ERROR_MASK", VMX_VMCS32_CTRL_PAGEFAULT_ERROR_MASK, false },
6664 { "VMX_VMCS32_CTRL_PAGEFAULT_ERROR_MATCH", VMX_VMCS32_CTRL_PAGEFAULT_ERROR_MATCH, false },
6665 { "VMX_VMCS_CTRL_CR0_MASK", VMX_VMCS_CTRL_CR0_MASK, false },
6666 { "VMX_VMCS_CTRL_CR0_READ_SHADOW", VMX_VMCS_CTRL_CR0_READ_SHADOW, false },
6667 { "VMX_VMCS_CTRL_CR4_MASK", VMX_VMCS_CTRL_CR4_MASK, false },
6668 { "VMX_VMCS_CTRL_CR4_READ_SHADOW", VMX_VMCS_CTRL_CR4_READ_SHADOW, false },
6669 { "VMX_VMCS64_CTRL_EPTP_FULL", VMX_VMCS64_CTRL_EPTP_FULL, true },
6670 { "VMX_VMCS_GUEST_RIP", VMX_VMCS_GUEST_RIP, false },
6671 { "VMX_VMCS_GUEST_RSP", VMX_VMCS_GUEST_RSP, false },
6672 { "VMX_VMCS_GUEST_RFLAGS", VMX_VMCS_GUEST_RFLAGS, false },
6673 { "VMX_VMCS16_VPID", VMX_VMCS16_VPID, true, },
6674 { "VMX_VMCS_HOST_CR0", VMX_VMCS_HOST_CR0, false },
6675 { "VMX_VMCS_HOST_CR3", VMX_VMCS_HOST_CR3, false },
6676 { "VMX_VMCS_HOST_CR4", VMX_VMCS_HOST_CR4, false },
6677 /* The order of selector fields below are fixed! */
6678 { "VMX_VMCS16_HOST_ES_SEL", VMX_VMCS16_HOST_ES_SEL, false },
6679 { "VMX_VMCS16_HOST_CS_SEL", VMX_VMCS16_HOST_CS_SEL, false },
6680 { "VMX_VMCS16_HOST_SS_SEL", VMX_VMCS16_HOST_SS_SEL, false },
6681 { "VMX_VMCS16_HOST_DS_SEL", VMX_VMCS16_HOST_DS_SEL, false },
6682 { "VMX_VMCS16_HOST_FS_SEL", VMX_VMCS16_HOST_FS_SEL, false },
6683 { "VMX_VMCS16_HOST_GS_SEL", VMX_VMCS16_HOST_GS_SEL, false },
6684 { "VMX_VMCS16_HOST_TR_SEL", VMX_VMCS16_HOST_TR_SEL, false },
6685 /* End of ordered selector fields. */
6686 { "VMX_VMCS_HOST_TR_BASE", VMX_VMCS_HOST_TR_BASE, false },
6687 { "VMX_VMCS_HOST_GDTR_BASE", VMX_VMCS_HOST_GDTR_BASE, false },
6688 { "VMX_VMCS_HOST_IDTR_BASE", VMX_VMCS_HOST_IDTR_BASE, false },
6689 { "VMX_VMCS32_HOST_SYSENTER_CS", VMX_VMCS32_HOST_SYSENTER_CS, false },
6690 { "VMX_VMCS_HOST_SYSENTER_EIP", VMX_VMCS_HOST_SYSENTER_EIP, false },
6691 { "VMX_VMCS_HOST_SYSENTER_ESP", VMX_VMCS_HOST_SYSENTER_ESP, false },
6692 { "VMX_VMCS_HOST_RSP", VMX_VMCS_HOST_RSP, false },
6693 { "VMX_VMCS_HOST_RIP", VMX_VMCS_HOST_RIP, false }
6694 };
6695
6696 RTGDTR HostGdtr;
6697 ASMGetGDTR(&HostGdtr);
6698
6699 uint32_t const cVmcsFields = RT_ELEMENTS(s_aVmcsFields);
6700 for (uint32_t i = 0; i < cVmcsFields; i++)
6701 {
6702 uint32_t const uVmcsField = s_aVmcsFields[i].uVmcsField;
6703
6704 bool fSupported;
6705 if (!s_aVmcsFields[i].fCheckSupport)
6706 fSupported = true;
6707 else
6708 {
6709 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
6710 switch (uVmcsField)
6711 {
6712 case VMX_VMCS64_CTRL_EPTP_FULL: fSupported = pVM->hm.s.fNestedPaging; break;
6713 case VMX_VMCS16_VPID: fSupported = pVM->hm.s.vmx.fVpid; break;
6714 case VMX_VMCS32_CTRL_PROC_EXEC2:
6715 fSupported = RT_BOOL(pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_USE_SECONDARY_CTLS);
6716 break;
6717 default:
6718 AssertMsgFailedReturnVoid(("Failed to provide VMCS field support for %#RX32\n", uVmcsField));
6719 }
6720 }
6721
6722 if (fSupported)
6723 {
6724 uint8_t const uWidth = RT_BF_GET(uVmcsField, VMX_BF_VMCSFIELD_WIDTH);
6725 switch (uWidth)
6726 {
6727 case VMX_VMCSFIELD_WIDTH_16BIT:
6728 {
6729 uint16_t u16Val;
6730 rc = VMXReadVmcs16(uVmcsField, &u16Val);
6731 AssertRC(rc);
6732 Log4(("%-40s = %#RX16\n", s_aVmcsFields[i].pszName, u16Val));
6733
6734 if ( uVmcsField >= VMX_VMCS16_HOST_ES_SEL
6735 && uVmcsField <= VMX_VMCS16_HOST_TR_SEL)
6736 {
6737 if (u16Val < HostGdtr.cbGdt)
6738 {
6739 /* Order of selectors in s_apszSel is fixed and matches the order in s_aVmcsFields. */
6740 static const char * const s_apszSel[] = { "Host ES", "Host CS", "Host SS", "Host DS",
6741 "Host FS", "Host GS", "Host TR" };
6742 uint8_t const idxSel = RT_BF_GET(uVmcsField, VMX_BF_VMCSFIELD_INDEX);
6743 Assert(idxSel < RT_ELEMENTS(s_apszSel));
6744 PCX86DESCHC pDesc = (PCX86DESCHC)(HostGdtr.pGdt + (u16Val & X86_SEL_MASK));
6745 hmR0DumpDescriptor(pDesc, u16Val, s_apszSel[idxSel]);
6746 }
6747 else
6748 Log4((" Selector value exceeds GDT limit!\n"));
6749 }
6750 break;
6751 }
6752
6753 case VMX_VMCSFIELD_WIDTH_32BIT:
6754 {
6755 uint32_t u32Val;
6756 rc = VMXReadVmcs32(uVmcsField, &u32Val);
6757 AssertRC(rc);
6758 Log4(("%-40s = %#RX32\n", s_aVmcsFields[i].pszName, u32Val));
6759 break;
6760 }
6761
6762 case VMX_VMCSFIELD_WIDTH_64BIT:
6763 case VMX_VMCSFIELD_WIDTH_NATURAL:
6764 {
6765 uint64_t u64Val;
6766 rc = VMXReadVmcs64(uVmcsField, &u64Val);
6767 AssertRC(rc);
6768 Log4(("%-40s = %#RX64\n", s_aVmcsFields[i].pszName, u64Val));
6769 break;
6770 }
6771 }
6772 }
6773 }
6774
6775 Log4(("MSR_K6_EFER = %#RX64\n", ASMRdMsr(MSR_K6_EFER)));
6776 Log4(("MSR_K8_CSTAR = %#RX64\n", ASMRdMsr(MSR_K8_CSTAR)));
6777 Log4(("MSR_K8_LSTAR = %#RX64\n", ASMRdMsr(MSR_K8_LSTAR)));
6778 Log4(("MSR_K6_STAR = %#RX64\n", ASMRdMsr(MSR_K6_STAR)));
6779 Log4(("MSR_K8_SF_MASK = %#RX64\n", ASMRdMsr(MSR_K8_SF_MASK)));
6780 Log4(("MSR_K8_KERNEL_GS_BASE = %#RX64\n", ASMRdMsr(MSR_K8_KERNEL_GS_BASE)));
6781#endif /* VBOX_STRICT */
6782 break;
6783 }
6784
6785 default:
6786 /* Impossible */
6787 AssertMsgFailed(("hmR0VmxReportWorldSwitchError %Rrc (%#x)\n", rcVMRun, rcVMRun));
6788 break;
6789 }
6790}
6791
6792
6793/**
6794 * Sets up the usage of TSC-offsetting and updates the VMCS.
6795 *
6796 * If offsetting is not possible, cause VM-exits on RDTSC(P)s. Also sets up the
6797 * VMX-preemption timer.
6798 *
6799 * @returns VBox status code.
6800 * @param pVCpu The cross context virtual CPU structure.
6801 * @param pVmxTransient The VMX-transient structure.
6802 *
6803 * @remarks No-long-jump zone!!!
6804 */
6805static void hmR0VmxUpdateTscOffsettingAndPreemptTimer(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
6806{
6807 bool fOffsettedTsc;
6808 bool fParavirtTsc;
6809 uint64_t uTscOffset;
6810 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
6811 PVMXVMCSINFO pVmcsInfo = hmGetVmxActiveVmcsInfo(pVCpu);
6812
6813 if (pVM->hm.s.vmx.fUsePreemptTimer)
6814 {
6815 uint64_t cTicksToDeadline = TMCpuTickGetDeadlineAndTscOffset(pVM, pVCpu, &uTscOffset, &fOffsettedTsc, &fParavirtTsc);
6816
6817 /* Make sure the returned values have sane upper and lower boundaries. */
6818 uint64_t u64CpuHz = SUPGetCpuHzFromGipBySetIndex(g_pSUPGlobalInfoPage, pVCpu->iHostCpuSet);
6819 cTicksToDeadline = RT_MIN(cTicksToDeadline, u64CpuHz / 64); /* 1/64th of a second */
6820 cTicksToDeadline = RT_MAX(cTicksToDeadline, u64CpuHz / 2048); /* 1/2048th of a second */
6821 cTicksToDeadline >>= pVM->hm.s.vmx.cPreemptTimerShift;
6822
6823 /** @todo r=ramshankar: We need to find a way to integrate nested-guest
6824 * preemption timers here. We probably need to clamp the preemption timer,
6825 * after converting the timer value to the host. */
6826 uint32_t const cPreemptionTickCount = (uint32_t)RT_MIN(cTicksToDeadline, UINT32_MAX - 16);
6827 int rc = VMXWriteVmcs32(VMX_VMCS32_PREEMPT_TIMER_VALUE, cPreemptionTickCount);
6828 AssertRC(rc);
6829 }
6830 else
6831 fOffsettedTsc = TMCpuTickCanUseRealTSC(pVM, pVCpu, &uTscOffset, &fParavirtTsc);
6832
6833 if (fParavirtTsc)
6834 {
6835 /* Currently neither Hyper-V nor KVM need to update their paravirt. TSC
6836 information before every VM-entry, hence disable it for performance sake. */
6837#if 0
6838 int rc = GIMR0UpdateParavirtTsc(pVM, 0 /* u64Offset */);
6839 AssertRC(rc);
6840#endif
6841 STAM_COUNTER_INC(&pVCpu->hm.s.StatTscParavirt);
6842 }
6843
6844 if ( fOffsettedTsc
6845 && RT_LIKELY(!pVCpu->hm.s.fDebugWantRdTscExit))
6846 {
6847 if (pVmxTransient->fIsNestedGuest)
6848 uTscOffset = CPUMApplyNestedGuestTscOffset(pVCpu, uTscOffset);
6849 hmR0VmxSetTscOffsetVmcs(pVmcsInfo, uTscOffset);
6850 hmR0VmxRemoveProcCtlsVmcs(pVCpu, pVmxTransient, VMX_PROC_CTLS_RDTSC_EXIT);
6851 }
6852 else
6853 {
6854 /* We can't use TSC-offsetting (non-fixed TSC, warp drive active etc.), VM-exit on RDTSC(P). */
6855 hmR0VmxSetProcCtlsVmcs(pVmxTransient, VMX_PROC_CTLS_RDTSC_EXIT);
6856 }
6857}
6858
6859
6860/**
6861 * Gets the IEM exception flags for the specified vector and IDT vectoring /
6862 * VM-exit interruption info type.
6863 *
6864 * @returns The IEM exception flags.
6865 * @param uVector The event vector.
6866 * @param uVmxEventType The VMX event type.
6867 *
6868 * @remarks This function currently only constructs flags required for
6869 * IEMEvaluateRecursiveXcpt and not the complete flags (e.g, error-code
6870 * and CR2 aspects of an exception are not included).
6871 */
6872static uint32_t hmR0VmxGetIemXcptFlags(uint8_t uVector, uint32_t uVmxEventType)
6873{
6874 uint32_t fIemXcptFlags;
6875 switch (uVmxEventType)
6876 {
6877 case VMX_IDT_VECTORING_INFO_TYPE_HW_XCPT:
6878 case VMX_IDT_VECTORING_INFO_TYPE_NMI:
6879 fIemXcptFlags = IEM_XCPT_FLAGS_T_CPU_XCPT;
6880 break;
6881
6882 case VMX_IDT_VECTORING_INFO_TYPE_EXT_INT:
6883 fIemXcptFlags = IEM_XCPT_FLAGS_T_EXT_INT;
6884 break;
6885
6886 case VMX_IDT_VECTORING_INFO_TYPE_PRIV_SW_XCPT:
6887 fIemXcptFlags = IEM_XCPT_FLAGS_T_SOFT_INT | IEM_XCPT_FLAGS_ICEBP_INSTR;
6888 break;
6889
6890 case VMX_IDT_VECTORING_INFO_TYPE_SW_XCPT:
6891 {
6892 fIemXcptFlags = IEM_XCPT_FLAGS_T_SOFT_INT;
6893 if (uVector == X86_XCPT_BP)
6894 fIemXcptFlags |= IEM_XCPT_FLAGS_BP_INSTR;
6895 else if (uVector == X86_XCPT_OF)
6896 fIemXcptFlags |= IEM_XCPT_FLAGS_OF_INSTR;
6897 else
6898 {
6899 fIemXcptFlags = 0;
6900 AssertMsgFailed(("Unexpected vector for software exception. uVector=%#x", uVector));
6901 }
6902 break;
6903 }
6904
6905 case VMX_IDT_VECTORING_INFO_TYPE_SW_INT:
6906 fIemXcptFlags = IEM_XCPT_FLAGS_T_SOFT_INT;
6907 break;
6908
6909 default:
6910 fIemXcptFlags = 0;
6911 AssertMsgFailed(("Unexpected vector type! uVmxEventType=%#x uVector=%#x", uVmxEventType, uVector));
6912 break;
6913 }
6914 return fIemXcptFlags;
6915}
6916
6917
6918/**
6919 * Sets an event as a pending event to be injected into the guest.
6920 *
6921 * @param pVCpu The cross context virtual CPU structure.
6922 * @param u32IntInfo The VM-entry interruption-information field.
6923 * @param cbInstr The VM-entry instruction length in bytes (for
6924 * software interrupts, exceptions and privileged
6925 * software exceptions).
6926 * @param u32ErrCode The VM-entry exception error code.
6927 * @param GCPtrFaultAddress The fault-address (CR2) in case it's a
6928 * page-fault.
6929 */
6930DECLINLINE(void) hmR0VmxSetPendingEvent(PVMCPUCC pVCpu, uint32_t u32IntInfo, uint32_t cbInstr, uint32_t u32ErrCode,
6931 RTGCUINTPTR GCPtrFaultAddress)
6932{
6933 Assert(!pVCpu->hm.s.Event.fPending);
6934 pVCpu->hm.s.Event.fPending = true;
6935 pVCpu->hm.s.Event.u64IntInfo = u32IntInfo;
6936 pVCpu->hm.s.Event.u32ErrCode = u32ErrCode;
6937 pVCpu->hm.s.Event.cbInstr = cbInstr;
6938 pVCpu->hm.s.Event.GCPtrFaultAddress = GCPtrFaultAddress;
6939}
6940
6941
6942/**
6943 * Sets an external interrupt as pending-for-injection into the VM.
6944 *
6945 * @param pVCpu The cross context virtual CPU structure.
6946 * @param u8Interrupt The external interrupt vector.
6947 */
6948DECLINLINE(void) hmR0VmxSetPendingExtInt(PVMCPUCC pVCpu, uint8_t u8Interrupt)
6949{
6950 uint32_t const u32IntInfo = RT_BF_MAKE(VMX_BF_EXIT_INT_INFO_VECTOR, u8Interrupt)
6951 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_TYPE, VMX_ENTRY_INT_INFO_TYPE_EXT_INT)
6952 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_ERR_CODE_VALID, 0)
6953 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_VALID, 1);
6954 hmR0VmxSetPendingEvent(pVCpu, u32IntInfo, 0 /* cbInstr */, 0 /* u32ErrCode */, 0 /* GCPtrFaultAddress */);
6955}
6956
6957
6958/**
6959 * Sets an NMI (\#NMI) exception as pending-for-injection into the VM.
6960 *
6961 * @param pVCpu The cross context virtual CPU structure.
6962 */
6963DECLINLINE(void) hmR0VmxSetPendingXcptNmi(PVMCPUCC pVCpu)
6964{
6965 uint32_t const u32IntInfo = RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_VECTOR, X86_XCPT_NMI)
6966 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_TYPE, VMX_ENTRY_INT_INFO_TYPE_NMI)
6967 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_ERR_CODE_VALID, 0)
6968 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_VALID, 1);
6969 hmR0VmxSetPendingEvent(pVCpu, u32IntInfo, 0 /* cbInstr */, 0 /* u32ErrCode */, 0 /* GCPtrFaultAddress */);
6970}
6971
6972
6973/**
6974 * Sets a double-fault (\#DF) exception as pending-for-injection into the VM.
6975 *
6976 * @param pVCpu The cross context virtual CPU structure.
6977 */
6978DECLINLINE(void) hmR0VmxSetPendingXcptDF(PVMCPUCC pVCpu)
6979{
6980 uint32_t const u32IntInfo = RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_VECTOR, X86_XCPT_DF)
6981 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_TYPE, VMX_EXIT_INT_INFO_TYPE_HW_XCPT)
6982 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_ERR_CODE_VALID, 1)
6983 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_VALID, 1);
6984 hmR0VmxSetPendingEvent(pVCpu, u32IntInfo, 0 /* cbInstr */, 0 /* u32ErrCode */, 0 /* GCPtrFaultAddress */);
6985}
6986
6987
6988/**
6989 * Sets an invalid-opcode (\#UD) exception as pending-for-injection into the VM.
6990 *
6991 * @param pVCpu The cross context virtual CPU structure.
6992 */
6993DECLINLINE(void) hmR0VmxSetPendingXcptUD(PVMCPUCC pVCpu)
6994{
6995 uint32_t const u32IntInfo = RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_VECTOR, X86_XCPT_UD)
6996 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_TYPE, VMX_EXIT_INT_INFO_TYPE_HW_XCPT)
6997 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_ERR_CODE_VALID, 0)
6998 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_VALID, 1);
6999 hmR0VmxSetPendingEvent(pVCpu, u32IntInfo, 0 /* cbInstr */, 0 /* u32ErrCode */, 0 /* GCPtrFaultAddress */);
7000}
7001
7002
7003/**
7004 * Sets a debug (\#DB) exception as pending-for-injection into the VM.
7005 *
7006 * @param pVCpu The cross context virtual CPU structure.
7007 */
7008DECLINLINE(void) hmR0VmxSetPendingXcptDB(PVMCPUCC pVCpu)
7009{
7010 uint32_t const u32IntInfo = RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_VECTOR, X86_XCPT_DB)
7011 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_TYPE, VMX_EXIT_INT_INFO_TYPE_HW_XCPT)
7012 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_ERR_CODE_VALID, 0)
7013 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_VALID, 1);
7014 hmR0VmxSetPendingEvent(pVCpu, u32IntInfo, 0 /* cbInstr */, 0 /* u32ErrCode */, 0 /* GCPtrFaultAddress */);
7015}
7016
7017
7018#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
7019/**
7020 * Sets a general-protection (\#GP) exception as pending-for-injection into the VM.
7021 *
7022 * @param pVCpu The cross context virtual CPU structure.
7023 * @param u32ErrCode The error code for the general-protection exception.
7024 */
7025DECLINLINE(void) hmR0VmxSetPendingXcptGP(PVMCPUCC pVCpu, uint32_t u32ErrCode)
7026{
7027 uint32_t const u32IntInfo = RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_VECTOR, X86_XCPT_GP)
7028 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_TYPE, VMX_EXIT_INT_INFO_TYPE_HW_XCPT)
7029 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_ERR_CODE_VALID, 1)
7030 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_VALID, 1);
7031 hmR0VmxSetPendingEvent(pVCpu, u32IntInfo, 0 /* cbInstr */, u32ErrCode, 0 /* GCPtrFaultAddress */);
7032}
7033
7034
7035/**
7036 * Sets a stack (\#SS) exception as pending-for-injection into the VM.
7037 *
7038 * @param pVCpu The cross context virtual CPU structure.
7039 * @param u32ErrCode The error code for the stack exception.
7040 */
7041DECLINLINE(void) hmR0VmxSetPendingXcptSS(PVMCPUCC pVCpu, uint32_t u32ErrCode)
7042{
7043 uint32_t const u32IntInfo = RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_VECTOR, X86_XCPT_SS)
7044 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_TYPE, VMX_EXIT_INT_INFO_TYPE_HW_XCPT)
7045 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_ERR_CODE_VALID, 1)
7046 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_VALID, 1);
7047 hmR0VmxSetPendingEvent(pVCpu, u32IntInfo, 0 /* cbInstr */, u32ErrCode, 0 /* GCPtrFaultAddress */);
7048}
7049#endif /* VBOX_WITH_NESTED_HWVIRT_VMX */
7050
7051
7052/**
7053 * Fixes up attributes for the specified segment register.
7054 *
7055 * @param pVCpu The cross context virtual CPU structure.
7056 * @param pSelReg The segment register that needs fixing.
7057 * @param idxSel The VMCS field for the corresponding segment register.
7058 */
7059static void hmR0VmxFixUnusableSegRegAttr(PVMCPUCC pVCpu, PCPUMSELREG pSelReg, uint32_t idxSel)
7060{
7061 Assert(pSelReg->Attr.u & X86DESCATTR_UNUSABLE);
7062
7063 /*
7064 * If VT-x marks the segment as unusable, most other bits remain undefined:
7065 * - For CS the L, D and G bits have meaning.
7066 * - For SS the DPL has meaning (it -is- the CPL for Intel and VBox).
7067 * - For the remaining data segments no bits are defined.
7068 *
7069 * The present bit and the unusable bit has been observed to be set at the
7070 * same time (the selector was supposed to be invalid as we started executing
7071 * a V8086 interrupt in ring-0).
7072 *
7073 * What should be important for the rest of the VBox code, is that the P bit is
7074 * cleared. Some of the other VBox code recognizes the unusable bit, but
7075 * AMD-V certainly don't, and REM doesn't really either. So, to be on the
7076 * safe side here, we'll strip off P and other bits we don't care about. If
7077 * any code breaks because Attr.u != 0 when Sel < 4, it should be fixed.
7078 *
7079 * See Intel spec. 27.3.2 "Saving Segment Registers and Descriptor-Table Registers".
7080 */
7081#ifdef VBOX_STRICT
7082 uint32_t const uAttr = pSelReg->Attr.u;
7083#endif
7084
7085 /* Masking off: X86DESCATTR_P, X86DESCATTR_LIMIT_HIGH, and X86DESCATTR_AVL. The latter two are really irrelevant. */
7086 pSelReg->Attr.u &= X86DESCATTR_UNUSABLE | X86DESCATTR_L | X86DESCATTR_D | X86DESCATTR_G
7087 | X86DESCATTR_DPL | X86DESCATTR_TYPE | X86DESCATTR_DT;
7088
7089#ifdef VBOX_STRICT
7090 VMMRZCallRing3Disable(pVCpu);
7091 Log4Func(("Unusable %#x: sel=%#x attr=%#x -> %#x\n", idxSel, pSelReg->Sel, uAttr, pSelReg->Attr.u));
7092# ifdef DEBUG_bird
7093 AssertMsg((uAttr & ~X86DESCATTR_P) == pSelReg->Attr.u,
7094 ("%#x: %#x != %#x (sel=%#x base=%#llx limit=%#x)\n",
7095 idxSel, uAttr, pSelReg->Attr.u, pSelReg->Sel, pSelReg->u64Base, pSelReg->u32Limit));
7096# endif
7097 VMMRZCallRing3Enable(pVCpu);
7098 NOREF(uAttr);
7099#endif
7100 RT_NOREF2(pVCpu, idxSel);
7101}
7102
7103
7104/**
7105 * Imports a guest segment register from the current VMCS into the guest-CPU
7106 * context.
7107 *
7108 * @param pVCpu The cross context virtual CPU structure.
7109 * @param iSegReg The segment register number (X86_SREG_XXX).
7110 *
7111 * @remarks Called with interrupts and/or preemption disabled.
7112 */
7113static void hmR0VmxImportGuestSegReg(PVMCPUCC pVCpu, uint8_t iSegReg)
7114{
7115 Assert(iSegReg < X86_SREG_COUNT);
7116
7117 uint32_t const idxSel = g_aVmcsSegSel[iSegReg];
7118 uint32_t const idxLimit = g_aVmcsSegLimit[iSegReg];
7119 uint32_t const idxAttr = g_aVmcsSegAttr[iSegReg];
7120 uint32_t const idxBase = g_aVmcsSegBase[iSegReg];
7121
7122 uint16_t u16Sel;
7123 uint64_t u64Base;
7124 uint32_t u32Limit, u32Attr;
7125 int rc = VMXReadVmcs16(idxSel, &u16Sel); AssertRC(rc);
7126 rc = VMXReadVmcs32(idxLimit, &u32Limit); AssertRC(rc);
7127 rc = VMXReadVmcs32(idxAttr, &u32Attr); AssertRC(rc);
7128 rc = VMXReadVmcsNw(idxBase, &u64Base); AssertRC(rc);
7129
7130 PCPUMSELREG pSelReg = &pVCpu->cpum.GstCtx.aSRegs[iSegReg];
7131 pSelReg->Sel = u16Sel;
7132 pSelReg->ValidSel = u16Sel;
7133 pSelReg->fFlags = CPUMSELREG_FLAGS_VALID;
7134 pSelReg->u32Limit = u32Limit;
7135 pSelReg->u64Base = u64Base;
7136 pSelReg->Attr.u = u32Attr;
7137 if (u32Attr & X86DESCATTR_UNUSABLE)
7138 hmR0VmxFixUnusableSegRegAttr(pVCpu, pSelReg, idxSel);
7139}
7140
7141
7142/**
7143 * Imports the guest LDTR from the current VMCS into the guest-CPU context.
7144 *
7145 * @param pVCpu The cross context virtual CPU structure.
7146 *
7147 * @remarks Called with interrupts and/or preemption disabled.
7148 */
7149static void hmR0VmxImportGuestLdtr(PVMCPUCC pVCpu)
7150{
7151 uint16_t u16Sel;
7152 uint64_t u64Base;
7153 uint32_t u32Limit, u32Attr;
7154 int rc = VMXReadVmcs16(VMX_VMCS16_GUEST_LDTR_SEL, &u16Sel); AssertRC(rc);
7155 rc = VMXReadVmcs32(VMX_VMCS32_GUEST_LDTR_LIMIT, &u32Limit); AssertRC(rc);
7156 rc = VMXReadVmcs32(VMX_VMCS32_GUEST_LDTR_ACCESS_RIGHTS, &u32Attr); AssertRC(rc);
7157 rc = VMXReadVmcsNw(VMX_VMCS_GUEST_LDTR_BASE, &u64Base); AssertRC(rc);
7158
7159 pVCpu->cpum.GstCtx.ldtr.Sel = u16Sel;
7160 pVCpu->cpum.GstCtx.ldtr.ValidSel = u16Sel;
7161 pVCpu->cpum.GstCtx.ldtr.fFlags = CPUMSELREG_FLAGS_VALID;
7162 pVCpu->cpum.GstCtx.ldtr.u32Limit = u32Limit;
7163 pVCpu->cpum.GstCtx.ldtr.u64Base = u64Base;
7164 pVCpu->cpum.GstCtx.ldtr.Attr.u = u32Attr;
7165 if (u32Attr & X86DESCATTR_UNUSABLE)
7166 hmR0VmxFixUnusableSegRegAttr(pVCpu, &pVCpu->cpum.GstCtx.ldtr, VMX_VMCS16_GUEST_LDTR_SEL);
7167}
7168
7169
7170/**
7171 * Imports the guest TR from the current VMCS into the guest-CPU context.
7172 *
7173 * @param pVCpu The cross context virtual CPU structure.
7174 *
7175 * @remarks Called with interrupts and/or preemption disabled.
7176 */
7177static void hmR0VmxImportGuestTr(PVMCPUCC pVCpu)
7178{
7179 uint16_t u16Sel;
7180 uint64_t u64Base;
7181 uint32_t u32Limit, u32Attr;
7182 int rc = VMXReadVmcs16(VMX_VMCS16_GUEST_TR_SEL, &u16Sel); AssertRC(rc);
7183 rc = VMXReadVmcs32(VMX_VMCS32_GUEST_TR_LIMIT, &u32Limit); AssertRC(rc);
7184 rc = VMXReadVmcs32(VMX_VMCS32_GUEST_TR_ACCESS_RIGHTS, &u32Attr); AssertRC(rc);
7185 rc = VMXReadVmcsNw(VMX_VMCS_GUEST_TR_BASE, &u64Base); AssertRC(rc);
7186
7187 pVCpu->cpum.GstCtx.tr.Sel = u16Sel;
7188 pVCpu->cpum.GstCtx.tr.ValidSel = u16Sel;
7189 pVCpu->cpum.GstCtx.tr.fFlags = CPUMSELREG_FLAGS_VALID;
7190 pVCpu->cpum.GstCtx.tr.u32Limit = u32Limit;
7191 pVCpu->cpum.GstCtx.tr.u64Base = u64Base;
7192 pVCpu->cpum.GstCtx.tr.Attr.u = u32Attr;
7193 /* TR is the only selector that can never be unusable. */
7194 Assert(!(u32Attr & X86DESCATTR_UNUSABLE));
7195}
7196
7197
7198/**
7199 * Imports the guest RIP from the VMCS back into the guest-CPU context.
7200 *
7201 * @param pVCpu The cross context virtual CPU structure.
7202 *
7203 * @remarks Called with interrupts and/or preemption disabled, should not assert!
7204 * @remarks Do -not- call this function directly, use hmR0VmxImportGuestState()
7205 * instead!!!
7206 */
7207static void hmR0VmxImportGuestRip(PVMCPUCC pVCpu)
7208{
7209 uint64_t u64Val;
7210 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
7211 if (pCtx->fExtrn & CPUMCTX_EXTRN_RIP)
7212 {
7213 int rc = VMXReadVmcsNw(VMX_VMCS_GUEST_RIP, &u64Val);
7214 AssertRC(rc);
7215
7216 pCtx->rip = u64Val;
7217 EMR0HistoryUpdatePC(pVCpu, pCtx->rip, false);
7218 pCtx->fExtrn &= ~CPUMCTX_EXTRN_RIP;
7219 }
7220}
7221
7222
7223/**
7224 * Imports the guest RFLAGS from the VMCS back into the guest-CPU context.
7225 *
7226 * @param pVCpu The cross context virtual CPU structure.
7227 * @param pVmcsInfo The VMCS info. object.
7228 *
7229 * @remarks Called with interrupts and/or preemption disabled, should not assert!
7230 * @remarks Do -not- call this function directly, use hmR0VmxImportGuestState()
7231 * instead!!!
7232 */
7233static void hmR0VmxImportGuestRFlags(PVMCPUCC pVCpu, PCVMXVMCSINFO pVmcsInfo)
7234{
7235 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
7236 if (pCtx->fExtrn & CPUMCTX_EXTRN_RFLAGS)
7237 {
7238 uint64_t u64Val;
7239 int rc = VMXReadVmcsNw(VMX_VMCS_GUEST_RFLAGS, &u64Val);
7240 AssertRC(rc);
7241
7242 pCtx->rflags.u64 = u64Val;
7243 if (pVmcsInfo->RealMode.fRealOnV86Active)
7244 {
7245 pCtx->eflags.Bits.u1VM = 0;
7246 pCtx->eflags.Bits.u2IOPL = pVmcsInfo->RealMode.Eflags.Bits.u2IOPL;
7247 }
7248 pCtx->fExtrn &= ~CPUMCTX_EXTRN_RFLAGS;
7249 }
7250}
7251
7252
7253/**
7254 * Imports the guest interruptibility-state from the VMCS back into the guest-CPU
7255 * context.
7256 *
7257 * @param pVCpu The cross context virtual CPU structure.
7258 * @param pVmcsInfo The VMCS info. object.
7259 *
7260 * @remarks Called with interrupts and/or preemption disabled, try not to assert and
7261 * do not log!
7262 * @remarks Do -not- call this function directly, use hmR0VmxImportGuestState()
7263 * instead!!!
7264 */
7265static void hmR0VmxImportGuestIntrState(PVMCPUCC pVCpu, PCVMXVMCSINFO pVmcsInfo)
7266{
7267 uint32_t u32Val;
7268 int rc = VMXReadVmcs32(VMX_VMCS32_GUEST_INT_STATE, &u32Val); AssertRC(rc);
7269 if (!u32Val)
7270 {
7271 if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS))
7272 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS);
7273 CPUMSetGuestNmiBlocking(pVCpu, false);
7274 }
7275 else
7276 {
7277 /*
7278 * We must import RIP here to set our EM interrupt-inhibited state.
7279 * We also import RFLAGS as our code that evaluates pending interrupts
7280 * before VM-entry requires it.
7281 */
7282 hmR0VmxImportGuestRip(pVCpu);
7283 hmR0VmxImportGuestRFlags(pVCpu, pVmcsInfo);
7284
7285 if (u32Val & (VMX_VMCS_GUEST_INT_STATE_BLOCK_MOVSS | VMX_VMCS_GUEST_INT_STATE_BLOCK_STI))
7286 EMSetInhibitInterruptsPC(pVCpu, pVCpu->cpum.GstCtx.rip);
7287 else if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS))
7288 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS);
7289
7290 bool const fNmiBlocking = RT_BOOL(u32Val & VMX_VMCS_GUEST_INT_STATE_BLOCK_NMI);
7291 CPUMSetGuestNmiBlocking(pVCpu, fNmiBlocking);
7292 }
7293}
7294
7295
7296/**
7297 * Worker for VMXR0ImportStateOnDemand.
7298 *
7299 * @returns VBox status code.
7300 * @param pVCpu The cross context virtual CPU structure.
7301 * @param pVmcsInfo The VMCS info. object.
7302 * @param fWhat What to import, CPUMCTX_EXTRN_XXX.
7303 */
7304static int hmR0VmxImportGuestState(PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo, uint64_t fWhat)
7305{
7306 int rc = VINF_SUCCESS;
7307 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
7308 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
7309 uint32_t u32Val;
7310
7311 /*
7312 * Note! This is hack to workaround a mysterious BSOD observed with release builds
7313 * on Windows 10 64-bit hosts. Profile and debug builds are not affected and
7314 * neither are other host platforms.
7315 *
7316 * Committing this temporarily as it prevents BSOD.
7317 *
7318 * Update: This is very likely a compiler optimization bug, see @bugref{9180}.
7319 */
7320#ifdef RT_OS_WINDOWS
7321 if (pVM == 0 || pVM == (void *)(uintptr_t)-1)
7322 return VERR_HM_IPE_1;
7323#endif
7324
7325 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatImportGuestState, x);
7326
7327 /*
7328 * We disable interrupts to make the updating of the state and in particular
7329 * the fExtrn modification atomic wrt to preemption hooks.
7330 */
7331 RTCCUINTREG const fEFlags = ASMIntDisableFlags();
7332
7333 fWhat &= pCtx->fExtrn;
7334 if (fWhat)
7335 {
7336 do
7337 {
7338 if (fWhat & CPUMCTX_EXTRN_RIP)
7339 hmR0VmxImportGuestRip(pVCpu);
7340
7341 if (fWhat & CPUMCTX_EXTRN_RFLAGS)
7342 hmR0VmxImportGuestRFlags(pVCpu, pVmcsInfo);
7343
7344 if (fWhat & CPUMCTX_EXTRN_HM_VMX_INT_STATE)
7345 hmR0VmxImportGuestIntrState(pVCpu, pVmcsInfo);
7346
7347 if (fWhat & CPUMCTX_EXTRN_RSP)
7348 {
7349 rc = VMXReadVmcsNw(VMX_VMCS_GUEST_RSP, &pCtx->rsp);
7350 AssertRC(rc);
7351 }
7352
7353 if (fWhat & CPUMCTX_EXTRN_SREG_MASK)
7354 {
7355 bool const fRealOnV86Active = pVmcsInfo->RealMode.fRealOnV86Active;
7356 if (fWhat & CPUMCTX_EXTRN_CS)
7357 {
7358 hmR0VmxImportGuestSegReg(pVCpu, X86_SREG_CS);
7359 hmR0VmxImportGuestRip(pVCpu);
7360 if (fRealOnV86Active)
7361 pCtx->cs.Attr.u = pVmcsInfo->RealMode.AttrCS.u;
7362 EMR0HistoryUpdatePC(pVCpu, pCtx->cs.u64Base + pCtx->rip, true /* fFlattened */);
7363 }
7364 if (fWhat & CPUMCTX_EXTRN_SS)
7365 {
7366 hmR0VmxImportGuestSegReg(pVCpu, X86_SREG_SS);
7367 if (fRealOnV86Active)
7368 pCtx->ss.Attr.u = pVmcsInfo->RealMode.AttrSS.u;
7369 }
7370 if (fWhat & CPUMCTX_EXTRN_DS)
7371 {
7372 hmR0VmxImportGuestSegReg(pVCpu, X86_SREG_DS);
7373 if (fRealOnV86Active)
7374 pCtx->ds.Attr.u = pVmcsInfo->RealMode.AttrDS.u;
7375 }
7376 if (fWhat & CPUMCTX_EXTRN_ES)
7377 {
7378 hmR0VmxImportGuestSegReg(pVCpu, X86_SREG_ES);
7379 if (fRealOnV86Active)
7380 pCtx->es.Attr.u = pVmcsInfo->RealMode.AttrES.u;
7381 }
7382 if (fWhat & CPUMCTX_EXTRN_FS)
7383 {
7384 hmR0VmxImportGuestSegReg(pVCpu, X86_SREG_FS);
7385 if (fRealOnV86Active)
7386 pCtx->fs.Attr.u = pVmcsInfo->RealMode.AttrFS.u;
7387 }
7388 if (fWhat & CPUMCTX_EXTRN_GS)
7389 {
7390 hmR0VmxImportGuestSegReg(pVCpu, X86_SREG_GS);
7391 if (fRealOnV86Active)
7392 pCtx->gs.Attr.u = pVmcsInfo->RealMode.AttrGS.u;
7393 }
7394 }
7395
7396 if (fWhat & CPUMCTX_EXTRN_TABLE_MASK)
7397 {
7398 if (fWhat & CPUMCTX_EXTRN_LDTR)
7399 hmR0VmxImportGuestLdtr(pVCpu);
7400
7401 if (fWhat & CPUMCTX_EXTRN_GDTR)
7402 {
7403 rc = VMXReadVmcsNw(VMX_VMCS_GUEST_GDTR_BASE, &pCtx->gdtr.pGdt); AssertRC(rc);
7404 rc = VMXReadVmcs32(VMX_VMCS32_GUEST_GDTR_LIMIT, &u32Val); AssertRC(rc);
7405 pCtx->gdtr.cbGdt = u32Val;
7406 }
7407
7408 /* Guest IDTR. */
7409 if (fWhat & CPUMCTX_EXTRN_IDTR)
7410 {
7411 rc = VMXReadVmcsNw(VMX_VMCS_GUEST_IDTR_BASE, &pCtx->idtr.pIdt); AssertRC(rc);
7412 rc = VMXReadVmcs32(VMX_VMCS32_GUEST_IDTR_LIMIT, &u32Val); AssertRC(rc);
7413 pCtx->idtr.cbIdt = u32Val;
7414 }
7415
7416 /* Guest TR. */
7417 if (fWhat & CPUMCTX_EXTRN_TR)
7418 {
7419 /* Real-mode emulation using virtual-8086 mode has the fake TSS (pRealModeTSS) in TR,
7420 don't need to import that one. */
7421 if (!pVmcsInfo->RealMode.fRealOnV86Active)
7422 hmR0VmxImportGuestTr(pVCpu);
7423 }
7424 }
7425
7426 if (fWhat & CPUMCTX_EXTRN_DR7)
7427 {
7428 if (!pVCpu->hm.s.fUsingHyperDR7)
7429 rc = VMXReadVmcsNw(VMX_VMCS_GUEST_DR7, &pCtx->dr[7]); AssertRC(rc);
7430 }
7431
7432 if (fWhat & CPUMCTX_EXTRN_SYSENTER_MSRS)
7433 {
7434 rc = VMXReadVmcsNw(VMX_VMCS_GUEST_SYSENTER_EIP, &pCtx->SysEnter.eip); AssertRC(rc);
7435 rc = VMXReadVmcsNw(VMX_VMCS_GUEST_SYSENTER_ESP, &pCtx->SysEnter.esp); AssertRC(rc);
7436 rc = VMXReadVmcs32(VMX_VMCS32_GUEST_SYSENTER_CS, &u32Val); AssertRC(rc);
7437 pCtx->SysEnter.cs = u32Val;
7438 }
7439
7440 if (fWhat & CPUMCTX_EXTRN_KERNEL_GS_BASE)
7441 {
7442 if ( pVM->hm.s.fAllow64BitGuests
7443 && (pVCpu->hm.s.vmx.fLazyMsrs & VMX_LAZY_MSRS_LOADED_GUEST))
7444 pCtx->msrKERNELGSBASE = ASMRdMsr(MSR_K8_KERNEL_GS_BASE);
7445 }
7446
7447 if (fWhat & CPUMCTX_EXTRN_SYSCALL_MSRS)
7448 {
7449 if ( pVM->hm.s.fAllow64BitGuests
7450 && (pVCpu->hm.s.vmx.fLazyMsrs & VMX_LAZY_MSRS_LOADED_GUEST))
7451 {
7452 pCtx->msrLSTAR = ASMRdMsr(MSR_K8_LSTAR);
7453 pCtx->msrSTAR = ASMRdMsr(MSR_K6_STAR);
7454 pCtx->msrSFMASK = ASMRdMsr(MSR_K8_SF_MASK);
7455 }
7456 }
7457
7458 if (fWhat & (CPUMCTX_EXTRN_TSC_AUX | CPUMCTX_EXTRN_OTHER_MSRS))
7459 {
7460 PCVMXAUTOMSR pMsrs = (PCVMXAUTOMSR)pVmcsInfo->pvGuestMsrStore;
7461 uint32_t const cMsrs = pVmcsInfo->cExitMsrStore;
7462 Assert(pMsrs);
7463 Assert(cMsrs <= VMX_MISC_MAX_MSRS(pVM->hm.s.vmx.Msrs.u64Misc));
7464 Assert(sizeof(*pMsrs) * cMsrs <= X86_PAGE_4K_SIZE);
7465 for (uint32_t i = 0; i < cMsrs; i++)
7466 {
7467 uint32_t const idMsr = pMsrs[i].u32Msr;
7468 switch (idMsr)
7469 {
7470 case MSR_K8_TSC_AUX: CPUMSetGuestTscAux(pVCpu, pMsrs[i].u64Value); break;
7471 case MSR_IA32_SPEC_CTRL: CPUMSetGuestSpecCtrl(pVCpu, pMsrs[i].u64Value); break;
7472 case MSR_K6_EFER: /* Can't be changed without causing a VM-exit */ break;
7473 default:
7474 {
7475 pCtx->fExtrn = 0;
7476 pVCpu->hm.s.u32HMError = pMsrs->u32Msr;
7477 ASMSetFlags(fEFlags);
7478 AssertMsgFailed(("Unexpected MSR in auto-load/store area. idMsr=%#RX32 cMsrs=%u\n", idMsr, cMsrs));
7479 return VERR_HM_UNEXPECTED_LD_ST_MSR;
7480 }
7481 }
7482 }
7483 }
7484
7485 if (fWhat & CPUMCTX_EXTRN_CR_MASK)
7486 {
7487 if (fWhat & CPUMCTX_EXTRN_CR0)
7488 {
7489 uint64_t u64Cr0;
7490 uint64_t u64Shadow;
7491 rc = VMXReadVmcsNw(VMX_VMCS_GUEST_CR0, &u64Cr0); AssertRC(rc);
7492 rc = VMXReadVmcsNw(VMX_VMCS_CTRL_CR0_READ_SHADOW, &u64Shadow); AssertRC(rc);
7493#ifndef VBOX_WITH_NESTED_HWVIRT_VMX
7494 u64Cr0 = (u64Cr0 & ~pVmcsInfo->u64Cr0Mask)
7495 | (u64Shadow & pVmcsInfo->u64Cr0Mask);
7496#else
7497 if (!CPUMIsGuestInVmxNonRootMode(pCtx))
7498 {
7499 u64Cr0 = (u64Cr0 & ~pVmcsInfo->u64Cr0Mask)
7500 | (u64Shadow & pVmcsInfo->u64Cr0Mask);
7501 }
7502 else
7503 {
7504 /*
7505 * We've merged the guest and nested-guest's CR0 guest/host mask while executing
7506 * the nested-guest using hardware-assisted VMX. Accordingly we need to
7507 * re-construct CR0. See @bugref{9180#c95} for details.
7508 */
7509 PCVMXVMCSINFO pVmcsInfoGst = &pVCpu->hm.s.vmx.VmcsInfo;
7510 PCVMXVVMCS pVmcsNstGst = pVCpu->cpum.GstCtx.hwvirt.vmx.CTX_SUFF(pVmcs);
7511 u64Cr0 = (u64Cr0 & ~pVmcsInfo->u64Cr0Mask)
7512 | (pVmcsNstGst->u64GuestCr0.u & pVmcsNstGst->u64Cr0Mask.u)
7513 | (u64Shadow & (pVmcsInfoGst->u64Cr0Mask & ~pVmcsNstGst->u64Cr0Mask.u));
7514 }
7515#endif
7516 VMMRZCallRing3Disable(pVCpu); /* May call into PGM which has Log statements. */
7517 CPUMSetGuestCR0(pVCpu, u64Cr0);
7518 VMMRZCallRing3Enable(pVCpu);
7519 }
7520
7521 if (fWhat & CPUMCTX_EXTRN_CR4)
7522 {
7523 uint64_t u64Cr4;
7524 uint64_t u64Shadow;
7525 rc = VMXReadVmcsNw(VMX_VMCS_GUEST_CR4, &u64Cr4); AssertRC(rc);
7526 rc |= VMXReadVmcsNw(VMX_VMCS_CTRL_CR4_READ_SHADOW, &u64Shadow); AssertRC(rc);
7527#ifndef VBOX_WITH_NESTED_HWVIRT_VMX
7528 u64Cr4 = (u64Cr4 & ~pVmcsInfo->u64Cr4Mask)
7529 | (u64Shadow & pVmcsInfo->u64Cr4Mask);
7530#else
7531 if (!CPUMIsGuestInVmxNonRootMode(pCtx))
7532 {
7533 u64Cr4 = (u64Cr4 & ~pVmcsInfo->u64Cr4Mask)
7534 | (u64Shadow & pVmcsInfo->u64Cr4Mask);
7535 }
7536 else
7537 {
7538 /*
7539 * We've merged the guest and nested-guest's CR4 guest/host mask while executing
7540 * the nested-guest using hardware-assisted VMX. Accordingly we need to
7541 * re-construct CR4. See @bugref{9180#c95} for details.
7542 */
7543 PCVMXVMCSINFO pVmcsInfoGst = &pVCpu->hm.s.vmx.VmcsInfo;
7544 PCVMXVVMCS pVmcsNstGst = pVCpu->cpum.GstCtx.hwvirt.vmx.CTX_SUFF(pVmcs);
7545 u64Cr4 = (u64Cr4 & ~pVmcsInfo->u64Cr4Mask)
7546 | (pVmcsNstGst->u64GuestCr4.u & pVmcsNstGst->u64Cr4Mask.u)
7547 | (u64Shadow & (pVmcsInfoGst->u64Cr4Mask & ~pVmcsNstGst->u64Cr4Mask.u));
7548 }
7549#endif
7550 pCtx->cr4 = u64Cr4;
7551 }
7552
7553 if (fWhat & CPUMCTX_EXTRN_CR3)
7554 {
7555 /* CR0.PG bit changes are always intercepted, so it's up to date. */
7556 if ( pVM->hm.s.vmx.fUnrestrictedGuest
7557 || ( pVM->hm.s.fNestedPaging
7558 && CPUMIsGuestPagingEnabledEx(pCtx)))
7559 {
7560 uint64_t u64Cr3;
7561 rc = VMXReadVmcsNw(VMX_VMCS_GUEST_CR3, &u64Cr3); AssertRC(rc);
7562 if (pCtx->cr3 != u64Cr3)
7563 {
7564 pCtx->cr3 = u64Cr3;
7565 VMCPU_FF_SET(pVCpu, VMCPU_FF_HM_UPDATE_CR3);
7566 }
7567
7568 /* If the guest is in PAE mode, sync back the PDPE's into the guest state.
7569 Note: CR4.PAE, CR0.PG, EFER MSR changes are always intercepted, so they're up to date. */
7570 if (CPUMIsGuestInPAEModeEx(pCtx))
7571 {
7572 rc = VMXReadVmcs64(VMX_VMCS64_GUEST_PDPTE0_FULL, &pVCpu->hm.s.aPdpes[0].u); AssertRC(rc);
7573 rc = VMXReadVmcs64(VMX_VMCS64_GUEST_PDPTE1_FULL, &pVCpu->hm.s.aPdpes[1].u); AssertRC(rc);
7574 rc = VMXReadVmcs64(VMX_VMCS64_GUEST_PDPTE2_FULL, &pVCpu->hm.s.aPdpes[2].u); AssertRC(rc);
7575 rc = VMXReadVmcs64(VMX_VMCS64_GUEST_PDPTE3_FULL, &pVCpu->hm.s.aPdpes[3].u); AssertRC(rc);
7576 VMCPU_FF_SET(pVCpu, VMCPU_FF_HM_UPDATE_PAE_PDPES);
7577 }
7578 }
7579 }
7580 }
7581
7582#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
7583 if (fWhat & CPUMCTX_EXTRN_HWVIRT)
7584 {
7585 if ( (pVmcsInfo->u32ProcCtls2 & VMX_PROC_CTLS2_VMCS_SHADOWING)
7586 && !CPUMIsGuestInVmxNonRootMode(pCtx))
7587 {
7588 Assert(CPUMIsGuestInVmxRootMode(pCtx));
7589 rc = hmR0VmxCopyShadowToNstGstVmcs(pVCpu, pVmcsInfo);
7590 if (RT_SUCCESS(rc))
7591 { /* likely */ }
7592 else
7593 break;
7594 }
7595 }
7596#endif
7597 } while (0);
7598
7599 if (RT_SUCCESS(rc))
7600 {
7601 /* Update fExtrn. */
7602 pCtx->fExtrn &= ~fWhat;
7603
7604 /* If everything has been imported, clear the HM keeper bit. */
7605 if (!(pCtx->fExtrn & HMVMX_CPUMCTX_EXTRN_ALL))
7606 {
7607 pCtx->fExtrn &= ~CPUMCTX_EXTRN_KEEPER_HM;
7608 Assert(!pCtx->fExtrn);
7609 }
7610 }
7611 }
7612 else
7613 AssertMsg(!pCtx->fExtrn || (pCtx->fExtrn & HMVMX_CPUMCTX_EXTRN_ALL), ("%#RX64\n", pCtx->fExtrn));
7614
7615 /*
7616 * Restore interrupts.
7617 */
7618 ASMSetFlags(fEFlags);
7619
7620 STAM_PROFILE_ADV_STOP(& pVCpu->hm.s.StatImportGuestState, x);
7621
7622 if (RT_SUCCESS(rc))
7623 { /* likely */ }
7624 else
7625 return rc;
7626
7627 /*
7628 * Honor any pending CR3 updates.
7629 *
7630 * Consider this scenario: VM-exit -> VMMRZCallRing3Enable() -> do stuff that causes a longjmp -> VMXR0CallRing3Callback()
7631 * -> VMMRZCallRing3Disable() -> hmR0VmxImportGuestState() -> Sets VMCPU_FF_HM_UPDATE_CR3 pending -> return from the longjmp
7632 * -> continue with VM-exit handling -> hmR0VmxImportGuestState() and here we are.
7633 *
7634 * The reason for such complicated handling is because VM-exits that call into PGM expect CR3 to be up-to-date and thus
7635 * if any CR3-saves -before- the VM-exit (longjmp) postponed the CR3 update via the force-flag, any VM-exit handler that
7636 * calls into PGM when it re-saves CR3 will end up here and we call PGMUpdateCR3(). This is why the code below should
7637 * -NOT- check if CPUMCTX_EXTRN_CR3 is set!
7638 *
7639 * The longjmp exit path can't check these CR3 force-flags and call code that takes a lock again. We cover for it here.
7640 */
7641 if (VMMRZCallRing3IsEnabled(pVCpu))
7642 {
7643 if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_HM_UPDATE_CR3))
7644 {
7645 Assert(!(ASMAtomicUoReadU64(&pCtx->fExtrn) & CPUMCTX_EXTRN_CR3));
7646 PGMUpdateCR3(pVCpu, CPUMGetGuestCR3(pVCpu));
7647 }
7648
7649 if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_HM_UPDATE_PAE_PDPES))
7650 PGMGstUpdatePaePdpes(pVCpu, &pVCpu->hm.s.aPdpes[0]);
7651
7652 Assert(!VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_HM_UPDATE_CR3));
7653 Assert(!VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_HM_UPDATE_PAE_PDPES));
7654 }
7655
7656 return VINF_SUCCESS;
7657}
7658
7659
7660/**
7661 * Saves the guest state from the VMCS into the guest-CPU context.
7662 *
7663 * @returns VBox status code.
7664 * @param pVCpu The cross context virtual CPU structure.
7665 * @param fWhat What to import, CPUMCTX_EXTRN_XXX.
7666 */
7667VMMR0DECL(int) VMXR0ImportStateOnDemand(PVMCPUCC pVCpu, uint64_t fWhat)
7668{
7669 AssertPtr(pVCpu);
7670 PVMXVMCSINFO pVmcsInfo = hmGetVmxActiveVmcsInfo(pVCpu);
7671 return hmR0VmxImportGuestState(pVCpu, pVmcsInfo, fWhat);
7672}
7673
7674
7675/**
7676 * Check per-VM and per-VCPU force flag actions that require us to go back to
7677 * ring-3 for one reason or another.
7678 *
7679 * @returns Strict VBox status code (i.e. informational status codes too)
7680 * @retval VINF_SUCCESS if we don't have any actions that require going back to
7681 * ring-3.
7682 * @retval VINF_PGM_SYNC_CR3 if we have pending PGM CR3 sync.
7683 * @retval VINF_EM_PENDING_REQUEST if we have pending requests (like hardware
7684 * interrupts)
7685 * @retval VINF_PGM_POOL_FLUSH_PENDING if PGM is doing a pool flush and requires
7686 * all EMTs to be in ring-3.
7687 * @retval VINF_EM_RAW_TO_R3 if there is pending DMA requests.
7688 * @retval VINF_EM_NO_MEMORY PGM is out of memory, we need to return
7689 * to the EM loop.
7690 *
7691 * @param pVCpu The cross context virtual CPU structure.
7692 * @param fStepping Whether we are single-stepping the guest using the
7693 * hypervisor debugger.
7694 *
7695 * @remarks This might cause nested-guest VM-exits, caller must check if the guest
7696 * is no longer in VMX non-root mode.
7697 */
7698static VBOXSTRICTRC hmR0VmxCheckForceFlags(PVMCPUCC pVCpu, bool fStepping)
7699{
7700 Assert(VMMRZCallRing3IsEnabled(pVCpu));
7701
7702 /*
7703 * Update pending interrupts into the APIC's IRR.
7704 */
7705 if (VMCPU_FF_TEST_AND_CLEAR(pVCpu, VMCPU_FF_UPDATE_APIC))
7706 APICUpdatePendingInterrupts(pVCpu);
7707
7708 /*
7709 * Anything pending? Should be more likely than not if we're doing a good job.
7710 */
7711 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
7712 if ( !fStepping
7713 ? !VM_FF_IS_ANY_SET(pVM, VM_FF_HP_R0_PRE_HM_MASK)
7714 && !VMCPU_FF_IS_ANY_SET(pVCpu, VMCPU_FF_HP_R0_PRE_HM_MASK)
7715 : !VM_FF_IS_ANY_SET(pVM, VM_FF_HP_R0_PRE_HM_STEP_MASK)
7716 && !VMCPU_FF_IS_ANY_SET(pVCpu, VMCPU_FF_HP_R0_PRE_HM_STEP_MASK) )
7717 return VINF_SUCCESS;
7718
7719 /* Pending PGM C3 sync. */
7720 if (VMCPU_FF_IS_ANY_SET(pVCpu,VMCPU_FF_PGM_SYNC_CR3 | VMCPU_FF_PGM_SYNC_CR3_NON_GLOBAL))
7721 {
7722 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
7723 Assert(!(ASMAtomicUoReadU64(&pCtx->fExtrn) & (CPUMCTX_EXTRN_CR0 | CPUMCTX_EXTRN_CR3 | CPUMCTX_EXTRN_CR4)));
7724 VBOXSTRICTRC rcStrict = PGMSyncCR3(pVCpu, pCtx->cr0, pCtx->cr3, pCtx->cr4,
7725 VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_PGM_SYNC_CR3));
7726 if (rcStrict != VINF_SUCCESS)
7727 {
7728 AssertRC(VBOXSTRICTRC_VAL(rcStrict));
7729 Log4Func(("PGMSyncCR3 forcing us back to ring-3. rc2=%d\n", VBOXSTRICTRC_VAL(rcStrict)));
7730 return rcStrict;
7731 }
7732 }
7733
7734 /* Pending HM-to-R3 operations (critsects, timers, EMT rendezvous etc.) */
7735 if ( VM_FF_IS_ANY_SET(pVM, VM_FF_HM_TO_R3_MASK)
7736 || VMCPU_FF_IS_ANY_SET(pVCpu, VMCPU_FF_HM_TO_R3_MASK))
7737 {
7738 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchHmToR3FF);
7739 int rc = RT_LIKELY(!VM_FF_IS_SET(pVM, VM_FF_PGM_NO_MEMORY)) ? VINF_EM_RAW_TO_R3 : VINF_EM_NO_MEMORY;
7740 Log4Func(("HM_TO_R3 forcing us back to ring-3. rc=%d\n", rc));
7741 return rc;
7742 }
7743
7744 /* Pending VM request packets, such as hardware interrupts. */
7745 if ( VM_FF_IS_SET(pVM, VM_FF_REQUEST)
7746 || VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_REQUEST))
7747 {
7748 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchVmReq);
7749 Log4Func(("Pending VM request forcing us back to ring-3\n"));
7750 return VINF_EM_PENDING_REQUEST;
7751 }
7752
7753 /* Pending PGM pool flushes. */
7754 if (VM_FF_IS_SET(pVM, VM_FF_PGM_POOL_FLUSH_PENDING))
7755 {
7756 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchPgmPoolFlush);
7757 Log4Func(("PGM pool flush pending forcing us back to ring-3\n"));
7758 return VINF_PGM_POOL_FLUSH_PENDING;
7759 }
7760
7761 /* Pending DMA requests. */
7762 if (VM_FF_IS_SET(pVM, VM_FF_PDM_DMA))
7763 {
7764 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchDma);
7765 Log4Func(("Pending DMA request forcing us back to ring-3\n"));
7766 return VINF_EM_RAW_TO_R3;
7767 }
7768
7769#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
7770 /* Pending nested-guest APIC-write (has highest priority among nested-guest FFs). */
7771 if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_VMX_APIC_WRITE))
7772 {
7773 Log4Func(("Pending nested-guest APIC-write\n"));
7774 VBOXSTRICTRC rcStrict = IEMExecVmxVmexitApicWrite(pVCpu);
7775 Assert(rcStrict != VINF_VMX_INTERCEPT_NOT_ACTIVE);
7776 return rcStrict;
7777 }
7778 /** @todo VMCPU_FF_VMX_MTF, VMCPU_FF_VMX_PREEMPT_TIMER */
7779#endif
7780
7781 return VINF_SUCCESS;
7782}
7783
7784
7785/**
7786 * Converts any TRPM trap into a pending HM event. This is typically used when
7787 * entering from ring-3 (not longjmp returns).
7788 *
7789 * @param pVCpu The cross context virtual CPU structure.
7790 */
7791static void hmR0VmxTrpmTrapToPendingEvent(PVMCPUCC pVCpu)
7792{
7793 Assert(TRPMHasTrap(pVCpu));
7794 Assert(!pVCpu->hm.s.Event.fPending);
7795
7796 uint8_t uVector;
7797 TRPMEVENT enmTrpmEvent;
7798 RTGCUINT uErrCode;
7799 RTGCUINTPTR GCPtrFaultAddress;
7800 uint8_t cbInstr;
7801
7802 int rc = TRPMQueryTrapAll(pVCpu, &uVector, &enmTrpmEvent, &uErrCode, &GCPtrFaultAddress, &cbInstr);
7803 AssertRC(rc);
7804
7805 uint32_t u32IntInfo;
7806 u32IntInfo = uVector | VMX_IDT_VECTORING_INFO_VALID;
7807 u32IntInfo |= HMTrpmEventTypeToVmxEventType(uVector, enmTrpmEvent);
7808
7809 rc = TRPMResetTrap(pVCpu);
7810 AssertRC(rc);
7811 Log4(("TRPM->HM event: u32IntInfo=%#RX32 enmTrpmEvent=%d cbInstr=%u uErrCode=%#RX32 GCPtrFaultAddress=%#RGv\n",
7812 u32IntInfo, enmTrpmEvent, cbInstr, uErrCode, GCPtrFaultAddress));
7813
7814 hmR0VmxSetPendingEvent(pVCpu, u32IntInfo, cbInstr, uErrCode, GCPtrFaultAddress);
7815}
7816
7817
7818/**
7819 * Converts the pending HM event into a TRPM trap.
7820 *
7821 * @param pVCpu The cross context virtual CPU structure.
7822 */
7823static void hmR0VmxPendingEventToTrpmTrap(PVMCPUCC pVCpu)
7824{
7825 Assert(pVCpu->hm.s.Event.fPending);
7826
7827 /* If a trap was already pending, we did something wrong! */
7828 Assert(TRPMQueryTrap(pVCpu, NULL /* pu8TrapNo */, NULL /* pEnmType */) == VERR_TRPM_NO_ACTIVE_TRAP);
7829
7830 uint32_t const u32IntInfo = pVCpu->hm.s.Event.u64IntInfo;
7831 uint32_t const uVector = VMX_IDT_VECTORING_INFO_VECTOR(u32IntInfo);
7832 TRPMEVENT const enmTrapType = HMVmxEventTypeToTrpmEventType(u32IntInfo);
7833
7834 Log4(("HM event->TRPM: uVector=%#x enmTrapType=%d\n", uVector, enmTrapType));
7835
7836 int rc = TRPMAssertTrap(pVCpu, uVector, enmTrapType);
7837 AssertRC(rc);
7838
7839 if (VMX_IDT_VECTORING_INFO_IS_ERROR_CODE_VALID(u32IntInfo))
7840 TRPMSetErrorCode(pVCpu, pVCpu->hm.s.Event.u32ErrCode);
7841
7842 if (VMX_IDT_VECTORING_INFO_IS_XCPT_PF(u32IntInfo))
7843 TRPMSetFaultAddress(pVCpu, pVCpu->hm.s.Event.GCPtrFaultAddress);
7844 else if (VMX_IDT_VECTORING_INFO_TYPE(u32IntInfo) == VMX_IDT_VECTORING_INFO_TYPE_SW_INT)
7845 TRPMSetInstrLength(pVCpu, pVCpu->hm.s.Event.cbInstr);
7846
7847 /* We're now done converting the pending event. */
7848 pVCpu->hm.s.Event.fPending = false;
7849}
7850
7851
7852/**
7853 * Sets the interrupt-window exiting control in the VMCS which instructs VT-x to
7854 * cause a VM-exit as soon as the guest is in a state to receive interrupts.
7855 *
7856 * @param pVCpu The cross context virtual CPU structure.
7857 * @param pVmcsInfo The VMCS info. object.
7858 */
7859static void hmR0VmxSetIntWindowExitVmcs(PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo)
7860{
7861 if (pVCpu->CTX_SUFF(pVM)->hm.s.vmx.Msrs.ProcCtls.n.allowed1 & VMX_PROC_CTLS_INT_WINDOW_EXIT)
7862 {
7863 if (!(pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_INT_WINDOW_EXIT))
7864 {
7865 pVmcsInfo->u32ProcCtls |= VMX_PROC_CTLS_INT_WINDOW_EXIT;
7866 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, pVmcsInfo->u32ProcCtls);
7867 AssertRC(rc);
7868 }
7869 } /* else we will deliver interrupts whenever the guest Vm-exits next and is in a state to receive the interrupt. */
7870}
7871
7872
7873/**
7874 * Clears the interrupt-window exiting control in the VMCS.
7875 *
7876 * @param pVmcsInfo The VMCS info. object.
7877 */
7878DECLINLINE(void) hmR0VmxClearIntWindowExitVmcs(PVMXVMCSINFO pVmcsInfo)
7879{
7880 if (pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_INT_WINDOW_EXIT)
7881 {
7882 pVmcsInfo->u32ProcCtls &= ~VMX_PROC_CTLS_INT_WINDOW_EXIT;
7883 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, pVmcsInfo->u32ProcCtls);
7884 AssertRC(rc);
7885 }
7886}
7887
7888
7889/**
7890 * Sets the NMI-window exiting control in the VMCS which instructs VT-x to
7891 * cause a VM-exit as soon as the guest is in a state to receive NMIs.
7892 *
7893 * @param pVCpu The cross context virtual CPU structure.
7894 * @param pVmcsInfo The VMCS info. object.
7895 */
7896static void hmR0VmxSetNmiWindowExitVmcs(PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo)
7897{
7898 if (pVCpu->CTX_SUFF(pVM)->hm.s.vmx.Msrs.ProcCtls.n.allowed1 & VMX_PROC_CTLS_NMI_WINDOW_EXIT)
7899 {
7900 if (!(pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_NMI_WINDOW_EXIT))
7901 {
7902 pVmcsInfo->u32ProcCtls |= VMX_PROC_CTLS_NMI_WINDOW_EXIT;
7903 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, pVmcsInfo->u32ProcCtls);
7904 AssertRC(rc);
7905 Log4Func(("Setup NMI-window exiting\n"));
7906 }
7907 } /* else we will deliver NMIs whenever we VM-exit next, even possibly nesting NMIs. Can't be helped on ancient CPUs. */
7908}
7909
7910
7911/**
7912 * Clears the NMI-window exiting control in the VMCS.
7913 *
7914 * @param pVmcsInfo The VMCS info. object.
7915 */
7916DECLINLINE(void) hmR0VmxClearNmiWindowExitVmcs(PVMXVMCSINFO pVmcsInfo)
7917{
7918 if (pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_NMI_WINDOW_EXIT)
7919 {
7920 pVmcsInfo->u32ProcCtls &= ~VMX_PROC_CTLS_NMI_WINDOW_EXIT;
7921 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, pVmcsInfo->u32ProcCtls);
7922 AssertRC(rc);
7923 }
7924}
7925
7926
7927/**
7928 * Does the necessary state syncing before returning to ring-3 for any reason
7929 * (longjmp, preemption, voluntary exits to ring-3) from VT-x.
7930 *
7931 * @returns VBox status code.
7932 * @param pVCpu The cross context virtual CPU structure.
7933 * @param fImportState Whether to import the guest state from the VMCS back
7934 * to the guest-CPU context.
7935 *
7936 * @remarks No-long-jmp zone!!!
7937 */
7938static int hmR0VmxLeave(PVMCPUCC pVCpu, bool fImportState)
7939{
7940 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
7941 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
7942
7943 RTCPUID const idCpu = RTMpCpuId();
7944 Log4Func(("HostCpuId=%u\n", idCpu));
7945
7946 /*
7947 * !!! IMPORTANT !!!
7948 * If you modify code here, check whether VMXR0CallRing3Callback() needs to be updated too.
7949 */
7950
7951 /* Save the guest state if necessary. */
7952 PVMXVMCSINFO pVmcsInfo = hmGetVmxActiveVmcsInfo(pVCpu);
7953 if (fImportState)
7954 {
7955 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, HMVMX_CPUMCTX_EXTRN_ALL);
7956 AssertRCReturn(rc, rc);
7957 }
7958
7959 /* Restore host FPU state if necessary. We will resync on next R0 reentry. */
7960 CPUMR0FpuStateMaybeSaveGuestAndRestoreHost(pVCpu);
7961 Assert(!CPUMIsGuestFPUStateActive(pVCpu));
7962
7963 /* Restore host debug registers if necessary. We will resync on next R0 reentry. */
7964#ifdef VBOX_STRICT
7965 if (CPUMIsHyperDebugStateActive(pVCpu))
7966 Assert(pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_MOV_DR_EXIT);
7967#endif
7968 CPUMR0DebugStateMaybeSaveGuestAndRestoreHost(pVCpu, true /* save DR6 */);
7969 Assert(!CPUMIsGuestDebugStateActive(pVCpu) && !CPUMIsGuestDebugStateActivePending(pVCpu));
7970 Assert(!CPUMIsHyperDebugStateActive(pVCpu) && !CPUMIsHyperDebugStateActivePending(pVCpu));
7971
7972 /* Restore host-state bits that VT-x only restores partially. */
7973 if ( (pVCpu->hm.s.vmx.fRestoreHostFlags & VMX_RESTORE_HOST_REQUIRED)
7974 && (pVCpu->hm.s.vmx.fRestoreHostFlags & ~VMX_RESTORE_HOST_REQUIRED))
7975 {
7976 Log4Func(("Restoring Host State: fRestoreHostFlags=%#RX32 HostCpuId=%u\n", pVCpu->hm.s.vmx.fRestoreHostFlags, idCpu));
7977 VMXRestoreHostState(pVCpu->hm.s.vmx.fRestoreHostFlags, &pVCpu->hm.s.vmx.RestoreHost);
7978 }
7979 pVCpu->hm.s.vmx.fRestoreHostFlags = 0;
7980
7981 /* Restore the lazy host MSRs as we're leaving VT-x context. */
7982 if (pVCpu->hm.s.vmx.fLazyMsrs & VMX_LAZY_MSRS_LOADED_GUEST)
7983 {
7984 /* We shouldn't restore the host MSRs without saving the guest MSRs first. */
7985 if (!fImportState)
7986 {
7987 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, CPUMCTX_EXTRN_KERNEL_GS_BASE | CPUMCTX_EXTRN_SYSCALL_MSRS);
7988 AssertRCReturn(rc, rc);
7989 }
7990 hmR0VmxLazyRestoreHostMsrs(pVCpu);
7991 Assert(!pVCpu->hm.s.vmx.fLazyMsrs);
7992 }
7993 else
7994 pVCpu->hm.s.vmx.fLazyMsrs = 0;
7995
7996 /* Update auto-load/store host MSRs values when we re-enter VT-x (as we could be on a different CPU). */
7997 pVCpu->hm.s.vmx.fUpdatedHostAutoMsrs = false;
7998
7999 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatEntry);
8000 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatImportGuestState);
8001 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatExportGuestState);
8002 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatPreExit);
8003 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatExitHandling);
8004 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatExitIO);
8005 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatExitMovCRx);
8006 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatExitXcptNmi);
8007 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatExitVmentry);
8008 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchLongJmpToR3);
8009
8010 VMCPU_CMPXCHG_STATE(pVCpu, VMCPUSTATE_STARTED_HM, VMCPUSTATE_STARTED_EXEC);
8011
8012 /** @todo This partially defeats the purpose of having preemption hooks.
8013 * The problem is, deregistering the hooks should be moved to a place that
8014 * lasts until the EMT is about to be destroyed not everytime while leaving HM
8015 * context.
8016 */
8017 int rc = hmR0VmxClearVmcs(pVmcsInfo);
8018 AssertRCReturn(rc, rc);
8019
8020#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
8021 /*
8022 * A valid shadow VMCS is made active as part of VM-entry. It is necessary to
8023 * clear a shadow VMCS before allowing that VMCS to become active on another
8024 * logical processor. We may or may not be importing guest state which clears
8025 * it, so cover for it here.
8026 *
8027 * See Intel spec. 24.11.1 "Software Use of Virtual-Machine Control Structures".
8028 */
8029 if ( pVmcsInfo->pvShadowVmcs
8030 && pVmcsInfo->fShadowVmcsState != VMX_V_VMCS_LAUNCH_STATE_CLEAR)
8031 {
8032 rc = hmR0VmxClearShadowVmcs(pVmcsInfo);
8033 AssertRCReturn(rc, rc);
8034 }
8035
8036 /*
8037 * Flag that we need to re-export the host state if we switch to this VMCS before
8038 * executing guest or nested-guest code.
8039 */
8040 pVmcsInfo->idHostCpuState = NIL_RTCPUID;
8041#endif
8042
8043 Log4Func(("Cleared Vmcs. HostCpuId=%u\n", idCpu));
8044 NOREF(idCpu);
8045 return VINF_SUCCESS;
8046}
8047
8048
8049/**
8050 * Leaves the VT-x session.
8051 *
8052 * @returns VBox status code.
8053 * @param pVCpu The cross context virtual CPU structure.
8054 *
8055 * @remarks No-long-jmp zone!!!
8056 */
8057static int hmR0VmxLeaveSession(PVMCPUCC pVCpu)
8058{
8059 HM_DISABLE_PREEMPT(pVCpu);
8060 HMVMX_ASSERT_CPU_SAFE(pVCpu);
8061 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
8062 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
8063
8064 /* When thread-context hooks are used, we can avoid doing the leave again if we had been preempted before
8065 and done this from the VMXR0ThreadCtxCallback(). */
8066 if (!pVCpu->hm.s.fLeaveDone)
8067 {
8068 int rc2 = hmR0VmxLeave(pVCpu, true /* fImportState */);
8069 AssertRCReturnStmt(rc2, HM_RESTORE_PREEMPT(), rc2);
8070 pVCpu->hm.s.fLeaveDone = true;
8071 }
8072 Assert(!pVCpu->cpum.GstCtx.fExtrn);
8073
8074 /*
8075 * !!! IMPORTANT !!!
8076 * If you modify code here, make sure to check whether VMXR0CallRing3Callback() needs to be updated too.
8077 */
8078
8079 /* Deregister hook now that we've left HM context before re-enabling preemption. */
8080 /** @todo Deregistering here means we need to VMCLEAR always
8081 * (longjmp/exit-to-r3) in VT-x which is not efficient, eliminate need
8082 * for calling VMMR0ThreadCtxHookDisable here! */
8083 VMMR0ThreadCtxHookDisable(pVCpu);
8084
8085 /* Leave HM context. This takes care of local init (term) and deregistering the longjmp-to-ring-3 callback. */
8086 int rc = HMR0LeaveCpu(pVCpu);
8087 HM_RESTORE_PREEMPT();
8088 return rc;
8089}
8090
8091
8092/**
8093 * Does the necessary state syncing before doing a longjmp to ring-3.
8094 *
8095 * @returns VBox status code.
8096 * @param pVCpu The cross context virtual CPU structure.
8097 *
8098 * @remarks No-long-jmp zone!!!
8099 */
8100DECLINLINE(int) hmR0VmxLongJmpToRing3(PVMCPUCC pVCpu)
8101{
8102 return hmR0VmxLeaveSession(pVCpu);
8103}
8104
8105
8106/**
8107 * Take necessary actions before going back to ring-3.
8108 *
8109 * An action requires us to go back to ring-3. This function does the necessary
8110 * steps before we can safely return to ring-3. This is not the same as longjmps
8111 * to ring-3, this is voluntary and prepares the guest so it may continue
8112 * executing outside HM (recompiler/IEM).
8113 *
8114 * @returns VBox status code.
8115 * @param pVCpu The cross context virtual CPU structure.
8116 * @param rcExit The reason for exiting to ring-3. Can be
8117 * VINF_VMM_UNKNOWN_RING3_CALL.
8118 */
8119static int hmR0VmxExitToRing3(PVMCPUCC pVCpu, VBOXSTRICTRC rcExit)
8120{
8121 HMVMX_ASSERT_PREEMPT_SAFE(pVCpu);
8122
8123 PVMXVMCSINFO pVmcsInfo = hmGetVmxActiveVmcsInfo(pVCpu);
8124 if (RT_UNLIKELY(rcExit == VERR_VMX_INVALID_VMCS_PTR))
8125 {
8126 VMXGetCurrentVmcs(&pVCpu->hm.s.vmx.LastError.HCPhysCurrentVmcs);
8127 pVCpu->hm.s.vmx.LastError.u32VmcsRev = *(uint32_t *)pVmcsInfo->pvVmcs;
8128 pVCpu->hm.s.vmx.LastError.idEnteredCpu = pVCpu->hm.s.idEnteredCpu;
8129 /* LastError.idCurrentCpu was updated in hmR0VmxPreRunGuestCommitted(). */
8130 }
8131
8132 /* Please, no longjumps here (any logging shouldn't flush jump back to ring-3). NO LOGGING BEFORE THIS POINT! */
8133 VMMRZCallRing3Disable(pVCpu);
8134 Log4Func(("rcExit=%d\n", VBOXSTRICTRC_VAL(rcExit)));
8135
8136 /*
8137 * Convert any pending HM events back to TRPM due to premature exits to ring-3.
8138 * We need to do this only on returns to ring-3 and not for longjmps to ring3.
8139 *
8140 * This is because execution may continue from ring-3 and we would need to inject
8141 * the event from there (hence place it back in TRPM).
8142 */
8143 if (pVCpu->hm.s.Event.fPending)
8144 {
8145 hmR0VmxPendingEventToTrpmTrap(pVCpu);
8146 Assert(!pVCpu->hm.s.Event.fPending);
8147
8148 /* Clear the events from the VMCS. */
8149 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_ENTRY_INTERRUPTION_INFO, 0);
8150 AssertRC(rc);
8151 }
8152#ifdef VBOX_STRICT
8153 else
8154 {
8155 /*
8156 * Ensure we don't accidentally clear a pending HM event without clearing the VMCS.
8157 * This can be pretty hard to debug otherwise, interrupts might get injected twice
8158 * occasionally, see @bugref{9180#c42}.
8159 *
8160 * However, if the VM-entry failed, any VM entry-interruption info. field would
8161 * be left unmodified as the event would not have been injected to the guest. In
8162 * such cases, don't assert, we're not going to continue guest execution anyway.
8163 */
8164 uint32_t uExitReason;
8165 uint32_t uEntryIntInfo;
8166 int rc = VMXReadVmcs32(VMX_VMCS32_RO_EXIT_REASON, &uExitReason);
8167 rc |= VMXReadVmcs32(VMX_VMCS32_CTRL_ENTRY_INTERRUPTION_INFO, &uEntryIntInfo);
8168 AssertRC(rc);
8169 Assert(VMX_EXIT_REASON_HAS_ENTRY_FAILED(uExitReason) || !VMX_ENTRY_INT_INFO_IS_VALID(uEntryIntInfo));
8170 }
8171#endif
8172
8173 /*
8174 * Clear the interrupt-window and NMI-window VMCS controls as we could have got
8175 * a VM-exit with higher priority than interrupt-window or NMI-window VM-exits
8176 * (e.g. TPR below threshold).
8177 */
8178 if (!CPUMIsGuestInVmxNonRootMode(&pVCpu->cpum.GstCtx))
8179 {
8180 hmR0VmxClearIntWindowExitVmcs(pVmcsInfo);
8181 hmR0VmxClearNmiWindowExitVmcs(pVmcsInfo);
8182 }
8183
8184 /* If we're emulating an instruction, we shouldn't have any TRPM traps pending
8185 and if we're injecting an event we should have a TRPM trap pending. */
8186 AssertMsg(rcExit != VINF_EM_RAW_INJECT_TRPM_EVENT || TRPMHasTrap(pVCpu), ("%Rrc\n", VBOXSTRICTRC_VAL(rcExit)));
8187#ifndef DEBUG_bird /* Triggered after firing an NMI against NT4SP1, possibly a triple fault in progress. */
8188 AssertMsg(rcExit != VINF_EM_RAW_EMULATE_INSTR || !TRPMHasTrap(pVCpu), ("%Rrc\n", VBOXSTRICTRC_VAL(rcExit)));
8189#endif
8190
8191 /* Save guest state and restore host state bits. */
8192 int rc = hmR0VmxLeaveSession(pVCpu);
8193 AssertRCReturn(rc, rc);
8194 STAM_COUNTER_DEC(&pVCpu->hm.s.StatSwitchLongJmpToR3);
8195
8196 /* Thread-context hooks are unregistered at this point!!! */
8197 /* Ring-3 callback notifications are unregistered at this point!!! */
8198
8199 /* Sync recompiler state. */
8200 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_TO_R3);
8201 CPUMSetChangedFlags(pVCpu, CPUM_CHANGED_SYSENTER_MSR
8202 | CPUM_CHANGED_LDTR
8203 | CPUM_CHANGED_GDTR
8204 | CPUM_CHANGED_IDTR
8205 | CPUM_CHANGED_TR
8206 | CPUM_CHANGED_HIDDEN_SEL_REGS);
8207 if ( pVCpu->CTX_SUFF(pVM)->hm.s.fNestedPaging
8208 && CPUMIsGuestPagingEnabledEx(&pVCpu->cpum.GstCtx))
8209 CPUMSetChangedFlags(pVCpu, CPUM_CHANGED_GLOBAL_TLB_FLUSH);
8210
8211 Assert(!pVCpu->hm.s.fClearTrapFlag);
8212
8213 /* Update the exit-to-ring 3 reason. */
8214 pVCpu->hm.s.rcLastExitToR3 = VBOXSTRICTRC_VAL(rcExit);
8215
8216 /* On our way back from ring-3 reload the guest state if there is a possibility of it being changed. */
8217 if ( rcExit != VINF_EM_RAW_INTERRUPT
8218 || CPUMIsGuestInVmxNonRootMode(&pVCpu->cpum.GstCtx))
8219 {
8220 Assert(!(pVCpu->cpum.GstCtx.fExtrn & HMVMX_CPUMCTX_EXTRN_ALL));
8221 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_ALL_GUEST);
8222 }
8223
8224 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchExitToR3);
8225 VMMRZCallRing3Enable(pVCpu);
8226 return rc;
8227}
8228
8229
8230/**
8231 * VMMRZCallRing3() callback wrapper which saves the guest state before we
8232 * longjump to ring-3 and possibly get preempted.
8233 *
8234 * @returns VBox status code.
8235 * @param pVCpu The cross context virtual CPU structure.
8236 * @param enmOperation The operation causing the ring-3 longjump.
8237 */
8238VMMR0DECL(int) VMXR0CallRing3Callback(PVMCPUCC pVCpu, VMMCALLRING3 enmOperation)
8239{
8240 if (enmOperation == VMMCALLRING3_VM_R0_ASSERTION)
8241 {
8242 /*
8243 * !!! IMPORTANT !!!
8244 * If you modify code here, check whether hmR0VmxLeave() and hmR0VmxLeaveSession() needs to be updated too.
8245 * This is a stripped down version which gets out ASAP, trying to not trigger any further assertions.
8246 */
8247 VMMRZCallRing3RemoveNotification(pVCpu);
8248 VMMRZCallRing3Disable(pVCpu);
8249 HM_DISABLE_PREEMPT(pVCpu);
8250
8251 PVMXVMCSINFO pVmcsInfo = hmGetVmxActiveVmcsInfo(pVCpu);
8252 hmR0VmxImportGuestState(pVCpu, pVmcsInfo, HMVMX_CPUMCTX_EXTRN_ALL);
8253 CPUMR0FpuStateMaybeSaveGuestAndRestoreHost(pVCpu);
8254 CPUMR0DebugStateMaybeSaveGuestAndRestoreHost(pVCpu, true /* save DR6 */);
8255
8256 /* Restore host-state bits that VT-x only restores partially. */
8257 if ( (pVCpu->hm.s.vmx.fRestoreHostFlags & VMX_RESTORE_HOST_REQUIRED)
8258 && (pVCpu->hm.s.vmx.fRestoreHostFlags & ~VMX_RESTORE_HOST_REQUIRED))
8259 VMXRestoreHostState(pVCpu->hm.s.vmx.fRestoreHostFlags, &pVCpu->hm.s.vmx.RestoreHost);
8260 pVCpu->hm.s.vmx.fRestoreHostFlags = 0;
8261
8262 /* Restore the lazy host MSRs as we're leaving VT-x context. */
8263 if (pVCpu->hm.s.vmx.fLazyMsrs & VMX_LAZY_MSRS_LOADED_GUEST)
8264 hmR0VmxLazyRestoreHostMsrs(pVCpu);
8265
8266 /* Update auto-load/store host MSRs values when we re-enter VT-x (as we could be on a different CPU). */
8267 pVCpu->hm.s.vmx.fUpdatedHostAutoMsrs = false;
8268 VMCPU_CMPXCHG_STATE(pVCpu, VMCPUSTATE_STARTED_HM, VMCPUSTATE_STARTED_EXEC);
8269
8270 /* Clear the current VMCS data back to memory (shadow VMCS if any would have been
8271 cleared as part of importing the guest state above. */
8272 hmR0VmxClearVmcs(pVmcsInfo);
8273
8274 /** @todo eliminate the need for calling VMMR0ThreadCtxHookDisable here! */
8275 VMMR0ThreadCtxHookDisable(pVCpu);
8276
8277 /* Leave HM context. This takes care of local init (term). */
8278 HMR0LeaveCpu(pVCpu);
8279 HM_RESTORE_PREEMPT();
8280 return VINF_SUCCESS;
8281 }
8282
8283 Assert(pVCpu);
8284 Assert(VMMRZCallRing3IsEnabled(pVCpu));
8285 HMVMX_ASSERT_PREEMPT_SAFE(pVCpu);
8286
8287 VMMRZCallRing3Disable(pVCpu);
8288 Assert(VMMR0IsLogFlushDisabled(pVCpu));
8289
8290 Log4Func(("-> hmR0VmxLongJmpToRing3 enmOperation=%d\n", enmOperation));
8291
8292 int rc = hmR0VmxLongJmpToRing3(pVCpu);
8293 AssertRCReturn(rc, rc);
8294
8295 VMMRZCallRing3Enable(pVCpu);
8296 return VINF_SUCCESS;
8297}
8298
8299
8300/**
8301 * Pushes a 2-byte value onto the real-mode (in virtual-8086 mode) guest's
8302 * stack.
8303 *
8304 * @returns Strict VBox status code (i.e. informational status codes too).
8305 * @retval VINF_EM_RESET if pushing a value to the stack caused a triple-fault.
8306 * @param pVCpu The cross context virtual CPU structure.
8307 * @param uValue The value to push to the guest stack.
8308 */
8309static VBOXSTRICTRC hmR0VmxRealModeGuestStackPush(PVMCPUCC pVCpu, uint16_t uValue)
8310{
8311 /*
8312 * The stack limit is 0xffff in real-on-virtual 8086 mode. Real-mode with weird stack limits cannot be run in
8313 * virtual 8086 mode in VT-x. See Intel spec. 26.3.1.2 "Checks on Guest Segment Registers".
8314 * See Intel Instruction reference for PUSH and Intel spec. 22.33.1 "Segment Wraparound".
8315 */
8316 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
8317 if (pCtx->sp == 1)
8318 return VINF_EM_RESET;
8319 pCtx->sp -= sizeof(uint16_t); /* May wrap around which is expected behaviour. */
8320 int rc = PGMPhysSimpleWriteGCPhys(pVCpu->CTX_SUFF(pVM), pCtx->ss.u64Base + pCtx->sp, &uValue, sizeof(uint16_t));
8321 AssertRC(rc);
8322 return rc;
8323}
8324
8325
8326/**
8327 * Injects an event into the guest upon VM-entry by updating the relevant fields
8328 * in the VM-entry area in the VMCS.
8329 *
8330 * @returns Strict VBox status code (i.e. informational status codes too).
8331 * @retval VINF_SUCCESS if the event is successfully injected into the VMCS.
8332 * @retval VINF_EM_RESET if event injection resulted in a triple-fault.
8333 *
8334 * @param pVCpu The cross context virtual CPU structure.
8335 * @param pVmxTransient The VMX-transient structure.
8336 * @param pEvent The event being injected.
8337 * @param pfIntrState Pointer to the VT-x guest-interruptibility-state. This
8338 * will be updated if necessary. This cannot not be NULL.
8339 * @param fStepping Whether we're single-stepping guest execution and should
8340 * return VINF_EM_DBG_STEPPED if the event is injected
8341 * directly (registers modified by us, not by hardware on
8342 * VM-entry).
8343 */
8344static VBOXSTRICTRC hmR0VmxInjectEventVmcs(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient, PCHMEVENT pEvent, bool fStepping,
8345 uint32_t *pfIntrState)
8346{
8347 /* Intel spec. 24.8.3 "VM-Entry Controls for Event Injection" specifies the interruption-information field to be 32-bits. */
8348 AssertMsg(!RT_HI_U32(pEvent->u64IntInfo), ("%#RX64\n", pEvent->u64IntInfo));
8349 Assert(pfIntrState);
8350
8351 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
8352 uint32_t u32IntInfo = pEvent->u64IntInfo;
8353 uint32_t const u32ErrCode = pEvent->u32ErrCode;
8354 uint32_t const cbInstr = pEvent->cbInstr;
8355 RTGCUINTPTR const GCPtrFault = pEvent->GCPtrFaultAddress;
8356 uint8_t const uVector = VMX_ENTRY_INT_INFO_VECTOR(u32IntInfo);
8357 uint32_t const uIntType = VMX_ENTRY_INT_INFO_TYPE(u32IntInfo);
8358
8359#ifdef VBOX_STRICT
8360 /*
8361 * Validate the error-code-valid bit for hardware exceptions.
8362 * No error codes for exceptions in real-mode.
8363 *
8364 * See Intel spec. 20.1.4 "Interrupt and Exception Handling"
8365 */
8366 if ( uIntType == VMX_EXIT_INT_INFO_TYPE_HW_XCPT
8367 && !CPUMIsGuestInRealModeEx(pCtx))
8368 {
8369 switch (uVector)
8370 {
8371 case X86_XCPT_PF:
8372 case X86_XCPT_DF:
8373 case X86_XCPT_TS:
8374 case X86_XCPT_NP:
8375 case X86_XCPT_SS:
8376 case X86_XCPT_GP:
8377 case X86_XCPT_AC:
8378 AssertMsg(VMX_ENTRY_INT_INFO_IS_ERROR_CODE_VALID(u32IntInfo),
8379 ("Error-code-valid bit not set for exception that has an error code uVector=%#x\n", uVector));
8380 RT_FALL_THRU();
8381 default:
8382 break;
8383 }
8384 }
8385
8386 /* Cannot inject an NMI when block-by-MOV SS is in effect. */
8387 Assert( uIntType != VMX_EXIT_INT_INFO_TYPE_NMI
8388 || !(*pfIntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_MOVSS));
8389#endif
8390
8391 STAM_COUNTER_INC(&pVCpu->hm.s.paStatInjectedIrqsR0[uVector & MASK_INJECT_IRQ_STAT]);
8392
8393 /*
8394 * Hardware interrupts & exceptions cannot be delivered through the software interrupt
8395 * redirection bitmap to the real mode task in virtual-8086 mode. We must jump to the
8396 * interrupt handler in the (real-mode) guest.
8397 *
8398 * See Intel spec. 20.3 "Interrupt and Exception handling in Virtual-8086 Mode".
8399 * See Intel spec. 20.1.4 "Interrupt and Exception Handling" for real-mode interrupt handling.
8400 */
8401 if (CPUMIsGuestInRealModeEx(pCtx)) /* CR0.PE bit changes are always intercepted, so it's up to date. */
8402 {
8403 if (pVCpu->CTX_SUFF(pVM)->hm.s.vmx.fUnrestrictedGuest)
8404 {
8405 /*
8406 * For CPUs with unrestricted guest execution enabled and with the guest
8407 * in real-mode, we must not set the deliver-error-code bit.
8408 *
8409 * See Intel spec. 26.2.1.3 "VM-Entry Control Fields".
8410 */
8411 u32IntInfo &= ~VMX_ENTRY_INT_INFO_ERROR_CODE_VALID;
8412 }
8413 else
8414 {
8415 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
8416 Assert(PDMVmmDevHeapIsEnabled(pVM));
8417 Assert(pVM->hm.s.vmx.pRealModeTSS);
8418 Assert(!CPUMIsGuestInVmxNonRootMode(&pVCpu->cpum.GstCtx));
8419
8420 /* We require RIP, RSP, RFLAGS, CS, IDTR, import them. */
8421 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
8422 int rc2 = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, CPUMCTX_EXTRN_SREG_MASK | CPUMCTX_EXTRN_TABLE_MASK
8423 | CPUMCTX_EXTRN_RIP | CPUMCTX_EXTRN_RSP | CPUMCTX_EXTRN_RFLAGS);
8424 AssertRCReturn(rc2, rc2);
8425
8426 /* Check if the interrupt handler is present in the IVT (real-mode IDT). IDT limit is (4N - 1). */
8427 size_t const cbIdtEntry = sizeof(X86IDTR16);
8428 if (uVector * cbIdtEntry + (cbIdtEntry - 1) > pCtx->idtr.cbIdt)
8429 {
8430 /* If we are trying to inject a #DF with no valid IDT entry, return a triple-fault. */
8431 if (uVector == X86_XCPT_DF)
8432 return VINF_EM_RESET;
8433
8434 /* If we're injecting a #GP with no valid IDT entry, inject a double-fault.
8435 No error codes for exceptions in real-mode. */
8436 if (uVector == X86_XCPT_GP)
8437 {
8438 uint32_t const uXcptDfInfo = RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_VECTOR, X86_XCPT_DF)
8439 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_TYPE, VMX_ENTRY_INT_INFO_TYPE_HW_XCPT)
8440 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_ERR_CODE_VALID, 0)
8441 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_VALID, 1);
8442 HMEVENT EventXcptDf;
8443 RT_ZERO(EventXcptDf);
8444 EventXcptDf.u64IntInfo = uXcptDfInfo;
8445 return hmR0VmxInjectEventVmcs(pVCpu, pVmxTransient, &EventXcptDf, fStepping, pfIntrState);
8446 }
8447
8448 /*
8449 * If we're injecting an event with no valid IDT entry, inject a #GP.
8450 * No error codes for exceptions in real-mode.
8451 *
8452 * See Intel spec. 20.1.4 "Interrupt and Exception Handling"
8453 */
8454 uint32_t const uXcptGpInfo = RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_VECTOR, X86_XCPT_GP)
8455 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_TYPE, VMX_ENTRY_INT_INFO_TYPE_HW_XCPT)
8456 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_ERR_CODE_VALID, 0)
8457 | RT_BF_MAKE(VMX_BF_ENTRY_INT_INFO_VALID, 1);
8458 HMEVENT EventXcptGp;
8459 RT_ZERO(EventXcptGp);
8460 EventXcptGp.u64IntInfo = uXcptGpInfo;
8461 return hmR0VmxInjectEventVmcs(pVCpu, pVmxTransient, &EventXcptGp, fStepping, pfIntrState);
8462 }
8463
8464 /* Software exceptions (#BP and #OF exceptions thrown as a result of INT3 or INTO) */
8465 uint16_t uGuestIp = pCtx->ip;
8466 if (uIntType == VMX_ENTRY_INT_INFO_TYPE_SW_XCPT)
8467 {
8468 Assert(uVector == X86_XCPT_BP || uVector == X86_XCPT_OF);
8469 /* #BP and #OF are both benign traps, we need to resume the next instruction. */
8470 uGuestIp = pCtx->ip + (uint16_t)cbInstr;
8471 }
8472 else if (uIntType == VMX_ENTRY_INT_INFO_TYPE_SW_INT)
8473 uGuestIp = pCtx->ip + (uint16_t)cbInstr;
8474
8475 /* Get the code segment selector and offset from the IDT entry for the interrupt handler. */
8476 X86IDTR16 IdtEntry;
8477 RTGCPHYS const GCPhysIdtEntry = (RTGCPHYS)pCtx->idtr.pIdt + uVector * cbIdtEntry;
8478 rc2 = PGMPhysSimpleReadGCPhys(pVM, &IdtEntry, GCPhysIdtEntry, cbIdtEntry);
8479 AssertRCReturn(rc2, rc2);
8480
8481 /* Construct the stack frame for the interrupt/exception handler. */
8482 VBOXSTRICTRC rcStrict;
8483 rcStrict = hmR0VmxRealModeGuestStackPush(pVCpu, pCtx->eflags.u32);
8484 if (rcStrict == VINF_SUCCESS)
8485 {
8486 rcStrict = hmR0VmxRealModeGuestStackPush(pVCpu, pCtx->cs.Sel);
8487 if (rcStrict == VINF_SUCCESS)
8488 rcStrict = hmR0VmxRealModeGuestStackPush(pVCpu, uGuestIp);
8489 }
8490
8491 /* Clear the required eflag bits and jump to the interrupt/exception handler. */
8492 if (rcStrict == VINF_SUCCESS)
8493 {
8494 pCtx->eflags.u32 &= ~(X86_EFL_IF | X86_EFL_TF | X86_EFL_RF | X86_EFL_AC);
8495 pCtx->rip = IdtEntry.offSel;
8496 pCtx->cs.Sel = IdtEntry.uSel;
8497 pCtx->cs.ValidSel = IdtEntry.uSel;
8498 pCtx->cs.u64Base = IdtEntry.uSel << cbIdtEntry;
8499 if ( uIntType == VMX_ENTRY_INT_INFO_TYPE_HW_XCPT
8500 && uVector == X86_XCPT_PF)
8501 pCtx->cr2 = GCPtrFault;
8502
8503 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_CS | HM_CHANGED_GUEST_CR2
8504 | HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS
8505 | HM_CHANGED_GUEST_RSP);
8506
8507 /*
8508 * If we delivered a hardware exception (other than an NMI) and if there was
8509 * block-by-STI in effect, we should clear it.
8510 */
8511 if (*pfIntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_STI)
8512 {
8513 Assert( uIntType != VMX_ENTRY_INT_INFO_TYPE_NMI
8514 && uIntType != VMX_ENTRY_INT_INFO_TYPE_EXT_INT);
8515 Log4Func(("Clearing inhibition due to STI\n"));
8516 *pfIntrState &= ~VMX_VMCS_GUEST_INT_STATE_BLOCK_STI;
8517 }
8518
8519 Log4(("Injected real-mode: u32IntInfo=%#x u32ErrCode=%#x cbInstr=%#x Eflags=%#x CS:EIP=%04x:%04x\n",
8520 u32IntInfo, u32ErrCode, cbInstr, pCtx->eflags.u, pCtx->cs.Sel, pCtx->eip));
8521
8522 /*
8523 * The event has been truly dispatched to the guest. Mark it as no longer pending so
8524 * we don't attempt to undo it if we are returning to ring-3 before executing guest code.
8525 */
8526 pVCpu->hm.s.Event.fPending = false;
8527
8528 /*
8529 * If we eventually support nested-guest execution without unrestricted guest execution,
8530 * we should set fInterceptEvents here.
8531 */
8532 Assert(!pVmxTransient->fIsNestedGuest);
8533
8534 /* If we're stepping and we've changed cs:rip above, bail out of the VMX R0 execution loop. */
8535 if (fStepping)
8536 rcStrict = VINF_EM_DBG_STEPPED;
8537 }
8538 AssertMsg(rcStrict == VINF_SUCCESS || rcStrict == VINF_EM_RESET || (rcStrict == VINF_EM_DBG_STEPPED && fStepping),
8539 ("%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
8540 return rcStrict;
8541 }
8542 }
8543
8544 /*
8545 * Validate.
8546 */
8547 Assert(VMX_ENTRY_INT_INFO_IS_VALID(u32IntInfo)); /* Bit 31 (Valid bit) must be set by caller. */
8548 Assert(!(u32IntInfo & VMX_BF_ENTRY_INT_INFO_RSVD_12_30_MASK)); /* Bits 30:12 MBZ. */
8549
8550 /*
8551 * Inject the event into the VMCS.
8552 */
8553 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_ENTRY_INTERRUPTION_INFO, u32IntInfo);
8554 if (VMX_ENTRY_INT_INFO_IS_ERROR_CODE_VALID(u32IntInfo))
8555 rc |= VMXWriteVmcs32(VMX_VMCS32_CTRL_ENTRY_EXCEPTION_ERRCODE, u32ErrCode);
8556 rc |= VMXWriteVmcs32(VMX_VMCS32_CTRL_ENTRY_INSTR_LENGTH, cbInstr);
8557 AssertRC(rc);
8558
8559 /*
8560 * Update guest CR2 if this is a page-fault.
8561 */
8562 if (VMX_ENTRY_INT_INFO_IS_XCPT_PF(u32IntInfo))
8563 pCtx->cr2 = GCPtrFault;
8564
8565 Log4(("Injecting u32IntInfo=%#x u32ErrCode=%#x cbInstr=%#x CR2=%#RX64\n", u32IntInfo, u32ErrCode, cbInstr, pCtx->cr2));
8566 return VINF_SUCCESS;
8567}
8568
8569
8570/**
8571 * Evaluates the event to be delivered to the guest and sets it as the pending
8572 * event.
8573 *
8574 * @returns Strict VBox status code (i.e. informational status codes too).
8575 * @param pVCpu The cross context virtual CPU structure.
8576 * @param pVmxTransient The VMX-transient structure.
8577 * @param pfIntrState Where to store the VT-x guest-interruptibility state.
8578 */
8579static VBOXSTRICTRC hmR0VmxEvaluatePendingEvent(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient, uint32_t *pfIntrState)
8580{
8581 Assert(pfIntrState);
8582 Assert(!TRPMHasTrap(pVCpu));
8583
8584 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
8585 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
8586 bool const fIsNestedGuest = pVmxTransient->fIsNestedGuest;
8587
8588 /*
8589 * Get the current interruptibility-state of the guest or nested-guest and
8590 * then figure out what needs to be injected.
8591 */
8592 uint32_t const fIntrState = hmR0VmxGetGuestIntrState(pVCpu, pVmxTransient);
8593 bool const fBlockMovSS = RT_BOOL(fIntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_MOVSS);
8594 bool const fBlockSti = RT_BOOL(fIntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_STI);
8595 bool const fBlockNmi = RT_BOOL(fIntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_NMI);
8596
8597 /* We don't support block-by-SMI yet.*/
8598 Assert(!(fIntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_SMI));
8599
8600 /* Block-by-STI must not be set when interrupts are disabled. */
8601 if (fBlockSti)
8602 {
8603 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_RFLAGS);
8604 Assert(pCtx->eflags.Bits.u1IF);
8605 }
8606
8607 /* Update interruptibility state to the caller. */
8608 *pfIntrState = fIntrState;
8609
8610 /*
8611 * Toggling of interrupt force-flags here is safe since we update TRPM on
8612 * premature exits to ring-3 before executing guest code, see hmR0VmxExitToRing3().
8613 * We must NOT restore these force-flags.
8614 */
8615
8616 /** @todo SMI. SMIs take priority over NMIs. */
8617
8618 /*
8619 * Check if an NMI is pending and if the guest or nested-guest can receive them.
8620 * NMIs take priority over external interrupts.
8621 */
8622 if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_INTERRUPT_NMI))
8623 {
8624 /* On some CPUs block-by-STI also blocks NMIs. See Intel spec. 26.3.1.5 "Checks On Guest Non-Register State". */
8625 if ( !pVCpu->hm.s.Event.fPending
8626 && !fBlockNmi
8627 && !fBlockSti
8628 && !fBlockMovSS)
8629 {
8630#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
8631 if ( fIsNestedGuest
8632 && CPUMIsGuestVmxPinCtlsSet(pVCpu, pCtx, VMX_PIN_CTLS_NMI_EXIT))
8633 return IEMExecVmxVmexitXcptNmi(pVCpu);
8634#endif
8635 hmR0VmxSetPendingXcptNmi(pVCpu);
8636 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INTERRUPT_NMI);
8637 Log4Func(("Pending NMI\n"));
8638 }
8639 else if (!fIsNestedGuest)
8640 hmR0VmxSetNmiWindowExitVmcs(pVCpu, pVmcsInfo);
8641 /* else: for nested-guests, NMI-window exiting will be picked up when merging VMCS controls. */
8642 }
8643 /*
8644 * Check if an external interrupt (PIC/APIC) is pending and if the guest or nested-guest
8645 * can receive them. Once PDMGetInterrupt() returns a valid interrupt we -must- deliver
8646 * the interrupt. We can no longer re-request it from the APIC.
8647 */
8648 else if ( VMCPU_FF_IS_ANY_SET(pVCpu, VMCPU_FF_INTERRUPT_APIC | VMCPU_FF_INTERRUPT_PIC)
8649 && !pVCpu->hm.s.fSingleInstruction)
8650 {
8651 Assert(!DBGFIsStepping(pVCpu));
8652 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, CPUMCTX_EXTRN_RFLAGS);
8653 AssertRCReturn(rc, rc);
8654
8655 bool const fBlockInt = !(pCtx->eflags.u32 & X86_EFL_IF);
8656 if ( !pVCpu->hm.s.Event.fPending
8657 && !fBlockInt
8658 && !fBlockSti
8659 && !fBlockMovSS)
8660 {
8661#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
8662 if ( fIsNestedGuest
8663 && CPUMIsGuestVmxPinCtlsSet(pVCpu, pCtx, VMX_PIN_CTLS_EXT_INT_EXIT)
8664 && !CPUMIsGuestVmxExitCtlsSet(pVCpu, pCtx, VMX_EXIT_CTLS_ACK_EXT_INT))
8665 {
8666 VBOXSTRICTRC rcStrict = IEMExecVmxVmexitExtInt(pVCpu, 0 /* uVector */, true /* fIntPending */);
8667 Assert(rcStrict != VINF_VMX_INTERCEPT_NOT_ACTIVE);
8668 return rcStrict;
8669 }
8670#endif
8671 uint8_t u8Interrupt;
8672 rc = PDMGetInterrupt(pVCpu, &u8Interrupt);
8673 if (RT_SUCCESS(rc))
8674 {
8675#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
8676 if ( fIsNestedGuest
8677 && CPUMIsGuestVmxPinCtlsSet(pVCpu, pCtx, VMX_PIN_CTLS_EXT_INT_EXIT)
8678 && CPUMIsGuestVmxExitCtlsSet(pVCpu, pCtx, VMX_EXIT_CTLS_ACK_EXT_INT))
8679 {
8680 VBOXSTRICTRC rcStrict = IEMExecVmxVmexitExtInt(pVCpu, u8Interrupt, false /* fIntPending */);
8681 Assert(rcStrict != VINF_VMX_INTERCEPT_NOT_ACTIVE);
8682 return rcStrict;
8683 }
8684#endif
8685 hmR0VmxSetPendingExtInt(pVCpu, u8Interrupt);
8686 Log4Func(("Pending external interrupt vector %#x\n", u8Interrupt));
8687 }
8688 else if (rc == VERR_APIC_INTR_MASKED_BY_TPR)
8689 {
8690 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchTprMaskedIrq);
8691
8692 if ( !fIsNestedGuest
8693 && (pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_USE_TPR_SHADOW))
8694 hmR0VmxApicSetTprThreshold(pVmcsInfo, u8Interrupt >> 4);
8695 /* else: for nested-guests, TPR threshold is picked up while merging VMCS controls. */
8696
8697 /*
8698 * If the CPU doesn't have TPR shadowing, we will always get a VM-exit on TPR changes and
8699 * APICSetTpr() will end up setting the VMCPU_FF_INTERRUPT_APIC if required, so there is no
8700 * need to re-set this force-flag here.
8701 */
8702 }
8703 else
8704 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchGuestIrq);
8705 }
8706 else if (!fIsNestedGuest)
8707 hmR0VmxSetIntWindowExitVmcs(pVCpu, pVmcsInfo);
8708 /* else: for nested-guests, interrupt-window exiting will be picked up when merging VMCS controls. */
8709 }
8710
8711 return VINF_SUCCESS;
8712}
8713
8714
8715/**
8716 * Injects any pending events into the guest if the guest is in a state to
8717 * receive them.
8718 *
8719 * @returns Strict VBox status code (i.e. informational status codes too).
8720 * @param pVCpu The cross context virtual CPU structure.
8721 * @param pVmxTransient The VMX-transient structure.
8722 * @param fIntrState The VT-x guest-interruptibility state.
8723 * @param fStepping Whether we are single-stepping the guest using the
8724 * hypervisor debugger and should return
8725 * VINF_EM_DBG_STEPPED if the event was dispatched
8726 * directly.
8727 */
8728static VBOXSTRICTRC hmR0VmxInjectPendingEvent(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient, uint32_t fIntrState, bool fStepping)
8729{
8730 HMVMX_ASSERT_PREEMPT_SAFE(pVCpu);
8731 Assert(VMMRZCallRing3IsEnabled(pVCpu));
8732
8733 bool const fBlockMovSS = RT_BOOL(fIntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_MOVSS);
8734 bool const fBlockSti = RT_BOOL(fIntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_STI);
8735
8736 Assert(!fBlockSti || !(ASMAtomicUoReadU64(&pVCpu->cpum.GstCtx.fExtrn) & CPUMCTX_EXTRN_RFLAGS));
8737 Assert(!fBlockSti || pVCpu->cpum.GstCtx.eflags.Bits.u1IF); /* Cannot set block-by-STI when interrupts are disabled. */
8738 Assert(!(fIntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_SMI)); /* We don't support block-by-SMI yet.*/
8739 Assert(!TRPMHasTrap(pVCpu));
8740
8741 VBOXSTRICTRC rcStrict = VINF_SUCCESS;
8742 if (pVCpu->hm.s.Event.fPending)
8743 {
8744 /*
8745 * Do -not- clear any interrupt-window exiting control here. We might have an interrupt
8746 * pending even while injecting an event and in this case, we want a VM-exit as soon as
8747 * the guest is ready for the next interrupt, see @bugref{6208#c45}.
8748 *
8749 * See Intel spec. 26.6.5 "Interrupt-Window Exiting and Virtual-Interrupt Delivery".
8750 */
8751 uint32_t const uIntType = VMX_ENTRY_INT_INFO_TYPE(pVCpu->hm.s.Event.u64IntInfo);
8752#ifdef VBOX_STRICT
8753 if (uIntType == VMX_ENTRY_INT_INFO_TYPE_EXT_INT)
8754 {
8755 bool const fBlockInt = !(pVCpu->cpum.GstCtx.eflags.u32 & X86_EFL_IF);
8756 Assert(!fBlockInt);
8757 Assert(!fBlockSti);
8758 Assert(!fBlockMovSS);
8759 }
8760 else if (uIntType == VMX_ENTRY_INT_INFO_TYPE_NMI)
8761 {
8762 bool const fBlockNmi = RT_BOOL(fIntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_NMI);
8763 Assert(!fBlockSti);
8764 Assert(!fBlockMovSS);
8765 Assert(!fBlockNmi);
8766 }
8767#endif
8768 Log4(("Injecting pending event vcpu[%RU32] u64IntInfo=%#RX64 Type=%#RX32\n", pVCpu->idCpu, pVCpu->hm.s.Event.u64IntInfo,
8769 uIntType));
8770
8771 /*
8772 * Inject the event and get any changes to the guest-interruptibility state.
8773 *
8774 * The guest-interruptibility state may need to be updated if we inject the event
8775 * into the guest IDT ourselves (for real-on-v86 guest injecting software interrupts).
8776 */
8777 rcStrict = hmR0VmxInjectEventVmcs(pVCpu, pVmxTransient, &pVCpu->hm.s.Event, fStepping, &fIntrState);
8778 AssertRCReturn(VBOXSTRICTRC_VAL(rcStrict), rcStrict);
8779
8780 if (uIntType == VMX_ENTRY_INT_INFO_TYPE_EXT_INT)
8781 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectInterrupt);
8782 else
8783 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectXcpt);
8784 }
8785
8786 /*
8787 * Update the guest-interruptibility state.
8788 *
8789 * This is required for the real-on-v86 software interrupt injection case above, as well as
8790 * updates to the guest state from ring-3 or IEM/REM.
8791 */
8792 int rc = VMXWriteVmcs32(VMX_VMCS32_GUEST_INT_STATE, fIntrState);
8793 AssertRC(rc);
8794
8795 /*
8796 * There's no need to clear the VM-entry interruption-information field here if we're not
8797 * injecting anything. VT-x clears the valid bit on every VM-exit.
8798 *
8799 * See Intel spec. 24.8.3 "VM-Entry Controls for Event Injection".
8800 */
8801
8802 Assert(rcStrict == VINF_SUCCESS || rcStrict == VINF_EM_RESET || (rcStrict == VINF_EM_DBG_STEPPED && fStepping));
8803 NOREF(fBlockMovSS); NOREF(fBlockSti);
8804 return rcStrict;
8805}
8806
8807
8808/**
8809 * Enters the VT-x session.
8810 *
8811 * @returns VBox status code.
8812 * @param pVCpu The cross context virtual CPU structure.
8813 */
8814VMMR0DECL(int) VMXR0Enter(PVMCPUCC pVCpu)
8815{
8816 AssertPtr(pVCpu);
8817 Assert(pVCpu->CTX_SUFF(pVM)->hm.s.vmx.fSupported);
8818 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
8819
8820 LogFlowFunc(("pVCpu=%p\n", pVCpu));
8821 Assert((pVCpu->hm.s.fCtxChanged & (HM_CHANGED_HOST_CONTEXT | HM_CHANGED_VMX_HOST_GUEST_SHARED_STATE))
8822 == (HM_CHANGED_HOST_CONTEXT | HM_CHANGED_VMX_HOST_GUEST_SHARED_STATE));
8823
8824#ifdef VBOX_STRICT
8825 /* At least verify VMX is enabled, since we can't check if we're in VMX root mode without #GP'ing. */
8826 RTCCUINTREG uHostCr4 = ASMGetCR4();
8827 if (!(uHostCr4 & X86_CR4_VMXE))
8828 {
8829 LogRelFunc(("X86_CR4_VMXE bit in CR4 is not set!\n"));
8830 return VERR_VMX_X86_CR4_VMXE_CLEARED;
8831 }
8832#endif
8833
8834 /*
8835 * Load the appropriate VMCS as the current and active one.
8836 */
8837 PVMXVMCSINFO pVmcsInfo;
8838 bool const fInNestedGuestMode = CPUMIsGuestInVmxNonRootMode(&pVCpu->cpum.GstCtx);
8839 if (!fInNestedGuestMode)
8840 pVmcsInfo = &pVCpu->hm.s.vmx.VmcsInfo;
8841 else
8842 pVmcsInfo = &pVCpu->hm.s.vmx.VmcsInfoNstGst;
8843 int rc = hmR0VmxLoadVmcs(pVmcsInfo);
8844 if (RT_SUCCESS(rc))
8845 {
8846 pVCpu->hm.s.vmx.fSwitchedToNstGstVmcs = fInNestedGuestMode;
8847 pVCpu->hm.s.fLeaveDone = false;
8848 Log4Func(("Loaded Vmcs. HostCpuId=%u\n", RTMpCpuId()));
8849
8850 /*
8851 * Do the EMT scheduled L1D flush here if needed.
8852 */
8853 if (pVCpu->CTX_SUFF(pVM)->hm.s.fL1dFlushOnSched)
8854 ASMWrMsr(MSR_IA32_FLUSH_CMD, MSR_IA32_FLUSH_CMD_F_L1D);
8855 else if (pVCpu->CTX_SUFF(pVM)->hm.s.fMdsClearOnSched)
8856 hmR0MdsClear();
8857 }
8858 return rc;
8859}
8860
8861
8862/**
8863 * The thread-context callback (only on platforms which support it).
8864 *
8865 * @param enmEvent The thread-context event.
8866 * @param pVCpu The cross context virtual CPU structure.
8867 * @param fGlobalInit Whether global VT-x/AMD-V init. was used.
8868 * @thread EMT(pVCpu)
8869 */
8870VMMR0DECL(void) VMXR0ThreadCtxCallback(RTTHREADCTXEVENT enmEvent, PVMCPUCC pVCpu, bool fGlobalInit)
8871{
8872 AssertPtr(pVCpu);
8873 RT_NOREF1(fGlobalInit);
8874
8875 switch (enmEvent)
8876 {
8877 case RTTHREADCTXEVENT_OUT:
8878 {
8879 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
8880 Assert(VMMR0ThreadCtxHookIsEnabled(pVCpu));
8881 VMCPU_ASSERT_EMT(pVCpu);
8882
8883 /* No longjmps (logger flushes, locks) in this fragile context. */
8884 VMMRZCallRing3Disable(pVCpu);
8885 Log4Func(("Preempting: HostCpuId=%u\n", RTMpCpuId()));
8886
8887 /* Restore host-state (FPU, debug etc.) */
8888 if (!pVCpu->hm.s.fLeaveDone)
8889 {
8890 /*
8891 * Do -not- import the guest-state here as we might already be in the middle of importing
8892 * it, esp. bad if we're holding the PGM lock, see comment in hmR0VmxImportGuestState().
8893 */
8894 hmR0VmxLeave(pVCpu, false /* fImportState */);
8895 pVCpu->hm.s.fLeaveDone = true;
8896 }
8897
8898 /* Leave HM context, takes care of local init (term). */
8899 int rc = HMR0LeaveCpu(pVCpu);
8900 AssertRC(rc);
8901
8902 /* Restore longjmp state. */
8903 VMMRZCallRing3Enable(pVCpu);
8904 STAM_REL_COUNTER_INC(&pVCpu->hm.s.StatSwitchPreempt);
8905 break;
8906 }
8907
8908 case RTTHREADCTXEVENT_IN:
8909 {
8910 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
8911 Assert(VMMR0ThreadCtxHookIsEnabled(pVCpu));
8912 VMCPU_ASSERT_EMT(pVCpu);
8913
8914 /* No longjmps here, as we don't want to trigger preemption (& its hook) while resuming. */
8915 VMMRZCallRing3Disable(pVCpu);
8916 Log4Func(("Resumed: HostCpuId=%u\n", RTMpCpuId()));
8917
8918 /* Initialize the bare minimum state required for HM. This takes care of
8919 initializing VT-x if necessary (onlined CPUs, local init etc.) */
8920 int rc = hmR0EnterCpu(pVCpu);
8921 AssertRC(rc);
8922 Assert( (pVCpu->hm.s.fCtxChanged & (HM_CHANGED_HOST_CONTEXT | HM_CHANGED_VMX_HOST_GUEST_SHARED_STATE))
8923 == (HM_CHANGED_HOST_CONTEXT | HM_CHANGED_VMX_HOST_GUEST_SHARED_STATE));
8924
8925 /* Load the active VMCS as the current one. */
8926 PVMXVMCSINFO pVmcsInfo = hmGetVmxActiveVmcsInfo(pVCpu);
8927 rc = hmR0VmxLoadVmcs(pVmcsInfo);
8928 AssertRC(rc);
8929 Log4Func(("Resumed: Loaded Vmcs. HostCpuId=%u\n", RTMpCpuId()));
8930 pVCpu->hm.s.fLeaveDone = false;
8931
8932 /* Do the EMT scheduled L1D flush if needed. */
8933 if (pVCpu->CTX_SUFF(pVM)->hm.s.fL1dFlushOnSched)
8934 ASMWrMsr(MSR_IA32_FLUSH_CMD, MSR_IA32_FLUSH_CMD_F_L1D);
8935
8936 /* Restore longjmp state. */
8937 VMMRZCallRing3Enable(pVCpu);
8938 break;
8939 }
8940
8941 default:
8942 break;
8943 }
8944}
8945
8946
8947/**
8948 * Exports the host state into the VMCS host-state area.
8949 * Sets up the VM-exit MSR-load area.
8950 *
8951 * The CPU state will be loaded from these fields on every successful VM-exit.
8952 *
8953 * @returns VBox status code.
8954 * @param pVCpu The cross context virtual CPU structure.
8955 *
8956 * @remarks No-long-jump zone!!!
8957 */
8958static int hmR0VmxExportHostState(PVMCPUCC pVCpu)
8959{
8960 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
8961
8962 int rc = VINF_SUCCESS;
8963 if (pVCpu->hm.s.fCtxChanged & HM_CHANGED_HOST_CONTEXT)
8964 {
8965 hmR0VmxExportHostControlRegs();
8966
8967 rc = hmR0VmxExportHostSegmentRegs(pVCpu);
8968 AssertLogRelMsgRCReturn(rc, ("rc=%Rrc\n", rc), rc);
8969
8970 hmR0VmxExportHostMsrs(pVCpu);
8971
8972 pVCpu->hm.s.fCtxChanged &= ~HM_CHANGED_HOST_CONTEXT;
8973 }
8974 return rc;
8975}
8976
8977
8978/**
8979 * Saves the host state in the VMCS host-state.
8980 *
8981 * @returns VBox status code.
8982 * @param pVCpu The cross context virtual CPU structure.
8983 *
8984 * @remarks No-long-jump zone!!!
8985 */
8986VMMR0DECL(int) VMXR0ExportHostState(PVMCPUCC pVCpu)
8987{
8988 AssertPtr(pVCpu);
8989 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
8990
8991 /*
8992 * Export the host state here while entering HM context.
8993 * When thread-context hooks are used, we might get preempted and have to re-save the host
8994 * state but most of the time we won't be, so do it here before we disable interrupts.
8995 */
8996 return hmR0VmxExportHostState(pVCpu);
8997}
8998
8999
9000/**
9001 * Exports the guest state into the VMCS guest-state area.
9002 *
9003 * The will typically be done before VM-entry when the guest-CPU state and the
9004 * VMCS state may potentially be out of sync.
9005 *
9006 * Sets up the VM-entry MSR-load and VM-exit MSR-store areas. Sets up the
9007 * VM-entry controls.
9008 * Sets up the appropriate VMX non-root function to execute guest code based on
9009 * the guest CPU mode.
9010 *
9011 * @returns VBox strict status code.
9012 * @retval VINF_EM_RESCHEDULE_REM if we try to emulate non-paged guest code
9013 * without unrestricted guest execution and the VMMDev is not presently
9014 * mapped (e.g. EFI32).
9015 *
9016 * @param pVCpu The cross context virtual CPU structure.
9017 * @param pVmxTransient The VMX-transient structure.
9018 *
9019 * @remarks No-long-jump zone!!!
9020 */
9021static VBOXSTRICTRC hmR0VmxExportGuestState(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
9022{
9023 AssertPtr(pVCpu);
9024 HMVMX_ASSERT_PREEMPT_SAFE(pVCpu);
9025 LogFlowFunc(("pVCpu=%p\n", pVCpu));
9026
9027 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatExportGuestState, x);
9028
9029 /*
9030 * Determine real-on-v86 mode.
9031 * Used when the guest is in real-mode and unrestricted guest execution is not used.
9032 */
9033 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
9034 if ( pVCpu->CTX_SUFF(pVM)->hm.s.vmx.fUnrestrictedGuest
9035 || !CPUMIsGuestInRealModeEx(&pVCpu->cpum.GstCtx))
9036 pVmcsInfo->RealMode. fRealOnV86Active = false;
9037 else
9038 {
9039 Assert(!pVmxTransient->fIsNestedGuest);
9040 pVmcsInfo->RealMode.fRealOnV86Active = true;
9041 }
9042
9043 /*
9044 * Any ordering dependency among the sub-functions below must be explicitly stated using comments.
9045 * Ideally, assert that the cross-dependent bits are up-to-date at the point of using it.
9046 */
9047 /** @todo r=ramshankar: Move hmR0VmxSelectVMRunHandler inside
9048 * hmR0VmxExportGuestEntryExitCtls and do it conditionally. There shouldn't
9049 * be a need to evaluate this everytime since I'm pretty sure we intercept
9050 * all guest paging mode changes. */
9051 int rc = hmR0VmxSelectVMRunHandler(pVCpu, pVmxTransient);
9052 AssertLogRelMsgRCReturn(rc, ("rc=%Rrc\n", rc), rc);
9053
9054 rc = hmR0VmxExportGuestEntryExitCtls(pVCpu, pVmxTransient);
9055 AssertLogRelMsgRCReturn(rc, ("rc=%Rrc\n", rc), rc);
9056
9057 rc = hmR0VmxExportGuestCR0(pVCpu, pVmxTransient);
9058 AssertLogRelMsgRCReturn(rc, ("rc=%Rrc\n", rc), rc);
9059
9060 VBOXSTRICTRC rcStrict = hmR0VmxExportGuestCR3AndCR4(pVCpu, pVmxTransient);
9061 if (rcStrict == VINF_SUCCESS)
9062 { /* likely */ }
9063 else
9064 {
9065 Assert(rcStrict == VINF_EM_RESCHEDULE_REM || RT_FAILURE_NP(rcStrict));
9066 return rcStrict;
9067 }
9068
9069 rc = hmR0VmxExportGuestSegRegsXdtr(pVCpu, pVmxTransient);
9070 AssertLogRelMsgRCReturn(rc, ("rc=%Rrc\n", rc), rc);
9071
9072 rc = hmR0VmxExportGuestMsrs(pVCpu, pVmxTransient);
9073 AssertLogRelMsgRCReturn(rc, ("rc=%Rrc\n", rc), rc);
9074
9075 rc = hmR0VmxExportGuestApicTpr(pVCpu, pVmxTransient);
9076 AssertLogRelMsgRCReturn(rc, ("rc=%Rrc\n", rc), rc);
9077
9078 rc = hmR0VmxExportGuestXcptIntercepts(pVCpu, pVmxTransient);
9079 AssertLogRelMsgRCReturn(rc, ("rc=%Rrc\n", rc), rc);
9080
9081 rc = hmR0VmxExportGuestRip(pVCpu);
9082 rc |= hmR0VmxExportGuestRsp(pVCpu);
9083 rc |= hmR0VmxExportGuestRflags(pVCpu, pVmxTransient);
9084 AssertLogRelMsgRCReturn(rc, ("rc=%Rrc\n", rc), rc);
9085
9086 rc = hmR0VmxExportGuestHwvirtState(pVCpu, pVmxTransient);
9087 AssertLogRelMsgRCReturn(rc, ("rc=%Rrc\n", rc), rc);
9088
9089 /* Clear any bits that may be set but exported unconditionally or unused/reserved bits. */
9090 ASMAtomicUoAndU64(&pVCpu->hm.s.fCtxChanged, ~( (HM_CHANGED_GUEST_GPRS_MASK & ~HM_CHANGED_GUEST_RSP)
9091 | HM_CHANGED_GUEST_CR2
9092 | (HM_CHANGED_GUEST_DR_MASK & ~HM_CHANGED_GUEST_DR7)
9093 | HM_CHANGED_GUEST_X87
9094 | HM_CHANGED_GUEST_SSE_AVX
9095 | HM_CHANGED_GUEST_OTHER_XSAVE
9096 | HM_CHANGED_GUEST_XCRx
9097 | HM_CHANGED_GUEST_KERNEL_GS_BASE /* Part of lazy or auto load-store MSRs. */
9098 | HM_CHANGED_GUEST_SYSCALL_MSRS /* Part of lazy or auto load-store MSRs. */
9099 | HM_CHANGED_GUEST_TSC_AUX
9100 | HM_CHANGED_GUEST_OTHER_MSRS
9101 | (HM_CHANGED_KEEPER_STATE_MASK & ~HM_CHANGED_VMX_MASK)));
9102
9103 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExportGuestState, x);
9104 return rc;
9105}
9106
9107
9108/**
9109 * Exports the state shared between the host and guest into the VMCS.
9110 *
9111 * @param pVCpu The cross context virtual CPU structure.
9112 * @param pVmxTransient The VMX-transient structure.
9113 *
9114 * @remarks No-long-jump zone!!!
9115 */
9116static void hmR0VmxExportSharedState(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
9117{
9118 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
9119 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
9120
9121 if (pVCpu->hm.s.fCtxChanged & HM_CHANGED_GUEST_DR_MASK)
9122 {
9123 int rc = hmR0VmxExportSharedDebugState(pVCpu, pVmxTransient);
9124 AssertRC(rc);
9125 pVCpu->hm.s.fCtxChanged &= ~HM_CHANGED_GUEST_DR_MASK;
9126
9127 /* Loading shared debug bits might have changed eflags.TF bit for debugging purposes. */
9128 if (pVCpu->hm.s.fCtxChanged & HM_CHANGED_GUEST_RFLAGS)
9129 {
9130 rc = hmR0VmxExportGuestRflags(pVCpu, pVmxTransient);
9131 AssertRC(rc);
9132 }
9133 }
9134
9135 if (pVCpu->hm.s.fCtxChanged & HM_CHANGED_VMX_GUEST_LAZY_MSRS)
9136 {
9137 hmR0VmxLazyLoadGuestMsrs(pVCpu);
9138 pVCpu->hm.s.fCtxChanged &= ~HM_CHANGED_VMX_GUEST_LAZY_MSRS;
9139 }
9140
9141 AssertMsg(!(pVCpu->hm.s.fCtxChanged & HM_CHANGED_VMX_HOST_GUEST_SHARED_STATE),
9142 ("fCtxChanged=%#RX64\n", pVCpu->hm.s.fCtxChanged));
9143}
9144
9145
9146/**
9147 * Worker for loading the guest-state bits in the inner VT-x execution loop.
9148 *
9149 * @returns Strict VBox status code (i.e. informational status codes too).
9150 * @retval VINF_EM_RESCHEDULE_REM if we try to emulate non-paged guest code
9151 * without unrestricted guest execution and the VMMDev is not presently
9152 * mapped (e.g. EFI32).
9153 *
9154 * @param pVCpu The cross context virtual CPU structure.
9155 * @param pVmxTransient The VMX-transient structure.
9156 *
9157 * @remarks No-long-jump zone!!!
9158 */
9159static VBOXSTRICTRC hmR0VmxExportGuestStateOptimal(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
9160{
9161 HMVMX_ASSERT_PREEMPT_SAFE(pVCpu);
9162 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
9163 Assert(VMMR0IsLogFlushDisabled(pVCpu));
9164
9165#ifdef HMVMX_ALWAYS_SYNC_FULL_GUEST_STATE
9166 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_ALL_GUEST);
9167#endif
9168
9169 /*
9170 * For many exits it's only RIP that changes and hence try to export it first
9171 * without going through a lot of change flag checks.
9172 */
9173 VBOXSTRICTRC rcStrict;
9174 uint64_t fCtxChanged = ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged);
9175 RT_UNTRUSTED_NONVOLATILE_COPY_FENCE();
9176 if ((fCtxChanged & (HM_CHANGED_ALL_GUEST & ~HM_CHANGED_VMX_HOST_GUEST_SHARED_STATE)) == HM_CHANGED_GUEST_RIP)
9177 {
9178 rcStrict = hmR0VmxExportGuestRip(pVCpu);
9179 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
9180 { /* likely */}
9181 else
9182 AssertMsgFailedReturn(("Failed to export guest RIP! rc=%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)), rcStrict);
9183 STAM_COUNTER_INC(&pVCpu->hm.s.StatExportMinimal);
9184 }
9185 else if (fCtxChanged & (HM_CHANGED_ALL_GUEST & ~HM_CHANGED_VMX_HOST_GUEST_SHARED_STATE))
9186 {
9187 rcStrict = hmR0VmxExportGuestState(pVCpu, pVmxTransient);
9188 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
9189 { /* likely */}
9190 else
9191 {
9192 AssertMsg(rcStrict == VINF_EM_RESCHEDULE_REM, ("Failed to export guest state! rc=%Rrc\n",
9193 VBOXSTRICTRC_VAL(rcStrict)));
9194 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
9195 return rcStrict;
9196 }
9197 STAM_COUNTER_INC(&pVCpu->hm.s.StatExportFull);
9198 }
9199 else
9200 rcStrict = VINF_SUCCESS;
9201
9202#ifdef VBOX_STRICT
9203 /* All the guest state bits should be loaded except maybe the host context and/or the shared host/guest bits. */
9204 fCtxChanged = ASMAtomicUoReadU64(&pVCpu->hm.s.fCtxChanged);
9205 RT_UNTRUSTED_NONVOLATILE_COPY_FENCE();
9206 AssertMsg(!(fCtxChanged & (HM_CHANGED_ALL_GUEST & ~HM_CHANGED_VMX_HOST_GUEST_SHARED_STATE)),
9207 ("fCtxChanged=%#RX64\n", fCtxChanged));
9208#endif
9209 return rcStrict;
9210}
9211
9212
9213/**
9214 * Tries to determine what part of the guest-state VT-x has deemed as invalid
9215 * and update error record fields accordingly.
9216 *
9217 * @returns VMX_IGS_* error codes.
9218 * @retval VMX_IGS_REASON_NOT_FOUND if this function could not find anything
9219 * wrong with the guest state.
9220 *
9221 * @param pVCpu The cross context virtual CPU structure.
9222 * @param pVmcsInfo The VMCS info. object.
9223 *
9224 * @remarks This function assumes our cache of the VMCS controls
9225 * are valid, i.e. hmR0VmxCheckVmcsCtls() succeeded.
9226 */
9227static uint32_t hmR0VmxCheckGuestState(PVMCPUCC pVCpu, PCVMXVMCSINFO pVmcsInfo)
9228{
9229#define HMVMX_ERROR_BREAK(err) { uError = (err); break; }
9230#define HMVMX_CHECK_BREAK(expr, err) do { \
9231 if (!(expr)) { uError = (err); break; } \
9232 } while (0)
9233
9234 int rc;
9235 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
9236 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
9237 uint32_t uError = VMX_IGS_ERROR;
9238 uint32_t u32Val;
9239 bool const fUnrestrictedGuest = pVM->hm.s.vmx.fUnrestrictedGuest;
9240
9241 do
9242 {
9243 /*
9244 * CR0.
9245 */
9246 /** @todo Why do we need to OR and AND the fixed-0 and fixed-1 bits below? */
9247 uint64_t fSetCr0 = (pVM->hm.s.vmx.Msrs.u64Cr0Fixed0 & pVM->hm.s.vmx.Msrs.u64Cr0Fixed1);
9248 uint64_t const fZapCr0 = (pVM->hm.s.vmx.Msrs.u64Cr0Fixed0 | pVM->hm.s.vmx.Msrs.u64Cr0Fixed1);
9249 /* Exceptions for unrestricted guest execution for fixed CR0 bits (PE, PG).
9250 See Intel spec. 26.3.1 "Checks on Guest Control Registers, Debug Registers and MSRs." */
9251 if (fUnrestrictedGuest)
9252 fSetCr0 &= ~(uint64_t)(X86_CR0_PE | X86_CR0_PG);
9253
9254 uint64_t u64GuestCr0;
9255 rc = VMXReadVmcsNw(VMX_VMCS_GUEST_CR0, &u64GuestCr0);
9256 AssertRC(rc);
9257 HMVMX_CHECK_BREAK((u64GuestCr0 & fSetCr0) == fSetCr0, VMX_IGS_CR0_FIXED1);
9258 HMVMX_CHECK_BREAK(!(u64GuestCr0 & ~fZapCr0), VMX_IGS_CR0_FIXED0);
9259 if ( !fUnrestrictedGuest
9260 && (u64GuestCr0 & X86_CR0_PG)
9261 && !(u64GuestCr0 & X86_CR0_PE))
9262 {
9263 HMVMX_ERROR_BREAK(VMX_IGS_CR0_PG_PE_COMBO);
9264 }
9265
9266 /*
9267 * CR4.
9268 */
9269 /** @todo Why do we need to OR and AND the fixed-0 and fixed-1 bits below? */
9270 uint64_t const fSetCr4 = (pVM->hm.s.vmx.Msrs.u64Cr4Fixed0 & pVM->hm.s.vmx.Msrs.u64Cr4Fixed1);
9271 uint64_t const fZapCr4 = (pVM->hm.s.vmx.Msrs.u64Cr4Fixed0 | pVM->hm.s.vmx.Msrs.u64Cr4Fixed1);
9272
9273 uint64_t u64GuestCr4;
9274 rc = VMXReadVmcsNw(VMX_VMCS_GUEST_CR4, &u64GuestCr4);
9275 AssertRC(rc);
9276 HMVMX_CHECK_BREAK((u64GuestCr4 & fSetCr4) == fSetCr4, VMX_IGS_CR4_FIXED1);
9277 HMVMX_CHECK_BREAK(!(u64GuestCr4 & ~fZapCr4), VMX_IGS_CR4_FIXED0);
9278
9279 /*
9280 * IA32_DEBUGCTL MSR.
9281 */
9282 uint64_t u64Val;
9283 rc = VMXReadVmcs64(VMX_VMCS64_GUEST_DEBUGCTL_FULL, &u64Val);
9284 AssertRC(rc);
9285 if ( (pVmcsInfo->u32EntryCtls & VMX_ENTRY_CTLS_LOAD_DEBUG)
9286 && (u64Val & 0xfffffe3c)) /* Bits 31:9, bits 5:2 MBZ. */
9287 {
9288 HMVMX_ERROR_BREAK(VMX_IGS_DEBUGCTL_MSR_RESERVED);
9289 }
9290 uint64_t u64DebugCtlMsr = u64Val;
9291
9292#ifdef VBOX_STRICT
9293 rc = VMXReadVmcs32(VMX_VMCS32_CTRL_ENTRY, &u32Val);
9294 AssertRC(rc);
9295 Assert(u32Val == pVmcsInfo->u32EntryCtls);
9296#endif
9297 bool const fLongModeGuest = RT_BOOL(pVmcsInfo->u32EntryCtls & VMX_ENTRY_CTLS_IA32E_MODE_GUEST);
9298
9299 /*
9300 * RIP and RFLAGS.
9301 */
9302 rc = VMXReadVmcsNw(VMX_VMCS_GUEST_RIP, &u64Val);
9303 AssertRC(rc);
9304 /* pCtx->rip can be different than the one in the VMCS (e.g. run guest code and VM-exits that don't update it). */
9305 if ( !fLongModeGuest
9306 || !pCtx->cs.Attr.n.u1Long)
9307 {
9308 HMVMX_CHECK_BREAK(!(u64Val & UINT64_C(0xffffffff00000000)), VMX_IGS_LONGMODE_RIP_INVALID);
9309 }
9310 /** @todo If the processor supports N < 64 linear-address bits, bits 63:N
9311 * must be identical if the "IA-32e mode guest" VM-entry
9312 * control is 1 and CS.L is 1. No check applies if the
9313 * CPU supports 64 linear-address bits. */
9314
9315 /* Flags in pCtx can be different (real-on-v86 for instance). We are only concerned about the VMCS contents here. */
9316 rc = VMXReadVmcsNw(VMX_VMCS_GUEST_RFLAGS, &u64Val);
9317 AssertRC(rc);
9318 HMVMX_CHECK_BREAK(!(u64Val & UINT64_C(0xffffffffffc08028)), /* Bit 63:22, Bit 15, 5, 3 MBZ. */
9319 VMX_IGS_RFLAGS_RESERVED);
9320 HMVMX_CHECK_BREAK((u64Val & X86_EFL_RA1_MASK), VMX_IGS_RFLAGS_RESERVED1); /* Bit 1 MB1. */
9321 uint32_t const u32Eflags = u64Val;
9322
9323 if ( fLongModeGuest
9324 || ( fUnrestrictedGuest
9325 && !(u64GuestCr0 & X86_CR0_PE)))
9326 {
9327 HMVMX_CHECK_BREAK(!(u32Eflags & X86_EFL_VM), VMX_IGS_RFLAGS_VM_INVALID);
9328 }
9329
9330 uint32_t u32EntryInfo;
9331 rc = VMXReadVmcs32(VMX_VMCS32_CTRL_ENTRY_INTERRUPTION_INFO, &u32EntryInfo);
9332 AssertRC(rc);
9333 if (VMX_ENTRY_INT_INFO_IS_EXT_INT(u32EntryInfo))
9334 HMVMX_CHECK_BREAK(u32Eflags & X86_EFL_IF, VMX_IGS_RFLAGS_IF_INVALID);
9335
9336 /*
9337 * 64-bit checks.
9338 */
9339 if (fLongModeGuest)
9340 {
9341 HMVMX_CHECK_BREAK(u64GuestCr0 & X86_CR0_PG, VMX_IGS_CR0_PG_LONGMODE);
9342 HMVMX_CHECK_BREAK(u64GuestCr4 & X86_CR4_PAE, VMX_IGS_CR4_PAE_LONGMODE);
9343 }
9344
9345 if ( !fLongModeGuest
9346 && (u64GuestCr4 & X86_CR4_PCIDE))
9347 {
9348 HMVMX_ERROR_BREAK(VMX_IGS_CR4_PCIDE);
9349 }
9350
9351 /** @todo CR3 field must be such that bits 63:52 and bits in the range
9352 * 51:32 beyond the processor's physical-address width are 0. */
9353
9354 if ( (pVmcsInfo->u32EntryCtls & VMX_ENTRY_CTLS_LOAD_DEBUG)
9355 && (pCtx->dr[7] & X86_DR7_MBZ_MASK))
9356 {
9357 HMVMX_ERROR_BREAK(VMX_IGS_DR7_RESERVED);
9358 }
9359
9360 rc = VMXReadVmcsNw(VMX_VMCS_HOST_SYSENTER_ESP, &u64Val);
9361 AssertRC(rc);
9362 HMVMX_CHECK_BREAK(X86_IS_CANONICAL(u64Val), VMX_IGS_SYSENTER_ESP_NOT_CANONICAL);
9363
9364 rc = VMXReadVmcsNw(VMX_VMCS_HOST_SYSENTER_EIP, &u64Val);
9365 AssertRC(rc);
9366 HMVMX_CHECK_BREAK(X86_IS_CANONICAL(u64Val), VMX_IGS_SYSENTER_EIP_NOT_CANONICAL);
9367
9368 /*
9369 * PERF_GLOBAL MSR.
9370 */
9371 if (pVmcsInfo->u32EntryCtls & VMX_ENTRY_CTLS_LOAD_PERF_MSR)
9372 {
9373 rc = VMXReadVmcs64(VMX_VMCS64_GUEST_PERF_GLOBAL_CTRL_FULL, &u64Val);
9374 AssertRC(rc);
9375 HMVMX_CHECK_BREAK(!(u64Val & UINT64_C(0xfffffff8fffffffc)),
9376 VMX_IGS_PERF_GLOBAL_MSR_RESERVED); /* Bits 63:35, bits 31:2 MBZ. */
9377 }
9378
9379 /*
9380 * PAT MSR.
9381 */
9382 if (pVmcsInfo->u32EntryCtls & VMX_ENTRY_CTLS_LOAD_PAT_MSR)
9383 {
9384 rc = VMXReadVmcs64(VMX_VMCS64_GUEST_PAT_FULL, &u64Val);
9385 AssertRC(rc);
9386 HMVMX_CHECK_BREAK(!(u64Val & UINT64_C(0x707070707070707)), VMX_IGS_PAT_MSR_RESERVED);
9387 for (unsigned i = 0; i < 8; i++)
9388 {
9389 uint8_t u8Val = (u64Val & 0xff);
9390 if ( u8Val != 0 /* UC */
9391 && u8Val != 1 /* WC */
9392 && u8Val != 4 /* WT */
9393 && u8Val != 5 /* WP */
9394 && u8Val != 6 /* WB */
9395 && u8Val != 7 /* UC- */)
9396 {
9397 HMVMX_ERROR_BREAK(VMX_IGS_PAT_MSR_INVALID);
9398 }
9399 u64Val >>= 8;
9400 }
9401 }
9402
9403 /*
9404 * EFER MSR.
9405 */
9406 if (pVmcsInfo->u32EntryCtls & VMX_ENTRY_CTLS_LOAD_EFER_MSR)
9407 {
9408 Assert(pVM->hm.s.vmx.fSupportsVmcsEfer);
9409 rc = VMXReadVmcs64(VMX_VMCS64_GUEST_EFER_FULL, &u64Val);
9410 AssertRC(rc);
9411 HMVMX_CHECK_BREAK(!(u64Val & UINT64_C(0xfffffffffffff2fe)),
9412 VMX_IGS_EFER_MSR_RESERVED); /* Bits 63:12, bit 9, bits 7:1 MBZ. */
9413 HMVMX_CHECK_BREAK(RT_BOOL(u64Val & MSR_K6_EFER_LMA) == RT_BOOL( pVmcsInfo->u32EntryCtls
9414 & VMX_ENTRY_CTLS_IA32E_MODE_GUEST),
9415 VMX_IGS_EFER_LMA_GUEST_MODE_MISMATCH);
9416 /** @todo r=ramshankar: Unrestricted check here is probably wrong, see
9417 * iemVmxVmentryCheckGuestState(). */
9418 HMVMX_CHECK_BREAK( fUnrestrictedGuest
9419 || !(u64GuestCr0 & X86_CR0_PG)
9420 || RT_BOOL(u64Val & MSR_K6_EFER_LMA) == RT_BOOL(u64Val & MSR_K6_EFER_LME),
9421 VMX_IGS_EFER_LMA_LME_MISMATCH);
9422 }
9423
9424 /*
9425 * Segment registers.
9426 */
9427 HMVMX_CHECK_BREAK( (pCtx->ldtr.Attr.u & X86DESCATTR_UNUSABLE)
9428 || !(pCtx->ldtr.Sel & X86_SEL_LDT), VMX_IGS_LDTR_TI_INVALID);
9429 if (!(u32Eflags & X86_EFL_VM))
9430 {
9431 /* CS */
9432 HMVMX_CHECK_BREAK(pCtx->cs.Attr.n.u1Present, VMX_IGS_CS_ATTR_P_INVALID);
9433 HMVMX_CHECK_BREAK(!(pCtx->cs.Attr.u & 0xf00), VMX_IGS_CS_ATTR_RESERVED);
9434 HMVMX_CHECK_BREAK(!(pCtx->cs.Attr.u & 0xfffe0000), VMX_IGS_CS_ATTR_RESERVED);
9435 HMVMX_CHECK_BREAK( (pCtx->cs.u32Limit & 0xfff) == 0xfff
9436 || !(pCtx->cs.Attr.n.u1Granularity), VMX_IGS_CS_ATTR_G_INVALID);
9437 HMVMX_CHECK_BREAK( !(pCtx->cs.u32Limit & 0xfff00000)
9438 || (pCtx->cs.Attr.n.u1Granularity), VMX_IGS_CS_ATTR_G_INVALID);
9439 /* CS cannot be loaded with NULL in protected mode. */
9440 HMVMX_CHECK_BREAK(pCtx->cs.Attr.u && !(pCtx->cs.Attr.u & X86DESCATTR_UNUSABLE), VMX_IGS_CS_ATTR_UNUSABLE);
9441 HMVMX_CHECK_BREAK(pCtx->cs.Attr.n.u1DescType, VMX_IGS_CS_ATTR_S_INVALID);
9442 if (pCtx->cs.Attr.n.u4Type == 9 || pCtx->cs.Attr.n.u4Type == 11)
9443 HMVMX_CHECK_BREAK(pCtx->cs.Attr.n.u2Dpl == pCtx->ss.Attr.n.u2Dpl, VMX_IGS_CS_SS_ATTR_DPL_UNEQUAL);
9444 else if (pCtx->cs.Attr.n.u4Type == 13 || pCtx->cs.Attr.n.u4Type == 15)
9445 HMVMX_CHECK_BREAK(pCtx->cs.Attr.n.u2Dpl <= pCtx->ss.Attr.n.u2Dpl, VMX_IGS_CS_SS_ATTR_DPL_MISMATCH);
9446 else if (pVM->hm.s.vmx.fUnrestrictedGuest && pCtx->cs.Attr.n.u4Type == 3)
9447 HMVMX_CHECK_BREAK(pCtx->cs.Attr.n.u2Dpl == 0, VMX_IGS_CS_ATTR_DPL_INVALID);
9448 else
9449 HMVMX_ERROR_BREAK(VMX_IGS_CS_ATTR_TYPE_INVALID);
9450
9451 /* SS */
9452 HMVMX_CHECK_BREAK( pVM->hm.s.vmx.fUnrestrictedGuest
9453 || (pCtx->ss.Sel & X86_SEL_RPL) == (pCtx->cs.Sel & X86_SEL_RPL), VMX_IGS_SS_CS_RPL_UNEQUAL);
9454 HMVMX_CHECK_BREAK(pCtx->ss.Attr.n.u2Dpl == (pCtx->ss.Sel & X86_SEL_RPL), VMX_IGS_SS_ATTR_DPL_RPL_UNEQUAL);
9455 if ( !(pCtx->cr0 & X86_CR0_PE)
9456 || pCtx->cs.Attr.n.u4Type == 3)
9457 {
9458 HMVMX_CHECK_BREAK(!pCtx->ss.Attr.n.u2Dpl, VMX_IGS_SS_ATTR_DPL_INVALID);
9459 }
9460 if (!(pCtx->ss.Attr.u & X86DESCATTR_UNUSABLE))
9461 {
9462 HMVMX_CHECK_BREAK(pCtx->ss.Attr.n.u4Type == 3 || pCtx->ss.Attr.n.u4Type == 7, VMX_IGS_SS_ATTR_TYPE_INVALID);
9463 HMVMX_CHECK_BREAK(pCtx->ss.Attr.n.u1Present, VMX_IGS_SS_ATTR_P_INVALID);
9464 HMVMX_CHECK_BREAK(!(pCtx->ss.Attr.u & 0xf00), VMX_IGS_SS_ATTR_RESERVED);
9465 HMVMX_CHECK_BREAK(!(pCtx->ss.Attr.u & 0xfffe0000), VMX_IGS_SS_ATTR_RESERVED);
9466 HMVMX_CHECK_BREAK( (pCtx->ss.u32Limit & 0xfff) == 0xfff
9467 || !(pCtx->ss.Attr.n.u1Granularity), VMX_IGS_SS_ATTR_G_INVALID);
9468 HMVMX_CHECK_BREAK( !(pCtx->ss.u32Limit & 0xfff00000)
9469 || (pCtx->ss.Attr.n.u1Granularity), VMX_IGS_SS_ATTR_G_INVALID);
9470 }
9471
9472 /* DS, ES, FS, GS - only check for usable selectors, see hmR0VmxExportGuestSReg(). */
9473 if (!(pCtx->ds.Attr.u & X86DESCATTR_UNUSABLE))
9474 {
9475 HMVMX_CHECK_BREAK(pCtx->ds.Attr.n.u4Type & X86_SEL_TYPE_ACCESSED, VMX_IGS_DS_ATTR_A_INVALID);
9476 HMVMX_CHECK_BREAK(pCtx->ds.Attr.n.u1Present, VMX_IGS_DS_ATTR_P_INVALID);
9477 HMVMX_CHECK_BREAK( pVM->hm.s.vmx.fUnrestrictedGuest
9478 || pCtx->ds.Attr.n.u4Type > 11
9479 || pCtx->ds.Attr.n.u2Dpl >= (pCtx->ds.Sel & X86_SEL_RPL), VMX_IGS_DS_ATTR_DPL_RPL_UNEQUAL);
9480 HMVMX_CHECK_BREAK(!(pCtx->ds.Attr.u & 0xf00), VMX_IGS_DS_ATTR_RESERVED);
9481 HMVMX_CHECK_BREAK(!(pCtx->ds.Attr.u & 0xfffe0000), VMX_IGS_DS_ATTR_RESERVED);
9482 HMVMX_CHECK_BREAK( (pCtx->ds.u32Limit & 0xfff) == 0xfff
9483 || !(pCtx->ds.Attr.n.u1Granularity), VMX_IGS_DS_ATTR_G_INVALID);
9484 HMVMX_CHECK_BREAK( !(pCtx->ds.u32Limit & 0xfff00000)
9485 || (pCtx->ds.Attr.n.u1Granularity), VMX_IGS_DS_ATTR_G_INVALID);
9486 HMVMX_CHECK_BREAK( !(pCtx->ds.Attr.n.u4Type & X86_SEL_TYPE_CODE)
9487 || (pCtx->ds.Attr.n.u4Type & X86_SEL_TYPE_READ), VMX_IGS_DS_ATTR_TYPE_INVALID);
9488 }
9489 if (!(pCtx->es.Attr.u & X86DESCATTR_UNUSABLE))
9490 {
9491 HMVMX_CHECK_BREAK(pCtx->es.Attr.n.u4Type & X86_SEL_TYPE_ACCESSED, VMX_IGS_ES_ATTR_A_INVALID);
9492 HMVMX_CHECK_BREAK(pCtx->es.Attr.n.u1Present, VMX_IGS_ES_ATTR_P_INVALID);
9493 HMVMX_CHECK_BREAK( pVM->hm.s.vmx.fUnrestrictedGuest
9494 || pCtx->es.Attr.n.u4Type > 11
9495 || pCtx->es.Attr.n.u2Dpl >= (pCtx->es.Sel & X86_SEL_RPL), VMX_IGS_DS_ATTR_DPL_RPL_UNEQUAL);
9496 HMVMX_CHECK_BREAK(!(pCtx->es.Attr.u & 0xf00), VMX_IGS_ES_ATTR_RESERVED);
9497 HMVMX_CHECK_BREAK(!(pCtx->es.Attr.u & 0xfffe0000), VMX_IGS_ES_ATTR_RESERVED);
9498 HMVMX_CHECK_BREAK( (pCtx->es.u32Limit & 0xfff) == 0xfff
9499 || !(pCtx->es.Attr.n.u1Granularity), VMX_IGS_ES_ATTR_G_INVALID);
9500 HMVMX_CHECK_BREAK( !(pCtx->es.u32Limit & 0xfff00000)
9501 || (pCtx->es.Attr.n.u1Granularity), VMX_IGS_ES_ATTR_G_INVALID);
9502 HMVMX_CHECK_BREAK( !(pCtx->es.Attr.n.u4Type & X86_SEL_TYPE_CODE)
9503 || (pCtx->es.Attr.n.u4Type & X86_SEL_TYPE_READ), VMX_IGS_ES_ATTR_TYPE_INVALID);
9504 }
9505 if (!(pCtx->fs.Attr.u & X86DESCATTR_UNUSABLE))
9506 {
9507 HMVMX_CHECK_BREAK(pCtx->fs.Attr.n.u4Type & X86_SEL_TYPE_ACCESSED, VMX_IGS_FS_ATTR_A_INVALID);
9508 HMVMX_CHECK_BREAK(pCtx->fs.Attr.n.u1Present, VMX_IGS_FS_ATTR_P_INVALID);
9509 HMVMX_CHECK_BREAK( pVM->hm.s.vmx.fUnrestrictedGuest
9510 || pCtx->fs.Attr.n.u4Type > 11
9511 || pCtx->fs.Attr.n.u2Dpl >= (pCtx->fs.Sel & X86_SEL_RPL), VMX_IGS_FS_ATTR_DPL_RPL_UNEQUAL);
9512 HMVMX_CHECK_BREAK(!(pCtx->fs.Attr.u & 0xf00), VMX_IGS_FS_ATTR_RESERVED);
9513 HMVMX_CHECK_BREAK(!(pCtx->fs.Attr.u & 0xfffe0000), VMX_IGS_FS_ATTR_RESERVED);
9514 HMVMX_CHECK_BREAK( (pCtx->fs.u32Limit & 0xfff) == 0xfff
9515 || !(pCtx->fs.Attr.n.u1Granularity), VMX_IGS_FS_ATTR_G_INVALID);
9516 HMVMX_CHECK_BREAK( !(pCtx->fs.u32Limit & 0xfff00000)
9517 || (pCtx->fs.Attr.n.u1Granularity), VMX_IGS_FS_ATTR_G_INVALID);
9518 HMVMX_CHECK_BREAK( !(pCtx->fs.Attr.n.u4Type & X86_SEL_TYPE_CODE)
9519 || (pCtx->fs.Attr.n.u4Type & X86_SEL_TYPE_READ), VMX_IGS_FS_ATTR_TYPE_INVALID);
9520 }
9521 if (!(pCtx->gs.Attr.u & X86DESCATTR_UNUSABLE))
9522 {
9523 HMVMX_CHECK_BREAK(pCtx->gs.Attr.n.u4Type & X86_SEL_TYPE_ACCESSED, VMX_IGS_GS_ATTR_A_INVALID);
9524 HMVMX_CHECK_BREAK(pCtx->gs.Attr.n.u1Present, VMX_IGS_GS_ATTR_P_INVALID);
9525 HMVMX_CHECK_BREAK( pVM->hm.s.vmx.fUnrestrictedGuest
9526 || pCtx->gs.Attr.n.u4Type > 11
9527 || pCtx->gs.Attr.n.u2Dpl >= (pCtx->gs.Sel & X86_SEL_RPL), VMX_IGS_GS_ATTR_DPL_RPL_UNEQUAL);
9528 HMVMX_CHECK_BREAK(!(pCtx->gs.Attr.u & 0xf00), VMX_IGS_GS_ATTR_RESERVED);
9529 HMVMX_CHECK_BREAK(!(pCtx->gs.Attr.u & 0xfffe0000), VMX_IGS_GS_ATTR_RESERVED);
9530 HMVMX_CHECK_BREAK( (pCtx->gs.u32Limit & 0xfff) == 0xfff
9531 || !(pCtx->gs.Attr.n.u1Granularity), VMX_IGS_GS_ATTR_G_INVALID);
9532 HMVMX_CHECK_BREAK( !(pCtx->gs.u32Limit & 0xfff00000)
9533 || (pCtx->gs.Attr.n.u1Granularity), VMX_IGS_GS_ATTR_G_INVALID);
9534 HMVMX_CHECK_BREAK( !(pCtx->gs.Attr.n.u4Type & X86_SEL_TYPE_CODE)
9535 || (pCtx->gs.Attr.n.u4Type & X86_SEL_TYPE_READ), VMX_IGS_GS_ATTR_TYPE_INVALID);
9536 }
9537 /* 64-bit capable CPUs. */
9538 HMVMX_CHECK_BREAK(X86_IS_CANONICAL(pCtx->fs.u64Base), VMX_IGS_FS_BASE_NOT_CANONICAL);
9539 HMVMX_CHECK_BREAK(X86_IS_CANONICAL(pCtx->gs.u64Base), VMX_IGS_GS_BASE_NOT_CANONICAL);
9540 HMVMX_CHECK_BREAK( (pCtx->ldtr.Attr.u & X86DESCATTR_UNUSABLE)
9541 || X86_IS_CANONICAL(pCtx->ldtr.u64Base), VMX_IGS_LDTR_BASE_NOT_CANONICAL);
9542 HMVMX_CHECK_BREAK(!RT_HI_U32(pCtx->cs.u64Base), VMX_IGS_LONGMODE_CS_BASE_INVALID);
9543 HMVMX_CHECK_BREAK((pCtx->ss.Attr.u & X86DESCATTR_UNUSABLE) || !RT_HI_U32(pCtx->ss.u64Base),
9544 VMX_IGS_LONGMODE_SS_BASE_INVALID);
9545 HMVMX_CHECK_BREAK((pCtx->ds.Attr.u & X86DESCATTR_UNUSABLE) || !RT_HI_U32(pCtx->ds.u64Base),
9546 VMX_IGS_LONGMODE_DS_BASE_INVALID);
9547 HMVMX_CHECK_BREAK((pCtx->es.Attr.u & X86DESCATTR_UNUSABLE) || !RT_HI_U32(pCtx->es.u64Base),
9548 VMX_IGS_LONGMODE_ES_BASE_INVALID);
9549 }
9550 else
9551 {
9552 /* V86 mode checks. */
9553 uint32_t u32CSAttr, u32SSAttr, u32DSAttr, u32ESAttr, u32FSAttr, u32GSAttr;
9554 if (pVmcsInfo->RealMode.fRealOnV86Active)
9555 {
9556 u32CSAttr = 0xf3; u32SSAttr = 0xf3;
9557 u32DSAttr = 0xf3; u32ESAttr = 0xf3;
9558 u32FSAttr = 0xf3; u32GSAttr = 0xf3;
9559 }
9560 else
9561 {
9562 u32CSAttr = pCtx->cs.Attr.u; u32SSAttr = pCtx->ss.Attr.u;
9563 u32DSAttr = pCtx->ds.Attr.u; u32ESAttr = pCtx->es.Attr.u;
9564 u32FSAttr = pCtx->fs.Attr.u; u32GSAttr = pCtx->gs.Attr.u;
9565 }
9566
9567 /* CS */
9568 HMVMX_CHECK_BREAK((pCtx->cs.u64Base == (uint64_t)pCtx->cs.Sel << 4), VMX_IGS_V86_CS_BASE_INVALID);
9569 HMVMX_CHECK_BREAK(pCtx->cs.u32Limit == 0xffff, VMX_IGS_V86_CS_LIMIT_INVALID);
9570 HMVMX_CHECK_BREAK(u32CSAttr == 0xf3, VMX_IGS_V86_CS_ATTR_INVALID);
9571 /* SS */
9572 HMVMX_CHECK_BREAK((pCtx->ss.u64Base == (uint64_t)pCtx->ss.Sel << 4), VMX_IGS_V86_SS_BASE_INVALID);
9573 HMVMX_CHECK_BREAK(pCtx->ss.u32Limit == 0xffff, VMX_IGS_V86_SS_LIMIT_INVALID);
9574 HMVMX_CHECK_BREAK(u32SSAttr == 0xf3, VMX_IGS_V86_SS_ATTR_INVALID);
9575 /* DS */
9576 HMVMX_CHECK_BREAK((pCtx->ds.u64Base == (uint64_t)pCtx->ds.Sel << 4), VMX_IGS_V86_DS_BASE_INVALID);
9577 HMVMX_CHECK_BREAK(pCtx->ds.u32Limit == 0xffff, VMX_IGS_V86_DS_LIMIT_INVALID);
9578 HMVMX_CHECK_BREAK(u32DSAttr == 0xf3, VMX_IGS_V86_DS_ATTR_INVALID);
9579 /* ES */
9580 HMVMX_CHECK_BREAK((pCtx->es.u64Base == (uint64_t)pCtx->es.Sel << 4), VMX_IGS_V86_ES_BASE_INVALID);
9581 HMVMX_CHECK_BREAK(pCtx->es.u32Limit == 0xffff, VMX_IGS_V86_ES_LIMIT_INVALID);
9582 HMVMX_CHECK_BREAK(u32ESAttr == 0xf3, VMX_IGS_V86_ES_ATTR_INVALID);
9583 /* FS */
9584 HMVMX_CHECK_BREAK((pCtx->fs.u64Base == (uint64_t)pCtx->fs.Sel << 4), VMX_IGS_V86_FS_BASE_INVALID);
9585 HMVMX_CHECK_BREAK(pCtx->fs.u32Limit == 0xffff, VMX_IGS_V86_FS_LIMIT_INVALID);
9586 HMVMX_CHECK_BREAK(u32FSAttr == 0xf3, VMX_IGS_V86_FS_ATTR_INVALID);
9587 /* GS */
9588 HMVMX_CHECK_BREAK((pCtx->gs.u64Base == (uint64_t)pCtx->gs.Sel << 4), VMX_IGS_V86_GS_BASE_INVALID);
9589 HMVMX_CHECK_BREAK(pCtx->gs.u32Limit == 0xffff, VMX_IGS_V86_GS_LIMIT_INVALID);
9590 HMVMX_CHECK_BREAK(u32GSAttr == 0xf3, VMX_IGS_V86_GS_ATTR_INVALID);
9591 /* 64-bit capable CPUs. */
9592 HMVMX_CHECK_BREAK(X86_IS_CANONICAL(pCtx->fs.u64Base), VMX_IGS_FS_BASE_NOT_CANONICAL);
9593 HMVMX_CHECK_BREAK(X86_IS_CANONICAL(pCtx->gs.u64Base), VMX_IGS_GS_BASE_NOT_CANONICAL);
9594 HMVMX_CHECK_BREAK( (pCtx->ldtr.Attr.u & X86DESCATTR_UNUSABLE)
9595 || X86_IS_CANONICAL(pCtx->ldtr.u64Base), VMX_IGS_LDTR_BASE_NOT_CANONICAL);
9596 HMVMX_CHECK_BREAK(!RT_HI_U32(pCtx->cs.u64Base), VMX_IGS_LONGMODE_CS_BASE_INVALID);
9597 HMVMX_CHECK_BREAK((pCtx->ss.Attr.u & X86DESCATTR_UNUSABLE) || !RT_HI_U32(pCtx->ss.u64Base),
9598 VMX_IGS_LONGMODE_SS_BASE_INVALID);
9599 HMVMX_CHECK_BREAK((pCtx->ds.Attr.u & X86DESCATTR_UNUSABLE) || !RT_HI_U32(pCtx->ds.u64Base),
9600 VMX_IGS_LONGMODE_DS_BASE_INVALID);
9601 HMVMX_CHECK_BREAK((pCtx->es.Attr.u & X86DESCATTR_UNUSABLE) || !RT_HI_U32(pCtx->es.u64Base),
9602 VMX_IGS_LONGMODE_ES_BASE_INVALID);
9603 }
9604
9605 /*
9606 * TR.
9607 */
9608 HMVMX_CHECK_BREAK(!(pCtx->tr.Sel & X86_SEL_LDT), VMX_IGS_TR_TI_INVALID);
9609 /* 64-bit capable CPUs. */
9610 HMVMX_CHECK_BREAK(X86_IS_CANONICAL(pCtx->tr.u64Base), VMX_IGS_TR_BASE_NOT_CANONICAL);
9611 if (fLongModeGuest)
9612 {
9613 HMVMX_CHECK_BREAK(pCtx->tr.Attr.n.u4Type == 11, /* 64-bit busy TSS. */
9614 VMX_IGS_LONGMODE_TR_ATTR_TYPE_INVALID);
9615 }
9616 else
9617 {
9618 HMVMX_CHECK_BREAK( pCtx->tr.Attr.n.u4Type == 3 /* 16-bit busy TSS. */
9619 || pCtx->tr.Attr.n.u4Type == 11, /* 32-bit busy TSS.*/
9620 VMX_IGS_TR_ATTR_TYPE_INVALID);
9621 }
9622 HMVMX_CHECK_BREAK(!pCtx->tr.Attr.n.u1DescType, VMX_IGS_TR_ATTR_S_INVALID);
9623 HMVMX_CHECK_BREAK(pCtx->tr.Attr.n.u1Present, VMX_IGS_TR_ATTR_P_INVALID);
9624 HMVMX_CHECK_BREAK(!(pCtx->tr.Attr.u & 0xf00), VMX_IGS_TR_ATTR_RESERVED); /* Bits 11:8 MBZ. */
9625 HMVMX_CHECK_BREAK( (pCtx->tr.u32Limit & 0xfff) == 0xfff
9626 || !(pCtx->tr.Attr.n.u1Granularity), VMX_IGS_TR_ATTR_G_INVALID);
9627 HMVMX_CHECK_BREAK( !(pCtx->tr.u32Limit & 0xfff00000)
9628 || (pCtx->tr.Attr.n.u1Granularity), VMX_IGS_TR_ATTR_G_INVALID);
9629 HMVMX_CHECK_BREAK(!(pCtx->tr.Attr.u & X86DESCATTR_UNUSABLE), VMX_IGS_TR_ATTR_UNUSABLE);
9630
9631 /*
9632 * GDTR and IDTR (64-bit capable checks).
9633 */
9634 rc = VMXReadVmcsNw(VMX_VMCS_GUEST_GDTR_BASE, &u64Val);
9635 AssertRC(rc);
9636 HMVMX_CHECK_BREAK(X86_IS_CANONICAL(u64Val), VMX_IGS_GDTR_BASE_NOT_CANONICAL);
9637
9638 rc = VMXReadVmcsNw(VMX_VMCS_GUEST_IDTR_BASE, &u64Val);
9639 AssertRC(rc);
9640 HMVMX_CHECK_BREAK(X86_IS_CANONICAL(u64Val), VMX_IGS_IDTR_BASE_NOT_CANONICAL);
9641
9642 rc = VMXReadVmcs32(VMX_VMCS32_GUEST_GDTR_LIMIT, &u32Val);
9643 AssertRC(rc);
9644 HMVMX_CHECK_BREAK(!(u32Val & 0xffff0000), VMX_IGS_GDTR_LIMIT_INVALID); /* Bits 31:16 MBZ. */
9645
9646 rc = VMXReadVmcs32(VMX_VMCS32_GUEST_IDTR_LIMIT, &u32Val);
9647 AssertRC(rc);
9648 HMVMX_CHECK_BREAK(!(u32Val & 0xffff0000), VMX_IGS_IDTR_LIMIT_INVALID); /* Bits 31:16 MBZ. */
9649
9650 /*
9651 * Guest Non-Register State.
9652 */
9653 /* Activity State. */
9654 uint32_t u32ActivityState;
9655 rc = VMXReadVmcs32(VMX_VMCS32_GUEST_ACTIVITY_STATE, &u32ActivityState);
9656 AssertRC(rc);
9657 HMVMX_CHECK_BREAK( !u32ActivityState
9658 || (u32ActivityState & RT_BF_GET(pVM->hm.s.vmx.Msrs.u64Misc, VMX_BF_MISC_ACTIVITY_STATES)),
9659 VMX_IGS_ACTIVITY_STATE_INVALID);
9660 HMVMX_CHECK_BREAK( !(pCtx->ss.Attr.n.u2Dpl)
9661 || u32ActivityState != VMX_VMCS_GUEST_ACTIVITY_HLT, VMX_IGS_ACTIVITY_STATE_HLT_INVALID);
9662 uint32_t u32IntrState;
9663 rc = VMXReadVmcs32(VMX_VMCS32_GUEST_INT_STATE, &u32IntrState);
9664 AssertRC(rc);
9665 if ( u32IntrState == VMX_VMCS_GUEST_INT_STATE_BLOCK_MOVSS
9666 || u32IntrState == VMX_VMCS_GUEST_INT_STATE_BLOCK_STI)
9667 {
9668 HMVMX_CHECK_BREAK(u32ActivityState == VMX_VMCS_GUEST_ACTIVITY_ACTIVE, VMX_IGS_ACTIVITY_STATE_ACTIVE_INVALID);
9669 }
9670
9671 /** @todo Activity state and injecting interrupts. Left as a todo since we
9672 * currently don't use activity states but ACTIVE. */
9673
9674 HMVMX_CHECK_BREAK( !(pVmcsInfo->u32EntryCtls & VMX_ENTRY_CTLS_ENTRY_TO_SMM)
9675 || u32ActivityState != VMX_VMCS_GUEST_ACTIVITY_SIPI_WAIT, VMX_IGS_ACTIVITY_STATE_SIPI_WAIT_INVALID);
9676
9677 /* Guest interruptibility-state. */
9678 HMVMX_CHECK_BREAK(!(u32IntrState & 0xffffffe0), VMX_IGS_INTERRUPTIBILITY_STATE_RESERVED);
9679 HMVMX_CHECK_BREAK((u32IntrState & (VMX_VMCS_GUEST_INT_STATE_BLOCK_STI | VMX_VMCS_GUEST_INT_STATE_BLOCK_MOVSS))
9680 != (VMX_VMCS_GUEST_INT_STATE_BLOCK_STI | VMX_VMCS_GUEST_INT_STATE_BLOCK_MOVSS),
9681 VMX_IGS_INTERRUPTIBILITY_STATE_STI_MOVSS_INVALID);
9682 HMVMX_CHECK_BREAK( (u32Eflags & X86_EFL_IF)
9683 || !(u32IntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_STI),
9684 VMX_IGS_INTERRUPTIBILITY_STATE_STI_EFL_INVALID);
9685 if (VMX_ENTRY_INT_INFO_IS_EXT_INT(u32EntryInfo))
9686 {
9687 HMVMX_CHECK_BREAK( !(u32IntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_STI)
9688 && !(u32IntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_MOVSS),
9689 VMX_IGS_INTERRUPTIBILITY_STATE_EXT_INT_INVALID);
9690 }
9691 else if (VMX_ENTRY_INT_INFO_IS_XCPT_NMI(u32EntryInfo))
9692 {
9693 HMVMX_CHECK_BREAK(!(u32IntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_MOVSS),
9694 VMX_IGS_INTERRUPTIBILITY_STATE_MOVSS_INVALID);
9695 HMVMX_CHECK_BREAK(!(u32IntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_STI),
9696 VMX_IGS_INTERRUPTIBILITY_STATE_STI_INVALID);
9697 }
9698 /** @todo Assumes the processor is not in SMM. */
9699 HMVMX_CHECK_BREAK(!(u32IntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_SMI),
9700 VMX_IGS_INTERRUPTIBILITY_STATE_SMI_INVALID);
9701 HMVMX_CHECK_BREAK( !(pVmcsInfo->u32EntryCtls & VMX_ENTRY_CTLS_ENTRY_TO_SMM)
9702 || (u32IntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_SMI),
9703 VMX_IGS_INTERRUPTIBILITY_STATE_SMI_SMM_INVALID);
9704 if ( (pVmcsInfo->u32PinCtls & VMX_PIN_CTLS_VIRT_NMI)
9705 && VMX_ENTRY_INT_INFO_IS_XCPT_NMI(u32EntryInfo))
9706 {
9707 HMVMX_CHECK_BREAK(!(u32IntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_NMI),
9708 VMX_IGS_INTERRUPTIBILITY_STATE_NMI_INVALID);
9709 }
9710
9711 /* Pending debug exceptions. */
9712 rc = VMXReadVmcsNw(VMX_VMCS_GUEST_PENDING_DEBUG_XCPTS, &u64Val);
9713 AssertRC(rc);
9714 /* Bits 63:15, Bit 13, Bits 11:4 MBZ. */
9715 HMVMX_CHECK_BREAK(!(u64Val & UINT64_C(0xffffffffffffaff0)), VMX_IGS_LONGMODE_PENDING_DEBUG_RESERVED);
9716 u32Val = u64Val; /* For pending debug exceptions checks below. */
9717
9718 if ( (u32IntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_STI)
9719 || (u32IntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_MOVSS)
9720 || u32ActivityState == VMX_VMCS_GUEST_ACTIVITY_HLT)
9721 {
9722 if ( (u32Eflags & X86_EFL_TF)
9723 && !(u64DebugCtlMsr & RT_BIT_64(1))) /* Bit 1 is IA32_DEBUGCTL.BTF. */
9724 {
9725 /* Bit 14 is PendingDebug.BS. */
9726 HMVMX_CHECK_BREAK(u32Val & RT_BIT(14), VMX_IGS_PENDING_DEBUG_XCPT_BS_NOT_SET);
9727 }
9728 if ( !(u32Eflags & X86_EFL_TF)
9729 || (u64DebugCtlMsr & RT_BIT_64(1))) /* Bit 1 is IA32_DEBUGCTL.BTF. */
9730 {
9731 /* Bit 14 is PendingDebug.BS. */
9732 HMVMX_CHECK_BREAK(!(u32Val & RT_BIT(14)), VMX_IGS_PENDING_DEBUG_XCPT_BS_NOT_CLEAR);
9733 }
9734 }
9735
9736 /* VMCS link pointer. */
9737 rc = VMXReadVmcs64(VMX_VMCS64_GUEST_VMCS_LINK_PTR_FULL, &u64Val);
9738 AssertRC(rc);
9739 if (u64Val != UINT64_C(0xffffffffffffffff))
9740 {
9741 HMVMX_CHECK_BREAK(!(u64Val & 0xfff), VMX_IGS_VMCS_LINK_PTR_RESERVED);
9742 /** @todo Bits beyond the processor's physical-address width MBZ. */
9743 /** @todo SMM checks. */
9744 Assert(pVmcsInfo->HCPhysShadowVmcs == u64Val);
9745 Assert(pVmcsInfo->pvShadowVmcs);
9746 VMXVMCSREVID VmcsRevId;
9747 VmcsRevId.u = *(uint32_t *)pVmcsInfo->pvShadowVmcs;
9748 HMVMX_CHECK_BREAK(VmcsRevId.n.u31RevisionId == RT_BF_GET(pVM->hm.s.vmx.Msrs.u64Basic, VMX_BF_BASIC_VMCS_ID),
9749 VMX_IGS_VMCS_LINK_PTR_SHADOW_VMCS_ID_INVALID);
9750 HMVMX_CHECK_BREAK(VmcsRevId.n.fIsShadowVmcs == (uint32_t)!!(pVmcsInfo->u32ProcCtls2 & VMX_PROC_CTLS2_VMCS_SHADOWING),
9751 VMX_IGS_VMCS_LINK_PTR_NOT_SHADOW);
9752 }
9753
9754 /** @todo Checks on Guest Page-Directory-Pointer-Table Entries when guest is
9755 * not using nested paging? */
9756 if ( pVM->hm.s.fNestedPaging
9757 && !fLongModeGuest
9758 && CPUMIsGuestInPAEModeEx(pCtx))
9759 {
9760 rc = VMXReadVmcs64(VMX_VMCS64_GUEST_PDPTE0_FULL, &u64Val);
9761 AssertRC(rc);
9762 HMVMX_CHECK_BREAK(!(u64Val & X86_PDPE_PAE_MBZ_MASK), VMX_IGS_PAE_PDPTE_RESERVED);
9763
9764 rc = VMXReadVmcs64(VMX_VMCS64_GUEST_PDPTE1_FULL, &u64Val);
9765 AssertRC(rc);
9766 HMVMX_CHECK_BREAK(!(u64Val & X86_PDPE_PAE_MBZ_MASK), VMX_IGS_PAE_PDPTE_RESERVED);
9767
9768 rc = VMXReadVmcs64(VMX_VMCS64_GUEST_PDPTE2_FULL, &u64Val);
9769 AssertRC(rc);
9770 HMVMX_CHECK_BREAK(!(u64Val & X86_PDPE_PAE_MBZ_MASK), VMX_IGS_PAE_PDPTE_RESERVED);
9771
9772 rc = VMXReadVmcs64(VMX_VMCS64_GUEST_PDPTE3_FULL, &u64Val);
9773 AssertRC(rc);
9774 HMVMX_CHECK_BREAK(!(u64Val & X86_PDPE_PAE_MBZ_MASK), VMX_IGS_PAE_PDPTE_RESERVED);
9775 }
9776
9777 /* Shouldn't happen but distinguish it from AssertRCBreak() errors. */
9778 if (uError == VMX_IGS_ERROR)
9779 uError = VMX_IGS_REASON_NOT_FOUND;
9780 } while (0);
9781
9782 pVCpu->hm.s.u32HMError = uError;
9783 return uError;
9784
9785#undef HMVMX_ERROR_BREAK
9786#undef HMVMX_CHECK_BREAK
9787}
9788
9789
9790/**
9791 * Map the APIC-access page for virtualizing APIC accesses.
9792 *
9793 * This can cause a longjumps to R3 due to the acquisition of the PGM lock. Hence,
9794 * this not done as part of exporting guest state, see @bugref{8721}.
9795 *
9796 * @returns VBox status code.
9797 * @param pVCpu The cross context virtual CPU structure.
9798 */
9799static int hmR0VmxMapHCApicAccessPage(PVMCPUCC pVCpu)
9800{
9801 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
9802 uint64_t const u64MsrApicBase = APICGetBaseMsrNoCheck(pVCpu);
9803
9804 Assert(PDMHasApic(pVM));
9805 Assert(u64MsrApicBase);
9806
9807 RTGCPHYS const GCPhysApicBase = u64MsrApicBase & PAGE_BASE_GC_MASK;
9808 Log4Func(("Mappping HC APIC-access page at %#RGp\n", GCPhysApicBase));
9809
9810 /* Unalias the existing mapping. */
9811 int rc = PGMHandlerPhysicalReset(pVM, GCPhysApicBase);
9812 AssertRCReturn(rc, rc);
9813
9814 /* Map the HC APIC-access page in place of the MMIO page, also updates the shadow page tables if necessary. */
9815 Assert(pVM->hm.s.vmx.HCPhysApicAccess != NIL_RTHCPHYS);
9816 rc = IOMMMIOMapMMIOHCPage(pVM, pVCpu, GCPhysApicBase, pVM->hm.s.vmx.HCPhysApicAccess, X86_PTE_RW | X86_PTE_P);
9817 AssertRCReturn(rc, rc);
9818
9819 /* Update the per-VCPU cache of the APIC base MSR. */
9820 pVCpu->hm.s.vmx.u64GstMsrApicBase = u64MsrApicBase;
9821 return VINF_SUCCESS;
9822}
9823
9824
9825/**
9826 * Worker function passed to RTMpOnSpecific() that is to be called on the target
9827 * CPU.
9828 *
9829 * @param idCpu The ID for the CPU the function is called on.
9830 * @param pvUser1 Null, not used.
9831 * @param pvUser2 Null, not used.
9832 */
9833static DECLCALLBACK(void) hmR0DispatchHostNmi(RTCPUID idCpu, void *pvUser1, void *pvUser2)
9834{
9835 RT_NOREF3(idCpu, pvUser1, pvUser2);
9836 VMXDispatchHostNmi();
9837}
9838
9839
9840/**
9841 * Dispatching an NMI on the host CPU that received it.
9842 *
9843 * @returns VBox status code.
9844 * @param pVCpu The cross context virtual CPU structure.
9845 * @param pVmcsInfo The VMCS info. object corresponding to the VMCS that was
9846 * executing when receiving the host NMI in VMX non-root
9847 * operation.
9848 */
9849static int hmR0VmxExitHostNmi(PVMCPUCC pVCpu, PCVMXVMCSINFO pVmcsInfo)
9850{
9851 RTCPUID const idCpu = pVmcsInfo->idHostCpuExec;
9852 Assert(idCpu != NIL_RTCPUID);
9853
9854 /*
9855 * We don't want to delay dispatching the NMI any more than we have to. However,
9856 * we have already chosen -not- to dispatch NMIs when interrupts were still disabled
9857 * after executing guest or nested-guest code for the following reasons:
9858 *
9859 * - We would need to perform VMREADs with interrupts disabled and is orders of
9860 * magnitude worse when we run as a guest hypervisor without VMCS shadowing
9861 * supported by the host hypervisor.
9862 *
9863 * - It affects the common VM-exit scenario and keeps interrupts disabled for a
9864 * longer period of time just for handling an edge case like host NMIs which do
9865 * not occur nearly as frequently as other VM-exits.
9866 *
9867 * Let's cover the most likely scenario first. Check if we are on the target CPU
9868 * and dispatch the NMI right away. This should be much faster than calling into
9869 * RTMpOnSpecific() machinery.
9870 */
9871 bool fDispatched = false;
9872 RTCCUINTREG const fEFlags = ASMIntDisableFlags();
9873 if (idCpu == RTMpCpuId())
9874 {
9875 VMXDispatchHostNmi();
9876 fDispatched = true;
9877 }
9878 ASMSetFlags(fEFlags);
9879 if (fDispatched)
9880 {
9881 STAM_REL_COUNTER_INC(&pVCpu->hm.s.StatExitHostNmiInGC);
9882 return VINF_SUCCESS;
9883 }
9884
9885 /*
9886 * RTMpOnSpecific() waits until the worker function has run on the target CPU. So
9887 * there should be no race or recursion even if we are unlucky enough to be preempted
9888 * (to the target CPU) without dispatching the host NMI above.
9889 */
9890 STAM_REL_COUNTER_INC(&pVCpu->hm.s.StatExitHostNmiInGCIpi);
9891 return RTMpOnSpecific(idCpu, &hmR0DispatchHostNmi, NULL /* pvUser1 */, NULL /* pvUser2 */);
9892}
9893
9894
9895#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
9896/**
9897 * Merges the guest with the nested-guest MSR bitmap in preparation of executing the
9898 * nested-guest using hardware-assisted VMX.
9899 *
9900 * @param pVCpu The cross context virtual CPU structure.
9901 * @param pVmcsInfoNstGst The nested-guest VMCS info. object.
9902 * @param pVmcsInfoGst The guest VMCS info. object.
9903 */
9904static void hmR0VmxMergeMsrBitmapNested(PCVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfoNstGst, PCVMXVMCSINFO pVmcsInfoGst)
9905{
9906 uint32_t const cbMsrBitmap = X86_PAGE_4K_SIZE;
9907 uint64_t *pu64MsrBitmap = (uint64_t *)pVmcsInfoNstGst->pvMsrBitmap;
9908 Assert(pu64MsrBitmap);
9909
9910 /*
9911 * We merge the guest MSR bitmap with the nested-guest MSR bitmap such that any
9912 * MSR that is intercepted by the guest is also intercepted while executing the
9913 * nested-guest using hardware-assisted VMX.
9914 *
9915 * Note! If the nested-guest is not using an MSR bitmap, ever MSR must cause a
9916 * nested-guest VM-exit even if the outer guest is not intercepting some
9917 * MSRs. We cannot assume the caller has initialized the nested-guest
9918 * MSR bitmap in this case.
9919 *
9920 * The guest hypervisor may also switch whether it uses MSR bitmaps for
9921 * each VM-entry, hence initializing it once per-VM while setting up the
9922 * nested-guest VMCS is not sufficient.
9923 */
9924 PCVMXVVMCS pVmcsNstGst = pVCpu->cpum.GstCtx.hwvirt.vmx.CTX_SUFF(pVmcs);
9925 if (pVmcsNstGst->u32ProcCtls & VMX_PROC_CTLS_USE_MSR_BITMAPS)
9926 {
9927 uint64_t const *pu64MsrBitmapNstGst = (uint64_t const *)pVCpu->cpum.GstCtx.hwvirt.vmx.CTX_SUFF(pvMsrBitmap);
9928 uint64_t const *pu64MsrBitmapGst = (uint64_t const *)pVmcsInfoGst->pvMsrBitmap;
9929 Assert(pu64MsrBitmapNstGst);
9930 Assert(pu64MsrBitmapGst);
9931
9932 uint32_t const cFrags = cbMsrBitmap / sizeof(uint64_t);
9933 for (uint32_t i = 0; i < cFrags; i++)
9934 pu64MsrBitmap[i] = pu64MsrBitmapNstGst[i] | pu64MsrBitmapGst[i];
9935 }
9936 else
9937 ASMMemFill32(pu64MsrBitmap, cbMsrBitmap, UINT32_C(0xffffffff));
9938}
9939
9940
9941/**
9942 * Merges the guest VMCS in to the nested-guest VMCS controls in preparation of
9943 * hardware-assisted VMX execution of the nested-guest.
9944 *
9945 * For a guest, we don't modify these controls once we set up the VMCS and hence
9946 * this function is never called.
9947 *
9948 * For nested-guests since the guest hypervisor provides these controls on every
9949 * nested-guest VM-entry and could potentially change them everytime we need to
9950 * merge them before every nested-guest VM-entry.
9951 *
9952 * @returns VBox status code.
9953 * @param pVCpu The cross context virtual CPU structure.
9954 */
9955static int hmR0VmxMergeVmcsNested(PVMCPUCC pVCpu)
9956{
9957 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
9958 PCVMXVMCSINFO pVmcsInfoGst = &pVCpu->hm.s.vmx.VmcsInfo;
9959 PCVMXVVMCS pVmcsNstGst = pVCpu->cpum.GstCtx.hwvirt.vmx.CTX_SUFF(pVmcs);
9960 Assert(pVmcsNstGst);
9961
9962 /*
9963 * Merge the controls with the requirements of the guest VMCS.
9964 *
9965 * We do not need to validate the nested-guest VMX features specified in the nested-guest
9966 * VMCS with the features supported by the physical CPU as it's already done by the
9967 * VMLAUNCH/VMRESUME instruction emulation.
9968 *
9969 * This is because the VMX features exposed by CPUM (through CPUID/MSRs) to the guest are
9970 * derived from the VMX features supported by the physical CPU.
9971 */
9972
9973 /* Pin-based VM-execution controls. */
9974 uint32_t const u32PinCtls = pVmcsNstGst->u32PinCtls | pVmcsInfoGst->u32PinCtls;
9975
9976 /* Processor-based VM-execution controls. */
9977 uint32_t u32ProcCtls = (pVmcsNstGst->u32ProcCtls & ~VMX_PROC_CTLS_USE_IO_BITMAPS)
9978 | (pVmcsInfoGst->u32ProcCtls & ~( VMX_PROC_CTLS_INT_WINDOW_EXIT
9979 | VMX_PROC_CTLS_NMI_WINDOW_EXIT
9980 | VMX_PROC_CTLS_USE_TPR_SHADOW
9981 | VMX_PROC_CTLS_MONITOR_TRAP_FLAG));
9982
9983 /* Secondary processor-based VM-execution controls. */
9984 uint32_t const u32ProcCtls2 = (pVmcsNstGst->u32ProcCtls2 & ~VMX_PROC_CTLS2_VPID)
9985 | (pVmcsInfoGst->u32ProcCtls2 & ~( VMX_PROC_CTLS2_VIRT_APIC_ACCESS
9986 | VMX_PROC_CTLS2_INVPCID
9987 | VMX_PROC_CTLS2_VMCS_SHADOWING
9988 | VMX_PROC_CTLS2_RDTSCP
9989 | VMX_PROC_CTLS2_XSAVES_XRSTORS
9990 | VMX_PROC_CTLS2_APIC_REG_VIRT
9991 | VMX_PROC_CTLS2_VIRT_INT_DELIVERY
9992 | VMX_PROC_CTLS2_VMFUNC));
9993
9994 /*
9995 * VM-entry controls:
9996 * These controls contains state that depends on the nested-guest state (primarily
9997 * EFER MSR) and is thus not constant between VMLAUNCH/VMRESUME and the nested-guest
9998 * VM-exit. Although the guest hypervisor cannot change it, we need to in order to
9999 * properly continue executing the nested-guest if the EFER MSR changes but does not
10000 * cause a nested-guest VM-exits.
10001 *
10002 * VM-exit controls:
10003 * These controls specify the host state on return. We cannot use the controls from
10004 * the guest hypervisor state as is as it would contain the guest state rather than
10005 * the host state. Since the host state is subject to change (e.g. preemption, trips
10006 * to ring-3, longjmp and rescheduling to a different host CPU) they are not constant
10007 * through VMLAUNCH/VMRESUME and the nested-guest VM-exit.
10008 *
10009 * VM-entry MSR-load:
10010 * The guest MSRs from the VM-entry MSR-load area are already loaded into the guest-CPU
10011 * context by the VMLAUNCH/VMRESUME instruction emulation.
10012 *
10013 * VM-exit MSR-store:
10014 * The VM-exit emulation will take care of populating the MSRs from the guest-CPU context
10015 * back into the VM-exit MSR-store area.
10016 *
10017 * VM-exit MSR-load areas:
10018 * This must contain the real host MSRs with hardware-assisted VMX execution. Hence, we
10019 * can entirely ignore what the guest hypervisor wants to load here.
10020 */
10021
10022 /*
10023 * Exception bitmap.
10024 *
10025 * We could remove #UD from the guest bitmap and merge it with the nested-guest bitmap
10026 * here (and avoid doing anything while exporting nested-guest state), but to keep the
10027 * code more flexible if intercepting exceptions become more dynamic in the future we do
10028 * it as part of exporting the nested-guest state.
10029 */
10030 uint32_t const u32XcptBitmap = pVmcsNstGst->u32XcptBitmap | pVmcsInfoGst->u32XcptBitmap;
10031
10032 /*
10033 * CR0/CR4 guest/host mask.
10034 *
10035 * Modifications by the nested-guest to CR0/CR4 bits owned by the host and the guest must
10036 * cause VM-exits, so we need to merge them here.
10037 */
10038 uint64_t const u64Cr0Mask = pVmcsNstGst->u64Cr0Mask.u | pVmcsInfoGst->u64Cr0Mask;
10039 uint64_t const u64Cr4Mask = pVmcsNstGst->u64Cr4Mask.u | pVmcsInfoGst->u64Cr4Mask;
10040
10041 /*
10042 * Page-fault error-code mask and match.
10043 *
10044 * Although we require unrestricted guest execution (and thereby nested-paging) for
10045 * hardware-assisted VMX execution of nested-guests and thus the outer guest doesn't
10046 * normally intercept #PFs, it might intercept them for debugging purposes.
10047 *
10048 * If the outer guest is not intercepting #PFs, we can use the nested-guest #PF filters.
10049 * If the outer guest is intercepting #PFs, we must intercept all #PFs.
10050 */
10051 uint32_t u32XcptPFMask;
10052 uint32_t u32XcptPFMatch;
10053 if (!(pVmcsInfoGst->u32XcptBitmap & RT_BIT(X86_XCPT_PF)))
10054 {
10055 u32XcptPFMask = pVmcsNstGst->u32XcptPFMask;
10056 u32XcptPFMatch = pVmcsNstGst->u32XcptPFMatch;
10057 }
10058 else
10059 {
10060 u32XcptPFMask = 0;
10061 u32XcptPFMatch = 0;
10062 }
10063
10064 /*
10065 * Pause-Loop exiting.
10066 */
10067 uint32_t const cPleGapTicks = RT_MIN(pVM->hm.s.vmx.cPleGapTicks, pVmcsNstGst->u32PleGap);
10068 uint32_t const cPleWindowTicks = RT_MIN(pVM->hm.s.vmx.cPleWindowTicks, pVmcsNstGst->u32PleWindow);
10069
10070 /*
10071 * Pending debug exceptions.
10072 * Currently just copy whatever the nested-guest provides us.
10073 */
10074 uint64_t const uPendingDbgXcpts = pVmcsNstGst->u64GuestPendingDbgXcpts.u;
10075
10076 /*
10077 * I/O Bitmap.
10078 *
10079 * We do not use the I/O bitmap that may be provided by the guest hypervisor as we always
10080 * intercept all I/O port accesses.
10081 */
10082 Assert(u32ProcCtls & VMX_PROC_CTLS_UNCOND_IO_EXIT);
10083 Assert(!(u32ProcCtls & VMX_PROC_CTLS_USE_IO_BITMAPS));
10084
10085 /*
10086 * VMCS shadowing.
10087 *
10088 * We do not yet expose VMCS shadowing to the guest and thus VMCS shadowing should not be
10089 * enabled while executing the nested-guest.
10090 */
10091 Assert(!(u32ProcCtls2 & VMX_PROC_CTLS2_VMCS_SHADOWING));
10092
10093 /*
10094 * APIC-access page.
10095 */
10096 RTHCPHYS HCPhysApicAccess;
10097 if (u32ProcCtls2 & VMX_PROC_CTLS2_VIRT_APIC_ACCESS)
10098 {
10099 Assert(pVM->hm.s.vmx.Msrs.ProcCtls2.n.allowed1 & VMX_PROC_CTLS2_VIRT_APIC_ACCESS);
10100 RTGCPHYS const GCPhysApicAccess = pVmcsNstGst->u64AddrApicAccess.u;
10101
10102 /** @todo NSTVMX: This is not really correct but currently is required to make
10103 * things work. We need to re-enable the page handler when we fallback to
10104 * IEM execution of the nested-guest! */
10105 PGMHandlerPhysicalPageTempOff(pVM, GCPhysApicAccess, GCPhysApicAccess);
10106
10107 void *pvPage;
10108 PGMPAGEMAPLOCK PgLockApicAccess;
10109 int rc = PGMPhysGCPhys2CCPtr(pVM, GCPhysApicAccess, &pvPage, &PgLockApicAccess);
10110 if (RT_SUCCESS(rc))
10111 {
10112 rc = PGMPhysGCPhys2HCPhys(pVM, GCPhysApicAccess, &HCPhysApicAccess);
10113 AssertMsgRCReturn(rc, ("Failed to get host-physical address for APIC-access page at %#RGp\n", GCPhysApicAccess), rc);
10114
10115 /** @todo Handle proper releasing of page-mapping lock later. */
10116 PGMPhysReleasePageMappingLock(pVCpu->CTX_SUFF(pVM), &PgLockApicAccess);
10117 }
10118 else
10119 return rc;
10120 }
10121 else
10122 HCPhysApicAccess = 0;
10123
10124 /*
10125 * Virtual-APIC page and TPR threshold.
10126 */
10127 PVMXVMCSINFO pVmcsInfoNstGst = &pVCpu->hm.s.vmx.VmcsInfoNstGst;
10128 RTHCPHYS HCPhysVirtApic;
10129 uint32_t u32TprThreshold;
10130 if (u32ProcCtls & VMX_PROC_CTLS_USE_TPR_SHADOW)
10131 {
10132 Assert(pVM->hm.s.vmx.Msrs.ProcCtls.n.allowed1 & VMX_PROC_CTLS_USE_TPR_SHADOW);
10133 RTGCPHYS const GCPhysVirtApic = pVmcsNstGst->u64AddrVirtApic.u;
10134
10135 void *pvPage;
10136 PGMPAGEMAPLOCK PgLockVirtApic;
10137 int rc = PGMPhysGCPhys2CCPtr(pVM, GCPhysVirtApic, &pvPage, &PgLockVirtApic);
10138 if (RT_SUCCESS(rc))
10139 {
10140 rc = PGMPhysGCPhys2HCPhys(pVM, GCPhysVirtApic, &HCPhysVirtApic);
10141 AssertMsgRCReturn(rc, ("Failed to get host-physical address for virtual-APIC page at %#RGp\n", GCPhysVirtApic), rc);
10142
10143 /** @todo Handle proper releasing of page-mapping lock later. */
10144 PGMPhysReleasePageMappingLock(pVCpu->CTX_SUFF(pVM), &PgLockVirtApic);
10145 }
10146 else
10147 return rc;
10148
10149 u32TprThreshold = pVmcsNstGst->u32TprThreshold;
10150 }
10151 else
10152 {
10153 HCPhysVirtApic = 0;
10154 u32TprThreshold = 0;
10155
10156 /*
10157 * We must make sure CR8 reads/write must cause VM-exits when TPR shadowing is not
10158 * used by the guest hypervisor. Preventing MMIO accesses to the physical APIC will
10159 * be taken care of by EPT/shadow paging.
10160 */
10161 if (pVM->hm.s.fAllow64BitGuests)
10162 {
10163 u32ProcCtls |= VMX_PROC_CTLS_CR8_STORE_EXIT
10164 | VMX_PROC_CTLS_CR8_LOAD_EXIT;
10165 }
10166 }
10167
10168 /*
10169 * Validate basic assumptions.
10170 */
10171 Assert(pVM->hm.s.vmx.fAllowUnrestricted);
10172 Assert(pVM->hm.s.vmx.Msrs.ProcCtls.n.allowed1 & VMX_PROC_CTLS_USE_SECONDARY_CTLS);
10173 Assert(hmGetVmxActiveVmcsInfo(pVCpu) == pVmcsInfoNstGst);
10174
10175 /*
10176 * Commit it to the nested-guest VMCS.
10177 */
10178 int rc = VINF_SUCCESS;
10179 if (pVmcsInfoNstGst->u32PinCtls != u32PinCtls)
10180 rc |= VMXWriteVmcs32(VMX_VMCS32_CTRL_PIN_EXEC, u32PinCtls);
10181 if (pVmcsInfoNstGst->u32ProcCtls != u32ProcCtls)
10182 rc |= VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, u32ProcCtls);
10183 if (pVmcsInfoNstGst->u32ProcCtls2 != u32ProcCtls2)
10184 rc |= VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC2, u32ProcCtls2);
10185 if (pVmcsInfoNstGst->u32XcptBitmap != u32XcptBitmap)
10186 rc |= VMXWriteVmcs32(VMX_VMCS32_CTRL_EXCEPTION_BITMAP, u32XcptBitmap);
10187 if (pVmcsInfoNstGst->u64Cr0Mask != u64Cr0Mask)
10188 rc |= VMXWriteVmcsNw(VMX_VMCS_CTRL_CR0_MASK, u64Cr0Mask);
10189 if (pVmcsInfoNstGst->u64Cr4Mask != u64Cr4Mask)
10190 rc |= VMXWriteVmcsNw(VMX_VMCS_CTRL_CR4_MASK, u64Cr4Mask);
10191 if (pVmcsInfoNstGst->u32XcptPFMask != u32XcptPFMask)
10192 rc |= VMXWriteVmcs32(VMX_VMCS32_CTRL_PAGEFAULT_ERROR_MASK, u32XcptPFMask);
10193 if (pVmcsInfoNstGst->u32XcptPFMatch != u32XcptPFMatch)
10194 rc |= VMXWriteVmcs32(VMX_VMCS32_CTRL_PAGEFAULT_ERROR_MATCH, u32XcptPFMatch);
10195 if ( !(u32ProcCtls & VMX_PROC_CTLS_PAUSE_EXIT)
10196 && (u32ProcCtls2 & VMX_PROC_CTLS2_PAUSE_LOOP_EXIT))
10197 {
10198 Assert(pVM->hm.s.vmx.Msrs.ProcCtls2.n.allowed1 & VMX_PROC_CTLS2_PAUSE_LOOP_EXIT);
10199 rc |= VMXWriteVmcs32(VMX_VMCS32_CTRL_PLE_GAP, cPleGapTicks);
10200 rc |= VMXWriteVmcs32(VMX_VMCS32_CTRL_PLE_WINDOW, cPleWindowTicks);
10201 }
10202 if (u32ProcCtls & VMX_PROC_CTLS_USE_TPR_SHADOW)
10203 {
10204 rc |= VMXWriteVmcs32(VMX_VMCS32_CTRL_TPR_THRESHOLD, u32TprThreshold);
10205 rc |= VMXWriteVmcs64(VMX_VMCS64_CTRL_VIRT_APIC_PAGEADDR_FULL, HCPhysVirtApic);
10206 }
10207 if (u32ProcCtls2 & VMX_PROC_CTLS2_VIRT_APIC_ACCESS)
10208 rc |= VMXWriteVmcs64(VMX_VMCS64_CTRL_APIC_ACCESSADDR_FULL, HCPhysApicAccess);
10209 rc |= VMXWriteVmcsNw(VMX_VMCS_GUEST_PENDING_DEBUG_XCPTS, uPendingDbgXcpts);
10210 AssertRC(rc);
10211
10212 /*
10213 * Update the nested-guest VMCS cache.
10214 */
10215 pVmcsInfoNstGst->u32PinCtls = u32PinCtls;
10216 pVmcsInfoNstGst->u32ProcCtls = u32ProcCtls;
10217 pVmcsInfoNstGst->u32ProcCtls2 = u32ProcCtls2;
10218 pVmcsInfoNstGst->u32XcptBitmap = u32XcptBitmap;
10219 pVmcsInfoNstGst->u64Cr0Mask = u64Cr0Mask;
10220 pVmcsInfoNstGst->u64Cr4Mask = u64Cr4Mask;
10221 pVmcsInfoNstGst->u32XcptPFMask = u32XcptPFMask;
10222 pVmcsInfoNstGst->u32XcptPFMatch = u32XcptPFMatch;
10223 pVmcsInfoNstGst->HCPhysVirtApic = HCPhysVirtApic;
10224
10225 /*
10226 * We need to flush the TLB if we are switching the APIC-access page address.
10227 * See Intel spec. 28.3.3.4 "Guidelines for Use of the INVEPT Instruction".
10228 */
10229 if (u32ProcCtls2 & VMX_PROC_CTLS2_VIRT_APIC_ACCESS)
10230 pVCpu->hm.s.vmx.fSwitchedNstGstFlushTlb = true;
10231
10232 /*
10233 * MSR bitmap.
10234 *
10235 * The MSR bitmap address has already been initialized while setting up the nested-guest
10236 * VMCS, here we need to merge the MSR bitmaps.
10237 */
10238 if (u32ProcCtls & VMX_PROC_CTLS_USE_MSR_BITMAPS)
10239 hmR0VmxMergeMsrBitmapNested(pVCpu, pVmcsInfoNstGst, pVmcsInfoGst);
10240
10241 return VINF_SUCCESS;
10242}
10243#endif /* VBOX_WITH_NESTED_HWVIRT_VMX */
10244
10245
10246/**
10247 * Does the preparations before executing guest code in VT-x.
10248 *
10249 * This may cause longjmps to ring-3 and may even result in rescheduling to the
10250 * recompiler/IEM. We must be cautious what we do here regarding committing
10251 * guest-state information into the VMCS assuming we assuredly execute the
10252 * guest in VT-x mode.
10253 *
10254 * If we fall back to the recompiler/IEM after updating the VMCS and clearing
10255 * the common-state (TRPM/forceflags), we must undo those changes so that the
10256 * recompiler/IEM can (and should) use them when it resumes guest execution.
10257 * Otherwise such operations must be done when we can no longer exit to ring-3.
10258 *
10259 * @returns Strict VBox status code (i.e. informational status codes too).
10260 * @retval VINF_SUCCESS if we can proceed with running the guest, interrupts
10261 * have been disabled.
10262 * @retval VINF_VMX_VMEXIT if a nested-guest VM-exit occurs (e.g., while evaluating
10263 * pending events).
10264 * @retval VINF_EM_RESET if a triple-fault occurs while injecting a
10265 * double-fault into the guest.
10266 * @retval VINF_EM_DBG_STEPPED if @a fStepping is true and an event was
10267 * dispatched directly.
10268 * @retval VINF_* scheduling changes, we have to go back to ring-3.
10269 *
10270 * @param pVCpu The cross context virtual CPU structure.
10271 * @param pVmxTransient The VMX-transient structure.
10272 * @param fStepping Whether we are single-stepping the guest in the
10273 * hypervisor debugger. Makes us ignore some of the reasons
10274 * for returning to ring-3, and return VINF_EM_DBG_STEPPED
10275 * if event dispatching took place.
10276 */
10277static VBOXSTRICTRC hmR0VmxPreRunGuest(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient, bool fStepping)
10278{
10279 Assert(VMMRZCallRing3IsEnabled(pVCpu));
10280
10281 Log4Func(("fIsNested=%RTbool fStepping=%RTbool\n", pVmxTransient->fIsNestedGuest, fStepping));
10282
10283#ifdef VBOX_WITH_NESTED_HWVIRT_ONLY_IN_IEM
10284 if (pVmxTransient->fIsNestedGuest)
10285 {
10286 RT_NOREF2(pVCpu, fStepping);
10287 Log2Func(("Rescheduling to IEM due to nested-hwvirt or forced IEM exec -> VINF_EM_RESCHEDULE_REM\n"));
10288 return VINF_EM_RESCHEDULE_REM;
10289 }
10290#endif
10291
10292#ifdef VBOX_WITH_2X_4GB_ADDR_SPACE_IN_R0
10293 PGMRZDynMapFlushAutoSet(pVCpu);
10294#endif
10295
10296 /*
10297 * Check and process force flag actions, some of which might require us to go back to ring-3.
10298 */
10299 VBOXSTRICTRC rcStrict = hmR0VmxCheckForceFlags(pVCpu, fStepping);
10300 if (rcStrict == VINF_SUCCESS)
10301 {
10302 /* FFs don't get set all the time. */
10303#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
10304 if ( pVmxTransient->fIsNestedGuest
10305 && !CPUMIsGuestInVmxNonRootMode(&pVCpu->cpum.GstCtx))
10306 {
10307 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchNstGstVmexit);
10308 return VINF_VMX_VMEXIT;
10309 }
10310#endif
10311 }
10312 else
10313 return rcStrict;
10314
10315 /*
10316 * Virtualize memory-mapped accesses to the physical APIC (may take locks).
10317 */
10318 /** @todo Doing this from ring-3 after VM setup phase causes a
10319 * VERR_IOM_MMIO_RANGE_NOT_FOUND guru while booting Visa 64 SMP VM. No
10320 * idea why atm. */
10321 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
10322 if ( !pVCpu->hm.s.vmx.u64GstMsrApicBase
10323 && (pVM->hm.s.vmx.Msrs.ProcCtls2.n.allowed1 & VMX_PROC_CTLS2_VIRT_APIC_ACCESS)
10324 && PDMHasApic(pVM))
10325 {
10326 int rc = hmR0VmxMapHCApicAccessPage(pVCpu);
10327 AssertRCReturn(rc, rc);
10328 }
10329
10330#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
10331 /*
10332 * Merge guest VMCS controls with the nested-guest VMCS controls.
10333 *
10334 * Even if we have not executed the guest prior to this (e.g. when resuming from a
10335 * saved state), we should be okay with merging controls as we initialize the
10336 * guest VMCS controls as part of VM setup phase.
10337 */
10338 if ( pVmxTransient->fIsNestedGuest
10339 && !pVCpu->hm.s.vmx.fMergedNstGstCtls)
10340 {
10341 int rc = hmR0VmxMergeVmcsNested(pVCpu);
10342 AssertRCReturn(rc, rc);
10343 pVCpu->hm.s.vmx.fMergedNstGstCtls = true;
10344 }
10345#endif
10346
10347 /*
10348 * Evaluate events to be injected into the guest.
10349 *
10350 * Events in TRPM can be injected without inspecting the guest state.
10351 * If any new events (interrupts/NMI) are pending currently, we try to set up the
10352 * guest to cause a VM-exit the next time they are ready to receive the event.
10353 *
10354 * With nested-guests, evaluating pending events may cause VM-exits.
10355 */
10356 if (TRPMHasTrap(pVCpu))
10357 {
10358 Assert(!pVmxTransient->fIsNestedGuest || !pVCpu->cpum.GstCtx.hwvirt.vmx.fInterceptEvents);
10359 hmR0VmxTrpmTrapToPendingEvent(pVCpu);
10360 }
10361
10362 uint32_t fIntrState;
10363 rcStrict = hmR0VmxEvaluatePendingEvent(pVCpu, pVmxTransient, &fIntrState);
10364
10365#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
10366 /*
10367 * While evaluating pending events if something failed (unlikely) or if we were
10368 * preparing to run a nested-guest but performed a nested-guest VM-exit, we should bail.
10369 */
10370 if (rcStrict != VINF_SUCCESS)
10371 return rcStrict;
10372 if ( pVmxTransient->fIsNestedGuest
10373 && !CPUMIsGuestInVmxNonRootMode(&pVCpu->cpum.GstCtx))
10374 {
10375 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchNstGstVmexit);
10376 return VINF_VMX_VMEXIT;
10377 }
10378#else
10379 Assert(rcStrict == VINF_SUCCESS);
10380#endif
10381
10382 /*
10383 * Event injection may take locks (currently the PGM lock for real-on-v86 case) and thus
10384 * needs to be done with longjmps or interrupts + preemption enabled. Event injection might
10385 * also result in triple-faulting the VM.
10386 *
10387 * With nested-guests, the above does not apply since unrestricted guest execution is a
10388 * requirement. Regardless, we do this here to avoid duplicating code elsewhere.
10389 */
10390 rcStrict = hmR0VmxInjectPendingEvent(pVCpu, pVmxTransient, fIntrState, fStepping);
10391 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
10392 { /* likely */ }
10393 else
10394 {
10395 AssertMsg(rcStrict == VINF_EM_RESET || (rcStrict == VINF_EM_DBG_STEPPED && fStepping),
10396 ("%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
10397 return rcStrict;
10398 }
10399
10400 /*
10401 * A longjump might result in importing CR3 even for VM-exits that don't necessarily
10402 * import CR3 themselves. We will need to update them here, as even as late as the above
10403 * hmR0VmxInjectPendingEvent() call may lazily import guest-CPU state on demand causing
10404 * the below force flags to be set.
10405 */
10406 if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_HM_UPDATE_CR3))
10407 {
10408 Assert(!(ASMAtomicUoReadU64(&pVCpu->cpum.GstCtx.fExtrn) & CPUMCTX_EXTRN_CR3));
10409 int rc2 = PGMUpdateCR3(pVCpu, CPUMGetGuestCR3(pVCpu));
10410 AssertMsgReturn(rc2 == VINF_SUCCESS || rc2 == VINF_PGM_SYNC_CR3,
10411 ("%Rrc\n", rc2), RT_FAILURE_NP(rc2) ? rc2 : VERR_IPE_UNEXPECTED_INFO_STATUS);
10412 Assert(!VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_HM_UPDATE_CR3));
10413 }
10414 if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_HM_UPDATE_PAE_PDPES))
10415 {
10416 PGMGstUpdatePaePdpes(pVCpu, &pVCpu->hm.s.aPdpes[0]);
10417 Assert(!VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_HM_UPDATE_PAE_PDPES));
10418 }
10419
10420#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
10421 /* Paranoia. */
10422 Assert(!pVmxTransient->fIsNestedGuest || CPUMIsGuestInVmxNonRootMode(&pVCpu->cpum.GstCtx));
10423#endif
10424
10425 /*
10426 * No longjmps to ring-3 from this point on!!!
10427 * Asserts() will still longjmp to ring-3 (but won't return), which is intentional, better than a kernel panic.
10428 * This also disables flushing of the R0-logger instance (if any).
10429 */
10430 VMMRZCallRing3Disable(pVCpu);
10431
10432 /*
10433 * Export the guest state bits.
10434 *
10435 * We cannot perform longjmps while loading the guest state because we do not preserve the
10436 * host/guest state (although the VMCS will be preserved) across longjmps which can cause
10437 * CPU migration.
10438 *
10439 * If we are injecting events to a real-on-v86 mode guest, we would have updated RIP and some segment
10440 * registers. Hence, exporting of the guest state needs to be done -after- injection of events.
10441 */
10442 rcStrict = hmR0VmxExportGuestStateOptimal(pVCpu, pVmxTransient);
10443 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
10444 { /* likely */ }
10445 else
10446 {
10447 VMMRZCallRing3Enable(pVCpu);
10448 return rcStrict;
10449 }
10450
10451 /*
10452 * We disable interrupts so that we don't miss any interrupts that would flag preemption
10453 * (IPI/timers etc.) when thread-context hooks aren't used and we've been running with
10454 * preemption disabled for a while. Since this is purely to aid the
10455 * RTThreadPreemptIsPending() code, it doesn't matter that it may temporarily reenable and
10456 * disable interrupt on NT.
10457 *
10458 * We need to check for force-flags that could've possible been altered since we last
10459 * checked them (e.g. by PDMGetInterrupt() leaving the PDM critical section,
10460 * see @bugref{6398}).
10461 *
10462 * We also check a couple of other force-flags as a last opportunity to get the EMT back
10463 * to ring-3 before executing guest code.
10464 */
10465 pVmxTransient->fEFlags = ASMIntDisableFlags();
10466
10467 if ( ( !VM_FF_IS_ANY_SET(pVM, VM_FF_EMT_RENDEZVOUS | VM_FF_TM_VIRTUAL_SYNC)
10468 && !VMCPU_FF_IS_ANY_SET(pVCpu, VMCPU_FF_HM_TO_R3_MASK))
10469 || ( fStepping /* Optimized for the non-stepping case, so a bit of unnecessary work when stepping. */
10470 && !VMCPU_FF_IS_ANY_SET(pVCpu, VMCPU_FF_HM_TO_R3_MASK & ~(VMCPU_FF_TIMER | VMCPU_FF_PDM_CRITSECT))) )
10471 {
10472 if (!RTThreadPreemptIsPending(NIL_RTTHREAD))
10473 {
10474#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
10475 /*
10476 * If we are executing a nested-guest make sure that we should intercept subsequent
10477 * events. The one we are injecting might be part of VM-entry. This is mainly to keep
10478 * the VM-exit instruction emulation happy.
10479 */
10480 if (pVmxTransient->fIsNestedGuest)
10481 pVCpu->cpum.GstCtx.hwvirt.vmx.fInterceptEvents = true;
10482#endif
10483
10484 /*
10485 * We've injected any pending events. This is really the point of no return (to ring-3).
10486 *
10487 * Note! The caller expects to continue with interrupts & longjmps disabled on successful
10488 * returns from this function, so do -not- enable them here.
10489 */
10490 pVCpu->hm.s.Event.fPending = false;
10491 return VINF_SUCCESS;
10492 }
10493
10494 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchPendingHostIrq);
10495 rcStrict = VINF_EM_RAW_INTERRUPT;
10496 }
10497 else
10498 {
10499 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchHmToR3FF);
10500 rcStrict = VINF_EM_RAW_TO_R3;
10501 }
10502
10503 ASMSetFlags(pVmxTransient->fEFlags);
10504 VMMRZCallRing3Enable(pVCpu);
10505
10506 return rcStrict;
10507}
10508
10509
10510/**
10511 * Final preparations before executing guest code using hardware-assisted VMX.
10512 *
10513 * We can no longer get preempted to a different host CPU and there are no returns
10514 * to ring-3. We ignore any errors that may happen from this point (e.g. VMWRITE
10515 * failures), this function is not intended to fail sans unrecoverable hardware
10516 * errors.
10517 *
10518 * @param pVCpu The cross context virtual CPU structure.
10519 * @param pVmxTransient The VMX-transient structure.
10520 *
10521 * @remarks Called with preemption disabled.
10522 * @remarks No-long-jump zone!!!
10523 */
10524static void hmR0VmxPreRunGuestCommitted(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
10525{
10526 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
10527 Assert(VMMR0IsLogFlushDisabled(pVCpu));
10528 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
10529 Assert(!pVCpu->hm.s.Event.fPending);
10530
10531 /*
10532 * Indicate start of guest execution and where poking EMT out of guest-context is recognized.
10533 */
10534 VMCPU_ASSERT_STATE(pVCpu, VMCPUSTATE_STARTED_HM);
10535 VMCPU_SET_STATE(pVCpu, VMCPUSTATE_STARTED_EXEC);
10536
10537 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
10538 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
10539 PHMPHYSCPU pHostCpu = hmR0GetCurrentCpu();
10540 RTCPUID const idCurrentCpu = pHostCpu->idCpu;
10541
10542 if (!CPUMIsGuestFPUStateActive(pVCpu))
10543 {
10544 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatLoadGuestFpuState, x);
10545 if (CPUMR0LoadGuestFPU(pVM, pVCpu) == VINF_CPUM_HOST_CR0_MODIFIED)
10546 pVCpu->hm.s.fCtxChanged |= HM_CHANGED_HOST_CONTEXT;
10547 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatLoadGuestFpuState, x);
10548 STAM_COUNTER_INC(&pVCpu->hm.s.StatLoadGuestFpu);
10549 }
10550
10551 /*
10552 * Re-export the host state bits as we may've been preempted (only happens when
10553 * thread-context hooks are used or when the VM start function changes) or if
10554 * the host CR0 is modified while loading the guest FPU state above.
10555 *
10556 * The 64-on-32 switcher saves the (64-bit) host state into the VMCS and if we
10557 * changed the switcher back to 32-bit, we *must* save the 32-bit host state here,
10558 * see @bugref{8432}.
10559 *
10560 * This may also happen when switching to/from a nested-guest VMCS without leaving
10561 * ring-0.
10562 */
10563 if (pVCpu->hm.s.fCtxChanged & HM_CHANGED_HOST_CONTEXT)
10564 {
10565 hmR0VmxExportHostState(pVCpu);
10566 STAM_COUNTER_INC(&pVCpu->hm.s.StatExportHostState);
10567 }
10568 Assert(!(pVCpu->hm.s.fCtxChanged & HM_CHANGED_HOST_CONTEXT));
10569
10570 /*
10571 * Export the state shared between host and guest (FPU, debug, lazy MSRs).
10572 */
10573 if (pVCpu->hm.s.fCtxChanged & HM_CHANGED_VMX_HOST_GUEST_SHARED_STATE)
10574 hmR0VmxExportSharedState(pVCpu, pVmxTransient);
10575 AssertMsg(!pVCpu->hm.s.fCtxChanged, ("fCtxChanged=%#RX64\n", pVCpu->hm.s.fCtxChanged));
10576
10577 /*
10578 * Store status of the shared guest/host debug state at the time of VM-entry.
10579 */
10580 pVmxTransient->fWasGuestDebugStateActive = CPUMIsGuestDebugStateActive(pVCpu);
10581 pVmxTransient->fWasHyperDebugStateActive = CPUMIsHyperDebugStateActive(pVCpu);
10582
10583 /*
10584 * Always cache the TPR-shadow if the virtual-APIC page exists, thereby skipping
10585 * more than one conditional check. The post-run side of our code shall determine
10586 * if it needs to sync. the virtual APIC TPR with the TPR-shadow.
10587 */
10588 if (pVmcsInfo->pbVirtApic)
10589 pVmxTransient->u8GuestTpr = pVmcsInfo->pbVirtApic[XAPIC_OFF_TPR];
10590
10591 /*
10592 * Update the host MSRs values in the VM-exit MSR-load area.
10593 */
10594 if (!pVCpu->hm.s.vmx.fUpdatedHostAutoMsrs)
10595 {
10596 if (pVmcsInfo->cExitMsrLoad > 0)
10597 hmR0VmxUpdateAutoLoadHostMsrs(pVCpu, pVmcsInfo);
10598 pVCpu->hm.s.vmx.fUpdatedHostAutoMsrs = true;
10599 }
10600
10601 /*
10602 * Evaluate if we need to intercept guest RDTSC/P accesses. Set up the
10603 * VMX-preemption timer based on the next virtual sync clock deadline.
10604 */
10605 if ( !pVmxTransient->fUpdatedTscOffsettingAndPreemptTimer
10606 || idCurrentCpu != pVCpu->hm.s.idLastCpu)
10607 {
10608 hmR0VmxUpdateTscOffsettingAndPreemptTimer(pVCpu, pVmxTransient);
10609 pVmxTransient->fUpdatedTscOffsettingAndPreemptTimer = true;
10610 }
10611
10612 /* Record statistics of how often we use TSC offsetting as opposed to intercepting RDTSC/P. */
10613 bool const fIsRdtscIntercepted = RT_BOOL(pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_RDTSC_EXIT);
10614 if (!fIsRdtscIntercepted)
10615 STAM_COUNTER_INC(&pVCpu->hm.s.StatTscOffset);
10616 else
10617 STAM_COUNTER_INC(&pVCpu->hm.s.StatTscIntercept);
10618
10619 ASMAtomicWriteBool(&pVCpu->hm.s.fCheckedTLBFlush, true); /* Used for TLB flushing, set this across the world switch. */
10620 hmR0VmxFlushTaggedTlb(pHostCpu, pVCpu, pVmcsInfo); /* Invalidate the appropriate guest entries from the TLB. */
10621 Assert(idCurrentCpu == pVCpu->hm.s.idLastCpu);
10622 pVCpu->hm.s.vmx.LastError.idCurrentCpu = idCurrentCpu; /* Record the error reporting info. with the current host CPU. */
10623 pVmcsInfo->idHostCpuState = idCurrentCpu; /* Record the CPU for which the host-state has been exported. */
10624 pVmcsInfo->idHostCpuExec = idCurrentCpu; /* Record the CPU on which we shall execute. */
10625
10626 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatEntry, &pVCpu->hm.s.StatInGC, x);
10627
10628 TMNotifyStartOfExecution(pVM, pVCpu); /* Notify TM to resume its clocks when TSC is tied to execution,
10629 as we're about to start executing the guest. */
10630
10631 /*
10632 * Load the guest TSC_AUX MSR when we are not intercepting RDTSCP.
10633 *
10634 * This is done this late as updating the TSC offsetting/preemption timer above
10635 * figures out if we can skip intercepting RDTSCP by calculating the number of
10636 * host CPU ticks till the next virtual sync deadline (for the dynamic case).
10637 */
10638 if ( (pVmcsInfo->u32ProcCtls2 & VMX_PROC_CTLS2_RDTSCP)
10639 && !fIsRdtscIntercepted)
10640 {
10641 hmR0VmxImportGuestState(pVCpu, pVmcsInfo, CPUMCTX_EXTRN_TSC_AUX);
10642
10643 /* NB: Because we call hmR0VmxAddAutoLoadStoreMsr with fUpdateHostMsr=true,
10644 it's safe even after hmR0VmxUpdateAutoLoadHostMsrs has already been done. */
10645 int rc = hmR0VmxAddAutoLoadStoreMsr(pVCpu, pVmxTransient, MSR_K8_TSC_AUX, CPUMGetGuestTscAux(pVCpu),
10646 true /* fSetReadWrite */, true /* fUpdateHostMsr */);
10647 AssertRC(rc);
10648 Assert(!pVmxTransient->fRemoveTscAuxMsr);
10649 pVmxTransient->fRemoveTscAuxMsr = true;
10650 }
10651
10652#ifdef VBOX_STRICT
10653 Assert(pVCpu->hm.s.vmx.fUpdatedHostAutoMsrs);
10654 hmR0VmxCheckAutoLoadStoreMsrs(pVCpu, pVmcsInfo, pVmxTransient->fIsNestedGuest);
10655 hmR0VmxCheckHostEferMsr(pVCpu, pVmcsInfo);
10656 AssertRC(hmR0VmxCheckVmcsCtls(pVCpu, pVmcsInfo, pVmxTransient->fIsNestedGuest));
10657#endif
10658
10659#ifdef HMVMX_ALWAYS_CHECK_GUEST_STATE
10660 /** @todo r=ramshankar: We can now probably use iemVmxVmentryCheckGuestState here.
10661 * Add a PVMXMSRS parameter to it, so that IEM can look at the host MSRs,
10662 * see @bugref{9180#c54}. */
10663 uint32_t const uInvalidReason = hmR0VmxCheckGuestState(pVCpu, pVmcsInfo);
10664 if (uInvalidReason != VMX_IGS_REASON_NOT_FOUND)
10665 Log4(("hmR0VmxCheckGuestState returned %#x\n", uInvalidReason));
10666#endif
10667}
10668
10669
10670/**
10671 * First C routine invoked after running guest code using hardware-assisted VMX.
10672 *
10673 * @param pVCpu The cross context virtual CPU structure.
10674 * @param pVmxTransient The VMX-transient structure.
10675 * @param rcVMRun Return code of VMLAUNCH/VMRESUME.
10676 *
10677 * @remarks Called with interrupts disabled, and returns with interrupts enabled!
10678 *
10679 * @remarks No-long-jump zone!!! This function will however re-enable longjmps
10680 * unconditionally when it is safe to do so.
10681 */
10682static void hmR0VmxPostRunGuest(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient, int rcVMRun)
10683{
10684 uint64_t const uHostTsc = ASMReadTSC(); /** @todo We can do a lot better here, see @bugref{9180#c38}. */
10685
10686 ASMAtomicWriteBool(&pVCpu->hm.s.fCheckedTLBFlush, false); /* See HMInvalidatePageOnAllVCpus(): used for TLB flushing. */
10687 ASMAtomicIncU32(&pVCpu->hm.s.cWorldSwitchExits); /* Initialized in vmR3CreateUVM(): used for EMT poking. */
10688 pVCpu->hm.s.fCtxChanged = 0; /* Exits/longjmps to ring-3 requires saving the guest state. */
10689 pVmxTransient->fVmcsFieldsRead = 0; /* Transient fields need to be read from the VMCS. */
10690 pVmxTransient->fVectoringPF = false; /* Vectoring page-fault needs to be determined later. */
10691 pVmxTransient->fVectoringDoublePF = false; /* Vectoring double page-fault needs to be determined later. */
10692
10693 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
10694 if (!(pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_RDTSC_EXIT))
10695 {
10696 uint64_t uGstTsc;
10697 if (!pVmxTransient->fIsNestedGuest)
10698 uGstTsc = uHostTsc + pVmcsInfo->u64TscOffset;
10699 else
10700 {
10701 uint64_t const uNstGstTsc = uHostTsc + pVmcsInfo->u64TscOffset;
10702 uGstTsc = CPUMRemoveNestedGuestTscOffset(pVCpu, uNstGstTsc);
10703 }
10704 TMCpuTickSetLastSeen(pVCpu, uGstTsc); /* Update TM with the guest TSC. */
10705 }
10706
10707 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatInGC, &pVCpu->hm.s.StatPreExit, x);
10708 TMNotifyEndOfExecution(pVCpu->CTX_SUFF(pVM), pVCpu); /* Notify TM that the guest is no longer running. */
10709 VMCPU_SET_STATE(pVCpu, VMCPUSTATE_STARTED_HM);
10710
10711 pVCpu->hm.s.vmx.fRestoreHostFlags |= VMX_RESTORE_HOST_REQUIRED; /* Some host state messed up by VMX needs restoring. */
10712 pVmcsInfo->fVmcsState |= VMX_V_VMCS_LAUNCH_STATE_LAUNCHED; /* Use VMRESUME instead of VMLAUNCH in the next run. */
10713#ifdef VBOX_STRICT
10714 hmR0VmxCheckHostEferMsr(pVCpu, pVmcsInfo); /* Verify that the host EFER MSR wasn't modified. */
10715#endif
10716 Assert(!ASMIntAreEnabled());
10717 ASMSetFlags(pVmxTransient->fEFlags); /* Enable interrupts. */
10718 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
10719
10720#ifdef HMVMX_ALWAYS_CLEAN_TRANSIENT
10721 /*
10722 * Clean all the VMCS fields in the transient structure before reading
10723 * anything from the VMCS.
10724 */
10725 pVmxTransient->uExitReason = 0;
10726 pVmxTransient->uExitIntErrorCode = 0;
10727 pVmxTransient->uExitQual = 0;
10728 pVmxTransient->uGuestLinearAddr = 0;
10729 pVmxTransient->uExitIntInfo = 0;
10730 pVmxTransient->cbExitInstr = 0;
10731 pVmxTransient->ExitInstrInfo.u = 0;
10732 pVmxTransient->uEntryIntInfo = 0;
10733 pVmxTransient->uEntryXcptErrorCode = 0;
10734 pVmxTransient->cbEntryInstr = 0;
10735 pVmxTransient->uIdtVectoringInfo = 0;
10736 pVmxTransient->uIdtVectoringErrorCode = 0;
10737#endif
10738
10739 /*
10740 * Save the basic VM-exit reason and check if the VM-entry failed.
10741 * See Intel spec. 24.9.1 "Basic VM-exit Information".
10742 */
10743 uint32_t uExitReason;
10744 int rc = VMXReadVmcs32(VMX_VMCS32_RO_EXIT_REASON, &uExitReason);
10745 AssertRC(rc);
10746 pVmxTransient->uExitReason = VMX_EXIT_REASON_BASIC(uExitReason);
10747 pVmxTransient->fVMEntryFailed = VMX_EXIT_REASON_HAS_ENTRY_FAILED(uExitReason);
10748
10749 /*
10750 * Log the VM-exit before logging anything else as otherwise it might be a
10751 * tad confusing what happens before and after the world-switch.
10752 */
10753 HMVMX_LOG_EXIT(pVCpu, uExitReason);
10754
10755 /*
10756 * Remove the TSC_AUX MSR from the auto-load/store MSR area and reset any MSR
10757 * bitmap permissions, if it was added before VM-entry.
10758 */
10759 if (pVmxTransient->fRemoveTscAuxMsr)
10760 {
10761 hmR0VmxRemoveAutoLoadStoreMsr(pVCpu, pVmxTransient, MSR_K8_TSC_AUX);
10762 pVmxTransient->fRemoveTscAuxMsr = false;
10763 }
10764
10765 /*
10766 * Check if VMLAUNCH/VMRESUME succeeded.
10767 * If this failed, we cause a guru meditation and cease further execution.
10768 *
10769 * However, if we are executing a nested-guest we might fail if we use the
10770 * fast path rather than fully emulating VMLAUNCH/VMRESUME instruction in IEM.
10771 */
10772 if (RT_LIKELY(rcVMRun == VINF_SUCCESS))
10773 {
10774 /*
10775 * Update the VM-exit history array here even if the VM-entry failed due to:
10776 * - Invalid guest state.
10777 * - MSR loading.
10778 * - Machine-check event.
10779 *
10780 * In any of the above cases we will still have a "valid" VM-exit reason
10781 * despite @a fVMEntryFailed being false.
10782 *
10783 * See Intel spec. 26.7 "VM-Entry failures during or after loading guest state".
10784 *
10785 * Note! We don't have CS or RIP at this point. Will probably address that later
10786 * by amending the history entry added here.
10787 */
10788 EMHistoryAddExit(pVCpu, EMEXIT_MAKE_FT(EMEXIT_F_KIND_VMX, pVmxTransient->uExitReason & EMEXIT_F_TYPE_MASK),
10789 UINT64_MAX, uHostTsc);
10790
10791 if (RT_LIKELY(!pVmxTransient->fVMEntryFailed))
10792 {
10793 VMMRZCallRing3Enable(pVCpu);
10794
10795 Assert(!VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_HM_UPDATE_CR3));
10796 Assert(!VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_HM_UPDATE_PAE_PDPES));
10797
10798#ifdef HMVMX_ALWAYS_SAVE_RO_GUEST_STATE
10799 hmR0VmxReadAllRoFieldsVmcs(pVmxTransient);
10800#endif
10801#if defined(HMVMX_ALWAYS_SYNC_FULL_GUEST_STATE) || defined(HMVMX_ALWAYS_SAVE_FULL_GUEST_STATE)
10802 rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, HMVMX_CPUMCTX_EXTRN_ALL);
10803 AssertRC(rc);
10804#elif defined(HMVMX_ALWAYS_SAVE_GUEST_RFLAGS)
10805 rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, HMVMX_CPUMCTX_EXTRN_RFLAGS);
10806 AssertRC(rc);
10807#else
10808 /*
10809 * Import the guest-interruptibility state always as we need it while evaluating
10810 * injecting events on re-entry.
10811 *
10812 * We don't import CR0 (when unrestricted guest execution is unavailable) despite
10813 * checking for real-mode while exporting the state because all bits that cause
10814 * mode changes wrt CR0 are intercepted.
10815 */
10816 rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, CPUMCTX_EXTRN_HM_VMX_INT_STATE);
10817 AssertRC(rc);
10818#endif
10819
10820 /*
10821 * Sync the TPR shadow with our APIC state.
10822 */
10823 if ( !pVmxTransient->fIsNestedGuest
10824 && (pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_USE_TPR_SHADOW))
10825 {
10826 Assert(pVmcsInfo->pbVirtApic);
10827 if (pVmxTransient->u8GuestTpr != pVmcsInfo->pbVirtApic[XAPIC_OFF_TPR])
10828 {
10829 rc = APICSetTpr(pVCpu, pVmcsInfo->pbVirtApic[XAPIC_OFF_TPR]);
10830 AssertRC(rc);
10831 ASMAtomicOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_APIC_TPR);
10832 }
10833 }
10834
10835 Assert(VMMRZCallRing3IsEnabled(pVCpu));
10836 return;
10837 }
10838 }
10839#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
10840 else if (pVmxTransient->fIsNestedGuest)
10841 AssertMsgFailed(("VMLAUNCH/VMRESUME failed but shouldn't happen when VMLAUNCH/VMRESUME was emulated in IEM!\n"));
10842#endif
10843 else
10844 Log4Func(("VM-entry failure: rcVMRun=%Rrc fVMEntryFailed=%RTbool\n", rcVMRun, pVmxTransient->fVMEntryFailed));
10845
10846 VMMRZCallRing3Enable(pVCpu);
10847}
10848
10849
10850/**
10851 * Runs the guest code using hardware-assisted VMX the normal way.
10852 *
10853 * @returns VBox status code.
10854 * @param pVCpu The cross context virtual CPU structure.
10855 * @param pcLoops Pointer to the number of executed loops.
10856 */
10857static VBOXSTRICTRC hmR0VmxRunGuestCodeNormal(PVMCPUCC pVCpu, uint32_t *pcLoops)
10858{
10859 uint32_t const cMaxResumeLoops = pVCpu->CTX_SUFF(pVM)->hm.s.cMaxResumeLoops;
10860 Assert(pcLoops);
10861 Assert(*pcLoops <= cMaxResumeLoops);
10862 Assert(!CPUMIsGuestInVmxNonRootMode(&pVCpu->cpum.GstCtx));
10863
10864#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
10865 /*
10866 * Switch to the guest VMCS as we may have transitioned from executing the nested-guest
10867 * without leaving ring-0. Otherwise, if we came from ring-3 we would have loaded the
10868 * guest VMCS while entering the VMX ring-0 session.
10869 */
10870 if (pVCpu->hm.s.vmx.fSwitchedToNstGstVmcs)
10871 {
10872 int rc = hmR0VmxSwitchToGstOrNstGstVmcs(pVCpu, false /* fSwitchToNstGstVmcs */);
10873 if (RT_SUCCESS(rc))
10874 { /* likely */ }
10875 else
10876 {
10877 LogRelFunc(("Failed to switch to the guest VMCS. rc=%Rrc\n", rc));
10878 return rc;
10879 }
10880 }
10881#endif
10882
10883 VMXTRANSIENT VmxTransient;
10884 RT_ZERO(VmxTransient);
10885 VmxTransient.pVmcsInfo = hmGetVmxActiveVmcsInfo(pVCpu);
10886
10887 /* Paranoia. */
10888 Assert(VmxTransient.pVmcsInfo == &pVCpu->hm.s.vmx.VmcsInfo);
10889
10890 VBOXSTRICTRC rcStrict = VERR_INTERNAL_ERROR_5;
10891 for (;;)
10892 {
10893 Assert(!HMR0SuspendPending());
10894 HMVMX_ASSERT_CPU_SAFE(pVCpu);
10895 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatEntry, x);
10896
10897 /*
10898 * Preparatory work for running nested-guest code, this may force us to
10899 * return to ring-3.
10900 *
10901 * Warning! This bugger disables interrupts on VINF_SUCCESS!
10902 */
10903 rcStrict = hmR0VmxPreRunGuest(pVCpu, &VmxTransient, false /* fStepping */);
10904 if (rcStrict != VINF_SUCCESS)
10905 break;
10906
10907 /* Interrupts are disabled at this point! */
10908 hmR0VmxPreRunGuestCommitted(pVCpu, &VmxTransient);
10909 int rcRun = hmR0VmxRunGuest(pVCpu, &VmxTransient);
10910 hmR0VmxPostRunGuest(pVCpu, &VmxTransient, rcRun);
10911 /* Interrupts are re-enabled at this point! */
10912
10913 /*
10914 * Check for errors with running the VM (VMLAUNCH/VMRESUME).
10915 */
10916 if (RT_SUCCESS(rcRun))
10917 { /* very likely */ }
10918 else
10919 {
10920 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatPreExit, x);
10921 hmR0VmxReportWorldSwitchError(pVCpu, rcRun, &VmxTransient);
10922 return rcRun;
10923 }
10924
10925 /*
10926 * Profile the VM-exit.
10927 */
10928 AssertMsg(VmxTransient.uExitReason <= VMX_EXIT_MAX, ("%#x\n", VmxTransient.uExitReason));
10929 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitAll);
10930 STAM_COUNTER_INC(&pVCpu->hm.s.paStatExitReasonR0[VmxTransient.uExitReason & MASK_EXITREASON_STAT]);
10931 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatPreExit, &pVCpu->hm.s.StatExitHandling, x);
10932 HMVMX_START_EXIT_DISPATCH_PROF();
10933
10934 VBOXVMM_R0_HMVMX_VMEXIT_NOCTX(pVCpu, &pVCpu->cpum.GstCtx, VmxTransient.uExitReason);
10935
10936 /*
10937 * Handle the VM-exit.
10938 */
10939#ifdef HMVMX_USE_FUNCTION_TABLE
10940 rcStrict = g_apfnVMExitHandlers[VmxTransient.uExitReason](pVCpu, &VmxTransient);
10941#else
10942 rcStrict = hmR0VmxHandleExit(pVCpu, &VmxTransient);
10943#endif
10944 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExitHandling, x);
10945 if (rcStrict == VINF_SUCCESS)
10946 {
10947 if (++(*pcLoops) <= cMaxResumeLoops)
10948 continue;
10949 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchMaxResumeLoops);
10950 rcStrict = VINF_EM_RAW_INTERRUPT;
10951 }
10952 break;
10953 }
10954
10955 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatEntry, x);
10956 return rcStrict;
10957}
10958
10959
10960#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
10961/**
10962 * Runs the nested-guest code using hardware-assisted VMX.
10963 *
10964 * @returns VBox status code.
10965 * @param pVCpu The cross context virtual CPU structure.
10966 * @param pcLoops Pointer to the number of executed loops.
10967 *
10968 * @sa hmR0VmxRunGuestCodeNormal.
10969 */
10970static VBOXSTRICTRC hmR0VmxRunGuestCodeNested(PVMCPUCC pVCpu, uint32_t *pcLoops)
10971{
10972 uint32_t const cMaxResumeLoops = pVCpu->CTX_SUFF(pVM)->hm.s.cMaxResumeLoops;
10973 Assert(pcLoops);
10974 Assert(*pcLoops <= cMaxResumeLoops);
10975 Assert(CPUMIsGuestInVmxNonRootMode(&pVCpu->cpum.GstCtx));
10976
10977 /*
10978 * Switch to the nested-guest VMCS as we may have transitioned from executing the
10979 * guest without leaving ring-0. Otherwise, if we came from ring-3 we would have
10980 * loaded the nested-guest VMCS while entering the VMX ring-0 session.
10981 */
10982 if (!pVCpu->hm.s.vmx.fSwitchedToNstGstVmcs)
10983 {
10984 int rc = hmR0VmxSwitchToGstOrNstGstVmcs(pVCpu, true /* fSwitchToNstGstVmcs */);
10985 if (RT_SUCCESS(rc))
10986 { /* likely */ }
10987 else
10988 {
10989 LogRelFunc(("Failed to switch to the nested-guest VMCS. rc=%Rrc\n", rc));
10990 return rc;
10991 }
10992 }
10993
10994 VMXTRANSIENT VmxTransient;
10995 RT_ZERO(VmxTransient);
10996 VmxTransient.pVmcsInfo = hmGetVmxActiveVmcsInfo(pVCpu);
10997 VmxTransient.fIsNestedGuest = true;
10998
10999 /* Paranoia. */
11000 Assert(VmxTransient.pVmcsInfo == &pVCpu->hm.s.vmx.VmcsInfoNstGst);
11001
11002 VBOXSTRICTRC rcStrict = VERR_INTERNAL_ERROR_5;
11003 for (;;)
11004 {
11005 Assert(!HMR0SuspendPending());
11006 HMVMX_ASSERT_CPU_SAFE(pVCpu);
11007 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatEntry, x);
11008
11009 /*
11010 * Preparatory work for running guest code, this may force us to
11011 * return to ring-3.
11012 *
11013 * Warning! This bugger disables interrupts on VINF_SUCCESS!
11014 */
11015 rcStrict = hmR0VmxPreRunGuest(pVCpu, &VmxTransient, false /* fStepping */);
11016 if (rcStrict != VINF_SUCCESS)
11017 break;
11018
11019 /* Interrupts are disabled at this point! */
11020 hmR0VmxPreRunGuestCommitted(pVCpu, &VmxTransient);
11021 int rcRun = hmR0VmxRunGuest(pVCpu, &VmxTransient);
11022 hmR0VmxPostRunGuest(pVCpu, &VmxTransient, rcRun);
11023 /* Interrupts are re-enabled at this point! */
11024
11025 /*
11026 * Check for errors with running the VM (VMLAUNCH/VMRESUME).
11027 */
11028 if (RT_SUCCESS(rcRun))
11029 { /* very likely */ }
11030 else
11031 {
11032 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatPreExit, x);
11033 hmR0VmxReportWorldSwitchError(pVCpu, rcRun, &VmxTransient);
11034 return rcRun;
11035 }
11036
11037 /*
11038 * Profile the VM-exit.
11039 */
11040 AssertMsg(VmxTransient.uExitReason <= VMX_EXIT_MAX, ("%#x\n", VmxTransient.uExitReason));
11041 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitAll);
11042 STAM_COUNTER_INC(&pVCpu->hm.s.StatNestedExitAll);
11043 STAM_COUNTER_INC(&pVCpu->hm.s.paStatNestedExitReasonR0[VmxTransient.uExitReason & MASK_EXITREASON_STAT]);
11044 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatPreExit, &pVCpu->hm.s.StatExitHandling, x);
11045 HMVMX_START_EXIT_DISPATCH_PROF();
11046
11047 VBOXVMM_R0_HMVMX_VMEXIT_NOCTX(pVCpu, &pVCpu->cpum.GstCtx, VmxTransient.uExitReason);
11048
11049 /*
11050 * Handle the VM-exit.
11051 */
11052 rcStrict = hmR0VmxHandleExitNested(pVCpu, &VmxTransient);
11053 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExitHandling, x);
11054 if (rcStrict == VINF_SUCCESS)
11055 {
11056 if (!CPUMIsGuestInVmxNonRootMode(&pVCpu->cpum.GstCtx))
11057 {
11058 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchNstGstVmexit);
11059 rcStrict = VINF_VMX_VMEXIT;
11060 }
11061 else
11062 {
11063 if (++(*pcLoops) <= cMaxResumeLoops)
11064 continue;
11065 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchMaxResumeLoops);
11066 rcStrict = VINF_EM_RAW_INTERRUPT;
11067 }
11068 }
11069 else
11070 Assert(rcStrict != VINF_VMX_VMEXIT);
11071 break;
11072 }
11073
11074 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatEntry, x);
11075 return rcStrict;
11076}
11077#endif /* VBOX_WITH_NESTED_HWVIRT_VMX */
11078
11079
11080/** @name Execution loop for single stepping, DBGF events and expensive Dtrace
11081 * probes.
11082 *
11083 * The following few functions and associated structure contains the bloat
11084 * necessary for providing detailed debug events and dtrace probes as well as
11085 * reliable host side single stepping. This works on the principle of
11086 * "subclassing" the normal execution loop and workers. We replace the loop
11087 * method completely and override selected helpers to add necessary adjustments
11088 * to their core operation.
11089 *
11090 * The goal is to keep the "parent" code lean and mean, so as not to sacrifice
11091 * any performance for debug and analysis features.
11092 *
11093 * @{
11094 */
11095
11096/**
11097 * Transient per-VCPU debug state of VMCS and related info. we save/restore in
11098 * the debug run loop.
11099 */
11100typedef struct VMXRUNDBGSTATE
11101{
11102 /** The RIP we started executing at. This is for detecting that we stepped. */
11103 uint64_t uRipStart;
11104 /** The CS we started executing with. */
11105 uint16_t uCsStart;
11106
11107 /** Whether we've actually modified the 1st execution control field. */
11108 bool fModifiedProcCtls : 1;
11109 /** Whether we've actually modified the 2nd execution control field. */
11110 bool fModifiedProcCtls2 : 1;
11111 /** Whether we've actually modified the exception bitmap. */
11112 bool fModifiedXcptBitmap : 1;
11113
11114 /** We desire the modified the CR0 mask to be cleared. */
11115 bool fClearCr0Mask : 1;
11116 /** We desire the modified the CR4 mask to be cleared. */
11117 bool fClearCr4Mask : 1;
11118 /** Stuff we need in VMX_VMCS32_CTRL_PROC_EXEC. */
11119 uint32_t fCpe1Extra;
11120 /** Stuff we do not want in VMX_VMCS32_CTRL_PROC_EXEC. */
11121 uint32_t fCpe1Unwanted;
11122 /** Stuff we need in VMX_VMCS32_CTRL_PROC_EXEC2. */
11123 uint32_t fCpe2Extra;
11124 /** Extra stuff we need in VMX_VMCS32_CTRL_EXCEPTION_BITMAP. */
11125 uint32_t bmXcptExtra;
11126 /** The sequence number of the Dtrace provider settings the state was
11127 * configured against. */
11128 uint32_t uDtraceSettingsSeqNo;
11129 /** VM-exits to check (one bit per VM-exit). */
11130 uint32_t bmExitsToCheck[3];
11131
11132 /** The initial VMX_VMCS32_CTRL_PROC_EXEC value (helps with restore). */
11133 uint32_t fProcCtlsInitial;
11134 /** The initial VMX_VMCS32_CTRL_PROC_EXEC2 value (helps with restore). */
11135 uint32_t fProcCtls2Initial;
11136 /** The initial VMX_VMCS32_CTRL_EXCEPTION_BITMAP value (helps with restore). */
11137 uint32_t bmXcptInitial;
11138} VMXRUNDBGSTATE;
11139AssertCompileMemberSize(VMXRUNDBGSTATE, bmExitsToCheck, (VMX_EXIT_MAX + 1 + 31) / 32 * 4);
11140typedef VMXRUNDBGSTATE *PVMXRUNDBGSTATE;
11141
11142
11143/**
11144 * Initializes the VMXRUNDBGSTATE structure.
11145 *
11146 * @param pVCpu The cross context virtual CPU structure of the
11147 * calling EMT.
11148 * @param pVmxTransient The VMX-transient structure.
11149 * @param pDbgState The debug state to initialize.
11150 */
11151static void hmR0VmxRunDebugStateInit(PVMCPUCC pVCpu, PCVMXTRANSIENT pVmxTransient, PVMXRUNDBGSTATE pDbgState)
11152{
11153 pDbgState->uRipStart = pVCpu->cpum.GstCtx.rip;
11154 pDbgState->uCsStart = pVCpu->cpum.GstCtx.cs.Sel;
11155
11156 pDbgState->fModifiedProcCtls = false;
11157 pDbgState->fModifiedProcCtls2 = false;
11158 pDbgState->fModifiedXcptBitmap = false;
11159 pDbgState->fClearCr0Mask = false;
11160 pDbgState->fClearCr4Mask = false;
11161 pDbgState->fCpe1Extra = 0;
11162 pDbgState->fCpe1Unwanted = 0;
11163 pDbgState->fCpe2Extra = 0;
11164 pDbgState->bmXcptExtra = 0;
11165 pDbgState->fProcCtlsInitial = pVmxTransient->pVmcsInfo->u32ProcCtls;
11166 pDbgState->fProcCtls2Initial = pVmxTransient->pVmcsInfo->u32ProcCtls2;
11167 pDbgState->bmXcptInitial = pVmxTransient->pVmcsInfo->u32XcptBitmap;
11168}
11169
11170
11171/**
11172 * Updates the VMSC fields with changes requested by @a pDbgState.
11173 *
11174 * This is performed after hmR0VmxPreRunGuestDebugStateUpdate as well
11175 * immediately before executing guest code, i.e. when interrupts are disabled.
11176 * We don't check status codes here as we cannot easily assert or return in the
11177 * latter case.
11178 *
11179 * @param pVCpu The cross context virtual CPU structure.
11180 * @param pVmxTransient The VMX-transient structure.
11181 * @param pDbgState The debug state.
11182 */
11183static void hmR0VmxPreRunGuestDebugStateApply(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient, PVMXRUNDBGSTATE pDbgState)
11184{
11185 /*
11186 * Ensure desired flags in VMCS control fields are set.
11187 * (Ignoring write failure here, as we're committed and it's just debug extras.)
11188 *
11189 * Note! We load the shadow CR0 & CR4 bits when we flag the clearing, so
11190 * there should be no stale data in pCtx at this point.
11191 */
11192 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
11193 if ( (pVmcsInfo->u32ProcCtls & pDbgState->fCpe1Extra) != pDbgState->fCpe1Extra
11194 || (pVmcsInfo->u32ProcCtls & pDbgState->fCpe1Unwanted))
11195 {
11196 pVmcsInfo->u32ProcCtls |= pDbgState->fCpe1Extra;
11197 pVmcsInfo->u32ProcCtls &= ~pDbgState->fCpe1Unwanted;
11198 VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, pVmcsInfo->u32ProcCtls);
11199 Log6Func(("VMX_VMCS32_CTRL_PROC_EXEC: %#RX32\n", pVmcsInfo->u32ProcCtls));
11200 pDbgState->fModifiedProcCtls = true;
11201 }
11202
11203 if ((pVmcsInfo->u32ProcCtls2 & pDbgState->fCpe2Extra) != pDbgState->fCpe2Extra)
11204 {
11205 pVmcsInfo->u32ProcCtls2 |= pDbgState->fCpe2Extra;
11206 VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC2, pVmcsInfo->u32ProcCtls2);
11207 Log6Func(("VMX_VMCS32_CTRL_PROC_EXEC2: %#RX32\n", pVmcsInfo->u32ProcCtls2));
11208 pDbgState->fModifiedProcCtls2 = true;
11209 }
11210
11211 if ((pVmcsInfo->u32XcptBitmap & pDbgState->bmXcptExtra) != pDbgState->bmXcptExtra)
11212 {
11213 pVmcsInfo->u32XcptBitmap |= pDbgState->bmXcptExtra;
11214 VMXWriteVmcs32(VMX_VMCS32_CTRL_EXCEPTION_BITMAP, pVmcsInfo->u32XcptBitmap);
11215 Log6Func(("VMX_VMCS32_CTRL_EXCEPTION_BITMAP: %#RX32\n", pVmcsInfo->u32XcptBitmap));
11216 pDbgState->fModifiedXcptBitmap = true;
11217 }
11218
11219 if (pDbgState->fClearCr0Mask && pVmcsInfo->u64Cr0Mask != 0)
11220 {
11221 pVmcsInfo->u64Cr0Mask = 0;
11222 VMXWriteVmcsNw(VMX_VMCS_CTRL_CR0_MASK, 0);
11223 Log6Func(("VMX_VMCS_CTRL_CR0_MASK: 0\n"));
11224 }
11225
11226 if (pDbgState->fClearCr4Mask && pVmcsInfo->u64Cr4Mask != 0)
11227 {
11228 pVmcsInfo->u64Cr4Mask = 0;
11229 VMXWriteVmcsNw(VMX_VMCS_CTRL_CR4_MASK, 0);
11230 Log6Func(("VMX_VMCS_CTRL_CR4_MASK: 0\n"));
11231 }
11232
11233 NOREF(pVCpu);
11234}
11235
11236
11237/**
11238 * Restores VMCS fields that were changed by hmR0VmxPreRunGuestDebugStateApply for
11239 * re-entry next time around.
11240 *
11241 * @returns Strict VBox status code (i.e. informational status codes too).
11242 * @param pVCpu The cross context virtual CPU structure.
11243 * @param pVmxTransient The VMX-transient structure.
11244 * @param pDbgState The debug state.
11245 * @param rcStrict The return code from executing the guest using single
11246 * stepping.
11247 */
11248static VBOXSTRICTRC hmR0VmxRunDebugStateRevert(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient, PVMXRUNDBGSTATE pDbgState,
11249 VBOXSTRICTRC rcStrict)
11250{
11251 /*
11252 * Restore VM-exit control settings as we may not reenter this function the
11253 * next time around.
11254 */
11255 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
11256
11257 /* We reload the initial value, trigger what we can of recalculations the
11258 next time around. From the looks of things, that's all that's required atm. */
11259 if (pDbgState->fModifiedProcCtls)
11260 {
11261 if (!(pDbgState->fProcCtlsInitial & VMX_PROC_CTLS_MOV_DR_EXIT) && CPUMIsHyperDebugStateActive(pVCpu))
11262 pDbgState->fProcCtlsInitial |= VMX_PROC_CTLS_MOV_DR_EXIT; /* Avoid assertion in hmR0VmxLeave */
11263 int rc2 = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, pDbgState->fProcCtlsInitial);
11264 AssertRC(rc2);
11265 pVmcsInfo->u32ProcCtls = pDbgState->fProcCtlsInitial;
11266 }
11267
11268 /* We're currently the only ones messing with this one, so just restore the
11269 cached value and reload the field. */
11270 if ( pDbgState->fModifiedProcCtls2
11271 && pVmcsInfo->u32ProcCtls2 != pDbgState->fProcCtls2Initial)
11272 {
11273 int rc2 = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC2, pDbgState->fProcCtls2Initial);
11274 AssertRC(rc2);
11275 pVmcsInfo->u32ProcCtls2 = pDbgState->fProcCtls2Initial;
11276 }
11277
11278 /* If we've modified the exception bitmap, we restore it and trigger
11279 reloading and partial recalculation the next time around. */
11280 if (pDbgState->fModifiedXcptBitmap)
11281 pVmcsInfo->u32XcptBitmap = pDbgState->bmXcptInitial;
11282
11283 return rcStrict;
11284}
11285
11286
11287/**
11288 * Configures VM-exit controls for current DBGF and DTrace settings.
11289 *
11290 * This updates @a pDbgState and the VMCS execution control fields to reflect
11291 * the necessary VM-exits demanded by DBGF and DTrace.
11292 *
11293 * @param pVCpu The cross context virtual CPU structure.
11294 * @param pVmxTransient The VMX-transient structure. May update
11295 * fUpdatedTscOffsettingAndPreemptTimer.
11296 * @param pDbgState The debug state.
11297 */
11298static void hmR0VmxPreRunGuestDebugStateUpdate(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient, PVMXRUNDBGSTATE pDbgState)
11299{
11300 /*
11301 * Take down the dtrace serial number so we can spot changes.
11302 */
11303 pDbgState->uDtraceSettingsSeqNo = VBOXVMM_GET_SETTINGS_SEQ_NO();
11304 ASMCompilerBarrier();
11305
11306 /*
11307 * We'll rebuild most of the middle block of data members (holding the
11308 * current settings) as we go along here, so start by clearing it all.
11309 */
11310 pDbgState->bmXcptExtra = 0;
11311 pDbgState->fCpe1Extra = 0;
11312 pDbgState->fCpe1Unwanted = 0;
11313 pDbgState->fCpe2Extra = 0;
11314 for (unsigned i = 0; i < RT_ELEMENTS(pDbgState->bmExitsToCheck); i++)
11315 pDbgState->bmExitsToCheck[i] = 0;
11316
11317 /*
11318 * Software interrupts (INT XXh) - no idea how to trigger these...
11319 */
11320 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
11321 if ( DBGF_IS_EVENT_ENABLED(pVM, DBGFEVENT_INTERRUPT_SOFTWARE)
11322 || VBOXVMM_INT_SOFTWARE_ENABLED())
11323 {
11324 ASMBitSet(pDbgState->bmExitsToCheck, VMX_EXIT_XCPT_OR_NMI);
11325 }
11326
11327 /*
11328 * INT3 breakpoints - triggered by #BP exceptions.
11329 */
11330 if (pVM->dbgf.ro.cEnabledInt3Breakpoints > 0)
11331 pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_BP);
11332
11333 /*
11334 * Exception bitmap and XCPT events+probes.
11335 */
11336 for (int iXcpt = 0; iXcpt < (DBGFEVENT_XCPT_LAST - DBGFEVENT_XCPT_FIRST + 1); iXcpt++)
11337 if (DBGF_IS_EVENT_ENABLED(pVM, (DBGFEVENTTYPE)(DBGFEVENT_XCPT_FIRST + iXcpt)))
11338 pDbgState->bmXcptExtra |= RT_BIT_32(iXcpt);
11339
11340 if (VBOXVMM_XCPT_DE_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_DE);
11341 if (VBOXVMM_XCPT_DB_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_DB);
11342 if (VBOXVMM_XCPT_BP_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_BP);
11343 if (VBOXVMM_XCPT_OF_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_OF);
11344 if (VBOXVMM_XCPT_BR_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_BR);
11345 if (VBOXVMM_XCPT_UD_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_UD);
11346 if (VBOXVMM_XCPT_NM_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_NM);
11347 if (VBOXVMM_XCPT_DF_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_DF);
11348 if (VBOXVMM_XCPT_TS_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_TS);
11349 if (VBOXVMM_XCPT_NP_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_NP);
11350 if (VBOXVMM_XCPT_SS_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_SS);
11351 if (VBOXVMM_XCPT_GP_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_GP);
11352 if (VBOXVMM_XCPT_PF_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_PF);
11353 if (VBOXVMM_XCPT_MF_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_MF);
11354 if (VBOXVMM_XCPT_AC_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_AC);
11355 if (VBOXVMM_XCPT_XF_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_XF);
11356 if (VBOXVMM_XCPT_VE_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_VE);
11357 if (VBOXVMM_XCPT_SX_ENABLED()) pDbgState->bmXcptExtra |= RT_BIT_32(X86_XCPT_SX);
11358
11359 if (pDbgState->bmXcptExtra)
11360 ASMBitSet(pDbgState->bmExitsToCheck, VMX_EXIT_XCPT_OR_NMI);
11361
11362 /*
11363 * Process events and probes for VM-exits, making sure we get the wanted VM-exits.
11364 *
11365 * Note! This is the reverse of what hmR0VmxHandleExitDtraceEvents does.
11366 * So, when adding/changing/removing please don't forget to update it.
11367 *
11368 * Some of the macros are picking up local variables to save horizontal space,
11369 * (being able to see it in a table is the lesser evil here).
11370 */
11371#define IS_EITHER_ENABLED(a_pVM, a_EventSubName) \
11372 ( DBGF_IS_EVENT_ENABLED(a_pVM, RT_CONCAT(DBGFEVENT_, a_EventSubName)) \
11373 || RT_CONCAT3(VBOXVMM_, a_EventSubName, _ENABLED)() )
11374#define SET_ONLY_XBM_IF_EITHER_EN(a_EventSubName, a_uExit) \
11375 if (IS_EITHER_ENABLED(pVM, a_EventSubName)) \
11376 { AssertCompile((unsigned)(a_uExit) < sizeof(pDbgState->bmExitsToCheck) * 8); \
11377 ASMBitSet((pDbgState)->bmExitsToCheck, a_uExit); \
11378 } else do { } while (0)
11379#define SET_CPE1_XBM_IF_EITHER_EN(a_EventSubName, a_uExit, a_fCtrlProcExec) \
11380 if (IS_EITHER_ENABLED(pVM, a_EventSubName)) \
11381 { \
11382 (pDbgState)->fCpe1Extra |= (a_fCtrlProcExec); \
11383 AssertCompile((unsigned)(a_uExit) < sizeof(pDbgState->bmExitsToCheck) * 8); \
11384 ASMBitSet((pDbgState)->bmExitsToCheck, a_uExit); \
11385 } else do { } while (0)
11386#define SET_CPEU_XBM_IF_EITHER_EN(a_EventSubName, a_uExit, a_fUnwantedCtrlProcExec) \
11387 if (IS_EITHER_ENABLED(pVM, a_EventSubName)) \
11388 { \
11389 (pDbgState)->fCpe1Unwanted |= (a_fUnwantedCtrlProcExec); \
11390 AssertCompile((unsigned)(a_uExit) < sizeof(pDbgState->bmExitsToCheck) * 8); \
11391 ASMBitSet((pDbgState)->bmExitsToCheck, a_uExit); \
11392 } else do { } while (0)
11393#define SET_CPE2_XBM_IF_EITHER_EN(a_EventSubName, a_uExit, a_fCtrlProcExec2) \
11394 if (IS_EITHER_ENABLED(pVM, a_EventSubName)) \
11395 { \
11396 (pDbgState)->fCpe2Extra |= (a_fCtrlProcExec2); \
11397 AssertCompile((unsigned)(a_uExit) < sizeof(pDbgState->bmExitsToCheck) * 8); \
11398 ASMBitSet((pDbgState)->bmExitsToCheck, a_uExit); \
11399 } else do { } while (0)
11400
11401 SET_ONLY_XBM_IF_EITHER_EN(EXIT_TASK_SWITCH, VMX_EXIT_TASK_SWITCH); /* unconditional */
11402 SET_ONLY_XBM_IF_EITHER_EN(EXIT_VMX_EPT_VIOLATION, VMX_EXIT_EPT_VIOLATION); /* unconditional */
11403 SET_ONLY_XBM_IF_EITHER_EN(EXIT_VMX_EPT_MISCONFIG, VMX_EXIT_EPT_MISCONFIG); /* unconditional (unless #VE) */
11404 SET_ONLY_XBM_IF_EITHER_EN(EXIT_VMX_VAPIC_ACCESS, VMX_EXIT_APIC_ACCESS); /* feature dependent, nothing to enable here */
11405 SET_ONLY_XBM_IF_EITHER_EN(EXIT_VMX_VAPIC_WRITE, VMX_EXIT_APIC_WRITE); /* feature dependent, nothing to enable here */
11406
11407 SET_ONLY_XBM_IF_EITHER_EN(INSTR_CPUID, VMX_EXIT_CPUID); /* unconditional */
11408 SET_ONLY_XBM_IF_EITHER_EN( EXIT_CPUID, VMX_EXIT_CPUID);
11409 SET_ONLY_XBM_IF_EITHER_EN(INSTR_GETSEC, VMX_EXIT_GETSEC); /* unconditional */
11410 SET_ONLY_XBM_IF_EITHER_EN( EXIT_GETSEC, VMX_EXIT_GETSEC);
11411 SET_CPE1_XBM_IF_EITHER_EN(INSTR_HALT, VMX_EXIT_HLT, VMX_PROC_CTLS_HLT_EXIT); /* paranoia */
11412 SET_ONLY_XBM_IF_EITHER_EN( EXIT_HALT, VMX_EXIT_HLT);
11413 SET_ONLY_XBM_IF_EITHER_EN(INSTR_INVD, VMX_EXIT_INVD); /* unconditional */
11414 SET_ONLY_XBM_IF_EITHER_EN( EXIT_INVD, VMX_EXIT_INVD);
11415 SET_CPE1_XBM_IF_EITHER_EN(INSTR_INVLPG, VMX_EXIT_INVLPG, VMX_PROC_CTLS_INVLPG_EXIT);
11416 SET_ONLY_XBM_IF_EITHER_EN( EXIT_INVLPG, VMX_EXIT_INVLPG);
11417 SET_CPE1_XBM_IF_EITHER_EN(INSTR_RDPMC, VMX_EXIT_RDPMC, VMX_PROC_CTLS_RDPMC_EXIT);
11418 SET_ONLY_XBM_IF_EITHER_EN( EXIT_RDPMC, VMX_EXIT_RDPMC);
11419 SET_CPE1_XBM_IF_EITHER_EN(INSTR_RDTSC, VMX_EXIT_RDTSC, VMX_PROC_CTLS_RDTSC_EXIT);
11420 SET_ONLY_XBM_IF_EITHER_EN( EXIT_RDTSC, VMX_EXIT_RDTSC);
11421 SET_ONLY_XBM_IF_EITHER_EN(INSTR_RSM, VMX_EXIT_RSM); /* unconditional */
11422 SET_ONLY_XBM_IF_EITHER_EN( EXIT_RSM, VMX_EXIT_RSM);
11423 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMM_CALL, VMX_EXIT_VMCALL); /* unconditional */
11424 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMM_CALL, VMX_EXIT_VMCALL);
11425 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMX_VMCLEAR, VMX_EXIT_VMCLEAR); /* unconditional */
11426 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_VMCLEAR, VMX_EXIT_VMCLEAR);
11427 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMX_VMLAUNCH, VMX_EXIT_VMLAUNCH); /* unconditional */
11428 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_VMLAUNCH, VMX_EXIT_VMLAUNCH);
11429 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMX_VMPTRLD, VMX_EXIT_VMPTRLD); /* unconditional */
11430 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_VMPTRLD, VMX_EXIT_VMPTRLD);
11431 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMX_VMPTRST, VMX_EXIT_VMPTRST); /* unconditional */
11432 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_VMPTRST, VMX_EXIT_VMPTRST);
11433 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMX_VMREAD, VMX_EXIT_VMREAD); /* unconditional */
11434 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_VMREAD, VMX_EXIT_VMREAD);
11435 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMX_VMRESUME, VMX_EXIT_VMRESUME); /* unconditional */
11436 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_VMRESUME, VMX_EXIT_VMRESUME);
11437 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMX_VMWRITE, VMX_EXIT_VMWRITE); /* unconditional */
11438 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_VMWRITE, VMX_EXIT_VMWRITE);
11439 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMX_VMXOFF, VMX_EXIT_VMXOFF); /* unconditional */
11440 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_VMXOFF, VMX_EXIT_VMXOFF);
11441 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMX_VMXON, VMX_EXIT_VMXON); /* unconditional */
11442 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_VMXON, VMX_EXIT_VMXON);
11443
11444 if ( IS_EITHER_ENABLED(pVM, INSTR_CRX_READ)
11445 || IS_EITHER_ENABLED(pVM, INSTR_CRX_WRITE))
11446 {
11447 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, CPUMCTX_EXTRN_CR0 | CPUMCTX_EXTRN_CR4
11448 | CPUMCTX_EXTRN_APIC_TPR);
11449 AssertRC(rc);
11450
11451#if 0 /** @todo fix me */
11452 pDbgState->fClearCr0Mask = true;
11453 pDbgState->fClearCr4Mask = true;
11454#endif
11455 if (IS_EITHER_ENABLED(pVM, INSTR_CRX_READ))
11456 pDbgState->fCpe1Extra |= VMX_PROC_CTLS_CR3_STORE_EXIT | VMX_PROC_CTLS_CR8_STORE_EXIT;
11457 if (IS_EITHER_ENABLED(pVM, INSTR_CRX_WRITE))
11458 pDbgState->fCpe1Extra |= VMX_PROC_CTLS_CR3_LOAD_EXIT | VMX_PROC_CTLS_CR8_LOAD_EXIT;
11459 pDbgState->fCpe1Unwanted |= VMX_PROC_CTLS_USE_TPR_SHADOW; /* risky? */
11460 /* Note! We currently don't use VMX_VMCS32_CTRL_CR3_TARGET_COUNT. It would
11461 require clearing here and in the loop if we start using it. */
11462 ASMBitSet(pDbgState->bmExitsToCheck, VMX_EXIT_MOV_CRX);
11463 }
11464 else
11465 {
11466 if (pDbgState->fClearCr0Mask)
11467 {
11468 pDbgState->fClearCr0Mask = false;
11469 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_CR0);
11470 }
11471 if (pDbgState->fClearCr4Mask)
11472 {
11473 pDbgState->fClearCr4Mask = false;
11474 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_CR4);
11475 }
11476 }
11477 SET_ONLY_XBM_IF_EITHER_EN( EXIT_CRX_READ, VMX_EXIT_MOV_CRX);
11478 SET_ONLY_XBM_IF_EITHER_EN( EXIT_CRX_WRITE, VMX_EXIT_MOV_CRX);
11479
11480 if ( IS_EITHER_ENABLED(pVM, INSTR_DRX_READ)
11481 || IS_EITHER_ENABLED(pVM, INSTR_DRX_WRITE))
11482 {
11483 /** @todo later, need to fix handler as it assumes this won't usually happen. */
11484 ASMBitSet(pDbgState->bmExitsToCheck, VMX_EXIT_MOV_DRX);
11485 }
11486 SET_ONLY_XBM_IF_EITHER_EN( EXIT_DRX_READ, VMX_EXIT_MOV_DRX);
11487 SET_ONLY_XBM_IF_EITHER_EN( EXIT_DRX_WRITE, VMX_EXIT_MOV_DRX);
11488
11489 SET_CPEU_XBM_IF_EITHER_EN(INSTR_RDMSR, VMX_EXIT_RDMSR, VMX_PROC_CTLS_USE_MSR_BITMAPS); /* risky clearing this? */
11490 SET_ONLY_XBM_IF_EITHER_EN( EXIT_RDMSR, VMX_EXIT_RDMSR);
11491 SET_CPEU_XBM_IF_EITHER_EN(INSTR_WRMSR, VMX_EXIT_WRMSR, VMX_PROC_CTLS_USE_MSR_BITMAPS);
11492 SET_ONLY_XBM_IF_EITHER_EN( EXIT_WRMSR, VMX_EXIT_WRMSR);
11493 SET_CPE1_XBM_IF_EITHER_EN(INSTR_MWAIT, VMX_EXIT_MWAIT, VMX_PROC_CTLS_MWAIT_EXIT); /* paranoia */
11494 SET_ONLY_XBM_IF_EITHER_EN( EXIT_MWAIT, VMX_EXIT_MWAIT);
11495 SET_CPE1_XBM_IF_EITHER_EN(INSTR_MONITOR, VMX_EXIT_MONITOR, VMX_PROC_CTLS_MONITOR_EXIT); /* paranoia */
11496 SET_ONLY_XBM_IF_EITHER_EN( EXIT_MONITOR, VMX_EXIT_MONITOR);
11497#if 0 /** @todo too slow, fix handler. */
11498 SET_CPE1_XBM_IF_EITHER_EN(INSTR_PAUSE, VMX_EXIT_PAUSE, VMX_PROC_CTLS_PAUSE_EXIT);
11499#endif
11500 SET_ONLY_XBM_IF_EITHER_EN( EXIT_PAUSE, VMX_EXIT_PAUSE);
11501
11502 if ( IS_EITHER_ENABLED(pVM, INSTR_SGDT)
11503 || IS_EITHER_ENABLED(pVM, INSTR_SIDT)
11504 || IS_EITHER_ENABLED(pVM, INSTR_LGDT)
11505 || IS_EITHER_ENABLED(pVM, INSTR_LIDT))
11506 {
11507 pDbgState->fCpe2Extra |= VMX_PROC_CTLS2_DESC_TABLE_EXIT;
11508 ASMBitSet(pDbgState->bmExitsToCheck, VMX_EXIT_GDTR_IDTR_ACCESS);
11509 }
11510 SET_ONLY_XBM_IF_EITHER_EN( EXIT_SGDT, VMX_EXIT_GDTR_IDTR_ACCESS);
11511 SET_ONLY_XBM_IF_EITHER_EN( EXIT_SIDT, VMX_EXIT_GDTR_IDTR_ACCESS);
11512 SET_ONLY_XBM_IF_EITHER_EN( EXIT_LGDT, VMX_EXIT_GDTR_IDTR_ACCESS);
11513 SET_ONLY_XBM_IF_EITHER_EN( EXIT_LIDT, VMX_EXIT_GDTR_IDTR_ACCESS);
11514
11515 if ( IS_EITHER_ENABLED(pVM, INSTR_SLDT)
11516 || IS_EITHER_ENABLED(pVM, INSTR_STR)
11517 || IS_EITHER_ENABLED(pVM, INSTR_LLDT)
11518 || IS_EITHER_ENABLED(pVM, INSTR_LTR))
11519 {
11520 pDbgState->fCpe2Extra |= VMX_PROC_CTLS2_DESC_TABLE_EXIT;
11521 ASMBitSet(pDbgState->bmExitsToCheck, VMX_EXIT_LDTR_TR_ACCESS);
11522 }
11523 SET_ONLY_XBM_IF_EITHER_EN( EXIT_SLDT, VMX_EXIT_LDTR_TR_ACCESS);
11524 SET_ONLY_XBM_IF_EITHER_EN( EXIT_STR, VMX_EXIT_LDTR_TR_ACCESS);
11525 SET_ONLY_XBM_IF_EITHER_EN( EXIT_LLDT, VMX_EXIT_LDTR_TR_ACCESS);
11526 SET_ONLY_XBM_IF_EITHER_EN( EXIT_LTR, VMX_EXIT_LDTR_TR_ACCESS);
11527
11528 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMX_INVEPT, VMX_EXIT_INVEPT); /* unconditional */
11529 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_INVEPT, VMX_EXIT_INVEPT);
11530 SET_CPE1_XBM_IF_EITHER_EN(INSTR_RDTSCP, VMX_EXIT_RDTSCP, VMX_PROC_CTLS_RDTSC_EXIT);
11531 SET_ONLY_XBM_IF_EITHER_EN( EXIT_RDTSCP, VMX_EXIT_RDTSCP);
11532 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMX_INVVPID, VMX_EXIT_INVVPID); /* unconditional */
11533 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_INVVPID, VMX_EXIT_INVVPID);
11534 SET_CPE2_XBM_IF_EITHER_EN(INSTR_WBINVD, VMX_EXIT_WBINVD, VMX_PROC_CTLS2_WBINVD_EXIT);
11535 SET_ONLY_XBM_IF_EITHER_EN( EXIT_WBINVD, VMX_EXIT_WBINVD);
11536 SET_ONLY_XBM_IF_EITHER_EN(INSTR_XSETBV, VMX_EXIT_XSETBV); /* unconditional */
11537 SET_ONLY_XBM_IF_EITHER_EN( EXIT_XSETBV, VMX_EXIT_XSETBV);
11538 SET_CPE2_XBM_IF_EITHER_EN(INSTR_RDRAND, VMX_EXIT_RDRAND, VMX_PROC_CTLS2_RDRAND_EXIT);
11539 SET_ONLY_XBM_IF_EITHER_EN( EXIT_RDRAND, VMX_EXIT_RDRAND);
11540 SET_CPE1_XBM_IF_EITHER_EN(INSTR_VMX_INVPCID, VMX_EXIT_INVPCID, VMX_PROC_CTLS_INVLPG_EXIT);
11541 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_INVPCID, VMX_EXIT_INVPCID);
11542 SET_ONLY_XBM_IF_EITHER_EN(INSTR_VMX_VMFUNC, VMX_EXIT_VMFUNC); /* unconditional for the current setup */
11543 SET_ONLY_XBM_IF_EITHER_EN( EXIT_VMX_VMFUNC, VMX_EXIT_VMFUNC);
11544 SET_CPE2_XBM_IF_EITHER_EN(INSTR_RDSEED, VMX_EXIT_RDSEED, VMX_PROC_CTLS2_RDSEED_EXIT);
11545 SET_ONLY_XBM_IF_EITHER_EN( EXIT_RDSEED, VMX_EXIT_RDSEED);
11546 SET_ONLY_XBM_IF_EITHER_EN(INSTR_XSAVES, VMX_EXIT_XSAVES); /* unconditional (enabled by host, guest cfg) */
11547 SET_ONLY_XBM_IF_EITHER_EN(EXIT_XSAVES, VMX_EXIT_XSAVES);
11548 SET_ONLY_XBM_IF_EITHER_EN(INSTR_XRSTORS, VMX_EXIT_XRSTORS); /* unconditional (enabled by host, guest cfg) */
11549 SET_ONLY_XBM_IF_EITHER_EN( EXIT_XRSTORS, VMX_EXIT_XRSTORS);
11550
11551#undef IS_EITHER_ENABLED
11552#undef SET_ONLY_XBM_IF_EITHER_EN
11553#undef SET_CPE1_XBM_IF_EITHER_EN
11554#undef SET_CPEU_XBM_IF_EITHER_EN
11555#undef SET_CPE2_XBM_IF_EITHER_EN
11556
11557 /*
11558 * Sanitize the control stuff.
11559 */
11560 pDbgState->fCpe2Extra &= pVM->hm.s.vmx.Msrs.ProcCtls2.n.allowed1;
11561 if (pDbgState->fCpe2Extra)
11562 pDbgState->fCpe1Extra |= VMX_PROC_CTLS_USE_SECONDARY_CTLS;
11563 pDbgState->fCpe1Extra &= pVM->hm.s.vmx.Msrs.ProcCtls.n.allowed1;
11564 pDbgState->fCpe1Unwanted &= ~pVM->hm.s.vmx.Msrs.ProcCtls.n.allowed0;
11565 if (pVCpu->hm.s.fDebugWantRdTscExit != RT_BOOL(pDbgState->fCpe1Extra & VMX_PROC_CTLS_RDTSC_EXIT))
11566 {
11567 pVCpu->hm.s.fDebugWantRdTscExit ^= true;
11568 pVmxTransient->fUpdatedTscOffsettingAndPreemptTimer = false;
11569 }
11570
11571 Log6(("HM: debug state: cpe1=%#RX32 cpeu=%#RX32 cpe2=%#RX32%s%s\n",
11572 pDbgState->fCpe1Extra, pDbgState->fCpe1Unwanted, pDbgState->fCpe2Extra,
11573 pDbgState->fClearCr0Mask ? " clr-cr0" : "",
11574 pDbgState->fClearCr4Mask ? " clr-cr4" : ""));
11575}
11576
11577
11578/**
11579 * Fires off DBGF events and dtrace probes for a VM-exit, when it's
11580 * appropriate.
11581 *
11582 * The caller has checked the VM-exit against the
11583 * VMXRUNDBGSTATE::bmExitsToCheck bitmap. The caller has checked for NMIs
11584 * already, so we don't have to do that either.
11585 *
11586 * @returns Strict VBox status code (i.e. informational status codes too).
11587 * @param pVCpu The cross context virtual CPU structure.
11588 * @param pVmxTransient The VMX-transient structure.
11589 * @param uExitReason The VM-exit reason.
11590 *
11591 * @remarks The name of this function is displayed by dtrace, so keep it short
11592 * and to the point. No longer than 33 chars long, please.
11593 */
11594static VBOXSTRICTRC hmR0VmxHandleExitDtraceEvents(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient, uint32_t uExitReason)
11595{
11596 /*
11597 * Translate the event into a DBGF event (enmEvent + uEventArg) and at the
11598 * same time check whether any corresponding Dtrace event is enabled (fDtrace).
11599 *
11600 * Note! This is the reverse operation of what hmR0VmxPreRunGuestDebugStateUpdate
11601 * does. Must add/change/remove both places. Same ordering, please.
11602 *
11603 * Added/removed events must also be reflected in the next section
11604 * where we dispatch dtrace events.
11605 */
11606 bool fDtrace1 = false;
11607 bool fDtrace2 = false;
11608 DBGFEVENTTYPE enmEvent1 = DBGFEVENT_END;
11609 DBGFEVENTTYPE enmEvent2 = DBGFEVENT_END;
11610 uint32_t uEventArg = 0;
11611#define SET_EXIT(a_EventSubName) \
11612 do { \
11613 enmEvent2 = RT_CONCAT(DBGFEVENT_EXIT_, a_EventSubName); \
11614 fDtrace2 = RT_CONCAT3(VBOXVMM_EXIT_, a_EventSubName, _ENABLED)(); \
11615 } while (0)
11616#define SET_BOTH(a_EventSubName) \
11617 do { \
11618 enmEvent1 = RT_CONCAT(DBGFEVENT_INSTR_, a_EventSubName); \
11619 enmEvent2 = RT_CONCAT(DBGFEVENT_EXIT_, a_EventSubName); \
11620 fDtrace1 = RT_CONCAT3(VBOXVMM_INSTR_, a_EventSubName, _ENABLED)(); \
11621 fDtrace2 = RT_CONCAT3(VBOXVMM_EXIT_, a_EventSubName, _ENABLED)(); \
11622 } while (0)
11623 switch (uExitReason)
11624 {
11625 case VMX_EXIT_MTF:
11626 return hmR0VmxExitMtf(pVCpu, pVmxTransient);
11627
11628 case VMX_EXIT_XCPT_OR_NMI:
11629 {
11630 uint8_t const idxVector = VMX_EXIT_INT_INFO_VECTOR(pVmxTransient->uExitIntInfo);
11631 switch (VMX_EXIT_INT_INFO_TYPE(pVmxTransient->uExitIntInfo))
11632 {
11633 case VMX_EXIT_INT_INFO_TYPE_HW_XCPT:
11634 case VMX_EXIT_INT_INFO_TYPE_SW_XCPT:
11635 case VMX_EXIT_INT_INFO_TYPE_PRIV_SW_XCPT:
11636 if (idxVector <= (unsigned)(DBGFEVENT_XCPT_LAST - DBGFEVENT_XCPT_FIRST))
11637 {
11638 if (VMX_EXIT_INT_INFO_IS_ERROR_CODE_VALID(pVmxTransient->uExitIntInfo))
11639 {
11640 hmR0VmxReadExitIntErrorCodeVmcs(pVmxTransient);
11641 uEventArg = pVmxTransient->uExitIntErrorCode;
11642 }
11643 enmEvent1 = (DBGFEVENTTYPE)(DBGFEVENT_XCPT_FIRST + idxVector);
11644 switch (enmEvent1)
11645 {
11646 case DBGFEVENT_XCPT_DE: fDtrace1 = VBOXVMM_XCPT_DE_ENABLED(); break;
11647 case DBGFEVENT_XCPT_DB: fDtrace1 = VBOXVMM_XCPT_DB_ENABLED(); break;
11648 case DBGFEVENT_XCPT_BP: fDtrace1 = VBOXVMM_XCPT_BP_ENABLED(); break;
11649 case DBGFEVENT_XCPT_OF: fDtrace1 = VBOXVMM_XCPT_OF_ENABLED(); break;
11650 case DBGFEVENT_XCPT_BR: fDtrace1 = VBOXVMM_XCPT_BR_ENABLED(); break;
11651 case DBGFEVENT_XCPT_UD: fDtrace1 = VBOXVMM_XCPT_UD_ENABLED(); break;
11652 case DBGFEVENT_XCPT_NM: fDtrace1 = VBOXVMM_XCPT_NM_ENABLED(); break;
11653 case DBGFEVENT_XCPT_DF: fDtrace1 = VBOXVMM_XCPT_DF_ENABLED(); break;
11654 case DBGFEVENT_XCPT_TS: fDtrace1 = VBOXVMM_XCPT_TS_ENABLED(); break;
11655 case DBGFEVENT_XCPT_NP: fDtrace1 = VBOXVMM_XCPT_NP_ENABLED(); break;
11656 case DBGFEVENT_XCPT_SS: fDtrace1 = VBOXVMM_XCPT_SS_ENABLED(); break;
11657 case DBGFEVENT_XCPT_GP: fDtrace1 = VBOXVMM_XCPT_GP_ENABLED(); break;
11658 case DBGFEVENT_XCPT_PF: fDtrace1 = VBOXVMM_XCPT_PF_ENABLED(); break;
11659 case DBGFEVENT_XCPT_MF: fDtrace1 = VBOXVMM_XCPT_MF_ENABLED(); break;
11660 case DBGFEVENT_XCPT_AC: fDtrace1 = VBOXVMM_XCPT_AC_ENABLED(); break;
11661 case DBGFEVENT_XCPT_XF: fDtrace1 = VBOXVMM_XCPT_XF_ENABLED(); break;
11662 case DBGFEVENT_XCPT_VE: fDtrace1 = VBOXVMM_XCPT_VE_ENABLED(); break;
11663 case DBGFEVENT_XCPT_SX: fDtrace1 = VBOXVMM_XCPT_SX_ENABLED(); break;
11664 default: break;
11665 }
11666 }
11667 else
11668 AssertFailed();
11669 break;
11670
11671 case VMX_EXIT_INT_INFO_TYPE_SW_INT:
11672 uEventArg = idxVector;
11673 enmEvent1 = DBGFEVENT_INTERRUPT_SOFTWARE;
11674 fDtrace1 = VBOXVMM_INT_SOFTWARE_ENABLED();
11675 break;
11676 }
11677 break;
11678 }
11679
11680 case VMX_EXIT_TRIPLE_FAULT:
11681 enmEvent1 = DBGFEVENT_TRIPLE_FAULT;
11682 //fDtrace1 = VBOXVMM_EXIT_TRIPLE_FAULT_ENABLED();
11683 break;
11684 case VMX_EXIT_TASK_SWITCH: SET_EXIT(TASK_SWITCH); break;
11685 case VMX_EXIT_EPT_VIOLATION: SET_EXIT(VMX_EPT_VIOLATION); break;
11686 case VMX_EXIT_EPT_MISCONFIG: SET_EXIT(VMX_EPT_MISCONFIG); break;
11687 case VMX_EXIT_APIC_ACCESS: SET_EXIT(VMX_VAPIC_ACCESS); break;
11688 case VMX_EXIT_APIC_WRITE: SET_EXIT(VMX_VAPIC_WRITE); break;
11689
11690 /* Instruction specific VM-exits: */
11691 case VMX_EXIT_CPUID: SET_BOTH(CPUID); break;
11692 case VMX_EXIT_GETSEC: SET_BOTH(GETSEC); break;
11693 case VMX_EXIT_HLT: SET_BOTH(HALT); break;
11694 case VMX_EXIT_INVD: SET_BOTH(INVD); break;
11695 case VMX_EXIT_INVLPG: SET_BOTH(INVLPG); break;
11696 case VMX_EXIT_RDPMC: SET_BOTH(RDPMC); break;
11697 case VMX_EXIT_RDTSC: SET_BOTH(RDTSC); break;
11698 case VMX_EXIT_RSM: SET_BOTH(RSM); break;
11699 case VMX_EXIT_VMCALL: SET_BOTH(VMM_CALL); break;
11700 case VMX_EXIT_VMCLEAR: SET_BOTH(VMX_VMCLEAR); break;
11701 case VMX_EXIT_VMLAUNCH: SET_BOTH(VMX_VMLAUNCH); break;
11702 case VMX_EXIT_VMPTRLD: SET_BOTH(VMX_VMPTRLD); break;
11703 case VMX_EXIT_VMPTRST: SET_BOTH(VMX_VMPTRST); break;
11704 case VMX_EXIT_VMREAD: SET_BOTH(VMX_VMREAD); break;
11705 case VMX_EXIT_VMRESUME: SET_BOTH(VMX_VMRESUME); break;
11706 case VMX_EXIT_VMWRITE: SET_BOTH(VMX_VMWRITE); break;
11707 case VMX_EXIT_VMXOFF: SET_BOTH(VMX_VMXOFF); break;
11708 case VMX_EXIT_VMXON: SET_BOTH(VMX_VMXON); break;
11709 case VMX_EXIT_MOV_CRX:
11710 hmR0VmxReadExitQualVmcs(pVmxTransient);
11711 if (VMX_EXIT_QUAL_CRX_ACCESS(pVmxTransient->uExitQual) == VMX_EXIT_QUAL_CRX_ACCESS_READ)
11712 SET_BOTH(CRX_READ);
11713 else
11714 SET_BOTH(CRX_WRITE);
11715 uEventArg = VMX_EXIT_QUAL_CRX_REGISTER(pVmxTransient->uExitQual);
11716 break;
11717 case VMX_EXIT_MOV_DRX:
11718 hmR0VmxReadExitQualVmcs(pVmxTransient);
11719 if ( VMX_EXIT_QUAL_DRX_DIRECTION(pVmxTransient->uExitQual)
11720 == VMX_EXIT_QUAL_DRX_DIRECTION_READ)
11721 SET_BOTH(DRX_READ);
11722 else
11723 SET_BOTH(DRX_WRITE);
11724 uEventArg = VMX_EXIT_QUAL_DRX_REGISTER(pVmxTransient->uExitQual);
11725 break;
11726 case VMX_EXIT_RDMSR: SET_BOTH(RDMSR); break;
11727 case VMX_EXIT_WRMSR: SET_BOTH(WRMSR); break;
11728 case VMX_EXIT_MWAIT: SET_BOTH(MWAIT); break;
11729 case VMX_EXIT_MONITOR: SET_BOTH(MONITOR); break;
11730 case VMX_EXIT_PAUSE: SET_BOTH(PAUSE); break;
11731 case VMX_EXIT_GDTR_IDTR_ACCESS:
11732 hmR0VmxReadExitInstrInfoVmcs(pVmxTransient);
11733 switch (RT_BF_GET(pVmxTransient->ExitInstrInfo.u, VMX_BF_XDTR_INSINFO_INSTR_ID))
11734 {
11735 case VMX_XDTR_INSINFO_II_SGDT: SET_BOTH(SGDT); break;
11736 case VMX_XDTR_INSINFO_II_SIDT: SET_BOTH(SIDT); break;
11737 case VMX_XDTR_INSINFO_II_LGDT: SET_BOTH(LGDT); break;
11738 case VMX_XDTR_INSINFO_II_LIDT: SET_BOTH(LIDT); break;
11739 }
11740 break;
11741
11742 case VMX_EXIT_LDTR_TR_ACCESS:
11743 hmR0VmxReadExitInstrInfoVmcs(pVmxTransient);
11744 switch (RT_BF_GET(pVmxTransient->ExitInstrInfo.u, VMX_BF_YYTR_INSINFO_INSTR_ID))
11745 {
11746 case VMX_YYTR_INSINFO_II_SLDT: SET_BOTH(SLDT); break;
11747 case VMX_YYTR_INSINFO_II_STR: SET_BOTH(STR); break;
11748 case VMX_YYTR_INSINFO_II_LLDT: SET_BOTH(LLDT); break;
11749 case VMX_YYTR_INSINFO_II_LTR: SET_BOTH(LTR); break;
11750 }
11751 break;
11752
11753 case VMX_EXIT_INVEPT: SET_BOTH(VMX_INVEPT); break;
11754 case VMX_EXIT_RDTSCP: SET_BOTH(RDTSCP); break;
11755 case VMX_EXIT_INVVPID: SET_BOTH(VMX_INVVPID); break;
11756 case VMX_EXIT_WBINVD: SET_BOTH(WBINVD); break;
11757 case VMX_EXIT_XSETBV: SET_BOTH(XSETBV); break;
11758 case VMX_EXIT_RDRAND: SET_BOTH(RDRAND); break;
11759 case VMX_EXIT_INVPCID: SET_BOTH(VMX_INVPCID); break;
11760 case VMX_EXIT_VMFUNC: SET_BOTH(VMX_VMFUNC); break;
11761 case VMX_EXIT_RDSEED: SET_BOTH(RDSEED); break;
11762 case VMX_EXIT_XSAVES: SET_BOTH(XSAVES); break;
11763 case VMX_EXIT_XRSTORS: SET_BOTH(XRSTORS); break;
11764
11765 /* Events that aren't relevant at this point. */
11766 case VMX_EXIT_EXT_INT:
11767 case VMX_EXIT_INT_WINDOW:
11768 case VMX_EXIT_NMI_WINDOW:
11769 case VMX_EXIT_TPR_BELOW_THRESHOLD:
11770 case VMX_EXIT_PREEMPT_TIMER:
11771 case VMX_EXIT_IO_INSTR:
11772 break;
11773
11774 /* Errors and unexpected events. */
11775 case VMX_EXIT_INIT_SIGNAL:
11776 case VMX_EXIT_SIPI:
11777 case VMX_EXIT_IO_SMI:
11778 case VMX_EXIT_SMI:
11779 case VMX_EXIT_ERR_INVALID_GUEST_STATE:
11780 case VMX_EXIT_ERR_MSR_LOAD:
11781 case VMX_EXIT_ERR_MACHINE_CHECK:
11782 case VMX_EXIT_PML_FULL:
11783 case VMX_EXIT_VIRTUALIZED_EOI:
11784 break;
11785
11786 default:
11787 AssertMsgFailed(("Unexpected VM-exit=%#x\n", uExitReason));
11788 break;
11789 }
11790#undef SET_BOTH
11791#undef SET_EXIT
11792
11793 /*
11794 * Dtrace tracepoints go first. We do them here at once so we don't
11795 * have to copy the guest state saving and stuff a few dozen times.
11796 * Down side is that we've got to repeat the switch, though this time
11797 * we use enmEvent since the probes are a subset of what DBGF does.
11798 */
11799 if (fDtrace1 || fDtrace2)
11800 {
11801 hmR0VmxReadExitQualVmcs(pVmxTransient);
11802 hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, HMVMX_CPUMCTX_EXTRN_ALL);
11803 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
11804 switch (enmEvent1)
11805 {
11806 /** @todo consider which extra parameters would be helpful for each probe. */
11807 case DBGFEVENT_END: break;
11808 case DBGFEVENT_XCPT_DE: VBOXVMM_XCPT_DE(pVCpu, pCtx); break;
11809 case DBGFEVENT_XCPT_DB: VBOXVMM_XCPT_DB(pVCpu, pCtx, pCtx->dr[6]); break;
11810 case DBGFEVENT_XCPT_BP: VBOXVMM_XCPT_BP(pVCpu, pCtx); break;
11811 case DBGFEVENT_XCPT_OF: VBOXVMM_XCPT_OF(pVCpu, pCtx); break;
11812 case DBGFEVENT_XCPT_BR: VBOXVMM_XCPT_BR(pVCpu, pCtx); break;
11813 case DBGFEVENT_XCPT_UD: VBOXVMM_XCPT_UD(pVCpu, pCtx); break;
11814 case DBGFEVENT_XCPT_NM: VBOXVMM_XCPT_NM(pVCpu, pCtx); break;
11815 case DBGFEVENT_XCPT_DF: VBOXVMM_XCPT_DF(pVCpu, pCtx); break;
11816 case DBGFEVENT_XCPT_TS: VBOXVMM_XCPT_TS(pVCpu, pCtx, uEventArg); break;
11817 case DBGFEVENT_XCPT_NP: VBOXVMM_XCPT_NP(pVCpu, pCtx, uEventArg); break;
11818 case DBGFEVENT_XCPT_SS: VBOXVMM_XCPT_SS(pVCpu, pCtx, uEventArg); break;
11819 case DBGFEVENT_XCPT_GP: VBOXVMM_XCPT_GP(pVCpu, pCtx, uEventArg); break;
11820 case DBGFEVENT_XCPT_PF: VBOXVMM_XCPT_PF(pVCpu, pCtx, uEventArg, pCtx->cr2); break;
11821 case DBGFEVENT_XCPT_MF: VBOXVMM_XCPT_MF(pVCpu, pCtx); break;
11822 case DBGFEVENT_XCPT_AC: VBOXVMM_XCPT_AC(pVCpu, pCtx); break;
11823 case DBGFEVENT_XCPT_XF: VBOXVMM_XCPT_XF(pVCpu, pCtx); break;
11824 case DBGFEVENT_XCPT_VE: VBOXVMM_XCPT_VE(pVCpu, pCtx); break;
11825 case DBGFEVENT_XCPT_SX: VBOXVMM_XCPT_SX(pVCpu, pCtx, uEventArg); break;
11826 case DBGFEVENT_INTERRUPT_SOFTWARE: VBOXVMM_INT_SOFTWARE(pVCpu, pCtx, (uint8_t)uEventArg); break;
11827 case DBGFEVENT_INSTR_CPUID: VBOXVMM_INSTR_CPUID(pVCpu, pCtx, pCtx->eax, pCtx->ecx); break;
11828 case DBGFEVENT_INSTR_GETSEC: VBOXVMM_INSTR_GETSEC(pVCpu, pCtx); break;
11829 case DBGFEVENT_INSTR_HALT: VBOXVMM_INSTR_HALT(pVCpu, pCtx); break;
11830 case DBGFEVENT_INSTR_INVD: VBOXVMM_INSTR_INVD(pVCpu, pCtx); break;
11831 case DBGFEVENT_INSTR_INVLPG: VBOXVMM_INSTR_INVLPG(pVCpu, pCtx); break;
11832 case DBGFEVENT_INSTR_RDPMC: VBOXVMM_INSTR_RDPMC(pVCpu, pCtx); break;
11833 case DBGFEVENT_INSTR_RDTSC: VBOXVMM_INSTR_RDTSC(pVCpu, pCtx); break;
11834 case DBGFEVENT_INSTR_RSM: VBOXVMM_INSTR_RSM(pVCpu, pCtx); break;
11835 case DBGFEVENT_INSTR_CRX_READ: VBOXVMM_INSTR_CRX_READ(pVCpu, pCtx, (uint8_t)uEventArg); break;
11836 case DBGFEVENT_INSTR_CRX_WRITE: VBOXVMM_INSTR_CRX_WRITE(pVCpu, pCtx, (uint8_t)uEventArg); break;
11837 case DBGFEVENT_INSTR_DRX_READ: VBOXVMM_INSTR_DRX_READ(pVCpu, pCtx, (uint8_t)uEventArg); break;
11838 case DBGFEVENT_INSTR_DRX_WRITE: VBOXVMM_INSTR_DRX_WRITE(pVCpu, pCtx, (uint8_t)uEventArg); break;
11839 case DBGFEVENT_INSTR_RDMSR: VBOXVMM_INSTR_RDMSR(pVCpu, pCtx, pCtx->ecx); break;
11840 case DBGFEVENT_INSTR_WRMSR: VBOXVMM_INSTR_WRMSR(pVCpu, pCtx, pCtx->ecx,
11841 RT_MAKE_U64(pCtx->eax, pCtx->edx)); break;
11842 case DBGFEVENT_INSTR_MWAIT: VBOXVMM_INSTR_MWAIT(pVCpu, pCtx); break;
11843 case DBGFEVENT_INSTR_MONITOR: VBOXVMM_INSTR_MONITOR(pVCpu, pCtx); break;
11844 case DBGFEVENT_INSTR_PAUSE: VBOXVMM_INSTR_PAUSE(pVCpu, pCtx); break;
11845 case DBGFEVENT_INSTR_SGDT: VBOXVMM_INSTR_SGDT(pVCpu, pCtx); break;
11846 case DBGFEVENT_INSTR_SIDT: VBOXVMM_INSTR_SIDT(pVCpu, pCtx); break;
11847 case DBGFEVENT_INSTR_LGDT: VBOXVMM_INSTR_LGDT(pVCpu, pCtx); break;
11848 case DBGFEVENT_INSTR_LIDT: VBOXVMM_INSTR_LIDT(pVCpu, pCtx); break;
11849 case DBGFEVENT_INSTR_SLDT: VBOXVMM_INSTR_SLDT(pVCpu, pCtx); break;
11850 case DBGFEVENT_INSTR_STR: VBOXVMM_INSTR_STR(pVCpu, pCtx); break;
11851 case DBGFEVENT_INSTR_LLDT: VBOXVMM_INSTR_LLDT(pVCpu, pCtx); break;
11852 case DBGFEVENT_INSTR_LTR: VBOXVMM_INSTR_LTR(pVCpu, pCtx); break;
11853 case DBGFEVENT_INSTR_RDTSCP: VBOXVMM_INSTR_RDTSCP(pVCpu, pCtx); break;
11854 case DBGFEVENT_INSTR_WBINVD: VBOXVMM_INSTR_WBINVD(pVCpu, pCtx); break;
11855 case DBGFEVENT_INSTR_XSETBV: VBOXVMM_INSTR_XSETBV(pVCpu, pCtx); break;
11856 case DBGFEVENT_INSTR_RDRAND: VBOXVMM_INSTR_RDRAND(pVCpu, pCtx); break;
11857 case DBGFEVENT_INSTR_RDSEED: VBOXVMM_INSTR_RDSEED(pVCpu, pCtx); break;
11858 case DBGFEVENT_INSTR_XSAVES: VBOXVMM_INSTR_XSAVES(pVCpu, pCtx); break;
11859 case DBGFEVENT_INSTR_XRSTORS: VBOXVMM_INSTR_XRSTORS(pVCpu, pCtx); break;
11860 case DBGFEVENT_INSTR_VMM_CALL: VBOXVMM_INSTR_VMM_CALL(pVCpu, pCtx); break;
11861 case DBGFEVENT_INSTR_VMX_VMCLEAR: VBOXVMM_INSTR_VMX_VMCLEAR(pVCpu, pCtx); break;
11862 case DBGFEVENT_INSTR_VMX_VMLAUNCH: VBOXVMM_INSTR_VMX_VMLAUNCH(pVCpu, pCtx); break;
11863 case DBGFEVENT_INSTR_VMX_VMPTRLD: VBOXVMM_INSTR_VMX_VMPTRLD(pVCpu, pCtx); break;
11864 case DBGFEVENT_INSTR_VMX_VMPTRST: VBOXVMM_INSTR_VMX_VMPTRST(pVCpu, pCtx); break;
11865 case DBGFEVENT_INSTR_VMX_VMREAD: VBOXVMM_INSTR_VMX_VMREAD(pVCpu, pCtx); break;
11866 case DBGFEVENT_INSTR_VMX_VMRESUME: VBOXVMM_INSTR_VMX_VMRESUME(pVCpu, pCtx); break;
11867 case DBGFEVENT_INSTR_VMX_VMWRITE: VBOXVMM_INSTR_VMX_VMWRITE(pVCpu, pCtx); break;
11868 case DBGFEVENT_INSTR_VMX_VMXOFF: VBOXVMM_INSTR_VMX_VMXOFF(pVCpu, pCtx); break;
11869 case DBGFEVENT_INSTR_VMX_VMXON: VBOXVMM_INSTR_VMX_VMXON(pVCpu, pCtx); break;
11870 case DBGFEVENT_INSTR_VMX_INVEPT: VBOXVMM_INSTR_VMX_INVEPT(pVCpu, pCtx); break;
11871 case DBGFEVENT_INSTR_VMX_INVVPID: VBOXVMM_INSTR_VMX_INVVPID(pVCpu, pCtx); break;
11872 case DBGFEVENT_INSTR_VMX_INVPCID: VBOXVMM_INSTR_VMX_INVPCID(pVCpu, pCtx); break;
11873 case DBGFEVENT_INSTR_VMX_VMFUNC: VBOXVMM_INSTR_VMX_VMFUNC(pVCpu, pCtx); break;
11874 default: AssertMsgFailed(("enmEvent1=%d uExitReason=%d\n", enmEvent1, uExitReason)); break;
11875 }
11876 switch (enmEvent2)
11877 {
11878 /** @todo consider which extra parameters would be helpful for each probe. */
11879 case DBGFEVENT_END: break;
11880 case DBGFEVENT_EXIT_TASK_SWITCH: VBOXVMM_EXIT_TASK_SWITCH(pVCpu, pCtx); break;
11881 case DBGFEVENT_EXIT_CPUID: VBOXVMM_EXIT_CPUID(pVCpu, pCtx, pCtx->eax, pCtx->ecx); break;
11882 case DBGFEVENT_EXIT_GETSEC: VBOXVMM_EXIT_GETSEC(pVCpu, pCtx); break;
11883 case DBGFEVENT_EXIT_HALT: VBOXVMM_EXIT_HALT(pVCpu, pCtx); break;
11884 case DBGFEVENT_EXIT_INVD: VBOXVMM_EXIT_INVD(pVCpu, pCtx); break;
11885 case DBGFEVENT_EXIT_INVLPG: VBOXVMM_EXIT_INVLPG(pVCpu, pCtx); break;
11886 case DBGFEVENT_EXIT_RDPMC: VBOXVMM_EXIT_RDPMC(pVCpu, pCtx); break;
11887 case DBGFEVENT_EXIT_RDTSC: VBOXVMM_EXIT_RDTSC(pVCpu, pCtx); break;
11888 case DBGFEVENT_EXIT_RSM: VBOXVMM_EXIT_RSM(pVCpu, pCtx); break;
11889 case DBGFEVENT_EXIT_CRX_READ: VBOXVMM_EXIT_CRX_READ(pVCpu, pCtx, (uint8_t)uEventArg); break;
11890 case DBGFEVENT_EXIT_CRX_WRITE: VBOXVMM_EXIT_CRX_WRITE(pVCpu, pCtx, (uint8_t)uEventArg); break;
11891 case DBGFEVENT_EXIT_DRX_READ: VBOXVMM_EXIT_DRX_READ(pVCpu, pCtx, (uint8_t)uEventArg); break;
11892 case DBGFEVENT_EXIT_DRX_WRITE: VBOXVMM_EXIT_DRX_WRITE(pVCpu, pCtx, (uint8_t)uEventArg); break;
11893 case DBGFEVENT_EXIT_RDMSR: VBOXVMM_EXIT_RDMSR(pVCpu, pCtx, pCtx->ecx); break;
11894 case DBGFEVENT_EXIT_WRMSR: VBOXVMM_EXIT_WRMSR(pVCpu, pCtx, pCtx->ecx,
11895 RT_MAKE_U64(pCtx->eax, pCtx->edx)); break;
11896 case DBGFEVENT_EXIT_MWAIT: VBOXVMM_EXIT_MWAIT(pVCpu, pCtx); break;
11897 case DBGFEVENT_EXIT_MONITOR: VBOXVMM_EXIT_MONITOR(pVCpu, pCtx); break;
11898 case DBGFEVENT_EXIT_PAUSE: VBOXVMM_EXIT_PAUSE(pVCpu, pCtx); break;
11899 case DBGFEVENT_EXIT_SGDT: VBOXVMM_EXIT_SGDT(pVCpu, pCtx); break;
11900 case DBGFEVENT_EXIT_SIDT: VBOXVMM_EXIT_SIDT(pVCpu, pCtx); break;
11901 case DBGFEVENT_EXIT_LGDT: VBOXVMM_EXIT_LGDT(pVCpu, pCtx); break;
11902 case DBGFEVENT_EXIT_LIDT: VBOXVMM_EXIT_LIDT(pVCpu, pCtx); break;
11903 case DBGFEVENT_EXIT_SLDT: VBOXVMM_EXIT_SLDT(pVCpu, pCtx); break;
11904 case DBGFEVENT_EXIT_STR: VBOXVMM_EXIT_STR(pVCpu, pCtx); break;
11905 case DBGFEVENT_EXIT_LLDT: VBOXVMM_EXIT_LLDT(pVCpu, pCtx); break;
11906 case DBGFEVENT_EXIT_LTR: VBOXVMM_EXIT_LTR(pVCpu, pCtx); break;
11907 case DBGFEVENT_EXIT_RDTSCP: VBOXVMM_EXIT_RDTSCP(pVCpu, pCtx); break;
11908 case DBGFEVENT_EXIT_WBINVD: VBOXVMM_EXIT_WBINVD(pVCpu, pCtx); break;
11909 case DBGFEVENT_EXIT_XSETBV: VBOXVMM_EXIT_XSETBV(pVCpu, pCtx); break;
11910 case DBGFEVENT_EXIT_RDRAND: VBOXVMM_EXIT_RDRAND(pVCpu, pCtx); break;
11911 case DBGFEVENT_EXIT_RDSEED: VBOXVMM_EXIT_RDSEED(pVCpu, pCtx); break;
11912 case DBGFEVENT_EXIT_XSAVES: VBOXVMM_EXIT_XSAVES(pVCpu, pCtx); break;
11913 case DBGFEVENT_EXIT_XRSTORS: VBOXVMM_EXIT_XRSTORS(pVCpu, pCtx); break;
11914 case DBGFEVENT_EXIT_VMM_CALL: VBOXVMM_EXIT_VMM_CALL(pVCpu, pCtx); break;
11915 case DBGFEVENT_EXIT_VMX_VMCLEAR: VBOXVMM_EXIT_VMX_VMCLEAR(pVCpu, pCtx); break;
11916 case DBGFEVENT_EXIT_VMX_VMLAUNCH: VBOXVMM_EXIT_VMX_VMLAUNCH(pVCpu, pCtx); break;
11917 case DBGFEVENT_EXIT_VMX_VMPTRLD: VBOXVMM_EXIT_VMX_VMPTRLD(pVCpu, pCtx); break;
11918 case DBGFEVENT_EXIT_VMX_VMPTRST: VBOXVMM_EXIT_VMX_VMPTRST(pVCpu, pCtx); break;
11919 case DBGFEVENT_EXIT_VMX_VMREAD: VBOXVMM_EXIT_VMX_VMREAD(pVCpu, pCtx); break;
11920 case DBGFEVENT_EXIT_VMX_VMRESUME: VBOXVMM_EXIT_VMX_VMRESUME(pVCpu, pCtx); break;
11921 case DBGFEVENT_EXIT_VMX_VMWRITE: VBOXVMM_EXIT_VMX_VMWRITE(pVCpu, pCtx); break;
11922 case DBGFEVENT_EXIT_VMX_VMXOFF: VBOXVMM_EXIT_VMX_VMXOFF(pVCpu, pCtx); break;
11923 case DBGFEVENT_EXIT_VMX_VMXON: VBOXVMM_EXIT_VMX_VMXON(pVCpu, pCtx); break;
11924 case DBGFEVENT_EXIT_VMX_INVEPT: VBOXVMM_EXIT_VMX_INVEPT(pVCpu, pCtx); break;
11925 case DBGFEVENT_EXIT_VMX_INVVPID: VBOXVMM_EXIT_VMX_INVVPID(pVCpu, pCtx); break;
11926 case DBGFEVENT_EXIT_VMX_INVPCID: VBOXVMM_EXIT_VMX_INVPCID(pVCpu, pCtx); break;
11927 case DBGFEVENT_EXIT_VMX_VMFUNC: VBOXVMM_EXIT_VMX_VMFUNC(pVCpu, pCtx); break;
11928 case DBGFEVENT_EXIT_VMX_EPT_MISCONFIG: VBOXVMM_EXIT_VMX_EPT_MISCONFIG(pVCpu, pCtx); break;
11929 case DBGFEVENT_EXIT_VMX_EPT_VIOLATION: VBOXVMM_EXIT_VMX_EPT_VIOLATION(pVCpu, pCtx); break;
11930 case DBGFEVENT_EXIT_VMX_VAPIC_ACCESS: VBOXVMM_EXIT_VMX_VAPIC_ACCESS(pVCpu, pCtx); break;
11931 case DBGFEVENT_EXIT_VMX_VAPIC_WRITE: VBOXVMM_EXIT_VMX_VAPIC_WRITE(pVCpu, pCtx); break;
11932 default: AssertMsgFailed(("enmEvent2=%d uExitReason=%d\n", enmEvent2, uExitReason)); break;
11933 }
11934 }
11935
11936 /*
11937 * Fire of the DBGF event, if enabled (our check here is just a quick one,
11938 * the DBGF call will do a full check).
11939 *
11940 * Note! DBGF sets DBGFEVENT_INTERRUPT_SOFTWARE in the bitmap.
11941 * Note! If we have to events, we prioritize the first, i.e. the instruction
11942 * one, in order to avoid event nesting.
11943 */
11944 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
11945 if ( enmEvent1 != DBGFEVENT_END
11946 && DBGF_IS_EVENT_ENABLED(pVM, enmEvent1))
11947 {
11948 hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, CPUMCTX_EXTRN_CS | CPUMCTX_EXTRN_RIP);
11949 VBOXSTRICTRC rcStrict = DBGFEventGenericWithArgs(pVM, pVCpu, enmEvent1, DBGFEVENTCTX_HM, 1, uEventArg);
11950 if (rcStrict != VINF_SUCCESS)
11951 return rcStrict;
11952 }
11953 else if ( enmEvent2 != DBGFEVENT_END
11954 && DBGF_IS_EVENT_ENABLED(pVM, enmEvent2))
11955 {
11956 hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, CPUMCTX_EXTRN_CS | CPUMCTX_EXTRN_RIP);
11957 VBOXSTRICTRC rcStrict = DBGFEventGenericWithArgs(pVM, pVCpu, enmEvent2, DBGFEVENTCTX_HM, 1, uEventArg);
11958 if (rcStrict != VINF_SUCCESS)
11959 return rcStrict;
11960 }
11961
11962 return VINF_SUCCESS;
11963}
11964
11965
11966/**
11967 * Single-stepping VM-exit filtering.
11968 *
11969 * This is preprocessing the VM-exits and deciding whether we've gotten far
11970 * enough to return VINF_EM_DBG_STEPPED already. If not, normal VM-exit
11971 * handling is performed.
11972 *
11973 * @returns Strict VBox status code (i.e. informational status codes too).
11974 * @param pVCpu The cross context virtual CPU structure of the calling EMT.
11975 * @param pVmxTransient The VMX-transient structure.
11976 * @param pDbgState The debug state.
11977 */
11978DECLINLINE(VBOXSTRICTRC) hmR0VmxRunDebugHandleExit(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient, PVMXRUNDBGSTATE pDbgState)
11979{
11980 /*
11981 * Expensive (saves context) generic dtrace VM-exit probe.
11982 */
11983 uint32_t const uExitReason = pVmxTransient->uExitReason;
11984 if (!VBOXVMM_R0_HMVMX_VMEXIT_ENABLED())
11985 { /* more likely */ }
11986 else
11987 {
11988 hmR0VmxReadExitQualVmcs(pVmxTransient);
11989 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, HMVMX_CPUMCTX_EXTRN_ALL);
11990 AssertRC(rc);
11991 VBOXVMM_R0_HMVMX_VMEXIT(pVCpu, &pVCpu->cpum.GstCtx, pVmxTransient->uExitReason, pVmxTransient->uExitQual);
11992 }
11993
11994 /*
11995 * Check for host NMI, just to get that out of the way.
11996 */
11997 if (uExitReason != VMX_EXIT_XCPT_OR_NMI)
11998 { /* normally likely */ }
11999 else
12000 {
12001 hmR0VmxReadExitIntInfoVmcs(pVmxTransient);
12002 uint32_t const uIntType = VMX_EXIT_INT_INFO_TYPE(pVmxTransient->uExitIntInfo);
12003 if (uIntType == VMX_EXIT_INT_INFO_TYPE_NMI)
12004 return hmR0VmxExitHostNmi(pVCpu, pVmxTransient->pVmcsInfo);
12005 }
12006
12007 /*
12008 * Check for single stepping event if we're stepping.
12009 */
12010 if (pVCpu->hm.s.fSingleInstruction)
12011 {
12012 switch (uExitReason)
12013 {
12014 case VMX_EXIT_MTF:
12015 return hmR0VmxExitMtf(pVCpu, pVmxTransient);
12016
12017 /* Various events: */
12018 case VMX_EXIT_XCPT_OR_NMI:
12019 case VMX_EXIT_EXT_INT:
12020 case VMX_EXIT_TRIPLE_FAULT:
12021 case VMX_EXIT_INT_WINDOW:
12022 case VMX_EXIT_NMI_WINDOW:
12023 case VMX_EXIT_TASK_SWITCH:
12024 case VMX_EXIT_TPR_BELOW_THRESHOLD:
12025 case VMX_EXIT_APIC_ACCESS:
12026 case VMX_EXIT_EPT_VIOLATION:
12027 case VMX_EXIT_EPT_MISCONFIG:
12028 case VMX_EXIT_PREEMPT_TIMER:
12029
12030 /* Instruction specific VM-exits: */
12031 case VMX_EXIT_CPUID:
12032 case VMX_EXIT_GETSEC:
12033 case VMX_EXIT_HLT:
12034 case VMX_EXIT_INVD:
12035 case VMX_EXIT_INVLPG:
12036 case VMX_EXIT_RDPMC:
12037 case VMX_EXIT_RDTSC:
12038 case VMX_EXIT_RSM:
12039 case VMX_EXIT_VMCALL:
12040 case VMX_EXIT_VMCLEAR:
12041 case VMX_EXIT_VMLAUNCH:
12042 case VMX_EXIT_VMPTRLD:
12043 case VMX_EXIT_VMPTRST:
12044 case VMX_EXIT_VMREAD:
12045 case VMX_EXIT_VMRESUME:
12046 case VMX_EXIT_VMWRITE:
12047 case VMX_EXIT_VMXOFF:
12048 case VMX_EXIT_VMXON:
12049 case VMX_EXIT_MOV_CRX:
12050 case VMX_EXIT_MOV_DRX:
12051 case VMX_EXIT_IO_INSTR:
12052 case VMX_EXIT_RDMSR:
12053 case VMX_EXIT_WRMSR:
12054 case VMX_EXIT_MWAIT:
12055 case VMX_EXIT_MONITOR:
12056 case VMX_EXIT_PAUSE:
12057 case VMX_EXIT_GDTR_IDTR_ACCESS:
12058 case VMX_EXIT_LDTR_TR_ACCESS:
12059 case VMX_EXIT_INVEPT:
12060 case VMX_EXIT_RDTSCP:
12061 case VMX_EXIT_INVVPID:
12062 case VMX_EXIT_WBINVD:
12063 case VMX_EXIT_XSETBV:
12064 case VMX_EXIT_RDRAND:
12065 case VMX_EXIT_INVPCID:
12066 case VMX_EXIT_VMFUNC:
12067 case VMX_EXIT_RDSEED:
12068 case VMX_EXIT_XSAVES:
12069 case VMX_EXIT_XRSTORS:
12070 {
12071 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, CPUMCTX_EXTRN_CS | CPUMCTX_EXTRN_RIP);
12072 AssertRCReturn(rc, rc);
12073 if ( pVCpu->cpum.GstCtx.rip != pDbgState->uRipStart
12074 || pVCpu->cpum.GstCtx.cs.Sel != pDbgState->uCsStart)
12075 return VINF_EM_DBG_STEPPED;
12076 break;
12077 }
12078
12079 /* Errors and unexpected events: */
12080 case VMX_EXIT_INIT_SIGNAL:
12081 case VMX_EXIT_SIPI:
12082 case VMX_EXIT_IO_SMI:
12083 case VMX_EXIT_SMI:
12084 case VMX_EXIT_ERR_INVALID_GUEST_STATE:
12085 case VMX_EXIT_ERR_MSR_LOAD:
12086 case VMX_EXIT_ERR_MACHINE_CHECK:
12087 case VMX_EXIT_PML_FULL:
12088 case VMX_EXIT_VIRTUALIZED_EOI:
12089 case VMX_EXIT_APIC_WRITE: /* Some talk about this being fault like, so I guess we must process it? */
12090 break;
12091
12092 default:
12093 AssertMsgFailed(("Unexpected VM-exit=%#x\n", uExitReason));
12094 break;
12095 }
12096 }
12097
12098 /*
12099 * Check for debugger event breakpoints and dtrace probes.
12100 */
12101 if ( uExitReason < RT_ELEMENTS(pDbgState->bmExitsToCheck) * 32U
12102 && ASMBitTest(pDbgState->bmExitsToCheck, uExitReason) )
12103 {
12104 VBOXSTRICTRC rcStrict = hmR0VmxHandleExitDtraceEvents(pVCpu, pVmxTransient, uExitReason);
12105 if (rcStrict != VINF_SUCCESS)
12106 return rcStrict;
12107 }
12108
12109 /*
12110 * Normal processing.
12111 */
12112#ifdef HMVMX_USE_FUNCTION_TABLE
12113 return g_apfnVMExitHandlers[uExitReason](pVCpu, pVmxTransient);
12114#else
12115 return hmR0VmxHandleExit(pVCpu, pVmxTransient, uExitReason);
12116#endif
12117}
12118
12119
12120/**
12121 * Single steps guest code using hardware-assisted VMX.
12122 *
12123 * This is -not- the same as the guest single-stepping itself (say using EFLAGS.TF)
12124 * but single-stepping through the hypervisor debugger.
12125 *
12126 * @returns Strict VBox status code (i.e. informational status codes too).
12127 * @param pVCpu The cross context virtual CPU structure.
12128 * @param pcLoops Pointer to the number of executed loops.
12129 *
12130 * @note Mostly the same as hmR0VmxRunGuestCodeNormal().
12131 */
12132static VBOXSTRICTRC hmR0VmxRunGuestCodeDebug(PVMCPUCC pVCpu, uint32_t *pcLoops)
12133{
12134 uint32_t const cMaxResumeLoops = pVCpu->CTX_SUFF(pVM)->hm.s.cMaxResumeLoops;
12135 Assert(pcLoops);
12136 Assert(*pcLoops <= cMaxResumeLoops);
12137
12138 VMXTRANSIENT VmxTransient;
12139 RT_ZERO(VmxTransient);
12140 VmxTransient.pVmcsInfo = hmGetVmxActiveVmcsInfo(pVCpu);
12141
12142 /* Set HMCPU indicators. */
12143 bool const fSavedSingleInstruction = pVCpu->hm.s.fSingleInstruction;
12144 pVCpu->hm.s.fSingleInstruction = pVCpu->hm.s.fSingleInstruction || DBGFIsStepping(pVCpu);
12145 pVCpu->hm.s.fDebugWantRdTscExit = false;
12146 pVCpu->hm.s.fUsingDebugLoop = true;
12147
12148 /* State we keep to help modify and later restore the VMCS fields we alter, and for detecting steps. */
12149 VMXRUNDBGSTATE DbgState;
12150 hmR0VmxRunDebugStateInit(pVCpu, &VmxTransient, &DbgState);
12151 hmR0VmxPreRunGuestDebugStateUpdate(pVCpu, &VmxTransient, &DbgState);
12152
12153 /*
12154 * The loop.
12155 */
12156 VBOXSTRICTRC rcStrict = VERR_INTERNAL_ERROR_5;
12157 for (;;)
12158 {
12159 Assert(!HMR0SuspendPending());
12160 HMVMX_ASSERT_CPU_SAFE(pVCpu);
12161 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatEntry, x);
12162 bool fStepping = pVCpu->hm.s.fSingleInstruction;
12163
12164 /* Set up VM-execution controls the next two can respond to. */
12165 hmR0VmxPreRunGuestDebugStateApply(pVCpu, &VmxTransient, &DbgState);
12166
12167 /*
12168 * Preparatory work for running guest code, this may force us to
12169 * return to ring-3.
12170 *
12171 * Warning! This bugger disables interrupts on VINF_SUCCESS!
12172 */
12173 rcStrict = hmR0VmxPreRunGuest(pVCpu, &VmxTransient, fStepping);
12174 if (rcStrict != VINF_SUCCESS)
12175 break;
12176
12177 /* Interrupts are disabled at this point! */
12178 hmR0VmxPreRunGuestCommitted(pVCpu, &VmxTransient);
12179
12180 /* Override any obnoxious code in the above two calls. */
12181 hmR0VmxPreRunGuestDebugStateApply(pVCpu, &VmxTransient, &DbgState);
12182
12183 /*
12184 * Finally execute the guest.
12185 */
12186 int rcRun = hmR0VmxRunGuest(pVCpu, &VmxTransient);
12187
12188 hmR0VmxPostRunGuest(pVCpu, &VmxTransient, rcRun);
12189 /* Interrupts are re-enabled at this point! */
12190
12191 /* Check for errors with running the VM (VMLAUNCH/VMRESUME). */
12192 if (RT_SUCCESS(rcRun))
12193 { /* very likely */ }
12194 else
12195 {
12196 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatPreExit, x);
12197 hmR0VmxReportWorldSwitchError(pVCpu, rcRun, &VmxTransient);
12198 return rcRun;
12199 }
12200
12201 /* Profile the VM-exit. */
12202 AssertMsg(VmxTransient.uExitReason <= VMX_EXIT_MAX, ("%#x\n", VmxTransient.uExitReason));
12203 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitAll);
12204 STAM_COUNTER_INC(&pVCpu->hm.s.paStatExitReasonR0[VmxTransient.uExitReason & MASK_EXITREASON_STAT]);
12205 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatPreExit, &pVCpu->hm.s.StatExitHandling, x);
12206 HMVMX_START_EXIT_DISPATCH_PROF();
12207
12208 VBOXVMM_R0_HMVMX_VMEXIT_NOCTX(pVCpu, &pVCpu->cpum.GstCtx, VmxTransient.uExitReason);
12209
12210 /*
12211 * Handle the VM-exit - we quit earlier on certain VM-exits, see hmR0VmxHandleExitDebug().
12212 */
12213 rcStrict = hmR0VmxRunDebugHandleExit(pVCpu, &VmxTransient, &DbgState);
12214 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExitHandling, x);
12215 if (rcStrict != VINF_SUCCESS)
12216 break;
12217 if (++(*pcLoops) > cMaxResumeLoops)
12218 {
12219 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchMaxResumeLoops);
12220 rcStrict = VINF_EM_RAW_INTERRUPT;
12221 break;
12222 }
12223
12224 /*
12225 * Stepping: Did the RIP change, if so, consider it a single step.
12226 * Otherwise, make sure one of the TFs gets set.
12227 */
12228 if (fStepping)
12229 {
12230 int rc = hmR0VmxImportGuestState(pVCpu, VmxTransient.pVmcsInfo, CPUMCTX_EXTRN_CS | CPUMCTX_EXTRN_RIP);
12231 AssertRC(rc);
12232 if ( pVCpu->cpum.GstCtx.rip != DbgState.uRipStart
12233 || pVCpu->cpum.GstCtx.cs.Sel != DbgState.uCsStart)
12234 {
12235 rcStrict = VINF_EM_DBG_STEPPED;
12236 break;
12237 }
12238 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_DR7);
12239 }
12240
12241 /*
12242 * Update when dtrace settings changes (DBGF kicks us, so no need to check).
12243 */
12244 if (VBOXVMM_GET_SETTINGS_SEQ_NO() != DbgState.uDtraceSettingsSeqNo)
12245 hmR0VmxPreRunGuestDebugStateUpdate(pVCpu, &VmxTransient, &DbgState);
12246 }
12247
12248 /*
12249 * Clear the X86_EFL_TF if necessary.
12250 */
12251 if (pVCpu->hm.s.fClearTrapFlag)
12252 {
12253 int rc = hmR0VmxImportGuestState(pVCpu, VmxTransient.pVmcsInfo, CPUMCTX_EXTRN_RFLAGS);
12254 AssertRC(rc);
12255 pVCpu->hm.s.fClearTrapFlag = false;
12256 pVCpu->cpum.GstCtx.eflags.Bits.u1TF = 0;
12257 }
12258 /** @todo there seems to be issues with the resume flag when the monitor trap
12259 * flag is pending without being used. Seen early in bios init when
12260 * accessing APIC page in protected mode. */
12261
12262 /*
12263 * Restore VM-exit control settings as we may not re-enter this function the
12264 * next time around.
12265 */
12266 rcStrict = hmR0VmxRunDebugStateRevert(pVCpu, &VmxTransient, &DbgState, rcStrict);
12267
12268 /* Restore HMCPU indicators. */
12269 pVCpu->hm.s.fUsingDebugLoop = false;
12270 pVCpu->hm.s.fDebugWantRdTscExit = false;
12271 pVCpu->hm.s.fSingleInstruction = fSavedSingleInstruction;
12272
12273 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatEntry, x);
12274 return rcStrict;
12275}
12276
12277
12278/** @} */
12279
12280
12281/**
12282 * Checks if any expensive dtrace probes are enabled and we should go to the
12283 * debug loop.
12284 *
12285 * @returns true if we should use debug loop, false if not.
12286 */
12287static bool hmR0VmxAnyExpensiveProbesEnabled(void)
12288{
12289 /* It's probably faster to OR the raw 32-bit counter variables together.
12290 Since the variables are in an array and the probes are next to one
12291 another (more or less), we have good locality. So, better read
12292 eight-nine cache lines ever time and only have one conditional, than
12293 128+ conditionals, right? */
12294 return ( VBOXVMM_R0_HMVMX_VMEXIT_ENABLED_RAW() /* expensive too due to context */
12295 | VBOXVMM_XCPT_DE_ENABLED_RAW()
12296 | VBOXVMM_XCPT_DB_ENABLED_RAW()
12297 | VBOXVMM_XCPT_BP_ENABLED_RAW()
12298 | VBOXVMM_XCPT_OF_ENABLED_RAW()
12299 | VBOXVMM_XCPT_BR_ENABLED_RAW()
12300 | VBOXVMM_XCPT_UD_ENABLED_RAW()
12301 | VBOXVMM_XCPT_NM_ENABLED_RAW()
12302 | VBOXVMM_XCPT_DF_ENABLED_RAW()
12303 | VBOXVMM_XCPT_TS_ENABLED_RAW()
12304 | VBOXVMM_XCPT_NP_ENABLED_RAW()
12305 | VBOXVMM_XCPT_SS_ENABLED_RAW()
12306 | VBOXVMM_XCPT_GP_ENABLED_RAW()
12307 | VBOXVMM_XCPT_PF_ENABLED_RAW()
12308 | VBOXVMM_XCPT_MF_ENABLED_RAW()
12309 | VBOXVMM_XCPT_AC_ENABLED_RAW()
12310 | VBOXVMM_XCPT_XF_ENABLED_RAW()
12311 | VBOXVMM_XCPT_VE_ENABLED_RAW()
12312 | VBOXVMM_XCPT_SX_ENABLED_RAW()
12313 | VBOXVMM_INT_SOFTWARE_ENABLED_RAW()
12314 | VBOXVMM_INT_HARDWARE_ENABLED_RAW()
12315 ) != 0
12316 || ( VBOXVMM_INSTR_HALT_ENABLED_RAW()
12317 | VBOXVMM_INSTR_MWAIT_ENABLED_RAW()
12318 | VBOXVMM_INSTR_MONITOR_ENABLED_RAW()
12319 | VBOXVMM_INSTR_CPUID_ENABLED_RAW()
12320 | VBOXVMM_INSTR_INVD_ENABLED_RAW()
12321 | VBOXVMM_INSTR_WBINVD_ENABLED_RAW()
12322 | VBOXVMM_INSTR_INVLPG_ENABLED_RAW()
12323 | VBOXVMM_INSTR_RDTSC_ENABLED_RAW()
12324 | VBOXVMM_INSTR_RDTSCP_ENABLED_RAW()
12325 | VBOXVMM_INSTR_RDPMC_ENABLED_RAW()
12326 | VBOXVMM_INSTR_RDMSR_ENABLED_RAW()
12327 | VBOXVMM_INSTR_WRMSR_ENABLED_RAW()
12328 | VBOXVMM_INSTR_CRX_READ_ENABLED_RAW()
12329 | VBOXVMM_INSTR_CRX_WRITE_ENABLED_RAW()
12330 | VBOXVMM_INSTR_DRX_READ_ENABLED_RAW()
12331 | VBOXVMM_INSTR_DRX_WRITE_ENABLED_RAW()
12332 | VBOXVMM_INSTR_PAUSE_ENABLED_RAW()
12333 | VBOXVMM_INSTR_XSETBV_ENABLED_RAW()
12334 | VBOXVMM_INSTR_SIDT_ENABLED_RAW()
12335 | VBOXVMM_INSTR_LIDT_ENABLED_RAW()
12336 | VBOXVMM_INSTR_SGDT_ENABLED_RAW()
12337 | VBOXVMM_INSTR_LGDT_ENABLED_RAW()
12338 | VBOXVMM_INSTR_SLDT_ENABLED_RAW()
12339 | VBOXVMM_INSTR_LLDT_ENABLED_RAW()
12340 | VBOXVMM_INSTR_STR_ENABLED_RAW()
12341 | VBOXVMM_INSTR_LTR_ENABLED_RAW()
12342 | VBOXVMM_INSTR_GETSEC_ENABLED_RAW()
12343 | VBOXVMM_INSTR_RSM_ENABLED_RAW()
12344 | VBOXVMM_INSTR_RDRAND_ENABLED_RAW()
12345 | VBOXVMM_INSTR_RDSEED_ENABLED_RAW()
12346 | VBOXVMM_INSTR_XSAVES_ENABLED_RAW()
12347 | VBOXVMM_INSTR_XRSTORS_ENABLED_RAW()
12348 | VBOXVMM_INSTR_VMM_CALL_ENABLED_RAW()
12349 | VBOXVMM_INSTR_VMX_VMCLEAR_ENABLED_RAW()
12350 | VBOXVMM_INSTR_VMX_VMLAUNCH_ENABLED_RAW()
12351 | VBOXVMM_INSTR_VMX_VMPTRLD_ENABLED_RAW()
12352 | VBOXVMM_INSTR_VMX_VMPTRST_ENABLED_RAW()
12353 | VBOXVMM_INSTR_VMX_VMREAD_ENABLED_RAW()
12354 | VBOXVMM_INSTR_VMX_VMRESUME_ENABLED_RAW()
12355 | VBOXVMM_INSTR_VMX_VMWRITE_ENABLED_RAW()
12356 | VBOXVMM_INSTR_VMX_VMXOFF_ENABLED_RAW()
12357 | VBOXVMM_INSTR_VMX_VMXON_ENABLED_RAW()
12358 | VBOXVMM_INSTR_VMX_VMFUNC_ENABLED_RAW()
12359 | VBOXVMM_INSTR_VMX_INVEPT_ENABLED_RAW()
12360 | VBOXVMM_INSTR_VMX_INVVPID_ENABLED_RAW()
12361 | VBOXVMM_INSTR_VMX_INVPCID_ENABLED_RAW()
12362 ) != 0
12363 || ( VBOXVMM_EXIT_TASK_SWITCH_ENABLED_RAW()
12364 | VBOXVMM_EXIT_HALT_ENABLED_RAW()
12365 | VBOXVMM_EXIT_MWAIT_ENABLED_RAW()
12366 | VBOXVMM_EXIT_MONITOR_ENABLED_RAW()
12367 | VBOXVMM_EXIT_CPUID_ENABLED_RAW()
12368 | VBOXVMM_EXIT_INVD_ENABLED_RAW()
12369 | VBOXVMM_EXIT_WBINVD_ENABLED_RAW()
12370 | VBOXVMM_EXIT_INVLPG_ENABLED_RAW()
12371 | VBOXVMM_EXIT_RDTSC_ENABLED_RAW()
12372 | VBOXVMM_EXIT_RDTSCP_ENABLED_RAW()
12373 | VBOXVMM_EXIT_RDPMC_ENABLED_RAW()
12374 | VBOXVMM_EXIT_RDMSR_ENABLED_RAW()
12375 | VBOXVMM_EXIT_WRMSR_ENABLED_RAW()
12376 | VBOXVMM_EXIT_CRX_READ_ENABLED_RAW()
12377 | VBOXVMM_EXIT_CRX_WRITE_ENABLED_RAW()
12378 | VBOXVMM_EXIT_DRX_READ_ENABLED_RAW()
12379 | VBOXVMM_EXIT_DRX_WRITE_ENABLED_RAW()
12380 | VBOXVMM_EXIT_PAUSE_ENABLED_RAW()
12381 | VBOXVMM_EXIT_XSETBV_ENABLED_RAW()
12382 | VBOXVMM_EXIT_SIDT_ENABLED_RAW()
12383 | VBOXVMM_EXIT_LIDT_ENABLED_RAW()
12384 | VBOXVMM_EXIT_SGDT_ENABLED_RAW()
12385 | VBOXVMM_EXIT_LGDT_ENABLED_RAW()
12386 | VBOXVMM_EXIT_SLDT_ENABLED_RAW()
12387 | VBOXVMM_EXIT_LLDT_ENABLED_RAW()
12388 | VBOXVMM_EXIT_STR_ENABLED_RAW()
12389 | VBOXVMM_EXIT_LTR_ENABLED_RAW()
12390 | VBOXVMM_EXIT_GETSEC_ENABLED_RAW()
12391 | VBOXVMM_EXIT_RSM_ENABLED_RAW()
12392 | VBOXVMM_EXIT_RDRAND_ENABLED_RAW()
12393 | VBOXVMM_EXIT_RDSEED_ENABLED_RAW()
12394 | VBOXVMM_EXIT_XSAVES_ENABLED_RAW()
12395 | VBOXVMM_EXIT_XRSTORS_ENABLED_RAW()
12396 | VBOXVMM_EXIT_VMM_CALL_ENABLED_RAW()
12397 | VBOXVMM_EXIT_VMX_VMCLEAR_ENABLED_RAW()
12398 | VBOXVMM_EXIT_VMX_VMLAUNCH_ENABLED_RAW()
12399 | VBOXVMM_EXIT_VMX_VMPTRLD_ENABLED_RAW()
12400 | VBOXVMM_EXIT_VMX_VMPTRST_ENABLED_RAW()
12401 | VBOXVMM_EXIT_VMX_VMREAD_ENABLED_RAW()
12402 | VBOXVMM_EXIT_VMX_VMRESUME_ENABLED_RAW()
12403 | VBOXVMM_EXIT_VMX_VMWRITE_ENABLED_RAW()
12404 | VBOXVMM_EXIT_VMX_VMXOFF_ENABLED_RAW()
12405 | VBOXVMM_EXIT_VMX_VMXON_ENABLED_RAW()
12406 | VBOXVMM_EXIT_VMX_VMFUNC_ENABLED_RAW()
12407 | VBOXVMM_EXIT_VMX_INVEPT_ENABLED_RAW()
12408 | VBOXVMM_EXIT_VMX_INVVPID_ENABLED_RAW()
12409 | VBOXVMM_EXIT_VMX_INVPCID_ENABLED_RAW()
12410 | VBOXVMM_EXIT_VMX_EPT_VIOLATION_ENABLED_RAW()
12411 | VBOXVMM_EXIT_VMX_EPT_MISCONFIG_ENABLED_RAW()
12412 | VBOXVMM_EXIT_VMX_VAPIC_ACCESS_ENABLED_RAW()
12413 | VBOXVMM_EXIT_VMX_VAPIC_WRITE_ENABLED_RAW()
12414 ) != 0;
12415}
12416
12417
12418/**
12419 * Runs the guest using hardware-assisted VMX.
12420 *
12421 * @returns Strict VBox status code (i.e. informational status codes too).
12422 * @param pVCpu The cross context virtual CPU structure.
12423 */
12424VMMR0DECL(VBOXSTRICTRC) VMXR0RunGuestCode(PVMCPUCC pVCpu)
12425{
12426 AssertPtr(pVCpu);
12427 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
12428 Assert(VMMRZCallRing3IsEnabled(pVCpu));
12429 Assert(!ASMAtomicUoReadU64(&pCtx->fExtrn));
12430 HMVMX_ASSERT_PREEMPT_SAFE(pVCpu);
12431
12432 VBOXSTRICTRC rcStrict;
12433 uint32_t cLoops = 0;
12434 for (;;)
12435 {
12436#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
12437 bool const fInNestedGuestMode = CPUMIsGuestInVmxNonRootMode(pCtx);
12438#else
12439 NOREF(pCtx);
12440 bool const fInNestedGuestMode = false;
12441#endif
12442 if (!fInNestedGuestMode)
12443 {
12444 if ( !pVCpu->hm.s.fUseDebugLoop
12445 && (!VBOXVMM_ANY_PROBES_ENABLED() || !hmR0VmxAnyExpensiveProbesEnabled())
12446 && !DBGFIsStepping(pVCpu)
12447 && !pVCpu->CTX_SUFF(pVM)->dbgf.ro.cEnabledInt3Breakpoints)
12448 rcStrict = hmR0VmxRunGuestCodeNormal(pVCpu, &cLoops);
12449 else
12450 rcStrict = hmR0VmxRunGuestCodeDebug(pVCpu, &cLoops);
12451 }
12452#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
12453 else
12454 rcStrict = hmR0VmxRunGuestCodeNested(pVCpu, &cLoops);
12455
12456 if (rcStrict == VINF_VMX_VMLAUNCH_VMRESUME)
12457 {
12458 Assert(CPUMIsGuestInVmxNonRootMode(pCtx));
12459 continue;
12460 }
12461 if (rcStrict == VINF_VMX_VMEXIT)
12462 {
12463 Assert(!CPUMIsGuestInVmxNonRootMode(pCtx));
12464 continue;
12465 }
12466#endif
12467 break;
12468 }
12469
12470 int const rcLoop = VBOXSTRICTRC_VAL(rcStrict);
12471 switch (rcLoop)
12472 {
12473 case VERR_EM_INTERPRETER: rcStrict = VINF_EM_RAW_EMULATE_INSTR; break;
12474 case VINF_EM_RESET: rcStrict = VINF_EM_TRIPLE_FAULT; break;
12475 }
12476
12477 int rc2 = hmR0VmxExitToRing3(pVCpu, rcStrict);
12478 if (RT_FAILURE(rc2))
12479 {
12480 pVCpu->hm.s.u32HMError = (uint32_t)VBOXSTRICTRC_VAL(rcStrict);
12481 rcStrict = rc2;
12482 }
12483 Assert(!ASMAtomicUoReadU64(&pCtx->fExtrn));
12484 Assert(!VMMRZCallRing3IsNotificationSet(pVCpu));
12485 return rcStrict;
12486}
12487
12488
12489#ifndef HMVMX_USE_FUNCTION_TABLE
12490/**
12491 * Handles a guest VM-exit from hardware-assisted VMX execution.
12492 *
12493 * @returns Strict VBox status code (i.e. informational status codes too).
12494 * @param pVCpu The cross context virtual CPU structure.
12495 * @param pVmxTransient The VMX-transient structure.
12496 */
12497DECLINLINE(VBOXSTRICTRC) hmR0VmxHandleExit(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
12498{
12499#ifdef DEBUG_ramshankar
12500# define VMEXIT_CALL_RET(a_fSave, a_CallExpr) \
12501 do { \
12502 if (a_fSave != 0) \
12503 hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, HMVMX_CPUMCTX_EXTRN_ALL); \
12504 VBOXSTRICTRC rcStrict = a_CallExpr; \
12505 if (a_fSave != 0) \
12506 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_ALL_GUEST); \
12507 return rcStrict; \
12508 } while (0)
12509#else
12510# define VMEXIT_CALL_RET(a_fSave, a_CallExpr) return a_CallExpr
12511#endif
12512 uint32_t const uExitReason = pVmxTransient->uExitReason;
12513 switch (uExitReason)
12514 {
12515 case VMX_EXIT_EPT_MISCONFIG: VMEXIT_CALL_RET(0, hmR0VmxExitEptMisconfig(pVCpu, pVmxTransient));
12516 case VMX_EXIT_EPT_VIOLATION: VMEXIT_CALL_RET(0, hmR0VmxExitEptViolation(pVCpu, pVmxTransient));
12517 case VMX_EXIT_IO_INSTR: VMEXIT_CALL_RET(0, hmR0VmxExitIoInstr(pVCpu, pVmxTransient));
12518 case VMX_EXIT_CPUID: VMEXIT_CALL_RET(0, hmR0VmxExitCpuid(pVCpu, pVmxTransient));
12519 case VMX_EXIT_RDTSC: VMEXIT_CALL_RET(0, hmR0VmxExitRdtsc(pVCpu, pVmxTransient));
12520 case VMX_EXIT_RDTSCP: VMEXIT_CALL_RET(0, hmR0VmxExitRdtscp(pVCpu, pVmxTransient));
12521 case VMX_EXIT_APIC_ACCESS: VMEXIT_CALL_RET(0, hmR0VmxExitApicAccess(pVCpu, pVmxTransient));
12522 case VMX_EXIT_XCPT_OR_NMI: VMEXIT_CALL_RET(0, hmR0VmxExitXcptOrNmi(pVCpu, pVmxTransient));
12523 case VMX_EXIT_MOV_CRX: VMEXIT_CALL_RET(0, hmR0VmxExitMovCRx(pVCpu, pVmxTransient));
12524 case VMX_EXIT_EXT_INT: VMEXIT_CALL_RET(0, hmR0VmxExitExtInt(pVCpu, pVmxTransient));
12525 case VMX_EXIT_INT_WINDOW: VMEXIT_CALL_RET(0, hmR0VmxExitIntWindow(pVCpu, pVmxTransient));
12526 case VMX_EXIT_TPR_BELOW_THRESHOLD: VMEXIT_CALL_RET(0, hmR0VmxExitTprBelowThreshold(pVCpu, pVmxTransient));
12527 case VMX_EXIT_MWAIT: VMEXIT_CALL_RET(0, hmR0VmxExitMwait(pVCpu, pVmxTransient));
12528 case VMX_EXIT_MONITOR: VMEXIT_CALL_RET(0, hmR0VmxExitMonitor(pVCpu, pVmxTransient));
12529 case VMX_EXIT_TASK_SWITCH: VMEXIT_CALL_RET(0, hmR0VmxExitTaskSwitch(pVCpu, pVmxTransient));
12530 case VMX_EXIT_PREEMPT_TIMER: VMEXIT_CALL_RET(0, hmR0VmxExitPreemptTimer(pVCpu, pVmxTransient));
12531 case VMX_EXIT_RDMSR: VMEXIT_CALL_RET(0, hmR0VmxExitRdmsr(pVCpu, pVmxTransient));
12532 case VMX_EXIT_WRMSR: VMEXIT_CALL_RET(0, hmR0VmxExitWrmsr(pVCpu, pVmxTransient));
12533 case VMX_EXIT_VMCALL: VMEXIT_CALL_RET(0, hmR0VmxExitVmcall(pVCpu, pVmxTransient));
12534 case VMX_EXIT_MOV_DRX: VMEXIT_CALL_RET(0, hmR0VmxExitMovDRx(pVCpu, pVmxTransient));
12535 case VMX_EXIT_HLT: VMEXIT_CALL_RET(0, hmR0VmxExitHlt(pVCpu, pVmxTransient));
12536 case VMX_EXIT_INVD: VMEXIT_CALL_RET(0, hmR0VmxExitInvd(pVCpu, pVmxTransient));
12537 case VMX_EXIT_INVLPG: VMEXIT_CALL_RET(0, hmR0VmxExitInvlpg(pVCpu, pVmxTransient));
12538 case VMX_EXIT_MTF: VMEXIT_CALL_RET(0, hmR0VmxExitMtf(pVCpu, pVmxTransient));
12539 case VMX_EXIT_PAUSE: VMEXIT_CALL_RET(0, hmR0VmxExitPause(pVCpu, pVmxTransient));
12540 case VMX_EXIT_WBINVD: VMEXIT_CALL_RET(0, hmR0VmxExitWbinvd(pVCpu, pVmxTransient));
12541 case VMX_EXIT_XSETBV: VMEXIT_CALL_RET(0, hmR0VmxExitXsetbv(pVCpu, pVmxTransient));
12542 case VMX_EXIT_INVPCID: VMEXIT_CALL_RET(0, hmR0VmxExitInvpcid(pVCpu, pVmxTransient));
12543 case VMX_EXIT_GETSEC: VMEXIT_CALL_RET(0, hmR0VmxExitGetsec(pVCpu, pVmxTransient));
12544 case VMX_EXIT_RDPMC: VMEXIT_CALL_RET(0, hmR0VmxExitRdpmc(pVCpu, pVmxTransient));
12545#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
12546 case VMX_EXIT_VMCLEAR: VMEXIT_CALL_RET(0, hmR0VmxExitVmclear(pVCpu, pVmxTransient));
12547 case VMX_EXIT_VMLAUNCH: VMEXIT_CALL_RET(0, hmR0VmxExitVmlaunch(pVCpu, pVmxTransient));
12548 case VMX_EXIT_VMPTRLD: VMEXIT_CALL_RET(0, hmR0VmxExitVmptrld(pVCpu, pVmxTransient));
12549 case VMX_EXIT_VMPTRST: VMEXIT_CALL_RET(0, hmR0VmxExitVmptrst(pVCpu, pVmxTransient));
12550 case VMX_EXIT_VMREAD: VMEXIT_CALL_RET(0, hmR0VmxExitVmread(pVCpu, pVmxTransient));
12551 case VMX_EXIT_VMRESUME: VMEXIT_CALL_RET(0, hmR0VmxExitVmwrite(pVCpu, pVmxTransient));
12552 case VMX_EXIT_VMWRITE: VMEXIT_CALL_RET(0, hmR0VmxExitVmresume(pVCpu, pVmxTransient));
12553 case VMX_EXIT_VMXOFF: VMEXIT_CALL_RET(0, hmR0VmxExitVmxoff(pVCpu, pVmxTransient));
12554 case VMX_EXIT_VMXON: VMEXIT_CALL_RET(0, hmR0VmxExitVmxon(pVCpu, pVmxTransient));
12555 case VMX_EXIT_INVVPID: VMEXIT_CALL_RET(0, hmR0VmxExitInvvpid(pVCpu, pVmxTransient));
12556 case VMX_EXIT_INVEPT: VMEXIT_CALL_RET(0, hmR0VmxExitSetPendingXcptUD(pVCpu, pVmxTransient));
12557#else
12558 case VMX_EXIT_VMCLEAR:
12559 case VMX_EXIT_VMLAUNCH:
12560 case VMX_EXIT_VMPTRLD:
12561 case VMX_EXIT_VMPTRST:
12562 case VMX_EXIT_VMREAD:
12563 case VMX_EXIT_VMRESUME:
12564 case VMX_EXIT_VMWRITE:
12565 case VMX_EXIT_VMXOFF:
12566 case VMX_EXIT_VMXON:
12567 case VMX_EXIT_INVVPID:
12568 case VMX_EXIT_INVEPT:
12569 return hmR0VmxExitSetPendingXcptUD(pVCpu, pVmxTransient);
12570#endif
12571
12572 case VMX_EXIT_TRIPLE_FAULT: return hmR0VmxExitTripleFault(pVCpu, pVmxTransient);
12573 case VMX_EXIT_NMI_WINDOW: return hmR0VmxExitNmiWindow(pVCpu, pVmxTransient);
12574 case VMX_EXIT_ERR_INVALID_GUEST_STATE: return hmR0VmxExitErrInvalidGuestState(pVCpu, pVmxTransient);
12575
12576 case VMX_EXIT_INIT_SIGNAL:
12577 case VMX_EXIT_SIPI:
12578 case VMX_EXIT_IO_SMI:
12579 case VMX_EXIT_SMI:
12580 case VMX_EXIT_ERR_MSR_LOAD:
12581 case VMX_EXIT_ERR_MACHINE_CHECK:
12582 case VMX_EXIT_PML_FULL:
12583 case VMX_EXIT_VIRTUALIZED_EOI:
12584 case VMX_EXIT_GDTR_IDTR_ACCESS:
12585 case VMX_EXIT_LDTR_TR_ACCESS:
12586 case VMX_EXIT_APIC_WRITE:
12587 case VMX_EXIT_RDRAND:
12588 case VMX_EXIT_RSM:
12589 case VMX_EXIT_VMFUNC:
12590 case VMX_EXIT_ENCLS:
12591 case VMX_EXIT_RDSEED:
12592 case VMX_EXIT_XSAVES:
12593 case VMX_EXIT_XRSTORS:
12594 case VMX_EXIT_UMWAIT:
12595 case VMX_EXIT_TPAUSE:
12596 default:
12597 return hmR0VmxExitErrUnexpected(pVCpu, pVmxTransient);
12598 }
12599#undef VMEXIT_CALL_RET
12600}
12601#endif /* !HMVMX_USE_FUNCTION_TABLE */
12602
12603
12604#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
12605/**
12606 * Handles a nested-guest VM-exit from hardware-assisted VMX execution.
12607 *
12608 * @returns Strict VBox status code (i.e. informational status codes too).
12609 * @param pVCpu The cross context virtual CPU structure.
12610 * @param pVmxTransient The VMX-transient structure.
12611 */
12612DECLINLINE(VBOXSTRICTRC) hmR0VmxHandleExitNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
12613{
12614 /** @todo NSTVMX: Remove after debugging page-fault issue. */
12615#ifdef DEBUG_ramshankar
12616 hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, HMVMX_CPUMCTX_EXTRN_ALL);
12617 Log4Func(("cs:rip=%#04x:%#RX64 rsp=%#RX64 eflags=%#RX32 cr3=%#RX64\n", pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip,
12618 pVCpu->cpum.GstCtx.rsp, pVCpu->cpum.GstCtx.eflags.u32, pVCpu->cpum.GstCtx.cr3));
12619#endif
12620
12621 uint32_t const uExitReason = pVmxTransient->uExitReason;
12622 switch (uExitReason)
12623 {
12624 case VMX_EXIT_EPT_MISCONFIG: return hmR0VmxExitEptMisconfig(pVCpu, pVmxTransient);
12625 case VMX_EXIT_EPT_VIOLATION: return hmR0VmxExitEptViolation(pVCpu, pVmxTransient);
12626 case VMX_EXIT_XCPT_OR_NMI: return hmR0VmxExitXcptOrNmiNested(pVCpu, pVmxTransient);
12627 case VMX_EXIT_IO_INSTR: return hmR0VmxExitIoInstrNested(pVCpu, pVmxTransient);
12628 case VMX_EXIT_HLT: return hmR0VmxExitHltNested(pVCpu, pVmxTransient);
12629
12630 /*
12631 * We shouldn't direct host physical interrupts to the nested-guest.
12632 */
12633 case VMX_EXIT_EXT_INT:
12634 return hmR0VmxExitExtInt(pVCpu, pVmxTransient);
12635
12636 /*
12637 * Instructions that cause VM-exits unconditionally or the condition is
12638 * always is taken solely from the guest hypervisor (meaning if the VM-exit
12639 * happens, it's guaranteed to be a nested-guest VM-exit).
12640 *
12641 * - Provides VM-exit instruction length ONLY.
12642 */
12643 case VMX_EXIT_CPUID: /* Unconditional. */
12644 case VMX_EXIT_VMCALL:
12645 case VMX_EXIT_GETSEC:
12646 case VMX_EXIT_INVD:
12647 case VMX_EXIT_XSETBV:
12648 case VMX_EXIT_VMLAUNCH:
12649 case VMX_EXIT_VMRESUME:
12650 case VMX_EXIT_VMXOFF:
12651 case VMX_EXIT_ENCLS: /* Condition specified solely by guest hypervisor. */
12652 case VMX_EXIT_VMFUNC:
12653 return hmR0VmxExitInstrNested(pVCpu, pVmxTransient);
12654
12655 /*
12656 * Instructions that cause VM-exits unconditionally or the condition is
12657 * always is taken solely from the guest hypervisor (meaning if the VM-exit
12658 * happens, it's guaranteed to be a nested-guest VM-exit).
12659 *
12660 * - Provides VM-exit instruction length.
12661 * - Provides VM-exit information.
12662 * - Optionally provides Exit qualification.
12663 *
12664 * Since Exit qualification is 0 for all VM-exits where it is not
12665 * applicable, reading and passing it to the guest should produce
12666 * defined behavior.
12667 *
12668 * See Intel spec. 27.2.1 "Basic VM-Exit Information".
12669 */
12670 case VMX_EXIT_INVEPT: /* Unconditional. */
12671 case VMX_EXIT_INVVPID:
12672 case VMX_EXIT_VMCLEAR:
12673 case VMX_EXIT_VMPTRLD:
12674 case VMX_EXIT_VMPTRST:
12675 case VMX_EXIT_VMXON:
12676 case VMX_EXIT_GDTR_IDTR_ACCESS: /* Condition specified solely by guest hypervisor. */
12677 case VMX_EXIT_LDTR_TR_ACCESS:
12678 case VMX_EXIT_RDRAND:
12679 case VMX_EXIT_RDSEED:
12680 case VMX_EXIT_XSAVES:
12681 case VMX_EXIT_XRSTORS:
12682 case VMX_EXIT_UMWAIT:
12683 case VMX_EXIT_TPAUSE:
12684 return hmR0VmxExitInstrWithInfoNested(pVCpu, pVmxTransient);
12685
12686 case VMX_EXIT_RDTSC: return hmR0VmxExitRdtscNested(pVCpu, pVmxTransient);
12687 case VMX_EXIT_RDTSCP: return hmR0VmxExitRdtscpNested(pVCpu, pVmxTransient);
12688 case VMX_EXIT_RDMSR: return hmR0VmxExitRdmsrNested(pVCpu, pVmxTransient);
12689 case VMX_EXIT_WRMSR: return hmR0VmxExitWrmsrNested(pVCpu, pVmxTransient);
12690 case VMX_EXIT_INVLPG: return hmR0VmxExitInvlpgNested(pVCpu, pVmxTransient);
12691 case VMX_EXIT_INVPCID: return hmR0VmxExitInvpcidNested(pVCpu, pVmxTransient);
12692 case VMX_EXIT_TASK_SWITCH: return hmR0VmxExitTaskSwitchNested(pVCpu, pVmxTransient);
12693 case VMX_EXIT_WBINVD: return hmR0VmxExitWbinvdNested(pVCpu, pVmxTransient);
12694 case VMX_EXIT_MTF: return hmR0VmxExitMtfNested(pVCpu, pVmxTransient);
12695 case VMX_EXIT_APIC_ACCESS: return hmR0VmxExitApicAccessNested(pVCpu, pVmxTransient);
12696 case VMX_EXIT_APIC_WRITE: return hmR0VmxExitApicWriteNested(pVCpu, pVmxTransient);
12697 case VMX_EXIT_VIRTUALIZED_EOI: return hmR0VmxExitVirtEoiNested(pVCpu, pVmxTransient);
12698 case VMX_EXIT_MOV_CRX: return hmR0VmxExitMovCRxNested(pVCpu, pVmxTransient);
12699 case VMX_EXIT_INT_WINDOW: return hmR0VmxExitIntWindowNested(pVCpu, pVmxTransient);
12700 case VMX_EXIT_NMI_WINDOW: return hmR0VmxExitNmiWindowNested(pVCpu, pVmxTransient);
12701 case VMX_EXIT_TPR_BELOW_THRESHOLD: return hmR0VmxExitTprBelowThresholdNested(pVCpu, pVmxTransient);
12702 case VMX_EXIT_MWAIT: return hmR0VmxExitMwaitNested(pVCpu, pVmxTransient);
12703 case VMX_EXIT_MONITOR: return hmR0VmxExitMonitorNested(pVCpu, pVmxTransient);
12704 case VMX_EXIT_PAUSE: return hmR0VmxExitPauseNested(pVCpu, pVmxTransient);
12705
12706 case VMX_EXIT_PREEMPT_TIMER:
12707 {
12708 /** @todo NSTVMX: Preempt timer. */
12709 return hmR0VmxExitPreemptTimer(pVCpu, pVmxTransient);
12710 }
12711
12712 case VMX_EXIT_MOV_DRX: return hmR0VmxExitMovDRxNested(pVCpu, pVmxTransient);
12713 case VMX_EXIT_RDPMC: return hmR0VmxExitRdpmcNested(pVCpu, pVmxTransient);
12714
12715 case VMX_EXIT_VMREAD:
12716 case VMX_EXIT_VMWRITE: return hmR0VmxExitVmreadVmwriteNested(pVCpu, pVmxTransient);
12717
12718 case VMX_EXIT_TRIPLE_FAULT: return hmR0VmxExitTripleFaultNested(pVCpu, pVmxTransient);
12719 case VMX_EXIT_ERR_INVALID_GUEST_STATE: return hmR0VmxExitErrInvalidGuestStateNested(pVCpu, pVmxTransient);
12720
12721 case VMX_EXIT_INIT_SIGNAL:
12722 case VMX_EXIT_SIPI:
12723 case VMX_EXIT_IO_SMI:
12724 case VMX_EXIT_SMI:
12725 case VMX_EXIT_ERR_MSR_LOAD:
12726 case VMX_EXIT_ERR_MACHINE_CHECK:
12727 case VMX_EXIT_PML_FULL:
12728 case VMX_EXIT_RSM:
12729 default:
12730 return hmR0VmxExitErrUnexpected(pVCpu, pVmxTransient);
12731 }
12732}
12733#endif /* VBOX_WITH_NESTED_HWVIRT_VMX */
12734
12735
12736/** @name VM-exit helpers.
12737 * @{
12738 */
12739/* -=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= */
12740/* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= VM-exit helpers -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- */
12741/* -=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= */
12742
12743/** Macro for VM-exits called unexpectedly. */
12744#define HMVMX_UNEXPECTED_EXIT_RET(a_pVCpu, a_HmError) \
12745 do { \
12746 (a_pVCpu)->hm.s.u32HMError = (a_HmError); \
12747 return VERR_VMX_UNEXPECTED_EXIT; \
12748 } while (0)
12749
12750#ifdef VBOX_STRICT
12751/* Is there some generic IPRT define for this that are not in Runtime/internal/\* ?? */
12752# define HMVMX_ASSERT_PREEMPT_CPUID_VAR() \
12753 RTCPUID const idAssertCpu = RTThreadPreemptIsEnabled(NIL_RTTHREAD) ? NIL_RTCPUID : RTMpCpuId()
12754
12755# define HMVMX_ASSERT_PREEMPT_CPUID() \
12756 do { \
12757 RTCPUID const idAssertCpuNow = RTThreadPreemptIsEnabled(NIL_RTTHREAD) ? NIL_RTCPUID : RTMpCpuId(); \
12758 AssertMsg(idAssertCpu == idAssertCpuNow, ("VMX %#x, %#x\n", idAssertCpu, idAssertCpuNow)); \
12759 } while (0)
12760
12761# define HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(a_pVCpu, a_pVmxTransient) \
12762 do { \
12763 AssertPtr((a_pVCpu)); \
12764 AssertPtr((a_pVmxTransient)); \
12765 Assert((a_pVmxTransient)->fVMEntryFailed == false); \
12766 Assert((a_pVmxTransient)->pVmcsInfo); \
12767 Assert(ASMIntAreEnabled()); \
12768 HMVMX_ASSERT_PREEMPT_SAFE(a_pVCpu); \
12769 HMVMX_ASSERT_PREEMPT_CPUID_VAR(); \
12770 Log4Func(("vcpu[%RU32]\n", (a_pVCpu)->idCpu)); \
12771 HMVMX_ASSERT_PREEMPT_SAFE(a_pVCpu); \
12772 if (VMMR0IsLogFlushDisabled((a_pVCpu))) \
12773 HMVMX_ASSERT_PREEMPT_CPUID(); \
12774 HMVMX_STOP_EXIT_DISPATCH_PROF(); \
12775 } while (0)
12776
12777# define HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(a_pVCpu, a_pVmxTransient) \
12778 do { \
12779 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(a_pVCpu, a_pVmxTransient); \
12780 Assert((a_pVmxTransient)->fIsNestedGuest); \
12781 } while (0)
12782
12783# define HMVMX_VALIDATE_EXIT_XCPT_HANDLER_PARAMS(a_pVCpu, a_pVmxTransient) \
12784 do { \
12785 Log4Func(("\n")); \
12786 } while (0)
12787#else
12788# define HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(a_pVCpu, a_pVmxTransient) \
12789 do { \
12790 HMVMX_STOP_EXIT_DISPATCH_PROF(); \
12791 NOREF((a_pVCpu)); NOREF((a_pVmxTransient)); \
12792 } while (0)
12793
12794# define HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(a_pVCpu, a_pVmxTransient) \
12795 do { HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(a_pVCpu, a_pVmxTransient); } while (0)
12796
12797# define HMVMX_VALIDATE_EXIT_XCPT_HANDLER_PARAMS(a_pVCpu, a_pVmxTransient) do { } while (0)
12798#endif
12799
12800#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
12801/** Macro that does the necessary privilege checks and intercepted VM-exits for
12802 * guests that attempted to execute a VMX instruction. */
12803# define HMVMX_CHECK_EXIT_DUE_TO_VMX_INSTR(a_pVCpu, a_uExitReason) \
12804 do \
12805 { \
12806 VBOXSTRICTRC rcStrictTmp = hmR0VmxCheckExitDueToVmxInstr((a_pVCpu), (a_uExitReason)); \
12807 if (rcStrictTmp == VINF_SUCCESS) \
12808 { /* likely */ } \
12809 else if (rcStrictTmp == VINF_HM_PENDING_XCPT) \
12810 { \
12811 Assert((a_pVCpu)->hm.s.Event.fPending); \
12812 Log4Func(("Privilege checks failed -> %#x\n", VMX_ENTRY_INT_INFO_VECTOR((a_pVCpu)->hm.s.Event.u64IntInfo))); \
12813 return VINF_SUCCESS; \
12814 } \
12815 else \
12816 { \
12817 int rcTmp = VBOXSTRICTRC_VAL(rcStrictTmp); \
12818 AssertMsgFailedReturn(("Unexpected failure. rc=%Rrc", rcTmp), rcTmp); \
12819 } \
12820 } while (0)
12821
12822/** Macro that decodes a memory operand for an VM-exit caused by an instruction. */
12823# define HMVMX_DECODE_MEM_OPERAND(a_pVCpu, a_uExitInstrInfo, a_uExitQual, a_enmMemAccess, a_pGCPtrEffAddr) \
12824 do \
12825 { \
12826 VBOXSTRICTRC rcStrictTmp = hmR0VmxDecodeMemOperand((a_pVCpu), (a_uExitInstrInfo), (a_uExitQual), (a_enmMemAccess), \
12827 (a_pGCPtrEffAddr)); \
12828 if (rcStrictTmp == VINF_SUCCESS) \
12829 { /* likely */ } \
12830 else if (rcStrictTmp == VINF_HM_PENDING_XCPT) \
12831 { \
12832 uint8_t const uXcptTmp = VMX_ENTRY_INT_INFO_VECTOR((a_pVCpu)->hm.s.Event.u64IntInfo); \
12833 Log4Func(("Memory operand decoding failed, raising xcpt %#x\n", uXcptTmp)); \
12834 NOREF(uXcptTmp); \
12835 return VINF_SUCCESS; \
12836 } \
12837 else \
12838 { \
12839 Log4Func(("hmR0VmxDecodeMemOperand failed. rc=%Rrc\n", VBOXSTRICTRC_VAL(rcStrictTmp))); \
12840 return rcStrictTmp; \
12841 } \
12842 } while (0)
12843#endif /* VBOX_WITH_NESTED_HWVIRT_VMX */
12844
12845
12846/**
12847 * Advances the guest RIP by the specified number of bytes.
12848 *
12849 * @param pVCpu The cross context virtual CPU structure.
12850 * @param cbInstr Number of bytes to advance the RIP by.
12851 *
12852 * @remarks No-long-jump zone!!!
12853 */
12854DECLINLINE(void) hmR0VmxAdvanceGuestRipBy(PVMCPUCC pVCpu, uint32_t cbInstr)
12855{
12856 /* Advance the RIP. */
12857 pVCpu->cpum.GstCtx.rip += cbInstr;
12858 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP);
12859
12860 /* Update interrupt inhibition. */
12861 if ( VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS)
12862 && pVCpu->cpum.GstCtx.rip != EMGetInhibitInterruptsPC(pVCpu))
12863 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS);
12864}
12865
12866
12867/**
12868 * Advances the guest RIP after reading it from the VMCS.
12869 *
12870 * @returns VBox status code, no informational status codes.
12871 * @param pVCpu The cross context virtual CPU structure.
12872 * @param pVmxTransient The VMX-transient structure.
12873 *
12874 * @remarks No-long-jump zone!!!
12875 */
12876static int hmR0VmxAdvanceGuestRip(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
12877{
12878 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
12879 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, CPUMCTX_EXTRN_RIP | CPUMCTX_EXTRN_RFLAGS);
12880 AssertRCReturn(rc, rc);
12881
12882 hmR0VmxAdvanceGuestRipBy(pVCpu, pVmxTransient->cbExitInstr);
12883 return VINF_SUCCESS;
12884}
12885
12886
12887/**
12888 * Handle a condition that occurred while delivering an event through the guest or
12889 * nested-guest IDT.
12890 *
12891 * @returns Strict VBox status code (i.e. informational status codes too).
12892 * @retval VINF_SUCCESS if we should continue handling the VM-exit.
12893 * @retval VINF_HM_DOUBLE_FAULT if a \#DF condition was detected and we ought
12894 * to continue execution of the guest which will delivery the \#DF.
12895 * @retval VINF_EM_RESET if we detected a triple-fault condition.
12896 * @retval VERR_EM_GUEST_CPU_HANG if we detected a guest CPU hang.
12897 *
12898 * @param pVCpu The cross context virtual CPU structure.
12899 * @param pVmxTransient The VMX-transient structure.
12900 *
12901 * @remarks Requires all fields in HMVMX_READ_XCPT_INFO to be read from the VMCS.
12902 * Additionally, HMVMX_READ_EXIT_QUALIFICATION is required if the VM-exit
12903 * is due to an EPT violation, PML full or SPP-related event.
12904 *
12905 * @remarks No-long-jump zone!!!
12906 */
12907static VBOXSTRICTRC hmR0VmxCheckExitDueToEventDelivery(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
12908{
12909 Assert(!pVCpu->hm.s.Event.fPending);
12910 HMVMX_ASSERT_READ(pVmxTransient, HMVMX_READ_XCPT_INFO);
12911 if ( pVmxTransient->uExitReason == VMX_EXIT_EPT_VIOLATION
12912 || pVmxTransient->uExitReason == VMX_EXIT_PML_FULL
12913 || pVmxTransient->uExitReason == VMX_EXIT_SPP_EVENT)
12914 HMVMX_ASSERT_READ(pVmxTransient, HMVMX_READ_EXIT_QUALIFICATION);
12915
12916 VBOXSTRICTRC rcStrict = VINF_SUCCESS;
12917 PCVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
12918 uint32_t const uIdtVectorInfo = pVmxTransient->uIdtVectoringInfo;
12919 uint32_t const uExitIntInfo = pVmxTransient->uExitIntInfo;
12920 if (VMX_IDT_VECTORING_INFO_IS_VALID(uIdtVectorInfo))
12921 {
12922 uint32_t const uIdtVector = VMX_IDT_VECTORING_INFO_VECTOR(uIdtVectorInfo);
12923 uint32_t const uIdtVectorType = VMX_IDT_VECTORING_INFO_TYPE(uIdtVectorInfo);
12924
12925 /*
12926 * If the event was a software interrupt (generated with INT n) or a software exception
12927 * (generated by INT3/INTO) or a privileged software exception (generated by INT1), we
12928 * can handle the VM-exit and continue guest execution which will re-execute the
12929 * instruction rather than re-injecting the exception, as that can cause premature
12930 * trips to ring-3 before injection and involve TRPM which currently has no way of
12931 * storing that these exceptions were caused by these instructions (ICEBP's #DB poses
12932 * the problem).
12933 */
12934 IEMXCPTRAISE enmRaise;
12935 IEMXCPTRAISEINFO fRaiseInfo;
12936 if ( uIdtVectorType == VMX_IDT_VECTORING_INFO_TYPE_SW_INT
12937 || uIdtVectorType == VMX_IDT_VECTORING_INFO_TYPE_SW_XCPT
12938 || uIdtVectorType == VMX_IDT_VECTORING_INFO_TYPE_PRIV_SW_XCPT)
12939 {
12940 enmRaise = IEMXCPTRAISE_REEXEC_INSTR;
12941 fRaiseInfo = IEMXCPTRAISEINFO_NONE;
12942 }
12943 else if (VMX_EXIT_INT_INFO_IS_VALID(uExitIntInfo))
12944 {
12945 uint32_t const uExitVectorType = VMX_EXIT_INT_INFO_TYPE(uExitIntInfo);
12946 uint8_t const uExitVector = VMX_EXIT_INT_INFO_VECTOR(uExitIntInfo);
12947 Assert(uExitVectorType == VMX_EXIT_INT_INFO_TYPE_HW_XCPT);
12948
12949 uint32_t const fIdtVectorFlags = hmR0VmxGetIemXcptFlags(uIdtVector, uIdtVectorType);
12950 uint32_t const fExitVectorFlags = hmR0VmxGetIemXcptFlags(uExitVector, uExitVectorType);
12951
12952 enmRaise = IEMEvaluateRecursiveXcpt(pVCpu, fIdtVectorFlags, uIdtVector, fExitVectorFlags, uExitVector, &fRaiseInfo);
12953
12954 /* Determine a vectoring #PF condition, see comment in hmR0VmxExitXcptPF(). */
12955 if (fRaiseInfo & (IEMXCPTRAISEINFO_EXT_INT_PF | IEMXCPTRAISEINFO_NMI_PF))
12956 {
12957 pVmxTransient->fVectoringPF = true;
12958 enmRaise = IEMXCPTRAISE_PREV_EVENT;
12959 }
12960 }
12961 else
12962 {
12963 /*
12964 * If an exception or hardware interrupt delivery caused an EPT violation/misconfig or APIC access
12965 * VM-exit, then the VM-exit interruption-information will not be valid and we end up here.
12966 * It is sufficient to reflect the original event to the guest after handling the VM-exit.
12967 */
12968 Assert( uIdtVectorType == VMX_IDT_VECTORING_INFO_TYPE_HW_XCPT
12969 || uIdtVectorType == VMX_IDT_VECTORING_INFO_TYPE_NMI
12970 || uIdtVectorType == VMX_IDT_VECTORING_INFO_TYPE_EXT_INT);
12971 enmRaise = IEMXCPTRAISE_PREV_EVENT;
12972 fRaiseInfo = IEMXCPTRAISEINFO_NONE;
12973 }
12974
12975 /*
12976 * On CPUs that support Virtual NMIs, if this VM-exit (be it an exception or EPT violation/misconfig
12977 * etc.) occurred while delivering the NMI, we need to clear the block-by-NMI field in the guest
12978 * interruptibility-state before re-delivering the NMI after handling the VM-exit. Otherwise the
12979 * subsequent VM-entry would fail, see @bugref{7445}.
12980 *
12981 * See Intel spec. 30.7.1.2 "Resuming Guest Software after Handling an Exception".
12982 */
12983 if ( uIdtVectorType == VMX_IDT_VECTORING_INFO_TYPE_NMI
12984 && enmRaise == IEMXCPTRAISE_PREV_EVENT
12985 && (pVmcsInfo->u32PinCtls & VMX_PIN_CTLS_VIRT_NMI)
12986 && CPUMIsGuestNmiBlocking(pVCpu))
12987 {
12988 CPUMSetGuestNmiBlocking(pVCpu, false);
12989 }
12990
12991 switch (enmRaise)
12992 {
12993 case IEMXCPTRAISE_CURRENT_XCPT:
12994 {
12995 Log4Func(("IDT: Pending secondary Xcpt: idtinfo=%#RX64 exitinfo=%#RX64\n", uIdtVectorInfo, uExitIntInfo));
12996 Assert(rcStrict == VINF_SUCCESS);
12997 break;
12998 }
12999
13000 case IEMXCPTRAISE_PREV_EVENT:
13001 {
13002 uint32_t u32ErrCode;
13003 if (VMX_IDT_VECTORING_INFO_IS_ERROR_CODE_VALID(uIdtVectorInfo))
13004 u32ErrCode = pVmxTransient->uIdtVectoringErrorCode;
13005 else
13006 u32ErrCode = 0;
13007
13008 /* If uExitVector is #PF, CR2 value will be updated from the VMCS if it's a guest #PF, see hmR0VmxExitXcptPF(). */
13009 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectReflect);
13010 hmR0VmxSetPendingEvent(pVCpu, VMX_ENTRY_INT_INFO_FROM_EXIT_IDT_INFO(uIdtVectorInfo), 0 /* cbInstr */,
13011 u32ErrCode, pVCpu->cpum.GstCtx.cr2);
13012
13013 Log4Func(("IDT: Pending vectoring event %#RX64 Err=%#RX32\n", pVCpu->hm.s.Event.u64IntInfo,
13014 pVCpu->hm.s.Event.u32ErrCode));
13015 Assert(rcStrict == VINF_SUCCESS);
13016 break;
13017 }
13018
13019 case IEMXCPTRAISE_REEXEC_INSTR:
13020 Assert(rcStrict == VINF_SUCCESS);
13021 break;
13022
13023 case IEMXCPTRAISE_DOUBLE_FAULT:
13024 {
13025 /*
13026 * Determing a vectoring double #PF condition. Used later, when PGM evaluates the
13027 * second #PF as a guest #PF (and not a shadow #PF) and needs to be converted into a #DF.
13028 */
13029 if (fRaiseInfo & IEMXCPTRAISEINFO_PF_PF)
13030 {
13031 pVmxTransient->fVectoringDoublePF = true;
13032 Log4Func(("IDT: Vectoring double #PF %#RX64 cr2=%#RX64\n", pVCpu->hm.s.Event.u64IntInfo,
13033 pVCpu->cpum.GstCtx.cr2));
13034 rcStrict = VINF_SUCCESS;
13035 }
13036 else
13037 {
13038 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectConvertDF);
13039 hmR0VmxSetPendingXcptDF(pVCpu);
13040 Log4Func(("IDT: Pending vectoring #DF %#RX64 uIdtVector=%#x uExitVector=%#x\n", pVCpu->hm.s.Event.u64IntInfo,
13041 uIdtVector, VMX_EXIT_INT_INFO_VECTOR(uExitIntInfo)));
13042 rcStrict = VINF_HM_DOUBLE_FAULT;
13043 }
13044 break;
13045 }
13046
13047 case IEMXCPTRAISE_TRIPLE_FAULT:
13048 {
13049 Log4Func(("IDT: Pending vectoring triple-fault uIdt=%#x uExit=%#x\n", uIdtVector,
13050 VMX_EXIT_INT_INFO_VECTOR(uExitIntInfo)));
13051 rcStrict = VINF_EM_RESET;
13052 break;
13053 }
13054
13055 case IEMXCPTRAISE_CPU_HANG:
13056 {
13057 Log4Func(("IDT: Bad guest! Entering CPU hang. fRaiseInfo=%#x\n", fRaiseInfo));
13058 rcStrict = VERR_EM_GUEST_CPU_HANG;
13059 break;
13060 }
13061
13062 default:
13063 {
13064 AssertMsgFailed(("IDT: vcpu[%RU32] Unexpected/invalid value! enmRaise=%#x\n", pVCpu->idCpu, enmRaise));
13065 rcStrict = VERR_VMX_IPE_2;
13066 break;
13067 }
13068 }
13069 }
13070 else if ( (pVmcsInfo->u32PinCtls & VMX_PIN_CTLS_VIRT_NMI)
13071 && !CPUMIsGuestNmiBlocking(pVCpu))
13072 {
13073 if ( VMX_EXIT_INT_INFO_IS_VALID(uExitIntInfo)
13074 && VMX_EXIT_INT_INFO_VECTOR(uExitIntInfo) != X86_XCPT_DF
13075 && VMX_EXIT_INT_INFO_IS_NMI_UNBLOCK_IRET(uExitIntInfo))
13076 {
13077 /*
13078 * Execution of IRET caused a fault when NMI blocking was in effect (i.e we're in
13079 * the guest or nested-guest NMI handler). We need to set the block-by-NMI field so
13080 * that NMIs remain blocked until the IRET execution is completed.
13081 *
13082 * See Intel spec. 31.7.1.2 "Resuming Guest Software After Handling An Exception".
13083 */
13084 CPUMSetGuestNmiBlocking(pVCpu, true);
13085 Log4Func(("Set NMI blocking. uExitReason=%u\n", pVmxTransient->uExitReason));
13086 }
13087 else if ( pVmxTransient->uExitReason == VMX_EXIT_EPT_VIOLATION
13088 || pVmxTransient->uExitReason == VMX_EXIT_PML_FULL
13089 || pVmxTransient->uExitReason == VMX_EXIT_SPP_EVENT)
13090 {
13091 /*
13092 * Execution of IRET caused an EPT violation, page-modification log-full event or
13093 * SPP-related event VM-exit when NMI blocking was in effect (i.e. we're in the
13094 * guest or nested-guest NMI handler). We need to set the block-by-NMI field so
13095 * that NMIs remain blocked until the IRET execution is completed.
13096 *
13097 * See Intel spec. 27.2.3 "Information about NMI unblocking due to IRET"
13098 */
13099 if (VMX_EXIT_QUAL_EPT_IS_NMI_UNBLOCK_IRET(pVmxTransient->uExitQual))
13100 {
13101 CPUMSetGuestNmiBlocking(pVCpu, true);
13102 Log4Func(("Set NMI blocking. uExitReason=%u\n", pVmxTransient->uExitReason));
13103 }
13104 }
13105 }
13106
13107 Assert( rcStrict == VINF_SUCCESS || rcStrict == VINF_HM_DOUBLE_FAULT
13108 || rcStrict == VINF_EM_RESET || rcStrict == VERR_EM_GUEST_CPU_HANG);
13109 return rcStrict;
13110}
13111
13112
13113#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
13114/**
13115 * Perform the relevant VMX instruction checks for VM-exits that occurred due to the
13116 * guest attempting to execute a VMX instruction.
13117 *
13118 * @returns Strict VBox status code (i.e. informational status codes too).
13119 * @retval VINF_SUCCESS if we should continue handling the VM-exit.
13120 * @retval VINF_HM_PENDING_XCPT if an exception was raised.
13121 *
13122 * @param pVCpu The cross context virtual CPU structure.
13123 * @param uExitReason The VM-exit reason.
13124 *
13125 * @todo NSTVMX: Document other error codes when VM-exit is implemented.
13126 * @remarks No-long-jump zone!!!
13127 */
13128static VBOXSTRICTRC hmR0VmxCheckExitDueToVmxInstr(PVMCPUCC pVCpu, uint32_t uExitReason)
13129{
13130 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_CR0 | CPUMCTX_EXTRN_RFLAGS | CPUMCTX_EXTRN_SS
13131 | CPUMCTX_EXTRN_CS | CPUMCTX_EXTRN_EFER);
13132
13133 /*
13134 * The physical CPU would have already checked the CPU mode/code segment.
13135 * We shall just assert here for paranoia.
13136 * See Intel spec. 25.1.1 "Relative Priority of Faults and VM Exits".
13137 */
13138 Assert(!CPUMIsGuestInRealOrV86ModeEx(&pVCpu->cpum.GstCtx));
13139 Assert( !CPUMIsGuestInLongModeEx(&pVCpu->cpum.GstCtx)
13140 || CPUMIsGuestIn64BitCodeEx(&pVCpu->cpum.GstCtx));
13141
13142 if (uExitReason == VMX_EXIT_VMXON)
13143 {
13144 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_CR4);
13145
13146 /*
13147 * We check CR4.VMXE because it is required to be always set while in VMX operation
13148 * by physical CPUs and our CR4 read-shadow is only consulted when executing specific
13149 * instructions (CLTS, LMSW, MOV CR, and SMSW) and thus doesn't affect CPU operation
13150 * otherwise (i.e. physical CPU won't automatically #UD if Cr4Shadow.VMXE is 0).
13151 */
13152 if (!CPUMIsGuestVmxEnabled(&pVCpu->cpum.GstCtx))
13153 {
13154 Log4Func(("CR4.VMXE is not set -> #UD\n"));
13155 hmR0VmxSetPendingXcptUD(pVCpu);
13156 return VINF_HM_PENDING_XCPT;
13157 }
13158 }
13159 else if (!CPUMIsGuestInVmxRootMode(&pVCpu->cpum.GstCtx))
13160 {
13161 /*
13162 * The guest has not entered VMX operation but attempted to execute a VMX instruction
13163 * (other than VMXON), we need to raise a #UD.
13164 */
13165 Log4Func(("Not in VMX root mode -> #UD\n"));
13166 hmR0VmxSetPendingXcptUD(pVCpu);
13167 return VINF_HM_PENDING_XCPT;
13168 }
13169
13170 /* All other checks (including VM-exit intercepts) are handled by IEM instruction emulation. */
13171 return VINF_SUCCESS;
13172}
13173
13174
13175/**
13176 * Decodes the memory operand of an instruction that caused a VM-exit.
13177 *
13178 * The Exit qualification field provides the displacement field for memory
13179 * operand instructions, if any.
13180 *
13181 * @returns Strict VBox status code (i.e. informational status codes too).
13182 * @retval VINF_SUCCESS if the operand was successfully decoded.
13183 * @retval VINF_HM_PENDING_XCPT if an exception was raised while decoding the
13184 * operand.
13185 * @param pVCpu The cross context virtual CPU structure.
13186 * @param uExitInstrInfo The VM-exit instruction information field.
13187 * @param enmMemAccess The memory operand's access type (read or write).
13188 * @param GCPtrDisp The instruction displacement field, if any. For
13189 * RIP-relative addressing pass RIP + displacement here.
13190 * @param pGCPtrMem Where to store the effective destination memory address.
13191 *
13192 * @remarks Warning! This function ASSUMES the instruction cannot be used in real or
13193 * virtual-8086 mode hence skips those checks while verifying if the
13194 * segment is valid.
13195 */
13196static VBOXSTRICTRC hmR0VmxDecodeMemOperand(PVMCPUCC pVCpu, uint32_t uExitInstrInfo, RTGCPTR GCPtrDisp, VMXMEMACCESS enmMemAccess,
13197 PRTGCPTR pGCPtrMem)
13198{
13199 Assert(pGCPtrMem);
13200 Assert(!CPUMIsGuestInRealOrV86Mode(pVCpu));
13201 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_RIP | CPUMCTX_EXTRN_RSP | CPUMCTX_EXTRN_SREG_MASK | CPUMCTX_EXTRN_EFER
13202 | CPUMCTX_EXTRN_CR0);
13203
13204 static uint64_t const s_auAddrSizeMasks[] = { UINT64_C(0xffff), UINT64_C(0xffffffff), UINT64_C(0xffffffffffffffff) };
13205 static uint64_t const s_auAccessSizeMasks[] = { sizeof(uint16_t), sizeof(uint32_t), sizeof(uint64_t) };
13206 AssertCompile(RT_ELEMENTS(s_auAccessSizeMasks) == RT_ELEMENTS(s_auAddrSizeMasks));
13207
13208 VMXEXITINSTRINFO ExitInstrInfo;
13209 ExitInstrInfo.u = uExitInstrInfo;
13210 uint8_t const uAddrSize = ExitInstrInfo.All.u3AddrSize;
13211 uint8_t const iSegReg = ExitInstrInfo.All.iSegReg;
13212 bool const fIdxRegValid = !ExitInstrInfo.All.fIdxRegInvalid;
13213 uint8_t const iIdxReg = ExitInstrInfo.All.iIdxReg;
13214 uint8_t const uScale = ExitInstrInfo.All.u2Scaling;
13215 bool const fBaseRegValid = !ExitInstrInfo.All.fBaseRegInvalid;
13216 uint8_t const iBaseReg = ExitInstrInfo.All.iBaseReg;
13217 bool const fIsMemOperand = !ExitInstrInfo.All.fIsRegOperand;
13218 bool const fIsLongMode = CPUMIsGuestInLongModeEx(&pVCpu->cpum.GstCtx);
13219
13220 /*
13221 * Validate instruction information.
13222 * This shouldn't happen on real hardware but useful while testing our nested hardware-virtualization code.
13223 */
13224 AssertLogRelMsgReturn(uAddrSize < RT_ELEMENTS(s_auAddrSizeMasks),
13225 ("Invalid address size. ExitInstrInfo=%#RX32\n", ExitInstrInfo.u), VERR_VMX_IPE_1);
13226 AssertLogRelMsgReturn(iSegReg < X86_SREG_COUNT,
13227 ("Invalid segment register. ExitInstrInfo=%#RX32\n", ExitInstrInfo.u), VERR_VMX_IPE_2);
13228 AssertLogRelMsgReturn(fIsMemOperand,
13229 ("Expected memory operand. ExitInstrInfo=%#RX32\n", ExitInstrInfo.u), VERR_VMX_IPE_3);
13230
13231 /*
13232 * Compute the complete effective address.
13233 *
13234 * See AMD instruction spec. 1.4.2 "SIB Byte Format"
13235 * See AMD spec. 4.5.2 "Segment Registers".
13236 */
13237 RTGCPTR GCPtrMem = GCPtrDisp;
13238 if (fBaseRegValid)
13239 GCPtrMem += pVCpu->cpum.GstCtx.aGRegs[iBaseReg].u64;
13240 if (fIdxRegValid)
13241 GCPtrMem += pVCpu->cpum.GstCtx.aGRegs[iIdxReg].u64 << uScale;
13242
13243 RTGCPTR const GCPtrOff = GCPtrMem;
13244 if ( !fIsLongMode
13245 || iSegReg >= X86_SREG_FS)
13246 GCPtrMem += pVCpu->cpum.GstCtx.aSRegs[iSegReg].u64Base;
13247 GCPtrMem &= s_auAddrSizeMasks[uAddrSize];
13248
13249 /*
13250 * Validate effective address.
13251 * See AMD spec. 4.5.3 "Segment Registers in 64-Bit Mode".
13252 */
13253 uint8_t const cbAccess = s_auAccessSizeMasks[uAddrSize];
13254 Assert(cbAccess > 0);
13255 if (fIsLongMode)
13256 {
13257 if (X86_IS_CANONICAL(GCPtrMem))
13258 {
13259 *pGCPtrMem = GCPtrMem;
13260 return VINF_SUCCESS;
13261 }
13262
13263 /** @todo r=ramshankar: We should probably raise \#SS or \#GP. See AMD spec. 4.12.2
13264 * "Data Limit Checks in 64-bit Mode". */
13265 Log4Func(("Long mode effective address is not canonical GCPtrMem=%#RX64\n", GCPtrMem));
13266 hmR0VmxSetPendingXcptGP(pVCpu, 0);
13267 return VINF_HM_PENDING_XCPT;
13268 }
13269
13270 /*
13271 * This is a watered down version of iemMemApplySegment().
13272 * Parts that are not applicable for VMX instructions like real-or-v8086 mode
13273 * and segment CPL/DPL checks are skipped.
13274 */
13275 RTGCPTR32 const GCPtrFirst32 = (RTGCPTR32)GCPtrOff;
13276 RTGCPTR32 const GCPtrLast32 = GCPtrFirst32 + cbAccess - 1;
13277 PCCPUMSELREG pSel = &pVCpu->cpum.GstCtx.aSRegs[iSegReg];
13278
13279 /* Check if the segment is present and usable. */
13280 if ( pSel->Attr.n.u1Present
13281 && !pSel->Attr.n.u1Unusable)
13282 {
13283 Assert(pSel->Attr.n.u1DescType);
13284 if (!(pSel->Attr.n.u4Type & X86_SEL_TYPE_CODE))
13285 {
13286 /* Check permissions for the data segment. */
13287 if ( enmMemAccess == VMXMEMACCESS_WRITE
13288 && !(pSel->Attr.n.u4Type & X86_SEL_TYPE_WRITE))
13289 {
13290 Log4Func(("Data segment access invalid. iSegReg=%#x Attr=%#RX32\n", iSegReg, pSel->Attr.u));
13291 hmR0VmxSetPendingXcptGP(pVCpu, iSegReg);
13292 return VINF_HM_PENDING_XCPT;
13293 }
13294
13295 /* Check limits if it's a normal data segment. */
13296 if (!(pSel->Attr.n.u4Type & X86_SEL_TYPE_DOWN))
13297 {
13298 if ( GCPtrFirst32 > pSel->u32Limit
13299 || GCPtrLast32 > pSel->u32Limit)
13300 {
13301 Log4Func(("Data segment limit exceeded. "
13302 "iSegReg=%#x GCPtrFirst32=%#RX32 GCPtrLast32=%#RX32 u32Limit=%#RX32\n", iSegReg, GCPtrFirst32,
13303 GCPtrLast32, pSel->u32Limit));
13304 if (iSegReg == X86_SREG_SS)
13305 hmR0VmxSetPendingXcptSS(pVCpu, 0);
13306 else
13307 hmR0VmxSetPendingXcptGP(pVCpu, 0);
13308 return VINF_HM_PENDING_XCPT;
13309 }
13310 }
13311 else
13312 {
13313 /* Check limits if it's an expand-down data segment.
13314 Note! The upper boundary is defined by the B bit, not the G bit! */
13315 if ( GCPtrFirst32 < pSel->u32Limit + UINT32_C(1)
13316 || GCPtrLast32 > (pSel->Attr.n.u1DefBig ? UINT32_MAX : UINT32_C(0xffff)))
13317 {
13318 Log4Func(("Expand-down data segment limit exceeded. "
13319 "iSegReg=%#x GCPtrFirst32=%#RX32 GCPtrLast32=%#RX32 u32Limit=%#RX32\n", iSegReg, GCPtrFirst32,
13320 GCPtrLast32, pSel->u32Limit));
13321 if (iSegReg == X86_SREG_SS)
13322 hmR0VmxSetPendingXcptSS(pVCpu, 0);
13323 else
13324 hmR0VmxSetPendingXcptGP(pVCpu, 0);
13325 return VINF_HM_PENDING_XCPT;
13326 }
13327 }
13328 }
13329 else
13330 {
13331 /* Check permissions for the code segment. */
13332 if ( enmMemAccess == VMXMEMACCESS_WRITE
13333 || ( enmMemAccess == VMXMEMACCESS_READ
13334 && !(pSel->Attr.n.u4Type & X86_SEL_TYPE_READ)))
13335 {
13336 Log4Func(("Code segment access invalid. Attr=%#RX32\n", pSel->Attr.u));
13337 Assert(!CPUMIsGuestInRealOrV86ModeEx(&pVCpu->cpum.GstCtx));
13338 hmR0VmxSetPendingXcptGP(pVCpu, 0);
13339 return VINF_HM_PENDING_XCPT;
13340 }
13341
13342 /* Check limits for the code segment (normal/expand-down not applicable for code segments). */
13343 if ( GCPtrFirst32 > pSel->u32Limit
13344 || GCPtrLast32 > pSel->u32Limit)
13345 {
13346 Log4Func(("Code segment limit exceeded. GCPtrFirst32=%#RX32 GCPtrLast32=%#RX32 u32Limit=%#RX32\n",
13347 GCPtrFirst32, GCPtrLast32, pSel->u32Limit));
13348 if (iSegReg == X86_SREG_SS)
13349 hmR0VmxSetPendingXcptSS(pVCpu, 0);
13350 else
13351 hmR0VmxSetPendingXcptGP(pVCpu, 0);
13352 return VINF_HM_PENDING_XCPT;
13353 }
13354 }
13355 }
13356 else
13357 {
13358 Log4Func(("Not present or unusable segment. iSegReg=%#x Attr=%#RX32\n", iSegReg, pSel->Attr.u));
13359 hmR0VmxSetPendingXcptGP(pVCpu, 0);
13360 return VINF_HM_PENDING_XCPT;
13361 }
13362
13363 *pGCPtrMem = GCPtrMem;
13364 return VINF_SUCCESS;
13365}
13366#endif /* VBOX_WITH_NESTED_HWVIRT_VMX */
13367
13368
13369/**
13370 * VM-exit helper for LMSW.
13371 */
13372static VBOXSTRICTRC hmR0VmxExitLmsw(PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo, uint8_t cbInstr, uint16_t uMsw, RTGCPTR GCPtrEffDst)
13373{
13374 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, IEM_CPUMCTX_EXTRN_MUST_MASK);
13375 AssertRCReturn(rc, rc);
13376
13377 VBOXSTRICTRC rcStrict = IEMExecDecodedLmsw(pVCpu, cbInstr, uMsw, GCPtrEffDst);
13378 AssertMsg( rcStrict == VINF_SUCCESS
13379 || rcStrict == VINF_IEM_RAISED_XCPT, ("%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
13380
13381 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS | HM_CHANGED_GUEST_CR0);
13382 if (rcStrict == VINF_IEM_RAISED_XCPT)
13383 {
13384 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
13385 rcStrict = VINF_SUCCESS;
13386 }
13387
13388 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitLmsw);
13389 Log4Func(("rcStrict=%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
13390 return rcStrict;
13391}
13392
13393
13394/**
13395 * VM-exit helper for CLTS.
13396 */
13397static VBOXSTRICTRC hmR0VmxExitClts(PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo, uint8_t cbInstr)
13398{
13399 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, IEM_CPUMCTX_EXTRN_MUST_MASK);
13400 AssertRCReturn(rc, rc);
13401
13402 VBOXSTRICTRC rcStrict = IEMExecDecodedClts(pVCpu, cbInstr);
13403 AssertMsg( rcStrict == VINF_SUCCESS
13404 || rcStrict == VINF_IEM_RAISED_XCPT, ("%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
13405
13406 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS | HM_CHANGED_GUEST_CR0);
13407 if (rcStrict == VINF_IEM_RAISED_XCPT)
13408 {
13409 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
13410 rcStrict = VINF_SUCCESS;
13411 }
13412
13413 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitClts);
13414 Log4Func(("rcStrict=%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
13415 return rcStrict;
13416}
13417
13418
13419/**
13420 * VM-exit helper for MOV from CRx (CRx read).
13421 */
13422static VBOXSTRICTRC hmR0VmxExitMovFromCrX(PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo, uint8_t cbInstr, uint8_t iGReg, uint8_t iCrReg)
13423{
13424 Assert(iCrReg < 16);
13425 Assert(iGReg < RT_ELEMENTS(pVCpu->cpum.GstCtx.aGRegs));
13426
13427 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, IEM_CPUMCTX_EXTRN_MUST_MASK);
13428 AssertRCReturn(rc, rc);
13429
13430 VBOXSTRICTRC rcStrict = IEMExecDecodedMovCRxRead(pVCpu, cbInstr, iGReg, iCrReg);
13431 AssertMsg( rcStrict == VINF_SUCCESS
13432 || rcStrict == VINF_IEM_RAISED_XCPT, ("%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
13433
13434 if (iGReg == X86_GREG_xSP)
13435 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS | HM_CHANGED_GUEST_RSP);
13436 else
13437 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS);
13438#ifdef VBOX_WITH_STATISTICS
13439 switch (iCrReg)
13440 {
13441 case 0: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCR0Read); break;
13442 case 2: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCR2Read); break;
13443 case 3: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCR3Read); break;
13444 case 4: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCR4Read); break;
13445 case 8: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCR8Read); break;
13446 }
13447#endif
13448 Log4Func(("CR%d Read access rcStrict=%Rrc\n", iCrReg, VBOXSTRICTRC_VAL(rcStrict)));
13449 return rcStrict;
13450}
13451
13452
13453/**
13454 * VM-exit helper for MOV to CRx (CRx write).
13455 */
13456static VBOXSTRICTRC hmR0VmxExitMovToCrX(PVMCPUCC pVCpu, PVMXVMCSINFO pVmcsInfo, uint8_t cbInstr, uint8_t iGReg, uint8_t iCrReg)
13457{
13458 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, IEM_CPUMCTX_EXTRN_MUST_MASK);
13459 AssertRCReturn(rc, rc);
13460
13461 VBOXSTRICTRC rcStrict = IEMExecDecodedMovCRxWrite(pVCpu, cbInstr, iCrReg, iGReg);
13462 AssertMsg( rcStrict == VINF_SUCCESS
13463 || rcStrict == VINF_IEM_RAISED_XCPT
13464 || rcStrict == VINF_PGM_SYNC_CR3, ("%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
13465
13466 switch (iCrReg)
13467 {
13468 case 0:
13469 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS | HM_CHANGED_GUEST_CR0
13470 | HM_CHANGED_GUEST_EFER_MSR | HM_CHANGED_VMX_ENTRY_EXIT_CTLS);
13471 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCR0Write);
13472 Log4Func(("CR0 write. rcStrict=%Rrc CR0=%#RX64\n", VBOXSTRICTRC_VAL(rcStrict), pVCpu->cpum.GstCtx.cr0));
13473 break;
13474
13475 case 2:
13476 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCR2Write);
13477 /* Nothing to do here, CR2 it's not part of the VMCS. */
13478 break;
13479
13480 case 3:
13481 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS | HM_CHANGED_GUEST_CR3);
13482 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCR3Write);
13483 Log4Func(("CR3 write. rcStrict=%Rrc CR3=%#RX64\n", VBOXSTRICTRC_VAL(rcStrict), pVCpu->cpum.GstCtx.cr3));
13484 break;
13485
13486 case 4:
13487 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS | HM_CHANGED_GUEST_CR4);
13488 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCR4Write);
13489 Log4Func(("CR4 write. rc=%Rrc CR4=%#RX64 fLoadSaveGuestXcr0=%u\n", VBOXSTRICTRC_VAL(rcStrict),
13490 pVCpu->cpum.GstCtx.cr4, pVCpu->hm.s.fLoadSaveGuestXcr0));
13491 break;
13492
13493 case 8:
13494 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged,
13495 HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS | HM_CHANGED_GUEST_APIC_TPR);
13496 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCR8Write);
13497 break;
13498
13499 default:
13500 AssertMsgFailed(("Invalid CRx register %#x\n", iCrReg));
13501 break;
13502 }
13503
13504 if (rcStrict == VINF_IEM_RAISED_XCPT)
13505 {
13506 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
13507 rcStrict = VINF_SUCCESS;
13508 }
13509 return rcStrict;
13510}
13511
13512
13513/**
13514 * VM-exit exception handler for \#PF (Page-fault exception).
13515 *
13516 * @remarks Requires all fields in HMVMX_READ_XCPT_INFO to be read from the VMCS.
13517 */
13518static VBOXSTRICTRC hmR0VmxExitXcptPF(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
13519{
13520 HMVMX_VALIDATE_EXIT_XCPT_HANDLER_PARAMS(pVCpu, pVmxTransient);
13521 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
13522 hmR0VmxReadExitQualVmcs(pVmxTransient);
13523
13524 if (!pVM->hm.s.fNestedPaging)
13525 { /* likely */ }
13526 else
13527 {
13528#if !defined(HMVMX_ALWAYS_TRAP_ALL_XCPTS) && !defined(HMVMX_ALWAYS_TRAP_PF)
13529 Assert(pVmxTransient->fIsNestedGuest || pVCpu->hm.s.fUsingDebugLoop);
13530#endif
13531 pVCpu->hm.s.Event.fPending = false; /* In case it's a contributory or vectoring #PF. */
13532 if (!pVmxTransient->fVectoringDoublePF)
13533 {
13534 hmR0VmxSetPendingEvent(pVCpu, VMX_ENTRY_INT_INFO_FROM_EXIT_INT_INFO(pVmxTransient->uExitIntInfo), 0 /* cbInstr */,
13535 pVmxTransient->uExitIntErrorCode, pVmxTransient->uExitQual);
13536 }
13537 else
13538 {
13539 /* A guest page-fault occurred during delivery of a page-fault. Inject #DF. */
13540 Assert(!pVmxTransient->fIsNestedGuest);
13541 hmR0VmxSetPendingXcptDF(pVCpu);
13542 Log4Func(("Pending #DF due to vectoring #PF w/ NestedPaging\n"));
13543 }
13544 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestPF);
13545 return VINF_SUCCESS;
13546 }
13547
13548 Assert(!pVmxTransient->fIsNestedGuest);
13549
13550 /* If it's a vectoring #PF, emulate injecting the original event injection as PGMTrap0eHandler() is incapable
13551 of differentiating between instruction emulation and event injection that caused a #PF. See @bugref{6607}. */
13552 if (pVmxTransient->fVectoringPF)
13553 {
13554 Assert(pVCpu->hm.s.Event.fPending);
13555 return VINF_EM_RAW_INJECT_TRPM_EVENT;
13556 }
13557
13558 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
13559 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, HMVMX_CPUMCTX_EXTRN_ALL);
13560 AssertRCReturn(rc, rc);
13561
13562 Log4Func(("#PF: cs:rip=%#04x:%#RX64 err_code=%#RX32 exit_qual=%#RX64 cr3=%#RX64\n", pCtx->cs.Sel, pCtx->rip,
13563 pVmxTransient->uExitIntErrorCode, pVmxTransient->uExitQual, pCtx->cr3));
13564
13565 TRPMAssertXcptPF(pVCpu, pVmxTransient->uExitQual, (RTGCUINT)pVmxTransient->uExitIntErrorCode);
13566 rc = PGMTrap0eHandler(pVCpu, pVmxTransient->uExitIntErrorCode, CPUMCTX2CORE(pCtx), (RTGCPTR)pVmxTransient->uExitQual);
13567
13568 Log4Func(("#PF: rc=%Rrc\n", rc));
13569 if (rc == VINF_SUCCESS)
13570 {
13571 /*
13572 * This is typically a shadow page table sync or a MMIO instruction. But we may have
13573 * emulated something like LTR or a far jump. Any part of the CPU context may have changed.
13574 */
13575 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_ALL_GUEST);
13576 TRPMResetTrap(pVCpu);
13577 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitShadowPF);
13578 return rc;
13579 }
13580
13581 if (rc == VINF_EM_RAW_GUEST_TRAP)
13582 {
13583 if (!pVmxTransient->fVectoringDoublePF)
13584 {
13585 /* It's a guest page fault and needs to be reflected to the guest. */
13586 uint32_t uGstErrorCode = TRPMGetErrorCode(pVCpu);
13587 TRPMResetTrap(pVCpu);
13588 pVCpu->hm.s.Event.fPending = false; /* In case it's a contributory #PF. */
13589 hmR0VmxSetPendingEvent(pVCpu, VMX_ENTRY_INT_INFO_FROM_EXIT_INT_INFO(pVmxTransient->uExitIntInfo), 0 /* cbInstr */,
13590 uGstErrorCode, pVmxTransient->uExitQual);
13591 }
13592 else
13593 {
13594 /* A guest page-fault occurred during delivery of a page-fault. Inject #DF. */
13595 TRPMResetTrap(pVCpu);
13596 pVCpu->hm.s.Event.fPending = false; /* Clear pending #PF to replace it with #DF. */
13597 hmR0VmxSetPendingXcptDF(pVCpu);
13598 Log4Func(("#PF: Pending #DF due to vectoring #PF\n"));
13599 }
13600
13601 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestPF);
13602 return VINF_SUCCESS;
13603 }
13604
13605 TRPMResetTrap(pVCpu);
13606 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitShadowPFEM);
13607 return rc;
13608}
13609
13610
13611/**
13612 * VM-exit exception handler for \#MF (Math Fault: floating point exception).
13613 *
13614 * @remarks Requires all fields in HMVMX_READ_XCPT_INFO to be read from the VMCS.
13615 */
13616static VBOXSTRICTRC hmR0VmxExitXcptMF(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
13617{
13618 HMVMX_VALIDATE_EXIT_XCPT_HANDLER_PARAMS(pVCpu, pVmxTransient);
13619 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestMF);
13620
13621 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, CPUMCTX_EXTRN_CR0);
13622 AssertRCReturn(rc, rc);
13623
13624 if (!(pVCpu->cpum.GstCtx.cr0 & X86_CR0_NE))
13625 {
13626 /* Convert a #MF into a FERR -> IRQ 13. See @bugref{6117}. */
13627 rc = PDMIsaSetIrq(pVCpu->CTX_SUFF(pVM), 13, 1, 0 /* uTagSrc */);
13628
13629 /** @todo r=ramshankar: The Intel spec. does -not- specify that this VM-exit
13630 * provides VM-exit instruction length. If this causes problem later,
13631 * disassemble the instruction like it's done on AMD-V. */
13632 int rc2 = hmR0VmxAdvanceGuestRip(pVCpu, pVmxTransient);
13633 AssertRCReturn(rc2, rc2);
13634 return rc;
13635 }
13636
13637 hmR0VmxSetPendingEvent(pVCpu, VMX_ENTRY_INT_INFO_FROM_EXIT_INT_INFO(pVmxTransient->uExitIntInfo), pVmxTransient->cbExitInstr,
13638 pVmxTransient->uExitIntErrorCode, 0 /* GCPtrFaultAddress */);
13639 return VINF_SUCCESS;
13640}
13641
13642
13643/**
13644 * VM-exit exception handler for \#BP (Breakpoint exception).
13645 *
13646 * @remarks Requires all fields in HMVMX_READ_XCPT_INFO to be read from the VMCS.
13647 */
13648static VBOXSTRICTRC hmR0VmxExitXcptBP(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
13649{
13650 HMVMX_VALIDATE_EXIT_XCPT_HANDLER_PARAMS(pVCpu, pVmxTransient);
13651 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestBP);
13652
13653 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, HMVMX_CPUMCTX_EXTRN_ALL);
13654 AssertRCReturn(rc, rc);
13655
13656 if (!pVmxTransient->fIsNestedGuest)
13657 rc = DBGFRZTrap03Handler(pVCpu->CTX_SUFF(pVM), pVCpu, CPUMCTX2CORE(&pVCpu->cpum.GstCtx));
13658 else
13659 rc = VINF_EM_RAW_GUEST_TRAP;
13660
13661 if (rc == VINF_EM_RAW_GUEST_TRAP)
13662 {
13663 hmR0VmxSetPendingEvent(pVCpu, VMX_ENTRY_INT_INFO_FROM_EXIT_INT_INFO(pVmxTransient->uExitIntInfo),
13664 pVmxTransient->cbExitInstr, pVmxTransient->uExitIntErrorCode, 0 /* GCPtrFaultAddress */);
13665 rc = VINF_SUCCESS;
13666 }
13667
13668 Assert(rc == VINF_SUCCESS || rc == VINF_EM_DBG_BREAKPOINT);
13669 return rc;
13670}
13671
13672
13673/**
13674 * VM-exit exception handler for \#AC (Alignment-check exception).
13675 *
13676 * @remarks Requires all fields in HMVMX_READ_XCPT_INFO to be read from the VMCS.
13677 */
13678static VBOXSTRICTRC hmR0VmxExitXcptAC(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
13679{
13680 HMVMX_VALIDATE_EXIT_XCPT_HANDLER_PARAMS(pVCpu, pVmxTransient);
13681 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestAC);
13682
13683 /* Re-inject it. We'll detect any nesting before getting here. */
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/**
13691 * VM-exit exception handler for \#DB (Debug exception).
13692 *
13693 * @remarks Requires all fields in HMVMX_READ_XCPT_INFO to be read from the VMCS.
13694 */
13695static VBOXSTRICTRC hmR0VmxExitXcptDB(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
13696{
13697 HMVMX_VALIDATE_EXIT_XCPT_HANDLER_PARAMS(pVCpu, pVmxTransient);
13698 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestDB);
13699
13700 /*
13701 * Get the DR6-like values from the Exit qualification and pass it to DBGF for processing.
13702 */
13703 hmR0VmxReadExitQualVmcs(pVmxTransient);
13704
13705 /* Refer Intel spec. Table 27-1. "Exit Qualifications for debug exceptions" for the format. */
13706 uint64_t const uDR6 = X86_DR6_INIT_VAL
13707 | (pVmxTransient->uExitQual & ( X86_DR6_B0 | X86_DR6_B1 | X86_DR6_B2 | X86_DR6_B3
13708 | X86_DR6_BD | X86_DR6_BS));
13709
13710 int rc;
13711 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
13712 if (!pVmxTransient->fIsNestedGuest)
13713 rc = DBGFRZTrap01Handler(pVCpu->CTX_SUFF(pVM), pVCpu, CPUMCTX2CORE(pCtx), uDR6, pVCpu->hm.s.fSingleInstruction);
13714 else
13715 rc = VINF_EM_RAW_GUEST_TRAP;
13716 Log6Func(("rc=%Rrc\n", rc));
13717 if (rc == VINF_EM_RAW_GUEST_TRAP)
13718 {
13719 /*
13720 * The exception was for the guest. Update DR6, DR7.GD and
13721 * IA32_DEBUGCTL.LBR before forwarding it.
13722 * See Intel spec. 27.1 "Architectural State before a VM-Exit".
13723 */
13724 VMMRZCallRing3Disable(pVCpu);
13725 HM_DISABLE_PREEMPT(pVCpu);
13726
13727 pCtx->dr[6] &= ~X86_DR6_B_MASK;
13728 pCtx->dr[6] |= uDR6;
13729 if (CPUMIsGuestDebugStateActive(pVCpu))
13730 ASMSetDR6(pCtx->dr[6]);
13731
13732 HM_RESTORE_PREEMPT();
13733 VMMRZCallRing3Enable(pVCpu);
13734
13735 rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, CPUMCTX_EXTRN_DR7);
13736 AssertRCReturn(rc, rc);
13737
13738 /* X86_DR7_GD will be cleared if DRx accesses should be trapped inside the guest. */
13739 pCtx->dr[7] &= ~(uint64_t)X86_DR7_GD;
13740
13741 /* Paranoia. */
13742 pCtx->dr[7] &= ~(uint64_t)X86_DR7_RAZ_MASK;
13743 pCtx->dr[7] |= X86_DR7_RA1_MASK;
13744
13745 rc = VMXWriteVmcsNw(VMX_VMCS_GUEST_DR7, pCtx->dr[7]);
13746 AssertRC(rc);
13747
13748 /*
13749 * Raise #DB in the guest.
13750 *
13751 * It is important to reflect exactly what the VM-exit gave us (preserving the
13752 * interruption-type) rather than use hmR0VmxSetPendingXcptDB() as the #DB could've
13753 * been raised while executing ICEBP (INT1) and not the regular #DB. Thus it may
13754 * trigger different handling in the CPU (like skipping DPL checks), see @bugref{6398}.
13755 *
13756 * Intel re-documented ICEBP/INT1 on May 2018 previously documented as part of
13757 * Intel 386, see Intel spec. 24.8.3 "VM-Entry Controls for Event Injection".
13758 */
13759 hmR0VmxSetPendingEvent(pVCpu, VMX_ENTRY_INT_INFO_FROM_EXIT_INT_INFO(pVmxTransient->uExitIntInfo),
13760 pVmxTransient->cbExitInstr, pVmxTransient->uExitIntErrorCode, 0 /* GCPtrFaultAddress */);
13761 return VINF_SUCCESS;
13762 }
13763
13764 /*
13765 * Not a guest trap, must be a hypervisor related debug event then.
13766 * Update DR6 in case someone is interested in it.
13767 */
13768 AssertMsg(rc == VINF_EM_DBG_STEPPED || rc == VINF_EM_DBG_BREAKPOINT, ("%Rrc\n", rc));
13769 AssertReturn(pVmxTransient->fWasHyperDebugStateActive, VERR_HM_IPE_5);
13770 CPUMSetHyperDR6(pVCpu, uDR6);
13771
13772 return rc;
13773}
13774
13775
13776/**
13777 * Hacks its way around the lovely mesa driver's backdoor accesses.
13778 *
13779 * @sa hmR0SvmHandleMesaDrvGp.
13780 */
13781static int hmR0VmxHandleMesaDrvGp(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient, PCPUMCTX pCtx)
13782{
13783 LogFunc(("cs:rip=%#04x:%#RX64 rcx=%#RX64 rbx=%#RX64\n", pCtx->cs.Sel, pCtx->rip, pCtx->rcx, pCtx->rbx));
13784 RT_NOREF(pCtx);
13785
13786 /* For now we'll just skip the instruction. */
13787 return hmR0VmxAdvanceGuestRip(pVCpu, pVmxTransient);
13788}
13789
13790
13791/**
13792 * Checks if the \#GP'ing instruction is the mesa driver doing it's lovely
13793 * backdoor logging w/o checking what it is running inside.
13794 *
13795 * This recognizes an "IN EAX,DX" instruction executed in flat ring-3, with the
13796 * backdoor port and magic numbers loaded in registers.
13797 *
13798 * @returns true if it is, false if it isn't.
13799 * @sa hmR0SvmIsMesaDrvGp.
13800 */
13801DECLINLINE(bool) hmR0VmxIsMesaDrvGp(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient, PCPUMCTX pCtx)
13802{
13803 /* 0xed: IN eAX,dx */
13804 uint8_t abInstr[1];
13805 if (pVmxTransient->cbExitInstr != sizeof(abInstr))
13806 return false;
13807
13808 /* Check that it is #GP(0). */
13809 if (pVmxTransient->uExitIntErrorCode != 0)
13810 return false;
13811
13812 /* Check magic and port. */
13813 Assert(!(pCtx->fExtrn & (CPUMCTX_EXTRN_RAX | CPUMCTX_EXTRN_RDX | CPUMCTX_EXTRN_RCX)));
13814 /*Log(("hmR0VmxIsMesaDrvGp: rax=%RX64 rdx=%RX64\n", pCtx->rax, pCtx->rdx));*/
13815 if (pCtx->rax != UINT32_C(0x564d5868))
13816 return false;
13817 if (pCtx->dx != UINT32_C(0x5658))
13818 return false;
13819
13820 /* Flat ring-3 CS. */
13821 AssertCompile(HMVMX_CPUMCTX_EXTRN_ALL & CPUMCTX_EXTRN_CS);
13822 Assert(!(pCtx->fExtrn & CPUMCTX_EXTRN_CS));
13823 /*Log(("hmR0VmxIsMesaDrvGp: cs.Attr.n.u2Dpl=%d base=%Rx64\n", pCtx->cs.Attr.n.u2Dpl, pCtx->cs.u64Base));*/
13824 if (pCtx->cs.Attr.n.u2Dpl != 3)
13825 return false;
13826 if (pCtx->cs.u64Base != 0)
13827 return false;
13828
13829 /* Check opcode. */
13830 AssertCompile(HMVMX_CPUMCTX_EXTRN_ALL & CPUMCTX_EXTRN_RIP);
13831 Assert(!(pCtx->fExtrn & CPUMCTX_EXTRN_RIP));
13832 int rc = PGMPhysSimpleReadGCPtr(pVCpu, abInstr, pCtx->rip, sizeof(abInstr));
13833 /*Log(("hmR0VmxIsMesaDrvGp: PGMPhysSimpleReadGCPtr -> %Rrc %#x\n", rc, abInstr[0]));*/
13834 if (RT_FAILURE(rc))
13835 return false;
13836 if (abInstr[0] != 0xed)
13837 return false;
13838
13839 return true;
13840}
13841
13842
13843/**
13844 * VM-exit exception handler for \#GP (General-protection exception).
13845 *
13846 * @remarks Requires all fields in HMVMX_READ_XCPT_INFO to be read from the VMCS.
13847 */
13848static VBOXSTRICTRC hmR0VmxExitXcptGP(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
13849{
13850 HMVMX_VALIDATE_EXIT_XCPT_HANDLER_PARAMS(pVCpu, pVmxTransient);
13851 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestGP);
13852
13853 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
13854 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
13855 if (pVmcsInfo->RealMode.fRealOnV86Active)
13856 { /* likely */ }
13857 else
13858 {
13859#ifndef HMVMX_ALWAYS_TRAP_ALL_XCPTS
13860 Assert(pVCpu->hm.s.fUsingDebugLoop || pVCpu->hm.s.fTrapXcptGpForLovelyMesaDrv || pVmxTransient->fIsNestedGuest);
13861#endif
13862 /*
13863 * If the guest is not in real-mode or we have unrestricted guest execution support, or if we are
13864 * executing a nested-guest, reflect #GP to the guest or nested-guest.
13865 */
13866 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, HMVMX_CPUMCTX_EXTRN_ALL);
13867 AssertRCReturn(rc, rc);
13868 Log4Func(("Gst: cs:rip=%#04x:%#RX64 ErrorCode=%#x cr0=%#RX64 cpl=%u tr=%#04x\n", pCtx->cs.Sel, pCtx->rip,
13869 pVmxTransient->uExitIntErrorCode, pCtx->cr0, CPUMGetGuestCPL(pVCpu), pCtx->tr.Sel));
13870
13871 if ( pVmxTransient->fIsNestedGuest
13872 || !pVCpu->hm.s.fTrapXcptGpForLovelyMesaDrv
13873 || !hmR0VmxIsMesaDrvGp(pVCpu, pVmxTransient, pCtx))
13874 hmR0VmxSetPendingEvent(pVCpu, VMX_ENTRY_INT_INFO_FROM_EXIT_INT_INFO(pVmxTransient->uExitIntInfo),
13875 pVmxTransient->cbExitInstr, pVmxTransient->uExitIntErrorCode, 0 /* GCPtrFaultAddress */);
13876 else
13877 rc = hmR0VmxHandleMesaDrvGp(pVCpu, pVmxTransient, pCtx);
13878 return rc;
13879 }
13880
13881 Assert(CPUMIsGuestInRealModeEx(pCtx));
13882 Assert(!pVCpu->CTX_SUFF(pVM)->hm.s.vmx.fUnrestrictedGuest);
13883 Assert(!pVmxTransient->fIsNestedGuest);
13884
13885 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, HMVMX_CPUMCTX_EXTRN_ALL);
13886 AssertRCReturn(rc, rc);
13887
13888 VBOXSTRICTRC rcStrict = IEMExecOne(pVCpu);
13889 if (rcStrict == VINF_SUCCESS)
13890 {
13891 if (!CPUMIsGuestInRealModeEx(pCtx))
13892 {
13893 /*
13894 * The guest is no longer in real-mode, check if we can continue executing the
13895 * guest using hardware-assisted VMX. Otherwise, fall back to emulation.
13896 */
13897 pVmcsInfo->RealMode.fRealOnV86Active = false;
13898 if (HMCanExecuteVmxGuest(pVCpu->pVMR0, pVCpu, pCtx))
13899 {
13900 Log4Func(("Mode changed but guest still suitable for executing using hardware-assisted VMX\n"));
13901 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_ALL_GUEST);
13902 }
13903 else
13904 {
13905 Log4Func(("Mode changed -> VINF_EM_RESCHEDULE\n"));
13906 rcStrict = VINF_EM_RESCHEDULE;
13907 }
13908 }
13909 else
13910 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_ALL_GUEST);
13911 }
13912 else if (rcStrict == VINF_IEM_RAISED_XCPT)
13913 {
13914 rcStrict = VINF_SUCCESS;
13915 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
13916 }
13917 return VBOXSTRICTRC_VAL(rcStrict);
13918}
13919
13920
13921/**
13922 * VM-exit exception handler wrapper for all other exceptions that are not handled
13923 * by a specific handler.
13924 *
13925 * This simply re-injects the exception back into the VM without any special
13926 * processing.
13927 *
13928 * @remarks Requires all fields in HMVMX_READ_XCPT_INFO to be read from the VMCS.
13929 */
13930static VBOXSTRICTRC hmR0VmxExitXcptOthers(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
13931{
13932 HMVMX_VALIDATE_EXIT_XCPT_HANDLER_PARAMS(pVCpu, pVmxTransient);
13933
13934#ifndef HMVMX_ALWAYS_TRAP_ALL_XCPTS
13935 PCVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
13936 AssertMsg(pVCpu->hm.s.fUsingDebugLoop || pVmcsInfo->RealMode.fRealOnV86Active || pVmxTransient->fIsNestedGuest,
13937 ("uVector=%#x u32XcptBitmap=%#X32\n",
13938 VMX_EXIT_INT_INFO_VECTOR(pVmxTransient->uExitIntInfo), pVmcsInfo->u32XcptBitmap));
13939 NOREF(pVmcsInfo);
13940#endif
13941
13942 /*
13943 * Re-inject the exception into the guest. This cannot be a double-fault condition which
13944 * would have been handled while checking exits due to event delivery.
13945 */
13946 uint8_t const uVector = VMX_EXIT_INT_INFO_VECTOR(pVmxTransient->uExitIntInfo);
13947
13948#ifdef HMVMX_ALWAYS_TRAP_ALL_XCPTS
13949 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, CPUMCTX_EXTRN_CS | CPUMCTX_EXTRN_RIP);
13950 AssertRCReturn(rc, rc);
13951 Log4Func(("Reinjecting Xcpt. uVector=%#x cs:rip=%#04x:%#RX64\n", uVector, pCtx->cs.Sel, pCtx->rip));
13952#endif
13953
13954#ifdef VBOX_WITH_STATISTICS
13955 switch (uVector)
13956 {
13957 case X86_XCPT_DE: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestDE); break;
13958 case X86_XCPT_DB: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestDB); break;
13959 case X86_XCPT_BP: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestBP); break;
13960 case X86_XCPT_OF: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestOF); break;
13961 case X86_XCPT_BR: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestBR); break;
13962 case X86_XCPT_UD: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestUD); break;
13963 case X86_XCPT_NM: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestOF); break;
13964 case X86_XCPT_DF: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestDF); break;
13965 case X86_XCPT_TS: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestTS); break;
13966 case X86_XCPT_NP: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestNP); break;
13967 case X86_XCPT_SS: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestSS); break;
13968 case X86_XCPT_GP: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestGP); break;
13969 case X86_XCPT_PF: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestPF); break;
13970 case X86_XCPT_MF: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestMF); break;
13971 case X86_XCPT_AC: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestAC); break;
13972 case X86_XCPT_XF: STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestXF); break;
13973 default:
13974 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestXcpUnk);
13975 break;
13976 }
13977#endif
13978
13979 /* We should never call this function for a page-fault, we'd need to pass on the fault address below otherwise. */
13980 Assert(!VMX_EXIT_INT_INFO_IS_XCPT_PF(pVmxTransient->uExitIntInfo));
13981 NOREF(uVector);
13982
13983 /* Re-inject the original exception into the guest. */
13984 hmR0VmxSetPendingEvent(pVCpu, VMX_ENTRY_INT_INFO_FROM_EXIT_INT_INFO(pVmxTransient->uExitIntInfo),
13985 pVmxTransient->cbExitInstr, pVmxTransient->uExitIntErrorCode, 0 /* GCPtrFaultAddress */);
13986 return VINF_SUCCESS;
13987}
13988
13989
13990/**
13991 * VM-exit exception handler for all exceptions (except NMIs!).
13992 *
13993 * @remarks This may be called for both guests and nested-guests. Take care to not
13994 * make assumptions and avoid doing anything that is not relevant when
13995 * executing a nested-guest (e.g., Mesa driver hacks).
13996 */
13997static VBOXSTRICTRC hmR0VmxExitXcpt(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
13998{
13999 HMVMX_ASSERT_READ(pVmxTransient, HMVMX_READ_XCPT_INFO);
14000
14001 /*
14002 * If this VM-exit occurred while delivering an event through the guest IDT, take
14003 * action based on the return code and additional hints (e.g. for page-faults)
14004 * that will be updated in the VMX transient structure.
14005 */
14006 VBOXSTRICTRC rcStrict = hmR0VmxCheckExitDueToEventDelivery(pVCpu, pVmxTransient);
14007 if (rcStrict == VINF_SUCCESS)
14008 {
14009 /*
14010 * If an exception caused a VM-exit due to delivery of an event, the original
14011 * event may have to be re-injected into the guest. We shall reinject it and
14012 * continue guest execution. However, page-fault is a complicated case and
14013 * needs additional processing done in hmR0VmxExitXcptPF().
14014 */
14015 Assert(VMX_EXIT_INT_INFO_IS_VALID(pVmxTransient->uExitIntInfo));
14016 uint8_t const uVector = VMX_EXIT_INT_INFO_VECTOR(pVmxTransient->uExitIntInfo);
14017 if ( !pVCpu->hm.s.Event.fPending
14018 || uVector == X86_XCPT_PF)
14019 {
14020 switch (uVector)
14021 {
14022 case X86_XCPT_PF: return hmR0VmxExitXcptPF(pVCpu, pVmxTransient);
14023 case X86_XCPT_GP: return hmR0VmxExitXcptGP(pVCpu, pVmxTransient);
14024 case X86_XCPT_MF: return hmR0VmxExitXcptMF(pVCpu, pVmxTransient);
14025 case X86_XCPT_DB: return hmR0VmxExitXcptDB(pVCpu, pVmxTransient);
14026 case X86_XCPT_BP: return hmR0VmxExitXcptBP(pVCpu, pVmxTransient);
14027 case X86_XCPT_AC: return hmR0VmxExitXcptAC(pVCpu, pVmxTransient);
14028 default:
14029 return hmR0VmxExitXcptOthers(pVCpu, pVmxTransient);
14030 }
14031 }
14032 /* else: inject pending event before resuming guest execution. */
14033 }
14034 else if (rcStrict == VINF_HM_DOUBLE_FAULT)
14035 {
14036 Assert(pVCpu->hm.s.Event.fPending);
14037 rcStrict = VINF_SUCCESS;
14038 }
14039
14040 return rcStrict;
14041}
14042/** @} */
14043
14044
14045/** @name VM-exit handlers.
14046 * @{
14047 */
14048/* -=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= */
14049/* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- VM-exit handlers -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- */
14050/* -=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= */
14051
14052/**
14053 * VM-exit handler for external interrupts (VMX_EXIT_EXT_INT).
14054 */
14055HMVMX_EXIT_DECL hmR0VmxExitExtInt(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14056{
14057 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14058 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitExtInt);
14059 /* Windows hosts (32-bit and 64-bit) have DPC latency issues. See @bugref{6853}. */
14060 if (VMMR0ThreadCtxHookIsEnabled(pVCpu))
14061 return VINF_SUCCESS;
14062 return VINF_EM_RAW_INTERRUPT;
14063}
14064
14065
14066/**
14067 * VM-exit handler for exceptions or NMIs (VMX_EXIT_XCPT_OR_NMI). Conditional
14068 * VM-exit.
14069 */
14070HMVMX_EXIT_DECL hmR0VmxExitXcptOrNmi(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14071{
14072 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14073 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatExitXcptNmi, y3);
14074
14075 hmR0VmxReadExitIntInfoVmcs(pVmxTransient);
14076
14077 uint32_t const uExitIntType = VMX_EXIT_INT_INFO_TYPE(pVmxTransient->uExitIntInfo);
14078 uint8_t const uVector = VMX_EXIT_INT_INFO_VECTOR(pVmxTransient->uExitIntInfo);
14079 Assert(VMX_EXIT_INT_INFO_IS_VALID(pVmxTransient->uExitIntInfo));
14080
14081 PCVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
14082 Assert( !(pVmcsInfo->u32ExitCtls & VMX_EXIT_CTLS_ACK_EXT_INT)
14083 && uExitIntType != VMX_EXIT_INT_INFO_TYPE_EXT_INT);
14084 NOREF(pVmcsInfo);
14085
14086 VBOXSTRICTRC rcStrict;
14087 switch (uExitIntType)
14088 {
14089 /*
14090 * Host physical NMIs:
14091 * This cannot be a guest NMI as the only way for the guest to receive an NMI is if we
14092 * injected it ourselves and anything we inject is not going to cause a VM-exit directly
14093 * for the event being injected[1]. Go ahead and dispatch the NMI to the host[2].
14094 *
14095 * See Intel spec. 27.2.3 "Information for VM Exits During Event Delivery".
14096 * See Intel spec. 27.5.5 "Updating Non-Register State".
14097 */
14098 case VMX_EXIT_INT_INFO_TYPE_NMI:
14099 {
14100 rcStrict = hmR0VmxExitHostNmi(pVCpu, pVmcsInfo);
14101 break;
14102 }
14103
14104 /*
14105 * Privileged software exceptions (#DB from ICEBP),
14106 * Software exceptions (#BP and #OF),
14107 * Hardware exceptions:
14108 * Process the required exceptions and resume guest execution if possible.
14109 */
14110 case VMX_EXIT_INT_INFO_TYPE_PRIV_SW_XCPT:
14111 Assert(uVector == X86_XCPT_DB);
14112 RT_FALL_THRU();
14113 case VMX_EXIT_INT_INFO_TYPE_SW_XCPT:
14114 Assert(uVector == X86_XCPT_BP || uVector == X86_XCPT_OF || uExitIntType == VMX_EXIT_INT_INFO_TYPE_PRIV_SW_XCPT);
14115 RT_FALL_THRU();
14116 case VMX_EXIT_INT_INFO_TYPE_HW_XCPT:
14117 {
14118 NOREF(uVector);
14119 hmR0VmxReadExitIntErrorCodeVmcs(pVmxTransient);
14120 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
14121 hmR0VmxReadIdtVectoringInfoVmcs(pVmxTransient);
14122 hmR0VmxReadIdtVectoringErrorCodeVmcs(pVmxTransient);
14123
14124 rcStrict = hmR0VmxExitXcpt(pVCpu, pVmxTransient);
14125 break;
14126 }
14127
14128 default:
14129 {
14130 pVCpu->hm.s.u32HMError = pVmxTransient->uExitIntInfo;
14131 rcStrict = VERR_VMX_UNEXPECTED_INTERRUPTION_EXIT_TYPE;
14132 AssertMsgFailed(("Invalid/unexpected VM-exit interruption info %#x\n", pVmxTransient->uExitIntInfo));
14133 break;
14134 }
14135 }
14136
14137 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExitXcptNmi, y3);
14138 return rcStrict;
14139}
14140
14141
14142/**
14143 * VM-exit handler for interrupt-window exiting (VMX_EXIT_INT_WINDOW).
14144 */
14145HMVMX_EXIT_NSRC_DECL hmR0VmxExitIntWindow(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14146{
14147 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14148
14149 /* Indicate that we no longer need to VM-exit when the guest is ready to receive interrupts, it is now ready. */
14150 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
14151 hmR0VmxClearIntWindowExitVmcs(pVmcsInfo);
14152
14153 /* Evaluate and deliver pending events and resume guest execution. */
14154 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIntWindow);
14155 return VINF_SUCCESS;
14156}
14157
14158
14159/**
14160 * VM-exit handler for NMI-window exiting (VMX_EXIT_NMI_WINDOW).
14161 */
14162HMVMX_EXIT_NSRC_DECL hmR0VmxExitNmiWindow(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14163{
14164 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14165
14166 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
14167 if (RT_UNLIKELY(!(pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_NMI_WINDOW_EXIT))) /** @todo NSTVMX: Turn this into an assertion. */
14168 {
14169 AssertMsgFailed(("Unexpected NMI-window exit.\n"));
14170 HMVMX_UNEXPECTED_EXIT_RET(pVCpu, pVmxTransient->uExitReason);
14171 }
14172
14173 Assert(!CPUMIsGuestNmiBlocking(pVCpu));
14174
14175 /*
14176 * If block-by-STI is set when we get this VM-exit, it means the CPU doesn't block NMIs following STI.
14177 * It is therefore safe to unblock STI and deliver the NMI ourselves. See @bugref{7445}.
14178 */
14179 uint32_t fIntrState;
14180 int rc = VMXReadVmcs32(VMX_VMCS32_GUEST_INT_STATE, &fIntrState);
14181 AssertRC(rc);
14182 Assert(!(fIntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_MOVSS));
14183 if (fIntrState & VMX_VMCS_GUEST_INT_STATE_BLOCK_STI)
14184 {
14185 if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS))
14186 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS);
14187
14188 fIntrState &= ~VMX_VMCS_GUEST_INT_STATE_BLOCK_STI;
14189 rc = VMXWriteVmcs32(VMX_VMCS32_GUEST_INT_STATE, fIntrState);
14190 AssertRC(rc);
14191 }
14192
14193 /* Indicate that we no longer need to VM-exit when the guest is ready to receive NMIs, it is now ready */
14194 hmR0VmxClearNmiWindowExitVmcs(pVmcsInfo);
14195
14196 /* Evaluate and deliver pending events and resume guest execution. */
14197 return VINF_SUCCESS;
14198}
14199
14200
14201/**
14202 * VM-exit handler for WBINVD (VMX_EXIT_WBINVD). Conditional VM-exit.
14203 */
14204HMVMX_EXIT_NSRC_DECL hmR0VmxExitWbinvd(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14205{
14206 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14207 return hmR0VmxAdvanceGuestRip(pVCpu, pVmxTransient);
14208}
14209
14210
14211/**
14212 * VM-exit handler for INVD (VMX_EXIT_INVD). Unconditional VM-exit.
14213 */
14214HMVMX_EXIT_NSRC_DECL hmR0VmxExitInvd(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14215{
14216 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14217 return hmR0VmxAdvanceGuestRip(pVCpu, pVmxTransient);
14218}
14219
14220
14221/**
14222 * VM-exit handler for CPUID (VMX_EXIT_CPUID). Unconditional VM-exit.
14223 */
14224HMVMX_EXIT_DECL hmR0VmxExitCpuid(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14225{
14226 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14227
14228 /*
14229 * Get the state we need and update the exit history entry.
14230 */
14231 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
14232 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
14233
14234 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, IEM_CPUMCTX_EXTRN_EXEC_DECODED_NO_MEM_MASK);
14235 AssertRCReturn(rc, rc);
14236
14237 VBOXSTRICTRC rcStrict;
14238 PCEMEXITREC pExitRec = EMHistoryUpdateFlagsAndTypeAndPC(pVCpu,
14239 EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM | EMEXIT_F_HM, EMEXITTYPE_CPUID),
14240 pVCpu->cpum.GstCtx.rip + pVCpu->cpum.GstCtx.cs.u64Base);
14241 if (!pExitRec)
14242 {
14243 /*
14244 * Regular CPUID instruction execution.
14245 */
14246 rcStrict = IEMExecDecodedCpuid(pVCpu, pVmxTransient->cbExitInstr);
14247 if (rcStrict == VINF_SUCCESS)
14248 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS);
14249 else if (rcStrict == VINF_IEM_RAISED_XCPT)
14250 {
14251 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
14252 rcStrict = VINF_SUCCESS;
14253 }
14254 }
14255 else
14256 {
14257 /*
14258 * Frequent exit or something needing probing. Get state and call EMHistoryExec.
14259 */
14260 int rc2 = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, HMVMX_CPUMCTX_EXTRN_ALL);
14261 AssertRCReturn(rc2, rc2);
14262
14263 Log4(("CpuIdExit/%u: %04x:%08RX64: %#x/%#x -> EMHistoryExec\n",
14264 pVCpu->idCpu, pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip, pVCpu->cpum.GstCtx.eax, pVCpu->cpum.GstCtx.ecx));
14265
14266 rcStrict = EMHistoryExec(pVCpu, pExitRec, 0);
14267 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_ALL_GUEST);
14268
14269 Log4(("CpuIdExit/%u: %04x:%08RX64: EMHistoryExec -> %Rrc + %04x:%08RX64\n",
14270 pVCpu->idCpu, pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip,
14271 VBOXSTRICTRC_VAL(rcStrict), pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip));
14272 }
14273 return rcStrict;
14274}
14275
14276
14277/**
14278 * VM-exit handler for GETSEC (VMX_EXIT_GETSEC). Unconditional VM-exit.
14279 */
14280HMVMX_EXIT_DECL hmR0VmxExitGetsec(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14281{
14282 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14283
14284 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
14285 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, CPUMCTX_EXTRN_CR4);
14286 AssertRCReturn(rc, rc);
14287
14288 if (pVCpu->cpum.GstCtx.cr4 & X86_CR4_SMXE)
14289 return VINF_EM_RAW_EMULATE_INSTR;
14290
14291 AssertMsgFailed(("hmR0VmxExitGetsec: Unexpected VM-exit when CR4.SMXE is 0.\n"));
14292 HMVMX_UNEXPECTED_EXIT_RET(pVCpu, pVmxTransient->uExitReason);
14293}
14294
14295
14296/**
14297 * VM-exit handler for RDTSC (VMX_EXIT_RDTSC). Conditional VM-exit.
14298 */
14299HMVMX_EXIT_DECL hmR0VmxExitRdtsc(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14300{
14301 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14302
14303 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
14304 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
14305 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, IEM_CPUMCTX_EXTRN_MUST_MASK);
14306 AssertRCReturn(rc, rc);
14307
14308 VBOXSTRICTRC rcStrict = IEMExecDecodedRdtsc(pVCpu, pVmxTransient->cbExitInstr);
14309 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
14310 {
14311 /* If we get a spurious VM-exit when TSC offsetting is enabled,
14312 we must reset offsetting on VM-entry. See @bugref{6634}. */
14313 if (pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_USE_TSC_OFFSETTING)
14314 pVmxTransient->fUpdatedTscOffsettingAndPreemptTimer = false;
14315 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS);
14316 }
14317 else if (rcStrict == VINF_IEM_RAISED_XCPT)
14318 {
14319 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
14320 rcStrict = VINF_SUCCESS;
14321 }
14322 return rcStrict;
14323}
14324
14325
14326/**
14327 * VM-exit handler for RDTSCP (VMX_EXIT_RDTSCP). Conditional VM-exit.
14328 */
14329HMVMX_EXIT_DECL hmR0VmxExitRdtscp(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14330{
14331 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14332
14333 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
14334 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
14335 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, IEM_CPUMCTX_EXTRN_MUST_MASK | CPUMCTX_EXTRN_TSC_AUX);
14336 AssertRCReturn(rc, rc);
14337
14338 VBOXSTRICTRC rcStrict = IEMExecDecodedRdtscp(pVCpu, pVmxTransient->cbExitInstr);
14339 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
14340 {
14341 /* If we get a spurious VM-exit when TSC offsetting is enabled,
14342 we must reset offsetting on VM-reentry. See @bugref{6634}. */
14343 if (pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_USE_TSC_OFFSETTING)
14344 pVmxTransient->fUpdatedTscOffsettingAndPreemptTimer = false;
14345 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS);
14346 }
14347 else if (rcStrict == VINF_IEM_RAISED_XCPT)
14348 {
14349 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
14350 rcStrict = VINF_SUCCESS;
14351 }
14352 return rcStrict;
14353}
14354
14355
14356/**
14357 * VM-exit handler for RDPMC (VMX_EXIT_RDPMC). Conditional VM-exit.
14358 */
14359HMVMX_EXIT_DECL hmR0VmxExitRdpmc(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14360{
14361 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14362
14363 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
14364 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, CPUMCTX_EXTRN_CR4 | CPUMCTX_EXTRN_CR0
14365 | CPUMCTX_EXTRN_RFLAGS | CPUMCTX_EXTRN_SS);
14366 AssertRCReturn(rc, rc);
14367
14368 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
14369 rc = EMInterpretRdpmc(pVCpu->CTX_SUFF(pVM), pVCpu, CPUMCTX2CORE(pCtx));
14370 if (RT_LIKELY(rc == VINF_SUCCESS))
14371 {
14372 rc = hmR0VmxAdvanceGuestRip(pVCpu, pVmxTransient);
14373 Assert(pVmxTransient->cbExitInstr == 2);
14374 }
14375 else
14376 {
14377 AssertMsgFailed(("hmR0VmxExitRdpmc: EMInterpretRdpmc failed with %Rrc\n", rc));
14378 rc = VERR_EM_INTERPRETER;
14379 }
14380 return rc;
14381}
14382
14383
14384/**
14385 * VM-exit handler for VMCALL (VMX_EXIT_VMCALL). Unconditional VM-exit.
14386 */
14387HMVMX_EXIT_DECL hmR0VmxExitVmcall(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14388{
14389 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14390
14391 VBOXSTRICTRC rcStrict = VERR_VMX_IPE_3;
14392 if (EMAreHypercallInstructionsEnabled(pVCpu))
14393 {
14394 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
14395 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, CPUMCTX_EXTRN_RIP | CPUMCTX_EXTRN_RFLAGS | CPUMCTX_EXTRN_CR0
14396 | CPUMCTX_EXTRN_SS | CPUMCTX_EXTRN_CS | CPUMCTX_EXTRN_EFER);
14397 AssertRCReturn(rc, rc);
14398
14399 /* Perform the hypercall. */
14400 rcStrict = GIMHypercall(pVCpu, &pVCpu->cpum.GstCtx);
14401 if (rcStrict == VINF_SUCCESS)
14402 {
14403 rc = hmR0VmxAdvanceGuestRip(pVCpu, pVmxTransient);
14404 AssertRCReturn(rc, rc);
14405 }
14406 else
14407 Assert( rcStrict == VINF_GIM_R3_HYPERCALL
14408 || rcStrict == VINF_GIM_HYPERCALL_CONTINUING
14409 || RT_FAILURE(rcStrict));
14410
14411 /* If the hypercall changes anything other than guest's general-purpose registers,
14412 we would need to reload the guest changed bits here before VM-entry. */
14413 }
14414 else
14415 Log4Func(("Hypercalls not enabled\n"));
14416
14417 /* If hypercalls are disabled or the hypercall failed for some reason, raise #UD and continue. */
14418 if (RT_FAILURE(rcStrict))
14419 {
14420 hmR0VmxSetPendingXcptUD(pVCpu);
14421 rcStrict = VINF_SUCCESS;
14422 }
14423
14424 return rcStrict;
14425}
14426
14427
14428/**
14429 * VM-exit handler for INVLPG (VMX_EXIT_INVLPG). Conditional VM-exit.
14430 */
14431HMVMX_EXIT_DECL hmR0VmxExitInvlpg(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14432{
14433 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14434 Assert(!pVCpu->CTX_SUFF(pVM)->hm.s.fNestedPaging || pVCpu->hm.s.fUsingDebugLoop);
14435
14436 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
14437 hmR0VmxReadExitQualVmcs(pVmxTransient);
14438 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
14439 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, IEM_CPUMCTX_EXTRN_EXEC_DECODED_MEM_MASK);
14440 AssertRCReturn(rc, rc);
14441
14442 VBOXSTRICTRC rcStrict = IEMExecDecodedInvlpg(pVCpu, pVmxTransient->cbExitInstr, pVmxTransient->uExitQual);
14443
14444 if (rcStrict == VINF_SUCCESS || rcStrict == VINF_PGM_SYNC_CR3)
14445 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS);
14446 else if (rcStrict == VINF_IEM_RAISED_XCPT)
14447 {
14448 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
14449 rcStrict = VINF_SUCCESS;
14450 }
14451 else
14452 AssertMsgFailed(("Unexpected IEMExecDecodedInvlpg(%#RX64) status: %Rrc\n", pVmxTransient->uExitQual,
14453 VBOXSTRICTRC_VAL(rcStrict)));
14454 return rcStrict;
14455}
14456
14457
14458/**
14459 * VM-exit handler for MONITOR (VMX_EXIT_MONITOR). Conditional VM-exit.
14460 */
14461HMVMX_EXIT_DECL hmR0VmxExitMonitor(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14462{
14463 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14464
14465 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
14466 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
14467 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, IEM_CPUMCTX_EXTRN_EXEC_DECODED_MEM_MASK | CPUMCTX_EXTRN_DS);
14468 AssertRCReturn(rc, rc);
14469
14470 VBOXSTRICTRC rcStrict = IEMExecDecodedMonitor(pVCpu, pVmxTransient->cbExitInstr);
14471 if (rcStrict == VINF_SUCCESS)
14472 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS);
14473 else if (rcStrict == VINF_IEM_RAISED_XCPT)
14474 {
14475 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
14476 rcStrict = VINF_SUCCESS;
14477 }
14478
14479 return rcStrict;
14480}
14481
14482
14483/**
14484 * VM-exit handler for MWAIT (VMX_EXIT_MWAIT). Conditional VM-exit.
14485 */
14486HMVMX_EXIT_DECL hmR0VmxExitMwait(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14487{
14488 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14489
14490 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
14491 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
14492 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, IEM_CPUMCTX_EXTRN_EXEC_DECODED_NO_MEM_MASK);
14493 AssertRCReturn(rc, rc);
14494
14495 VBOXSTRICTRC rcStrict = IEMExecDecodedMwait(pVCpu, pVmxTransient->cbExitInstr);
14496 if (RT_SUCCESS(rcStrict))
14497 {
14498 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS);
14499 if (EMMonitorWaitShouldContinue(pVCpu, &pVCpu->cpum.GstCtx))
14500 rcStrict = VINF_SUCCESS;
14501 }
14502
14503 return rcStrict;
14504}
14505
14506
14507/**
14508 * VM-exit handler for triple faults (VMX_EXIT_TRIPLE_FAULT). Unconditional
14509 * VM-exit.
14510 */
14511HMVMX_EXIT_DECL hmR0VmxExitTripleFault(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14512{
14513 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14514 return VINF_EM_RESET;
14515}
14516
14517
14518/**
14519 * VM-exit handler for HLT (VMX_EXIT_HLT). Conditional VM-exit.
14520 */
14521HMVMX_EXIT_DECL hmR0VmxExitHlt(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14522{
14523 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14524
14525 int rc = hmR0VmxAdvanceGuestRip(pVCpu, pVmxTransient);
14526 AssertRCReturn(rc, rc);
14527
14528 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_RFLAGS); /* Advancing the RIP above should've imported eflags. */
14529 if (EMShouldContinueAfterHalt(pVCpu, &pVCpu->cpum.GstCtx)) /* Requires eflags. */
14530 rc = VINF_SUCCESS;
14531 else
14532 rc = VINF_EM_HALT;
14533
14534 if (rc != VINF_SUCCESS)
14535 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchHltToR3);
14536 return rc;
14537}
14538
14539
14540/**
14541 * VM-exit handler for instructions that result in a \#UD exception delivered to
14542 * the guest.
14543 */
14544HMVMX_EXIT_NSRC_DECL hmR0VmxExitSetPendingXcptUD(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14545{
14546 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14547 hmR0VmxSetPendingXcptUD(pVCpu);
14548 return VINF_SUCCESS;
14549}
14550
14551
14552/**
14553 * VM-exit handler for expiry of the VMX-preemption timer.
14554 */
14555HMVMX_EXIT_DECL hmR0VmxExitPreemptTimer(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14556{
14557 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14558
14559 /* If the VMX-preemption timer has expired, reinitialize the preemption timer on next VM-entry. */
14560 pVmxTransient->fUpdatedTscOffsettingAndPreemptTimer = false;
14561
14562 /* If there are any timer events pending, fall back to ring-3, otherwise resume guest execution. */
14563 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
14564 bool fTimersPending = TMTimerPollBool(pVM, pVCpu);
14565 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitPreemptTimer);
14566 return fTimersPending ? VINF_EM_RAW_TIMER_PENDING : VINF_SUCCESS;
14567}
14568
14569
14570/**
14571 * VM-exit handler for XSETBV (VMX_EXIT_XSETBV). Unconditional VM-exit.
14572 */
14573HMVMX_EXIT_DECL hmR0VmxExitXsetbv(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14574{
14575 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14576
14577 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
14578 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
14579 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, IEM_CPUMCTX_EXTRN_MUST_MASK | CPUMCTX_EXTRN_CR4);
14580 AssertRCReturn(rc, rc);
14581
14582 VBOXSTRICTRC rcStrict = IEMExecDecodedXsetbv(pVCpu, pVmxTransient->cbExitInstr);
14583 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, rcStrict != VINF_IEM_RAISED_XCPT ? HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS
14584 : HM_CHANGED_RAISED_XCPT_MASK);
14585
14586 PCCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
14587 pVCpu->hm.s.fLoadSaveGuestXcr0 = (pCtx->cr4 & X86_CR4_OSXSAVE) && pCtx->aXcr[0] != ASMGetXcr0();
14588
14589 return rcStrict;
14590}
14591
14592
14593/**
14594 * VM-exit handler for INVPCID (VMX_EXIT_INVPCID). Conditional VM-exit.
14595 */
14596HMVMX_EXIT_DECL hmR0VmxExitInvpcid(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14597{
14598 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14599
14600#if 1
14601 /** @todo Use VM-exit instruction information. */
14602 return VERR_EM_INTERPRETER;
14603#else
14604 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
14605 hmR0VmxReadExitInstrInfoVmcs(pVmxTransient);
14606 hmR0VmxReadExitQualVmcs(pVmxTransient);
14607 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, CPUMCTX_EXTRN_RSP | CPUMCTX_EXTRN_SREG_MASK
14608 | IEM_CPUMCTX_EXTRN_EXEC_DECODED_MEM_MASK);
14609 AssertRCReturn(rc, rc);
14610
14611 /* Paranoia. Ensure this has a memory operand. */
14612 Assert(!pVmxTransient->ExitInstrInfo.Inv.u1Cleared0);
14613
14614 uint8_t const iGReg = pVmxTransient->ExitInstrInfo.VmreadVmwrite.iReg2;
14615 Assert(iGReg < RT_ELEMENTS(pVCpu->cpum.GstCtx.aGRegs));
14616 uint64_t const uType = CPUMIsGuestIn64BitCode(pVCpu) ? pVCpu->cpum.GstCtx.aGRegs[iGReg].u64
14617 : pVCpu->cpum.GstCtx.aGRegs[iGReg].u32;
14618
14619 RTGCPTR GCPtrDesc;
14620 HMVMX_DECODE_MEM_OPERAND(pVCpu, pVmxTransient->ExitInstrInfo.u, pVmxTransient->uExitQual, VMXMEMACCESS_READ, &GCPtrDesc);
14621
14622 VBOXSTRICTRC rcStrict = IEMExecDecodedInvpcid(pVCpu, pVmxTransient->cbExitInstr, pVmxTransient->ExitInstrInfo.Inv.iSegReg,
14623 GCPtrDesc, uType);
14624 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
14625 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS);
14626 else if (rcStrict == VINF_IEM_RAISED_XCPT)
14627 {
14628 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
14629 rcStrict = VINF_SUCCESS;
14630 }
14631 return rcStrict;
14632#endif
14633}
14634
14635
14636/**
14637 * VM-exit handler for invalid-guest-state (VMX_EXIT_ERR_INVALID_GUEST_STATE). Error
14638 * VM-exit.
14639 */
14640HMVMX_EXIT_NSRC_DECL hmR0VmxExitErrInvalidGuestState(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14641{
14642 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
14643 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, HMVMX_CPUMCTX_EXTRN_ALL);
14644 AssertRCReturn(rc, rc);
14645
14646 rc = hmR0VmxCheckVmcsCtls(pVCpu, pVmcsInfo, pVmxTransient->fIsNestedGuest);
14647 if (RT_FAILURE(rc))
14648 return rc;
14649
14650 uint32_t const uInvalidReason = hmR0VmxCheckGuestState(pVCpu, pVmcsInfo);
14651 NOREF(uInvalidReason);
14652
14653#ifdef VBOX_STRICT
14654 uint32_t fIntrState;
14655 uint64_t u64Val;
14656 hmR0VmxReadEntryIntInfoVmcs(pVmxTransient);
14657 hmR0VmxReadEntryXcptErrorCodeVmcs(pVmxTransient);
14658 hmR0VmxReadEntryInstrLenVmcs(pVmxTransient);
14659
14660 Log4(("uInvalidReason %u\n", uInvalidReason));
14661 Log4(("VMX_VMCS32_CTRL_ENTRY_INTERRUPTION_INFO %#RX32\n", pVmxTransient->uEntryIntInfo));
14662 Log4(("VMX_VMCS32_CTRL_ENTRY_EXCEPTION_ERRCODE %#RX32\n", pVmxTransient->uEntryXcptErrorCode));
14663 Log4(("VMX_VMCS32_CTRL_ENTRY_INSTR_LENGTH %#RX32\n", pVmxTransient->cbEntryInstr));
14664
14665 rc = VMXReadVmcs32(VMX_VMCS32_GUEST_INT_STATE, &fIntrState); AssertRC(rc);
14666 Log4(("VMX_VMCS32_GUEST_INT_STATE %#RX32\n", fIntrState));
14667 rc = VMXReadVmcsNw(VMX_VMCS_GUEST_CR0, &u64Val); AssertRC(rc);
14668 Log4(("VMX_VMCS_GUEST_CR0 %#RX64\n", u64Val));
14669 rc = VMXReadVmcsNw(VMX_VMCS_CTRL_CR0_MASK, &u64Val); AssertRC(rc);
14670 Log4(("VMX_VMCS_CTRL_CR0_MASK %#RX64\n", u64Val));
14671 rc = VMXReadVmcsNw(VMX_VMCS_CTRL_CR0_READ_SHADOW, &u64Val); AssertRC(rc);
14672 Log4(("VMX_VMCS_CTRL_CR4_READ_SHADOW %#RX64\n", u64Val));
14673 rc = VMXReadVmcsNw(VMX_VMCS_CTRL_CR4_MASK, &u64Val); AssertRC(rc);
14674 Log4(("VMX_VMCS_CTRL_CR4_MASK %#RX64\n", u64Val));
14675 rc = VMXReadVmcsNw(VMX_VMCS_CTRL_CR4_READ_SHADOW, &u64Val); AssertRC(rc);
14676 Log4(("VMX_VMCS_CTRL_CR4_READ_SHADOW %#RX64\n", u64Val));
14677 if (pVCpu->CTX_SUFF(pVM)->hm.s.fNestedPaging)
14678 {
14679 rc = VMXReadVmcs64(VMX_VMCS64_CTRL_EPTP_FULL, &u64Val); AssertRC(rc);
14680 Log4(("VMX_VMCS64_CTRL_EPTP_FULL %#RX64\n", u64Val));
14681 }
14682 hmR0DumpRegs(pVCpu, HM_DUMP_REG_FLAGS_ALL);
14683#endif
14684
14685 return VERR_VMX_INVALID_GUEST_STATE;
14686}
14687
14688/**
14689 * VM-exit handler for all undefined/unexpected reasons. Should never happen.
14690 */
14691HMVMX_EXIT_NSRC_DECL hmR0VmxExitErrUnexpected(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14692{
14693 /*
14694 * Cumulative notes of all recognized but unexpected VM-exits.
14695 *
14696 * 1. This does -not- cover scenarios like a page-fault VM-exit occurring when
14697 * nested-paging is used.
14698 *
14699 * 2. Any instruction that causes a VM-exit unconditionally (for e.g. VMXON) must be
14700 * emulated or a #UD must be raised in the guest. Therefore, we should -not- be using
14701 * this function (and thereby stop VM execution) for handling such instructions.
14702 *
14703 *
14704 * VMX_EXIT_INIT_SIGNAL:
14705 * INIT signals are blocked in VMX root operation by VMXON and by SMI in SMM.
14706 * It is -NOT- blocked in VMX non-root operation so we can, in theory, still get these
14707 * VM-exits. However, we should not receive INIT signals VM-exit while executing a VM.
14708 *
14709 * See Intel spec. 33.14.1 Default Treatment of SMI Delivery"
14710 * See Intel spec. 29.3 "VMX Instructions" for "VMXON".
14711 * See Intel spec. "23.8 Restrictions on VMX operation".
14712 *
14713 * VMX_EXIT_SIPI:
14714 * SIPI exits can only occur in VMX non-root operation when the "wait-for-SIPI" guest
14715 * activity state is used. We don't make use of it as our guests don't have direct
14716 * access to the host local APIC.
14717 *
14718 * See Intel spec. 25.3 "Other Causes of VM-exits".
14719 *
14720 * VMX_EXIT_IO_SMI:
14721 * VMX_EXIT_SMI:
14722 * This can only happen if we support dual-monitor treatment of SMI, which can be
14723 * activated by executing VMCALL in VMX root operation. Only an STM (SMM transfer
14724 * monitor) would get this VM-exit when we (the executive monitor) execute a VMCALL in
14725 * VMX root mode or receive an SMI. If we get here, something funny is going on.
14726 *
14727 * See Intel spec. 33.15.6 "Activating the Dual-Monitor Treatment"
14728 * See Intel spec. 25.3 "Other Causes of VM-Exits"
14729 *
14730 * VMX_EXIT_ERR_MSR_LOAD:
14731 * Failures while loading MSRs are part of the VM-entry MSR-load area are unexpected
14732 * and typically indicates a bug in the hypervisor code. We thus cannot not resume
14733 * execution.
14734 *
14735 * See Intel spec. 26.7 "VM-Entry Failures During Or After Loading Guest State".
14736 *
14737 * VMX_EXIT_ERR_MACHINE_CHECK:
14738 * Machine check exceptions indicates a fatal/unrecoverable hardware condition
14739 * including but not limited to system bus, ECC, parity, cache and TLB errors. A
14740 * #MC exception abort class exception is raised. We thus cannot assume a
14741 * reasonable chance of continuing any sort of execution and we bail.
14742 *
14743 * See Intel spec. 15.1 "Machine-check Architecture".
14744 * See Intel spec. 27.1 "Architectural State Before A VM Exit".
14745 *
14746 * VMX_EXIT_PML_FULL:
14747 * VMX_EXIT_VIRTUALIZED_EOI:
14748 * VMX_EXIT_APIC_WRITE:
14749 * We do not currently support any of these features and thus they are all unexpected
14750 * VM-exits.
14751 *
14752 * VMX_EXIT_GDTR_IDTR_ACCESS:
14753 * VMX_EXIT_LDTR_TR_ACCESS:
14754 * VMX_EXIT_RDRAND:
14755 * VMX_EXIT_RSM:
14756 * VMX_EXIT_VMFUNC:
14757 * VMX_EXIT_ENCLS:
14758 * VMX_EXIT_RDSEED:
14759 * VMX_EXIT_XSAVES:
14760 * VMX_EXIT_XRSTORS:
14761 * VMX_EXIT_UMWAIT:
14762 * VMX_EXIT_TPAUSE:
14763 * These VM-exits are -not- caused unconditionally by execution of the corresponding
14764 * instruction. Any VM-exit for these instructions indicate a hardware problem,
14765 * unsupported CPU modes (like SMM) or potentially corrupt VMCS controls.
14766 *
14767 * See Intel spec. 25.1.3 "Instructions That Cause VM Exits Conditionally".
14768 */
14769 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14770 AssertMsgFailed(("Unexpected VM-exit %u\n", pVmxTransient->uExitReason));
14771 HMVMX_UNEXPECTED_EXIT_RET(pVCpu, pVmxTransient->uExitReason);
14772}
14773
14774
14775/**
14776 * VM-exit handler for RDMSR (VMX_EXIT_RDMSR).
14777 */
14778HMVMX_EXIT_DECL hmR0VmxExitRdmsr(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14779{
14780 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14781
14782 /** @todo Optimize this: We currently drag in the whole MSR state
14783 * (CPUMCTX_EXTRN_ALL_MSRS) here. We should optimize this to only get
14784 * MSRs required. That would require changes to IEM and possibly CPUM too.
14785 * (Should probably do it lazy fashion from CPUMAllMsrs.cpp). */
14786 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
14787 uint32_t const idMsr = pVCpu->cpum.GstCtx.ecx;
14788 uint64_t fImport = IEM_CPUMCTX_EXTRN_EXEC_DECODED_NO_MEM_MASK | CPUMCTX_EXTRN_ALL_MSRS;
14789 switch (idMsr)
14790 {
14791 case MSR_K8_FS_BASE: fImport |= CPUMCTX_EXTRN_FS; break;
14792 case MSR_K8_GS_BASE: fImport |= CPUMCTX_EXTRN_GS; break;
14793 }
14794
14795 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
14796 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, fImport);
14797 AssertRCReturn(rc, rc);
14798
14799 Log4Func(("ecx=%#RX32\n", idMsr));
14800
14801#ifdef VBOX_STRICT
14802 Assert(!pVmxTransient->fIsNestedGuest);
14803 if (pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_USE_MSR_BITMAPS)
14804 {
14805 if ( hmR0VmxIsAutoLoadGuestMsr(pVmcsInfo, idMsr)
14806 && idMsr != MSR_K6_EFER)
14807 {
14808 AssertMsgFailed(("Unexpected RDMSR for an MSR in the auto-load/store area in the VMCS. ecx=%#RX32\n", idMsr));
14809 HMVMX_UNEXPECTED_EXIT_RET(pVCpu, idMsr);
14810 }
14811 if (hmR0VmxIsLazyGuestMsr(pVCpu, idMsr))
14812 {
14813 Assert(pVmcsInfo->pvMsrBitmap);
14814 uint32_t fMsrpm = CPUMGetVmxMsrPermission(pVmcsInfo->pvMsrBitmap, idMsr);
14815 if (fMsrpm & VMXMSRPM_ALLOW_RD)
14816 {
14817 AssertMsgFailed(("Unexpected RDMSR for a passthru lazy-restore MSR. ecx=%#RX32\n", idMsr));
14818 HMVMX_UNEXPECTED_EXIT_RET(pVCpu, idMsr);
14819 }
14820 }
14821 }
14822#endif
14823
14824 VBOXSTRICTRC rcStrict = IEMExecDecodedRdmsr(pVCpu, pVmxTransient->cbExitInstr);
14825 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitRdmsr);
14826 if (rcStrict == VINF_SUCCESS)
14827 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS
14828 | HM_CHANGED_GUEST_RAX | HM_CHANGED_GUEST_RDX);
14829 else if (rcStrict == VINF_IEM_RAISED_XCPT)
14830 {
14831 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
14832 rcStrict = VINF_SUCCESS;
14833 }
14834 else
14835 AssertMsg(rcStrict == VINF_CPUM_R3_MSR_READ, ("Unexpected IEMExecDecodedRdmsr rc (%Rrc)\n", VBOXSTRICTRC_VAL(rcStrict)));
14836
14837 return rcStrict;
14838}
14839
14840
14841/**
14842 * VM-exit handler for WRMSR (VMX_EXIT_WRMSR).
14843 */
14844HMVMX_EXIT_DECL hmR0VmxExitWrmsr(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14845{
14846 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14847
14848 /** @todo Optimize this: We currently drag in the whole MSR state
14849 * (CPUMCTX_EXTRN_ALL_MSRS) here. We should optimize this to only get
14850 * MSRs required. That would require changes to IEM and possibly CPUM too.
14851 * (Should probably do it lazy fashion from CPUMAllMsrs.cpp). */
14852 uint32_t const idMsr = pVCpu->cpum.GstCtx.ecx;
14853 uint64_t fImport = IEM_CPUMCTX_EXTRN_EXEC_DECODED_NO_MEM_MASK | CPUMCTX_EXTRN_ALL_MSRS;
14854
14855 /*
14856 * The FS and GS base MSRs are not part of the above all-MSRs mask.
14857 * Although we don't need to fetch the base as it will be overwritten shortly, while
14858 * loading guest-state we would also load the entire segment register including limit
14859 * and attributes and thus we need to load them here.
14860 */
14861 switch (idMsr)
14862 {
14863 case MSR_K8_FS_BASE: fImport |= CPUMCTX_EXTRN_FS; break;
14864 case MSR_K8_GS_BASE: fImport |= CPUMCTX_EXTRN_GS; break;
14865 }
14866
14867 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
14868 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
14869 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, fImport);
14870 AssertRCReturn(rc, rc);
14871
14872 Log4Func(("ecx=%#RX32 edx:eax=%#RX32:%#RX32\n", idMsr, pVCpu->cpum.GstCtx.edx, pVCpu->cpum.GstCtx.eax));
14873
14874 VBOXSTRICTRC rcStrict = IEMExecDecodedWrmsr(pVCpu, pVmxTransient->cbExitInstr);
14875 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitWrmsr);
14876
14877 if (rcStrict == VINF_SUCCESS)
14878 {
14879 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS);
14880
14881 /* If this is an X2APIC WRMSR access, update the APIC state as well. */
14882 if ( idMsr == MSR_IA32_APICBASE
14883 || ( idMsr >= MSR_IA32_X2APIC_START
14884 && idMsr <= MSR_IA32_X2APIC_END))
14885 {
14886 /*
14887 * We've already saved the APIC related guest-state (TPR) in post-run phase.
14888 * When full APIC register virtualization is implemented we'll have to make
14889 * sure APIC state is saved from the VMCS before IEM changes it.
14890 */
14891 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_APIC_TPR);
14892 }
14893 else if (idMsr == MSR_IA32_TSC) /* Windows 7 does this during bootup. See @bugref{6398}. */
14894 pVmxTransient->fUpdatedTscOffsettingAndPreemptTimer = false;
14895 else if (idMsr == MSR_K6_EFER)
14896 {
14897 /*
14898 * If the guest touches the EFER MSR we need to update the VM-Entry and VM-Exit controls
14899 * as well, even if it is -not- touching bits that cause paging mode changes (LMA/LME).
14900 * We care about the other bits as well, SCE and NXE. See @bugref{7368}.
14901 */
14902 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_EFER_MSR | HM_CHANGED_VMX_ENTRY_EXIT_CTLS);
14903 }
14904
14905 /* Update MSRs that are part of the VMCS and auto-load/store area when MSR-bitmaps are not used. */
14906 if (!(pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_USE_MSR_BITMAPS))
14907 {
14908 switch (idMsr)
14909 {
14910 case MSR_IA32_SYSENTER_CS: ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_SYSENTER_CS_MSR); break;
14911 case MSR_IA32_SYSENTER_EIP: ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_SYSENTER_EIP_MSR); break;
14912 case MSR_IA32_SYSENTER_ESP: ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_SYSENTER_ESP_MSR); break;
14913 case MSR_K8_FS_BASE: ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_FS); break;
14914 case MSR_K8_GS_BASE: ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_GS); break;
14915 case MSR_K6_EFER: /* Nothing to do, already handled above. */ break;
14916 default:
14917 {
14918 if (hmR0VmxIsLazyGuestMsr(pVCpu, idMsr))
14919 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_VMX_GUEST_LAZY_MSRS);
14920 else if (hmR0VmxIsAutoLoadGuestMsr(pVmcsInfo, idMsr))
14921 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_VMX_GUEST_AUTO_MSRS);
14922 break;
14923 }
14924 }
14925 }
14926#ifdef VBOX_STRICT
14927 else
14928 {
14929 /* Paranoia. Validate that MSRs in the MSR-bitmaps with write-passthru are not intercepted. */
14930 switch (idMsr)
14931 {
14932 case MSR_IA32_SYSENTER_CS:
14933 case MSR_IA32_SYSENTER_EIP:
14934 case MSR_IA32_SYSENTER_ESP:
14935 case MSR_K8_FS_BASE:
14936 case MSR_K8_GS_BASE:
14937 {
14938 AssertMsgFailed(("Unexpected WRMSR for an MSR in the VMCS. ecx=%#RX32\n", idMsr));
14939 HMVMX_UNEXPECTED_EXIT_RET(pVCpu, idMsr);
14940 }
14941
14942 /* Writes to MSRs in auto-load/store area/swapped MSRs, shouldn't cause VM-exits with MSR-bitmaps. */
14943 default:
14944 {
14945 if (hmR0VmxIsAutoLoadGuestMsr(pVmcsInfo, idMsr))
14946 {
14947 /* EFER MSR writes are always intercepted. */
14948 if (idMsr != MSR_K6_EFER)
14949 {
14950 AssertMsgFailed(("Unexpected WRMSR for an MSR in the auto-load/store area in the VMCS. ecx=%#RX32\n",
14951 idMsr));
14952 HMVMX_UNEXPECTED_EXIT_RET(pVCpu, idMsr);
14953 }
14954 }
14955
14956 if (hmR0VmxIsLazyGuestMsr(pVCpu, idMsr))
14957 {
14958 Assert(pVmcsInfo->pvMsrBitmap);
14959 uint32_t fMsrpm = CPUMGetVmxMsrPermission(pVmcsInfo->pvMsrBitmap, idMsr);
14960 if (fMsrpm & VMXMSRPM_ALLOW_WR)
14961 {
14962 AssertMsgFailed(("Unexpected WRMSR for passthru, lazy-restore MSR. ecx=%#RX32\n", idMsr));
14963 HMVMX_UNEXPECTED_EXIT_RET(pVCpu, idMsr);
14964 }
14965 }
14966 break;
14967 }
14968 }
14969 }
14970#endif /* VBOX_STRICT */
14971 }
14972 else if (rcStrict == VINF_IEM_RAISED_XCPT)
14973 {
14974 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
14975 rcStrict = VINF_SUCCESS;
14976 }
14977 else
14978 AssertMsg(rcStrict == VINF_CPUM_R3_MSR_WRITE, ("Unexpected IEMExecDecodedWrmsr rc (%Rrc)\n", VBOXSTRICTRC_VAL(rcStrict)));
14979
14980 return rcStrict;
14981}
14982
14983
14984/**
14985 * VM-exit handler for PAUSE (VMX_EXIT_PAUSE). Conditional VM-exit.
14986 */
14987HMVMX_EXIT_DECL hmR0VmxExitPause(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
14988{
14989 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
14990
14991 /** @todo The guest has likely hit a contended spinlock. We might want to
14992 * poke a schedule different guest VCPU. */
14993 int rc = hmR0VmxAdvanceGuestRip(pVCpu, pVmxTransient);
14994 if (RT_SUCCESS(rc))
14995 return VINF_EM_RAW_INTERRUPT;
14996
14997 AssertMsgFailed(("hmR0VmxExitPause: Failed to increment RIP. rc=%Rrc\n", rc));
14998 return rc;
14999}
15000
15001
15002/**
15003 * VM-exit handler for when the TPR value is lowered below the specified
15004 * threshold (VMX_EXIT_TPR_BELOW_THRESHOLD). Conditional VM-exit.
15005 */
15006HMVMX_EXIT_NSRC_DECL hmR0VmxExitTprBelowThreshold(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
15007{
15008 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
15009 Assert(pVmxTransient->pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_USE_TPR_SHADOW);
15010
15011 /*
15012 * The TPR shadow would've been synced with the APIC TPR in the post-run phase.
15013 * We'll re-evaluate pending interrupts and inject them before the next VM
15014 * entry so we can just continue execution here.
15015 */
15016 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitTprBelowThreshold);
15017 return VINF_SUCCESS;
15018}
15019
15020
15021/**
15022 * VM-exit handler for control-register accesses (VMX_EXIT_MOV_CRX). Conditional
15023 * VM-exit.
15024 *
15025 * @retval VINF_SUCCESS when guest execution can continue.
15026 * @retval VINF_PGM_SYNC_CR3 CR3 sync is required, back to ring-3.
15027 * @retval VERR_EM_RESCHEDULE_REM when we need to return to ring-3 due to
15028 * incompatible guest state for VMX execution (real-on-v86 case).
15029 */
15030HMVMX_EXIT_DECL hmR0VmxExitMovCRx(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
15031{
15032 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
15033 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatExitMovCRx, y2);
15034
15035 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
15036 hmR0VmxReadExitQualVmcs(pVmxTransient);
15037 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
15038
15039 VBOXSTRICTRC rcStrict;
15040 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
15041 uint64_t const uExitQual = pVmxTransient->uExitQual;
15042 uint32_t const uAccessType = VMX_EXIT_QUAL_CRX_ACCESS(uExitQual);
15043 switch (uAccessType)
15044 {
15045 /*
15046 * MOV to CRx.
15047 */
15048 case VMX_EXIT_QUAL_CRX_ACCESS_WRITE:
15049 {
15050 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, IEM_CPUMCTX_EXTRN_MUST_MASK);
15051 AssertRCReturn(rc, rc);
15052
15053 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_CR0);
15054 uint32_t const uOldCr0 = pVCpu->cpum.GstCtx.cr0;
15055 uint8_t const iGReg = VMX_EXIT_QUAL_CRX_GENREG(uExitQual);
15056 uint8_t const iCrReg = VMX_EXIT_QUAL_CRX_REGISTER(uExitQual);
15057
15058 /*
15059 * MOV to CR3 only cause a VM-exit when one or more of the following are true:
15060 * - When nested paging isn't used.
15061 * - If the guest doesn't have paging enabled (intercept CR3 to update shadow page tables).
15062 * - We are executing in the VM debug loop.
15063 */
15064 Assert( iCrReg != 3
15065 || !pVM->hm.s.fNestedPaging
15066 || !CPUMIsGuestPagingEnabledEx(&pVCpu->cpum.GstCtx)
15067 || pVCpu->hm.s.fUsingDebugLoop);
15068
15069 /* MOV to CR8 writes only cause VM-exits when TPR shadow is not used. */
15070 Assert( iCrReg != 8
15071 || !(pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_USE_TPR_SHADOW));
15072
15073 rcStrict = hmR0VmxExitMovToCrX(pVCpu, pVmcsInfo, pVmxTransient->cbExitInstr, iGReg, iCrReg);
15074 AssertMsg( rcStrict == VINF_SUCCESS
15075 || rcStrict == VINF_PGM_SYNC_CR3, ("%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
15076
15077 /*
15078 * This is a kludge for handling switches back to real mode when we try to use
15079 * V86 mode to run real mode code directly. Problem is that V86 mode cannot
15080 * deal with special selector values, so we have to return to ring-3 and run
15081 * there till the selector values are V86 mode compatible.
15082 *
15083 * Note! Using VINF_EM_RESCHEDULE_REM here rather than VINF_EM_RESCHEDULE since the
15084 * latter is an alias for VINF_IEM_RAISED_XCPT which is asserted at the end of
15085 * this function.
15086 */
15087 if ( iCrReg == 0
15088 && rcStrict == VINF_SUCCESS
15089 && !pVM->hm.s.vmx.fUnrestrictedGuest
15090 && CPUMIsGuestInRealModeEx(&pVCpu->cpum.GstCtx)
15091 && (uOldCr0 & X86_CR0_PE)
15092 && !(pVCpu->cpum.GstCtx.cr0 & X86_CR0_PE))
15093 {
15094 /** @todo Check selectors rather than returning all the time. */
15095 Assert(!pVmxTransient->fIsNestedGuest);
15096 Log4Func(("CR0 write, back to real mode -> VINF_EM_RESCHEDULE_REM\n"));
15097 rcStrict = VINF_EM_RESCHEDULE_REM;
15098 }
15099 break;
15100 }
15101
15102 /*
15103 * MOV from CRx.
15104 */
15105 case VMX_EXIT_QUAL_CRX_ACCESS_READ:
15106 {
15107 uint8_t const iGReg = VMX_EXIT_QUAL_CRX_GENREG(uExitQual);
15108 uint8_t const iCrReg = VMX_EXIT_QUAL_CRX_REGISTER(uExitQual);
15109
15110 /*
15111 * MOV from CR3 only cause a VM-exit when one or more of the following are true:
15112 * - When nested paging isn't used.
15113 * - If the guest doesn't have paging enabled (pass guest's CR3 rather than our identity mapped CR3).
15114 * - We are executing in the VM debug loop.
15115 */
15116 Assert( iCrReg != 3
15117 || !pVM->hm.s.fNestedPaging
15118 || !CPUMIsGuestPagingEnabledEx(&pVCpu->cpum.GstCtx)
15119 || pVCpu->hm.s.fUsingDebugLoop);
15120
15121 /* MOV from CR8 reads only cause a VM-exit when the TPR shadow feature isn't enabled. */
15122 Assert( iCrReg != 8
15123 || !(pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_USE_TPR_SHADOW));
15124
15125 rcStrict = hmR0VmxExitMovFromCrX(pVCpu, pVmcsInfo, pVmxTransient->cbExitInstr, iGReg, iCrReg);
15126 break;
15127 }
15128
15129 /*
15130 * CLTS (Clear Task-Switch Flag in CR0).
15131 */
15132 case VMX_EXIT_QUAL_CRX_ACCESS_CLTS:
15133 {
15134 rcStrict = hmR0VmxExitClts(pVCpu, pVmcsInfo, pVmxTransient->cbExitInstr);
15135 break;
15136 }
15137
15138 /*
15139 * LMSW (Load Machine-Status Word into CR0).
15140 * LMSW cannot clear CR0.PE, so no fRealOnV86Active kludge needed here.
15141 */
15142 case VMX_EXIT_QUAL_CRX_ACCESS_LMSW:
15143 {
15144 RTGCPTR GCPtrEffDst;
15145 uint8_t const cbInstr = pVmxTransient->cbExitInstr;
15146 uint16_t const uMsw = VMX_EXIT_QUAL_CRX_LMSW_DATA(uExitQual);
15147 bool const fMemOperand = VMX_EXIT_QUAL_CRX_LMSW_OP_MEM(uExitQual);
15148 if (fMemOperand)
15149 {
15150 hmR0VmxReadGuestLinearAddrVmcs(pVmxTransient);
15151 GCPtrEffDst = pVmxTransient->uGuestLinearAddr;
15152 }
15153 else
15154 GCPtrEffDst = NIL_RTGCPTR;
15155 rcStrict = hmR0VmxExitLmsw(pVCpu, pVmcsInfo, cbInstr, uMsw, GCPtrEffDst);
15156 break;
15157 }
15158
15159 default:
15160 {
15161 AssertMsgFailed(("Unrecognized Mov CRX access type %#x\n", uAccessType));
15162 HMVMX_UNEXPECTED_EXIT_RET(pVCpu, uAccessType);
15163 }
15164 }
15165
15166 Assert((pVCpu->hm.s.fCtxChanged & (HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS))
15167 == (HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS));
15168 Assert(rcStrict != VINF_IEM_RAISED_XCPT);
15169
15170 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExitMovCRx, y2);
15171 NOREF(pVM);
15172 return rcStrict;
15173}
15174
15175
15176/**
15177 * VM-exit handler for I/O instructions (VMX_EXIT_IO_INSTR). Conditional
15178 * VM-exit.
15179 */
15180HMVMX_EXIT_DECL hmR0VmxExitIoInstr(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
15181{
15182 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
15183 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatExitIO, y1);
15184
15185 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
15186 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
15187 hmR0VmxReadExitQualVmcs(pVmxTransient);
15188 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
15189 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, IEM_CPUMCTX_EXTRN_MUST_MASK | CPUMCTX_EXTRN_SREG_MASK
15190 | CPUMCTX_EXTRN_EFER);
15191 /* EFER MSR also required for longmode checks in EMInterpretDisasCurrent(), but it's always up-to-date. */
15192 AssertRCReturn(rc, rc);
15193
15194 /* Refer Intel spec. 27-5. "Exit Qualifications for I/O Instructions" for the format. */
15195 uint32_t const uIOPort = VMX_EXIT_QUAL_IO_PORT(pVmxTransient->uExitQual);
15196 uint8_t const uIOSize = VMX_EXIT_QUAL_IO_SIZE(pVmxTransient->uExitQual);
15197 bool const fIOWrite = (VMX_EXIT_QUAL_IO_DIRECTION(pVmxTransient->uExitQual) == VMX_EXIT_QUAL_IO_DIRECTION_OUT);
15198 bool const fIOString = VMX_EXIT_QUAL_IO_IS_STRING(pVmxTransient->uExitQual);
15199 bool const fGstStepping = RT_BOOL(pCtx->eflags.Bits.u1TF);
15200 bool const fDbgStepping = pVCpu->hm.s.fSingleInstruction;
15201 AssertReturn(uIOSize <= 3 && uIOSize != 2, VERR_VMX_IPE_1);
15202
15203 /*
15204 * Update exit history to see if this exit can be optimized.
15205 */
15206 VBOXSTRICTRC rcStrict;
15207 PCEMEXITREC pExitRec = NULL;
15208 if ( !fGstStepping
15209 && !fDbgStepping)
15210 pExitRec = EMHistoryUpdateFlagsAndTypeAndPC(pVCpu,
15211 !fIOString
15212 ? !fIOWrite
15213 ? EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM | EMEXIT_F_HM, EMEXITTYPE_IO_PORT_READ)
15214 : EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM | EMEXIT_F_HM, EMEXITTYPE_IO_PORT_WRITE)
15215 : !fIOWrite
15216 ? EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM | EMEXIT_F_HM, EMEXITTYPE_IO_PORT_STR_READ)
15217 : EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM | EMEXIT_F_HM, EMEXITTYPE_IO_PORT_STR_WRITE),
15218 pVCpu->cpum.GstCtx.rip + pVCpu->cpum.GstCtx.cs.u64Base);
15219 if (!pExitRec)
15220 {
15221 static uint32_t const s_aIOSizes[4] = { 1, 2, 0, 4 }; /* Size of the I/O accesses in bytes. */
15222 static uint32_t const s_aIOOpAnd[4] = { 0xff, 0xffff, 0, 0xffffffff }; /* AND masks for saving result in AL/AX/EAX. */
15223
15224 uint32_t const cbValue = s_aIOSizes[uIOSize];
15225 uint32_t const cbInstr = pVmxTransient->cbExitInstr;
15226 bool fUpdateRipAlready = false; /* ugly hack, should be temporary. */
15227 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
15228 if (fIOString)
15229 {
15230 /*
15231 * INS/OUTS - I/O String instruction.
15232 *
15233 * Use instruction-information if available, otherwise fall back on
15234 * interpreting the instruction.
15235 */
15236 Log4Func(("cs:rip=%#04x:%#RX64 %#06x/%u %c str\n", pCtx->cs.Sel, pCtx->rip, uIOPort, cbValue, fIOWrite ? 'w' : 'r'));
15237 AssertReturn(pCtx->dx == uIOPort, VERR_VMX_IPE_2);
15238 bool const fInsOutsInfo = RT_BF_GET(pVM->hm.s.vmx.Msrs.u64Basic, VMX_BF_BASIC_VMCS_INS_OUTS);
15239 if (fInsOutsInfo)
15240 {
15241 hmR0VmxReadExitInstrInfoVmcs(pVmxTransient);
15242 AssertReturn(pVmxTransient->ExitInstrInfo.StrIo.u3AddrSize <= 2, VERR_VMX_IPE_3);
15243 AssertCompile(IEMMODE_16BIT == 0 && IEMMODE_32BIT == 1 && IEMMODE_64BIT == 2);
15244 IEMMODE const enmAddrMode = (IEMMODE)pVmxTransient->ExitInstrInfo.StrIo.u3AddrSize;
15245 bool const fRep = VMX_EXIT_QUAL_IO_IS_REP(pVmxTransient->uExitQual);
15246 if (fIOWrite)
15247 rcStrict = IEMExecStringIoWrite(pVCpu, cbValue, enmAddrMode, fRep, cbInstr,
15248 pVmxTransient->ExitInstrInfo.StrIo.iSegReg, true /*fIoChecked*/);
15249 else
15250 {
15251 /*
15252 * The segment prefix for INS cannot be overridden and is always ES. We can safely assume X86_SREG_ES.
15253 * Hence "iSegReg" field is undefined in the instruction-information field in VT-x for INS.
15254 * See Intel Instruction spec. for "INS".
15255 * See Intel spec. Table 27-8 "Format of the VM-Exit Instruction-Information Field as Used for INS and OUTS".
15256 */
15257 rcStrict = IEMExecStringIoRead(pVCpu, cbValue, enmAddrMode, fRep, cbInstr, true /*fIoChecked*/);
15258 }
15259 }
15260 else
15261 rcStrict = IEMExecOne(pVCpu);
15262
15263 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP);
15264 fUpdateRipAlready = true;
15265 }
15266 else
15267 {
15268 /*
15269 * IN/OUT - I/O instruction.
15270 */
15271 Log4Func(("cs:rip=%04x:%08RX64 %#06x/%u %c\n", pCtx->cs.Sel, pCtx->rip, uIOPort, cbValue, fIOWrite ? 'w' : 'r'));
15272 uint32_t const uAndVal = s_aIOOpAnd[uIOSize];
15273 Assert(!VMX_EXIT_QUAL_IO_IS_REP(pVmxTransient->uExitQual));
15274 if (fIOWrite)
15275 {
15276 rcStrict = IOMIOPortWrite(pVM, pVCpu, uIOPort, pCtx->eax & uAndVal, cbValue);
15277 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIOWrite);
15278 if ( rcStrict == VINF_IOM_R3_IOPORT_WRITE
15279 && !pCtx->eflags.Bits.u1TF)
15280 rcStrict = EMRZSetPendingIoPortWrite(pVCpu, uIOPort, cbInstr, cbValue, pCtx->eax & uAndVal);
15281 }
15282 else
15283 {
15284 uint32_t u32Result = 0;
15285 rcStrict = IOMIOPortRead(pVM, pVCpu, uIOPort, &u32Result, cbValue);
15286 if (IOM_SUCCESS(rcStrict))
15287 {
15288 /* Save result of I/O IN instr. in AL/AX/EAX. */
15289 pCtx->eax = (pCtx->eax & ~uAndVal) | (u32Result & uAndVal);
15290 }
15291 if ( rcStrict == VINF_IOM_R3_IOPORT_READ
15292 && !pCtx->eflags.Bits.u1TF)
15293 rcStrict = EMRZSetPendingIoPortRead(pVCpu, uIOPort, cbInstr, cbValue);
15294 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIORead);
15295 }
15296 }
15297
15298 if (IOM_SUCCESS(rcStrict))
15299 {
15300 if (!fUpdateRipAlready)
15301 {
15302 hmR0VmxAdvanceGuestRipBy(pVCpu, cbInstr);
15303 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP);
15304 }
15305
15306 /*
15307 * INS/OUTS with REP prefix updates RFLAGS, can be observed with triple-fault guru
15308 * while booting Fedora 17 64-bit guest.
15309 *
15310 * See Intel Instruction reference for REP/REPE/REPZ/REPNE/REPNZ.
15311 */
15312 if (fIOString)
15313 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RFLAGS);
15314
15315 /*
15316 * If any I/O breakpoints are armed, we need to check if one triggered
15317 * and take appropriate action.
15318 * Note that the I/O breakpoint type is undefined if CR4.DE is 0.
15319 */
15320 rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, CPUMCTX_EXTRN_DR7);
15321 AssertRCReturn(rc, rc);
15322
15323 /** @todo Optimize away the DBGFBpIsHwIoArmed call by having DBGF tell the
15324 * execution engines about whether hyper BPs and such are pending. */
15325 uint32_t const uDr7 = pCtx->dr[7];
15326 if (RT_UNLIKELY( ( (uDr7 & X86_DR7_ENABLED_MASK)
15327 && X86_DR7_ANY_RW_IO(uDr7)
15328 && (pCtx->cr4 & X86_CR4_DE))
15329 || DBGFBpIsHwIoArmed(pVM)))
15330 {
15331 STAM_COUNTER_INC(&pVCpu->hm.s.StatDRxIoCheck);
15332
15333 /* We're playing with the host CPU state here, make sure we don't preempt or longjmp. */
15334 VMMRZCallRing3Disable(pVCpu);
15335 HM_DISABLE_PREEMPT(pVCpu);
15336
15337 bool fIsGuestDbgActive = CPUMR0DebugStateMaybeSaveGuest(pVCpu, true /* fDr6 */);
15338
15339 VBOXSTRICTRC rcStrict2 = DBGFBpCheckIo(pVM, pVCpu, pCtx, uIOPort, cbValue);
15340 if (rcStrict2 == VINF_EM_RAW_GUEST_TRAP)
15341 {
15342 /* Raise #DB. */
15343 if (fIsGuestDbgActive)
15344 ASMSetDR6(pCtx->dr[6]);
15345 if (pCtx->dr[7] != uDr7)
15346 pVCpu->hm.s.fCtxChanged |= HM_CHANGED_GUEST_DR7;
15347
15348 hmR0VmxSetPendingXcptDB(pVCpu);
15349 }
15350 /* rcStrict is VINF_SUCCESS, VINF_IOM_R3_IOPORT_COMMIT_WRITE, or in [VINF_EM_FIRST..VINF_EM_LAST],
15351 however we can ditch VINF_IOM_R3_IOPORT_COMMIT_WRITE as it has VMCPU_FF_IOM as backup. */
15352 else if ( rcStrict2 != VINF_SUCCESS
15353 && (rcStrict == VINF_SUCCESS || rcStrict2 < rcStrict))
15354 rcStrict = rcStrict2;
15355 AssertCompile(VINF_EM_LAST < VINF_IOM_R3_IOPORT_COMMIT_WRITE);
15356
15357 HM_RESTORE_PREEMPT();
15358 VMMRZCallRing3Enable(pVCpu);
15359 }
15360 }
15361
15362#ifdef VBOX_STRICT
15363 if ( rcStrict == VINF_IOM_R3_IOPORT_READ
15364 || rcStrict == VINF_EM_PENDING_R3_IOPORT_READ)
15365 Assert(!fIOWrite);
15366 else if ( rcStrict == VINF_IOM_R3_IOPORT_WRITE
15367 || rcStrict == VINF_IOM_R3_IOPORT_COMMIT_WRITE
15368 || rcStrict == VINF_EM_PENDING_R3_IOPORT_WRITE)
15369 Assert(fIOWrite);
15370 else
15371 {
15372# if 0 /** @todo r=bird: This is missing a bunch of VINF_EM_FIRST..VINF_EM_LAST
15373 * statuses, that the VMM device and some others may return. See
15374 * IOM_SUCCESS() for guidance. */
15375 AssertMsg( RT_FAILURE(rcStrict)
15376 || rcStrict == VINF_SUCCESS
15377 || rcStrict == VINF_EM_RAW_EMULATE_INSTR
15378 || rcStrict == VINF_EM_DBG_BREAKPOINT
15379 || rcStrict == VINF_EM_RAW_GUEST_TRAP
15380 || rcStrict == VINF_EM_RAW_TO_R3
15381 || rcStrict == VINF_TRPM_XCPT_DISPATCHED, ("%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
15382# endif
15383 }
15384#endif
15385 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExitIO, y1);
15386 }
15387 else
15388 {
15389 /*
15390 * Frequent exit or something needing probing. Get state and call EMHistoryExec.
15391 */
15392 int rc2 = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, HMVMX_CPUMCTX_EXTRN_ALL);
15393 AssertRCReturn(rc2, rc2);
15394 STAM_COUNTER_INC(!fIOString ? fIOWrite ? &pVCpu->hm.s.StatExitIOWrite : &pVCpu->hm.s.StatExitIORead
15395 : fIOWrite ? &pVCpu->hm.s.StatExitIOStringWrite : &pVCpu->hm.s.StatExitIOStringRead);
15396 Log4(("IOExit/%u: %04x:%08RX64: %s%s%s %#x LB %u -> EMHistoryExec\n",
15397 pVCpu->idCpu, pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip,
15398 VMX_EXIT_QUAL_IO_IS_REP(pVmxTransient->uExitQual) ? "REP " : "",
15399 fIOWrite ? "OUT" : "IN", fIOString ? "S" : "", uIOPort, uIOSize));
15400
15401 rcStrict = EMHistoryExec(pVCpu, pExitRec, 0);
15402 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_ALL_GUEST);
15403
15404 Log4(("IOExit/%u: %04x:%08RX64: EMHistoryExec -> %Rrc + %04x:%08RX64\n",
15405 pVCpu->idCpu, pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip,
15406 VBOXSTRICTRC_VAL(rcStrict), pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip));
15407 }
15408 return rcStrict;
15409}
15410
15411
15412/**
15413 * VM-exit handler for task switches (VMX_EXIT_TASK_SWITCH). Unconditional
15414 * VM-exit.
15415 */
15416HMVMX_EXIT_DECL hmR0VmxExitTaskSwitch(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
15417{
15418 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
15419
15420 /* Check if this task-switch occurred while delivery an event through the guest IDT. */
15421 hmR0VmxReadExitQualVmcs(pVmxTransient);
15422 if (VMX_EXIT_QUAL_TASK_SWITCH_TYPE(pVmxTransient->uExitQual) == VMX_EXIT_QUAL_TASK_SWITCH_TYPE_IDT)
15423 {
15424 hmR0VmxReadIdtVectoringInfoVmcs(pVmxTransient);
15425 if (VMX_IDT_VECTORING_INFO_IS_VALID(pVmxTransient->uIdtVectoringInfo))
15426 {
15427 uint32_t uErrCode;
15428 if (VMX_IDT_VECTORING_INFO_IS_ERROR_CODE_VALID(pVmxTransient->uIdtVectoringInfo))
15429 {
15430 hmR0VmxReadIdtVectoringErrorCodeVmcs(pVmxTransient);
15431 uErrCode = pVmxTransient->uIdtVectoringErrorCode;
15432 }
15433 else
15434 uErrCode = 0;
15435
15436 RTGCUINTPTR GCPtrFaultAddress;
15437 if (VMX_IDT_VECTORING_INFO_IS_XCPT_PF(pVmxTransient->uIdtVectoringInfo))
15438 GCPtrFaultAddress = pVCpu->cpum.GstCtx.cr2;
15439 else
15440 GCPtrFaultAddress = 0;
15441
15442 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
15443
15444 hmR0VmxSetPendingEvent(pVCpu, VMX_ENTRY_INT_INFO_FROM_EXIT_IDT_INFO(pVmxTransient->uIdtVectoringInfo),
15445 pVmxTransient->cbExitInstr, uErrCode, GCPtrFaultAddress);
15446
15447 Log4Func(("Pending event. uIntType=%#x uVector=%#x\n", VMX_IDT_VECTORING_INFO_TYPE(pVmxTransient->uIdtVectoringInfo),
15448 VMX_IDT_VECTORING_INFO_VECTOR(pVmxTransient->uIdtVectoringInfo)));
15449 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitTaskSwitch);
15450 return VINF_EM_RAW_INJECT_TRPM_EVENT;
15451 }
15452 }
15453
15454 /* Fall back to the interpreter to emulate the task-switch. */
15455 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitTaskSwitch);
15456 return VERR_EM_INTERPRETER;
15457}
15458
15459
15460/**
15461 * VM-exit handler for monitor-trap-flag (VMX_EXIT_MTF). Conditional VM-exit.
15462 */
15463HMVMX_EXIT_DECL hmR0VmxExitMtf(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
15464{
15465 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
15466
15467 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
15468 pVmcsInfo->u32ProcCtls &= ~VMX_PROC_CTLS_MONITOR_TRAP_FLAG;
15469 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, pVmcsInfo->u32ProcCtls);
15470 AssertRC(rc);
15471 return VINF_EM_DBG_STEPPED;
15472}
15473
15474
15475/**
15476 * VM-exit handler for APIC access (VMX_EXIT_APIC_ACCESS). Conditional VM-exit.
15477 */
15478HMVMX_EXIT_DECL hmR0VmxExitApicAccess(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
15479{
15480 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
15481 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitApicAccess);
15482
15483 hmR0VmxReadExitIntInfoVmcs(pVmxTransient);
15484 hmR0VmxReadExitIntErrorCodeVmcs(pVmxTransient);
15485 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
15486 hmR0VmxReadIdtVectoringInfoVmcs(pVmxTransient);
15487 hmR0VmxReadIdtVectoringErrorCodeVmcs(pVmxTransient);
15488
15489 /*
15490 * If this VM-exit occurred while delivering an event through the guest IDT, handle it accordingly.
15491 */
15492 VBOXSTRICTRC rcStrict = hmR0VmxCheckExitDueToEventDelivery(pVCpu, pVmxTransient);
15493 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
15494 {
15495 /* For some crazy guest, if an event delivery causes an APIC-access VM-exit, go to instruction emulation. */
15496 if (RT_UNLIKELY(pVCpu->hm.s.Event.fPending))
15497 {
15498 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectInterpret);
15499 return VINF_EM_RAW_INJECT_TRPM_EVENT;
15500 }
15501 }
15502 else
15503 {
15504 Assert(rcStrict != VINF_HM_DOUBLE_FAULT);
15505 return rcStrict;
15506 }
15507
15508 /* IOMMIOPhysHandler() below may call into IEM, save the necessary state. */
15509 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
15510 hmR0VmxReadExitQualVmcs(pVmxTransient);
15511 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, IEM_CPUMCTX_EXTRN_MUST_MASK);
15512 AssertRCReturn(rc, rc);
15513
15514 /* See Intel spec. 27-6 "Exit Qualifications for APIC-access VM-exits from Linear Accesses & Guest-Phyiscal Addresses" */
15515 uint32_t const uAccessType = VMX_EXIT_QUAL_APIC_ACCESS_TYPE(pVmxTransient->uExitQual);
15516 switch (uAccessType)
15517 {
15518 case VMX_APIC_ACCESS_TYPE_LINEAR_WRITE:
15519 case VMX_APIC_ACCESS_TYPE_LINEAR_READ:
15520 {
15521 AssertMsg( !(pVmcsInfo->u32ProcCtls & VMX_PROC_CTLS_USE_TPR_SHADOW)
15522 || VMX_EXIT_QUAL_APIC_ACCESS_OFFSET(pVmxTransient->uExitQual) != XAPIC_OFF_TPR,
15523 ("hmR0VmxExitApicAccess: can't access TPR offset while using TPR shadowing.\n"));
15524
15525 RTGCPHYS GCPhys = pVCpu->hm.s.vmx.u64GstMsrApicBase; /* Always up-to-date, as it is not part of the VMCS. */
15526 GCPhys &= PAGE_BASE_GC_MASK;
15527 GCPhys += VMX_EXIT_QUAL_APIC_ACCESS_OFFSET(pVmxTransient->uExitQual);
15528 Log4Func(("Linear access uAccessType=%#x GCPhys=%#RGp Off=%#x\n", uAccessType, GCPhys,
15529 VMX_EXIT_QUAL_APIC_ACCESS_OFFSET(pVmxTransient->uExitQual)));
15530
15531 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
15532 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
15533 rcStrict = IOMMMIOPhysHandler(pVM, pVCpu,
15534 uAccessType == VMX_APIC_ACCESS_TYPE_LINEAR_READ ? 0 : X86_TRAP_PF_RW,
15535 CPUMCTX2CORE(pCtx), GCPhys);
15536 Log4Func(("IOMMMIOPhysHandler returned %Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
15537 if ( rcStrict == VINF_SUCCESS
15538 || rcStrict == VERR_PAGE_TABLE_NOT_PRESENT
15539 || rcStrict == VERR_PAGE_NOT_PRESENT)
15540 {
15541 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RSP | HM_CHANGED_GUEST_RFLAGS
15542 | HM_CHANGED_GUEST_APIC_TPR);
15543 rcStrict = VINF_SUCCESS;
15544 }
15545 break;
15546 }
15547
15548 default:
15549 {
15550 Log4Func(("uAccessType=%#x\n", uAccessType));
15551 rcStrict = VINF_EM_RAW_EMULATE_INSTR;
15552 break;
15553 }
15554 }
15555
15556 if (rcStrict != VINF_SUCCESS)
15557 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchApicAccessToR3);
15558 return rcStrict;
15559}
15560
15561
15562/**
15563 * VM-exit handler for debug-register accesses (VMX_EXIT_MOV_DRX). Conditional
15564 * VM-exit.
15565 */
15566HMVMX_EXIT_DECL hmR0VmxExitMovDRx(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
15567{
15568 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
15569 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
15570
15571 /* We might get this VM-exit if the nested-guest is not intercepting MOV DRx accesses. */
15572 if (!pVmxTransient->fIsNestedGuest)
15573 {
15574 /* We should -not- get this VM-exit if the guest's debug registers were active. */
15575 if (pVmxTransient->fWasGuestDebugStateActive)
15576 {
15577 AssertMsgFailed(("Unexpected MOV DRx exit\n"));
15578 HMVMX_UNEXPECTED_EXIT_RET(pVCpu, pVmxTransient->uExitReason);
15579 }
15580
15581 if ( !pVCpu->hm.s.fSingleInstruction
15582 && !pVmxTransient->fWasHyperDebugStateActive)
15583 {
15584 Assert(!DBGFIsStepping(pVCpu));
15585 Assert(pVmcsInfo->u32XcptBitmap & RT_BIT(X86_XCPT_DB));
15586
15587 /* Don't intercept MOV DRx any more. */
15588 pVmcsInfo->u32ProcCtls &= ~VMX_PROC_CTLS_MOV_DR_EXIT;
15589 int rc = VMXWriteVmcs32(VMX_VMCS32_CTRL_PROC_EXEC, pVmcsInfo->u32ProcCtls);
15590 AssertRC(rc);
15591
15592 /* We're playing with the host CPU state here, make sure we can't preempt or longjmp. */
15593 VMMRZCallRing3Disable(pVCpu);
15594 HM_DISABLE_PREEMPT(pVCpu);
15595
15596 /* Save the host & load the guest debug state, restart execution of the MOV DRx instruction. */
15597 CPUMR0LoadGuestDebugState(pVCpu, true /* include DR6 */);
15598 Assert(CPUMIsGuestDebugStateActive(pVCpu));
15599
15600 HM_RESTORE_PREEMPT();
15601 VMMRZCallRing3Enable(pVCpu);
15602
15603#ifdef VBOX_WITH_STATISTICS
15604 hmR0VmxReadExitQualVmcs(pVmxTransient);
15605 if (VMX_EXIT_QUAL_DRX_DIRECTION(pVmxTransient->uExitQual) == VMX_EXIT_QUAL_DRX_DIRECTION_WRITE)
15606 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitDRxWrite);
15607 else
15608 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitDRxRead);
15609#endif
15610 STAM_COUNTER_INC(&pVCpu->hm.s.StatDRxContextSwitch);
15611 return VINF_SUCCESS;
15612 }
15613 }
15614
15615 /*
15616 * EMInterpretDRx[Write|Read]() calls CPUMIsGuestIn64BitCode() which requires EFER MSR, CS.
15617 * The EFER MSR is always up-to-date.
15618 * Update the segment registers and DR7 from the CPU.
15619 */
15620 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
15621 hmR0VmxReadExitQualVmcs(pVmxTransient);
15622 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, CPUMCTX_EXTRN_SREG_MASK | CPUMCTX_EXTRN_DR7);
15623 AssertRCReturn(rc, rc);
15624 Log4Func(("cs:rip=%#04x:%#RX64\n", pCtx->cs.Sel, pCtx->rip));
15625
15626 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
15627 if (VMX_EXIT_QUAL_DRX_DIRECTION(pVmxTransient->uExitQual) == VMX_EXIT_QUAL_DRX_DIRECTION_WRITE)
15628 {
15629 rc = EMInterpretDRxWrite(pVM, pVCpu, CPUMCTX2CORE(pCtx),
15630 VMX_EXIT_QUAL_DRX_REGISTER(pVmxTransient->uExitQual),
15631 VMX_EXIT_QUAL_DRX_GENREG(pVmxTransient->uExitQual));
15632 if (RT_SUCCESS(rc))
15633 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_DR7);
15634 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitDRxWrite);
15635 }
15636 else
15637 {
15638 rc = EMInterpretDRxRead(pVM, pVCpu, CPUMCTX2CORE(pCtx),
15639 VMX_EXIT_QUAL_DRX_GENREG(pVmxTransient->uExitQual),
15640 VMX_EXIT_QUAL_DRX_REGISTER(pVmxTransient->uExitQual));
15641 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitDRxRead);
15642 }
15643
15644 Assert(rc == VINF_SUCCESS || rc == VERR_EM_INTERPRETER);
15645 if (RT_SUCCESS(rc))
15646 {
15647 int rc2 = hmR0VmxAdvanceGuestRip(pVCpu, pVmxTransient);
15648 AssertRCReturn(rc2, rc2);
15649 return VINF_SUCCESS;
15650 }
15651 return rc;
15652}
15653
15654
15655/**
15656 * VM-exit handler for EPT misconfiguration (VMX_EXIT_EPT_MISCONFIG).
15657 * Conditional VM-exit.
15658 */
15659HMVMX_EXIT_DECL hmR0VmxExitEptMisconfig(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
15660{
15661 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
15662 Assert(pVCpu->CTX_SUFF(pVM)->hm.s.fNestedPaging);
15663
15664 hmR0VmxReadExitIntInfoVmcs(pVmxTransient);
15665 hmR0VmxReadExitIntErrorCodeVmcs(pVmxTransient);
15666 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
15667 hmR0VmxReadIdtVectoringInfoVmcs(pVmxTransient);
15668 hmR0VmxReadIdtVectoringErrorCodeVmcs(pVmxTransient);
15669
15670 /*
15671 * If this VM-exit occurred while delivering an event through the guest IDT, handle it accordingly.
15672 */
15673 VBOXSTRICTRC rcStrict = hmR0VmxCheckExitDueToEventDelivery(pVCpu, pVmxTransient);
15674 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
15675 {
15676 /*
15677 * In the unlikely case where delivering an event causes an EPT misconfig (MMIO), go back to
15678 * instruction emulation to inject the original event. Otherwise, injecting the original event
15679 * using hardware-assisted VMX would trigger the same EPT misconfig VM-exit again.
15680 */
15681 if (!pVCpu->hm.s.Event.fPending)
15682 { /* likely */ }
15683 else
15684 {
15685 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectInterpret);
15686#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
15687 /** @todo NSTVMX: Think about how this should be handled. */
15688 if (pVmxTransient->fIsNestedGuest)
15689 return VERR_VMX_IPE_3;
15690#endif
15691 return VINF_EM_RAW_INJECT_TRPM_EVENT;
15692 }
15693 }
15694 else
15695 {
15696 Assert(rcStrict != VINF_HM_DOUBLE_FAULT);
15697 return rcStrict;
15698 }
15699
15700 /*
15701 * Get sufficient state and update the exit history entry.
15702 */
15703 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
15704 hmR0VmxReadGuestPhysicalAddrVmcs(pVmxTransient);
15705 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, IEM_CPUMCTX_EXTRN_MUST_MASK);
15706 AssertRCReturn(rc, rc);
15707
15708 RTGCPHYS const GCPhys = pVmxTransient->uGuestPhysicalAddr;
15709 PCEMEXITREC pExitRec = EMHistoryUpdateFlagsAndTypeAndPC(pVCpu,
15710 EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM | EMEXIT_F_HM, EMEXITTYPE_MMIO),
15711 pVCpu->cpum.GstCtx.rip + pVCpu->cpum.GstCtx.cs.u64Base);
15712 if (!pExitRec)
15713 {
15714 /*
15715 * If we succeed, resume guest execution.
15716 * If we fail in interpreting the instruction because we couldn't get the guest physical address
15717 * of the page containing the instruction via the guest's page tables (we would invalidate the guest page
15718 * in the host TLB), resume execution which would cause a guest page fault to let the guest handle this
15719 * weird case. See @bugref{6043}.
15720 */
15721 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
15722 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
15723 rcStrict = PGMR0Trap0eHandlerNPMisconfig(pVM, pVCpu, PGMMODE_EPT, CPUMCTX2CORE(pCtx), GCPhys, UINT32_MAX);
15724 Log4Func(("At %#RGp RIP=%#RX64 rc=%Rrc\n", GCPhys, pCtx->rip, VBOXSTRICTRC_VAL(rcStrict)));
15725 if ( rcStrict == VINF_SUCCESS
15726 || rcStrict == VERR_PAGE_TABLE_NOT_PRESENT
15727 || rcStrict == VERR_PAGE_NOT_PRESENT)
15728 {
15729 /* Successfully handled MMIO operation. */
15730 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RSP | HM_CHANGED_GUEST_RFLAGS
15731 | HM_CHANGED_GUEST_APIC_TPR);
15732 rcStrict = VINF_SUCCESS;
15733 }
15734 }
15735 else
15736 {
15737 /*
15738 * Frequent exit or something needing probing. Call EMHistoryExec.
15739 */
15740 Log4(("EptMisscfgExit/%u: %04x:%08RX64: %RGp -> EMHistoryExec\n",
15741 pVCpu->idCpu, pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip, GCPhys));
15742
15743 rcStrict = EMHistoryExec(pVCpu, pExitRec, 0);
15744 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_ALL_GUEST);
15745
15746 Log4(("EptMisscfgExit/%u: %04x:%08RX64: EMHistoryExec -> %Rrc + %04x:%08RX64\n",
15747 pVCpu->idCpu, pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip,
15748 VBOXSTRICTRC_VAL(rcStrict), pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip));
15749 }
15750 return rcStrict;
15751}
15752
15753
15754/**
15755 * VM-exit handler for EPT violation (VMX_EXIT_EPT_VIOLATION). Conditional
15756 * VM-exit.
15757 */
15758HMVMX_EXIT_DECL hmR0VmxExitEptViolation(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
15759{
15760 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
15761 Assert(pVCpu->CTX_SUFF(pVM)->hm.s.fNestedPaging);
15762
15763 hmR0VmxReadExitQualVmcs(pVmxTransient);
15764 hmR0VmxReadExitIntInfoVmcs(pVmxTransient);
15765 hmR0VmxReadExitIntErrorCodeVmcs(pVmxTransient);
15766 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
15767 hmR0VmxReadIdtVectoringInfoVmcs(pVmxTransient);
15768 hmR0VmxReadIdtVectoringErrorCodeVmcs(pVmxTransient);
15769
15770 /*
15771 * If this VM-exit occurred while delivering an event through the guest IDT, handle it accordingly.
15772 */
15773 VBOXSTRICTRC rcStrict = hmR0VmxCheckExitDueToEventDelivery(pVCpu, pVmxTransient);
15774 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
15775 {
15776 /*
15777 * If delivery of an event causes an EPT violation (true nested #PF and not MMIO),
15778 * we shall resolve the nested #PF and re-inject the original event.
15779 */
15780 if (pVCpu->hm.s.Event.fPending)
15781 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectReflectNPF);
15782 }
15783 else
15784 {
15785 Assert(rcStrict != VINF_HM_DOUBLE_FAULT);
15786 return rcStrict;
15787 }
15788
15789 PVMXVMCSINFO pVmcsInfo = pVmxTransient->pVmcsInfo;
15790 hmR0VmxReadGuestPhysicalAddrVmcs(pVmxTransient);
15791 int rc = hmR0VmxImportGuestState(pVCpu, pVmcsInfo, IEM_CPUMCTX_EXTRN_MUST_MASK);
15792 AssertRCReturn(rc, rc);
15793
15794 RTGCPHYS const GCPhys = pVmxTransient->uGuestPhysicalAddr;
15795 uint64_t const uExitQual = pVmxTransient->uExitQual;
15796 AssertMsg(((pVmxTransient->uExitQual >> 7) & 3) != 2, ("%#RX64", uExitQual));
15797
15798 RTGCUINT uErrorCode = 0;
15799 if (uExitQual & VMX_EXIT_QUAL_EPT_INSTR_FETCH)
15800 uErrorCode |= X86_TRAP_PF_ID;
15801 if (uExitQual & VMX_EXIT_QUAL_EPT_DATA_WRITE)
15802 uErrorCode |= X86_TRAP_PF_RW;
15803 if (uExitQual & VMX_EXIT_QUAL_EPT_ENTRY_PRESENT)
15804 uErrorCode |= X86_TRAP_PF_P;
15805
15806 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
15807 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
15808 Log4Func(("at %#RX64 (%#RX64 errcode=%#x) cs:rip=%#04x:%#RX64\n", GCPhys, uExitQual, uErrorCode, pCtx->cs.Sel, pCtx->rip));
15809
15810 /*
15811 * Handle the pagefault trap for the nested shadow table.
15812 */
15813 TRPMAssertXcptPF(pVCpu, GCPhys, uErrorCode);
15814 rcStrict = PGMR0Trap0eHandlerNestedPaging(pVM, pVCpu, PGMMODE_EPT, uErrorCode, CPUMCTX2CORE(pCtx), GCPhys);
15815 TRPMResetTrap(pVCpu);
15816
15817 /* Same case as PGMR0Trap0eHandlerNPMisconfig(). See comment above, @bugref{6043}. */
15818 if ( rcStrict == VINF_SUCCESS
15819 || rcStrict == VERR_PAGE_TABLE_NOT_PRESENT
15820 || rcStrict == VERR_PAGE_NOT_PRESENT)
15821 {
15822 /* Successfully synced our nested page tables. */
15823 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitReasonNpf);
15824 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RSP | HM_CHANGED_GUEST_RFLAGS);
15825 return VINF_SUCCESS;
15826 }
15827
15828 Log4Func(("EPT return to ring-3 rcStrict2=%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
15829 return rcStrict;
15830}
15831
15832
15833#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
15834/**
15835 * VM-exit handler for VMCLEAR (VMX_EXIT_VMCLEAR). Unconditional VM-exit.
15836 */
15837HMVMX_EXIT_DECL hmR0VmxExitVmclear(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
15838{
15839 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
15840
15841 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
15842 hmR0VmxReadExitInstrInfoVmcs(pVmxTransient);
15843 hmR0VmxReadExitQualVmcs(pVmxTransient);
15844 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, CPUMCTX_EXTRN_RSP | CPUMCTX_EXTRN_SREG_MASK
15845 | CPUMCTX_EXTRN_HWVIRT
15846 | IEM_CPUMCTX_EXTRN_EXEC_DECODED_MEM_MASK);
15847 AssertRCReturn(rc, rc);
15848
15849 HMVMX_CHECK_EXIT_DUE_TO_VMX_INSTR(pVCpu, pVmxTransient->uExitReason);
15850
15851 VMXVEXITINFO ExitInfo;
15852 RT_ZERO(ExitInfo);
15853 ExitInfo.uReason = pVmxTransient->uExitReason;
15854 ExitInfo.u64Qual = pVmxTransient->uExitQual;
15855 ExitInfo.InstrInfo.u = pVmxTransient->ExitInstrInfo.u;
15856 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
15857 HMVMX_DECODE_MEM_OPERAND(pVCpu, ExitInfo.InstrInfo.u, ExitInfo.u64Qual, VMXMEMACCESS_READ, &ExitInfo.GCPtrEffAddr);
15858
15859 VBOXSTRICTRC rcStrict = IEMExecDecodedVmclear(pVCpu, &ExitInfo);
15860 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
15861 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS | HM_CHANGED_GUEST_HWVIRT);
15862 else if (rcStrict == VINF_IEM_RAISED_XCPT)
15863 {
15864 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
15865 rcStrict = VINF_SUCCESS;
15866 }
15867 return rcStrict;
15868}
15869
15870
15871/**
15872 * VM-exit handler for VMLAUNCH (VMX_EXIT_VMLAUNCH). Unconditional VM-exit.
15873 */
15874HMVMX_EXIT_DECL hmR0VmxExitVmlaunch(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
15875{
15876 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
15877
15878 /* Import the entire VMCS state for now as we would be switching VMCS on successful VMLAUNCH,
15879 otherwise we could import just IEM_CPUMCTX_EXTRN_VMX_VMENTRY_MASK. */
15880 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
15881 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, HMVMX_CPUMCTX_EXTRN_ALL);
15882 AssertRCReturn(rc, rc);
15883
15884 HMVMX_CHECK_EXIT_DUE_TO_VMX_INSTR(pVCpu, pVmxTransient->uExitReason);
15885
15886 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatExitVmentry, z);
15887 VBOXSTRICTRC rcStrict = IEMExecDecodedVmlaunchVmresume(pVCpu, pVmxTransient->cbExitInstr, VMXINSTRID_VMLAUNCH);
15888 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExitVmentry, z);
15889 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
15890 {
15891 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_ALL_GUEST);
15892 if (CPUMIsGuestInVmxNonRootMode(&pVCpu->cpum.GstCtx))
15893 rcStrict = VINF_VMX_VMLAUNCH_VMRESUME;
15894 }
15895 Assert(rcStrict != VINF_IEM_RAISED_XCPT);
15896 return rcStrict;
15897}
15898
15899
15900/**
15901 * VM-exit handler for VMPTRLD (VMX_EXIT_VMPTRLD). Unconditional VM-exit.
15902 */
15903HMVMX_EXIT_DECL hmR0VmxExitVmptrld(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
15904{
15905 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
15906
15907 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
15908 hmR0VmxReadExitInstrInfoVmcs(pVmxTransient);
15909 hmR0VmxReadExitQualVmcs(pVmxTransient);
15910 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, CPUMCTX_EXTRN_RSP | CPUMCTX_EXTRN_SREG_MASK
15911 | CPUMCTX_EXTRN_HWVIRT
15912 | IEM_CPUMCTX_EXTRN_EXEC_DECODED_MEM_MASK);
15913 AssertRCReturn(rc, rc);
15914
15915 HMVMX_CHECK_EXIT_DUE_TO_VMX_INSTR(pVCpu, pVmxTransient->uExitReason);
15916
15917 VMXVEXITINFO ExitInfo;
15918 RT_ZERO(ExitInfo);
15919 ExitInfo.uReason = pVmxTransient->uExitReason;
15920 ExitInfo.u64Qual = pVmxTransient->uExitQual;
15921 ExitInfo.InstrInfo.u = pVmxTransient->ExitInstrInfo.u;
15922 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
15923 HMVMX_DECODE_MEM_OPERAND(pVCpu, ExitInfo.InstrInfo.u, ExitInfo.u64Qual, VMXMEMACCESS_READ, &ExitInfo.GCPtrEffAddr);
15924
15925 VBOXSTRICTRC rcStrict = IEMExecDecodedVmptrld(pVCpu, &ExitInfo);
15926 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
15927 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS | HM_CHANGED_GUEST_HWVIRT);
15928 else if (rcStrict == VINF_IEM_RAISED_XCPT)
15929 {
15930 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
15931 rcStrict = VINF_SUCCESS;
15932 }
15933 return rcStrict;
15934}
15935
15936
15937/**
15938 * VM-exit handler for VMPTRST (VMX_EXIT_VMPTRST). Unconditional VM-exit.
15939 */
15940HMVMX_EXIT_DECL hmR0VmxExitVmptrst(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
15941{
15942 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
15943
15944 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
15945 hmR0VmxReadExitInstrInfoVmcs(pVmxTransient);
15946 hmR0VmxReadExitQualVmcs(pVmxTransient);
15947 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, CPUMCTX_EXTRN_RSP | CPUMCTX_EXTRN_SREG_MASK
15948 | CPUMCTX_EXTRN_HWVIRT
15949 | IEM_CPUMCTX_EXTRN_EXEC_DECODED_MEM_MASK);
15950 AssertRCReturn(rc, rc);
15951
15952 HMVMX_CHECK_EXIT_DUE_TO_VMX_INSTR(pVCpu, pVmxTransient->uExitReason);
15953
15954 VMXVEXITINFO ExitInfo;
15955 RT_ZERO(ExitInfo);
15956 ExitInfo.uReason = pVmxTransient->uExitReason;
15957 ExitInfo.u64Qual = pVmxTransient->uExitQual;
15958 ExitInfo.InstrInfo.u = pVmxTransient->ExitInstrInfo.u;
15959 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
15960 HMVMX_DECODE_MEM_OPERAND(pVCpu, ExitInfo.InstrInfo.u, ExitInfo.u64Qual, VMXMEMACCESS_WRITE, &ExitInfo.GCPtrEffAddr);
15961
15962 VBOXSTRICTRC rcStrict = IEMExecDecodedVmptrst(pVCpu, &ExitInfo);
15963 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
15964 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS);
15965 else if (rcStrict == VINF_IEM_RAISED_XCPT)
15966 {
15967 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
15968 rcStrict = VINF_SUCCESS;
15969 }
15970 return rcStrict;
15971}
15972
15973
15974/**
15975 * VM-exit handler for VMREAD (VMX_EXIT_VMREAD). Conditional VM-exit.
15976 */
15977HMVMX_EXIT_DECL hmR0VmxExitVmread(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
15978{
15979 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
15980
15981 /*
15982 * Strictly speaking we should not get VMREAD VM-exits for shadow VMCS fields and
15983 * thus might not need to import the shadow VMCS state, it's safer just in case
15984 * code elsewhere dares look at unsynced VMCS fields.
15985 */
15986 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
15987 hmR0VmxReadExitInstrInfoVmcs(pVmxTransient);
15988 hmR0VmxReadExitQualVmcs(pVmxTransient);
15989 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, CPUMCTX_EXTRN_RSP | CPUMCTX_EXTRN_SREG_MASK
15990 | CPUMCTX_EXTRN_HWVIRT
15991 | IEM_CPUMCTX_EXTRN_EXEC_DECODED_MEM_MASK);
15992 AssertRCReturn(rc, rc);
15993
15994 HMVMX_CHECK_EXIT_DUE_TO_VMX_INSTR(pVCpu, pVmxTransient->uExitReason);
15995
15996 VMXVEXITINFO ExitInfo;
15997 RT_ZERO(ExitInfo);
15998 ExitInfo.uReason = pVmxTransient->uExitReason;
15999 ExitInfo.u64Qual = pVmxTransient->uExitQual;
16000 ExitInfo.InstrInfo.u = pVmxTransient->ExitInstrInfo.u;
16001 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
16002 if (!ExitInfo.InstrInfo.VmreadVmwrite.fIsRegOperand)
16003 HMVMX_DECODE_MEM_OPERAND(pVCpu, ExitInfo.InstrInfo.u, ExitInfo.u64Qual, VMXMEMACCESS_WRITE, &ExitInfo.GCPtrEffAddr);
16004
16005 VBOXSTRICTRC rcStrict = IEMExecDecodedVmread(pVCpu, &ExitInfo);
16006 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
16007 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS);
16008 else if (rcStrict == VINF_IEM_RAISED_XCPT)
16009 {
16010 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
16011 rcStrict = VINF_SUCCESS;
16012 }
16013 return rcStrict;
16014}
16015
16016
16017/**
16018 * VM-exit handler for VMRESUME (VMX_EXIT_VMRESUME). Unconditional VM-exit.
16019 */
16020HMVMX_EXIT_DECL hmR0VmxExitVmresume(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16021{
16022 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16023
16024 /* Import the entire VMCS state for now as we would be switching VMCS on successful VMRESUME,
16025 otherwise we could import just IEM_CPUMCTX_EXTRN_VMX_VMENTRY_MASK. */
16026 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16027 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, HMVMX_CPUMCTX_EXTRN_ALL);
16028 AssertRCReturn(rc, rc);
16029
16030 HMVMX_CHECK_EXIT_DUE_TO_VMX_INSTR(pVCpu, pVmxTransient->uExitReason);
16031
16032 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatExitVmentry, z);
16033 VBOXSTRICTRC rcStrict = IEMExecDecodedVmlaunchVmresume(pVCpu, pVmxTransient->cbExitInstr, VMXINSTRID_VMRESUME);
16034 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExitVmentry, z);
16035 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
16036 {
16037 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_ALL_GUEST);
16038 if (CPUMIsGuestInVmxNonRootMode(&pVCpu->cpum.GstCtx))
16039 rcStrict = VINF_VMX_VMLAUNCH_VMRESUME;
16040 }
16041 Assert(rcStrict != VINF_IEM_RAISED_XCPT);
16042 return rcStrict;
16043}
16044
16045
16046/**
16047 * VM-exit handler for VMWRITE (VMX_EXIT_VMWRITE). Conditional VM-exit.
16048 */
16049HMVMX_EXIT_DECL hmR0VmxExitVmwrite(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16050{
16051 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16052
16053 /*
16054 * Although we should not get VMWRITE VM-exits for shadow VMCS fields, since our HM hook
16055 * gets invoked when IEM's VMWRITE instruction emulation modifies the current VMCS and it
16056 * flags re-loading the entire shadow VMCS, we should save the entire shadow VMCS here.
16057 */
16058 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16059 hmR0VmxReadExitInstrInfoVmcs(pVmxTransient);
16060 hmR0VmxReadExitQualVmcs(pVmxTransient);
16061 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, CPUMCTX_EXTRN_RSP | CPUMCTX_EXTRN_SREG_MASK
16062 | CPUMCTX_EXTRN_HWVIRT
16063 | IEM_CPUMCTX_EXTRN_EXEC_DECODED_MEM_MASK);
16064 AssertRCReturn(rc, rc);
16065
16066 HMVMX_CHECK_EXIT_DUE_TO_VMX_INSTR(pVCpu, pVmxTransient->uExitReason);
16067
16068 VMXVEXITINFO ExitInfo;
16069 RT_ZERO(ExitInfo);
16070 ExitInfo.uReason = pVmxTransient->uExitReason;
16071 ExitInfo.u64Qual = pVmxTransient->uExitQual;
16072 ExitInfo.InstrInfo.u = pVmxTransient->ExitInstrInfo.u;
16073 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
16074 if (!ExitInfo.InstrInfo.VmreadVmwrite.fIsRegOperand)
16075 HMVMX_DECODE_MEM_OPERAND(pVCpu, ExitInfo.InstrInfo.u, ExitInfo.u64Qual, VMXMEMACCESS_READ, &ExitInfo.GCPtrEffAddr);
16076
16077 VBOXSTRICTRC rcStrict = IEMExecDecodedVmwrite(pVCpu, &ExitInfo);
16078 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
16079 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS | HM_CHANGED_GUEST_HWVIRT);
16080 else if (rcStrict == VINF_IEM_RAISED_XCPT)
16081 {
16082 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
16083 rcStrict = VINF_SUCCESS;
16084 }
16085 return rcStrict;
16086}
16087
16088
16089/**
16090 * VM-exit handler for VMXOFF (VMX_EXIT_VMXOFF). Unconditional VM-exit.
16091 */
16092HMVMX_EXIT_DECL hmR0VmxExitVmxoff(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16093{
16094 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16095
16096 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16097 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, CPUMCTX_EXTRN_CR4
16098 | CPUMCTX_EXTRN_HWVIRT
16099 | IEM_CPUMCTX_EXTRN_EXEC_DECODED_NO_MEM_MASK);
16100 AssertRCReturn(rc, rc);
16101
16102 HMVMX_CHECK_EXIT_DUE_TO_VMX_INSTR(pVCpu, pVmxTransient->uExitReason);
16103
16104 VBOXSTRICTRC rcStrict = IEMExecDecodedVmxoff(pVCpu, pVmxTransient->cbExitInstr);
16105 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
16106 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_HWVIRT);
16107 else if (rcStrict == VINF_IEM_RAISED_XCPT)
16108 {
16109 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
16110 rcStrict = VINF_SUCCESS;
16111 }
16112 return rcStrict;
16113}
16114
16115
16116/**
16117 * VM-exit handler for VMXON (VMX_EXIT_VMXON). Unconditional VM-exit.
16118 */
16119HMVMX_EXIT_DECL hmR0VmxExitVmxon(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16120{
16121 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16122
16123 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16124 hmR0VmxReadExitInstrInfoVmcs(pVmxTransient);
16125 hmR0VmxReadExitQualVmcs(pVmxTransient);
16126 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, CPUMCTX_EXTRN_RSP | CPUMCTX_EXTRN_SREG_MASK
16127 | CPUMCTX_EXTRN_HWVIRT
16128 | IEM_CPUMCTX_EXTRN_EXEC_DECODED_MEM_MASK);
16129 AssertRCReturn(rc, rc);
16130
16131 HMVMX_CHECK_EXIT_DUE_TO_VMX_INSTR(pVCpu, pVmxTransient->uExitReason);
16132
16133 VMXVEXITINFO ExitInfo;
16134 RT_ZERO(ExitInfo);
16135 ExitInfo.uReason = pVmxTransient->uExitReason;
16136 ExitInfo.u64Qual = pVmxTransient->uExitQual;
16137 ExitInfo.InstrInfo.u = pVmxTransient->ExitInstrInfo.u;
16138 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
16139 HMVMX_DECODE_MEM_OPERAND(pVCpu, ExitInfo.InstrInfo.u, ExitInfo.u64Qual, VMXMEMACCESS_READ, &ExitInfo.GCPtrEffAddr);
16140
16141 VBOXSTRICTRC rcStrict = IEMExecDecodedVmxon(pVCpu, &ExitInfo);
16142 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
16143 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS | HM_CHANGED_GUEST_HWVIRT);
16144 else if (rcStrict == VINF_IEM_RAISED_XCPT)
16145 {
16146 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
16147 rcStrict = VINF_SUCCESS;
16148 }
16149 return rcStrict;
16150}
16151
16152
16153/**
16154 * VM-exit handler for INVVPID (VMX_EXIT_INVVPID). Unconditional VM-exit.
16155 */
16156HMVMX_EXIT_DECL hmR0VmxExitInvvpid(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16157{
16158 HMVMX_VALIDATE_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16159
16160 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16161 hmR0VmxReadExitInstrInfoVmcs(pVmxTransient);
16162 hmR0VmxReadExitQualVmcs(pVmxTransient);
16163 int rc = hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, CPUMCTX_EXTRN_RSP | CPUMCTX_EXTRN_SREG_MASK
16164 | IEM_CPUMCTX_EXTRN_EXEC_DECODED_MEM_MASK);
16165 AssertRCReturn(rc, rc);
16166
16167 HMVMX_CHECK_EXIT_DUE_TO_VMX_INSTR(pVCpu, pVmxTransient->uExitReason);
16168
16169 VMXVEXITINFO ExitInfo;
16170 RT_ZERO(ExitInfo);
16171 ExitInfo.uReason = pVmxTransient->uExitReason;
16172 ExitInfo.u64Qual = pVmxTransient->uExitQual;
16173 ExitInfo.InstrInfo.u = pVmxTransient->ExitInstrInfo.u;
16174 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
16175 HMVMX_DECODE_MEM_OPERAND(pVCpu, ExitInfo.InstrInfo.u, ExitInfo.u64Qual, VMXMEMACCESS_READ, &ExitInfo.GCPtrEffAddr);
16176
16177 VBOXSTRICTRC rcStrict = IEMExecDecodedInvvpid(pVCpu, &ExitInfo);
16178 if (RT_LIKELY(rcStrict == VINF_SUCCESS))
16179 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_RIP | HM_CHANGED_GUEST_RFLAGS);
16180 else if (rcStrict == VINF_IEM_RAISED_XCPT)
16181 {
16182 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
16183 rcStrict = VINF_SUCCESS;
16184 }
16185 return rcStrict;
16186}
16187#endif /* VBOX_WITH_NESTED_HWVIRT_VMX */
16188/** @} */
16189
16190
16191#ifdef VBOX_WITH_NESTED_HWVIRT_VMX
16192/** @name Nested-guest VM-exit handlers.
16193 * @{
16194 */
16195/* -=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= */
16196/* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- Nested-guest VM-exit handlers -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= */
16197/* -=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= */
16198
16199/**
16200 * Nested-guest VM-exit handler for exceptions or NMIs (VMX_EXIT_XCPT_OR_NMI).
16201 * Conditional VM-exit.
16202 */
16203HMVMX_EXIT_DECL hmR0VmxExitXcptOrNmiNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16204{
16205 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16206
16207 hmR0VmxReadExitIntInfoVmcs(pVmxTransient);
16208
16209 uint64_t const uExitIntInfo = pVmxTransient->uExitIntInfo;
16210 uint32_t const uExitIntType = VMX_EXIT_INT_INFO_TYPE(uExitIntInfo);
16211 Assert(VMX_EXIT_INT_INFO_IS_VALID(uExitIntInfo));
16212
16213 switch (uExitIntType)
16214 {
16215 /*
16216 * Physical NMIs:
16217 * We shouldn't direct host physical NMIs to the nested-guest. Dispatch it to the host.
16218 */
16219 case VMX_EXIT_INT_INFO_TYPE_NMI:
16220 return hmR0VmxExitHostNmi(pVCpu, pVmxTransient->pVmcsInfo);
16221
16222 /*
16223 * Hardware exceptions,
16224 * Software exceptions,
16225 * Privileged software exceptions:
16226 * Figure out if the exception must be delivered to the guest or the nested-guest.
16227 */
16228 case VMX_EXIT_INT_INFO_TYPE_SW_XCPT:
16229 case VMX_EXIT_INT_INFO_TYPE_PRIV_SW_XCPT:
16230 case VMX_EXIT_INT_INFO_TYPE_HW_XCPT:
16231 {
16232 hmR0VmxReadExitIntErrorCodeVmcs(pVmxTransient);
16233 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16234 hmR0VmxReadIdtVectoringInfoVmcs(pVmxTransient);
16235 hmR0VmxReadIdtVectoringErrorCodeVmcs(pVmxTransient);
16236
16237 PCCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
16238 bool const fIntercept = CPUMIsGuestVmxXcptInterceptSet(pVCpu, pCtx, VMX_EXIT_INT_INFO_VECTOR(uExitIntInfo),
16239 pVmxTransient->uExitIntErrorCode);
16240 if (fIntercept)
16241 {
16242 /* Exit qualification is required for debug and page-fault exceptions. */
16243 hmR0VmxReadExitQualVmcs(pVmxTransient);
16244
16245 /*
16246 * For VM-exits due to software exceptions (those generated by INT3 or INTO) and privileged
16247 * software exceptions (those generated by INT1/ICEBP) we need to supply the VM-exit instruction
16248 * length. However, if delivery of a software interrupt, software exception or privileged
16249 * software exception causes a VM-exit, that too provides the VM-exit instruction length.
16250 */
16251 VMXVEXITINFO ExitInfo;
16252 RT_ZERO(ExitInfo);
16253 ExitInfo.uReason = pVmxTransient->uExitReason;
16254 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
16255 ExitInfo.u64Qual = pVmxTransient->uExitQual;
16256
16257 VMXVEXITEVENTINFO ExitEventInfo;
16258 RT_ZERO(ExitEventInfo);
16259 ExitEventInfo.uExitIntInfo = pVmxTransient->uExitIntInfo;
16260 ExitEventInfo.uExitIntErrCode = pVmxTransient->uExitIntErrorCode;
16261 ExitEventInfo.uIdtVectoringInfo = pVmxTransient->uIdtVectoringInfo;
16262 ExitEventInfo.uIdtVectoringErrCode = pVmxTransient->uIdtVectoringErrorCode;
16263
16264#ifdef DEBUG_ramshankar
16265 hmR0VmxImportGuestState(pVCpu, pVmxTransient->pVmcsInfo, HMVMX_CPUMCTX_EXTRN_ALL);
16266 Log4Func(("exit_int_info=%#RX32 err_code=%#RX32 exit_qual=%#RX64\n", pVmxTransient->uExitIntInfo,
16267 pVmxTransient->uExitIntErrorCode, pVmxTransient->uExitQual));
16268 if (VMX_IDT_VECTORING_INFO_IS_VALID(pVmxTransient->uIdtVectoringInfo))
16269 {
16270 Log4Func(("idt_info=%#RX32 idt_errcode=%#RX32 cr2=%#RX64\n", pVmxTransient->uIdtVectoringInfo,
16271 pVmxTransient->uIdtVectoringErrorCode, pCtx->cr2));
16272 }
16273#endif
16274 return IEMExecVmxVmexitXcpt(pVCpu, &ExitInfo, &ExitEventInfo);
16275 }
16276
16277 /* Nested paging is currently a requirement, otherwise we would need to handle shadow #PFs in hmR0VmxExitXcptPF. */
16278 Assert(pVCpu->CTX_SUFF(pVM)->hm.s.fNestedPaging);
16279 return hmR0VmxExitXcpt(pVCpu, pVmxTransient);
16280 }
16281
16282 /*
16283 * Software interrupts:
16284 * VM-exits cannot be caused by software interrupts.
16285 *
16286 * External interrupts:
16287 * This should only happen when "acknowledge external interrupts on VM-exit"
16288 * control is set. However, we never set this when executing a guest or
16289 * nested-guest. For nested-guests it is emulated while injecting interrupts into
16290 * the guest.
16291 */
16292 case VMX_EXIT_INT_INFO_TYPE_SW_INT:
16293 case VMX_EXIT_INT_INFO_TYPE_EXT_INT:
16294 default:
16295 {
16296 pVCpu->hm.s.u32HMError = pVmxTransient->uExitIntInfo;
16297 return VERR_VMX_UNEXPECTED_INTERRUPTION_EXIT_TYPE;
16298 }
16299 }
16300}
16301
16302
16303/**
16304 * Nested-guest VM-exit handler for triple faults (VMX_EXIT_TRIPLE_FAULT).
16305 * Unconditional VM-exit.
16306 */
16307HMVMX_EXIT_DECL hmR0VmxExitTripleFaultNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16308{
16309 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16310 return IEMExecVmxVmexitTripleFault(pVCpu);
16311}
16312
16313
16314/**
16315 * Nested-guest VM-exit handler for interrupt-window exiting (VMX_EXIT_INT_WINDOW).
16316 */
16317HMVMX_EXIT_NSRC_DECL hmR0VmxExitIntWindowNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16318{
16319 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16320
16321 if (CPUMIsGuestVmxProcCtlsSet(pVCpu, &pVCpu->cpum.GstCtx, VMX_PROC_CTLS_INT_WINDOW_EXIT))
16322 return IEMExecVmxVmexit(pVCpu, pVmxTransient->uExitReason, 0 /* uExitQual */);
16323 return hmR0VmxExitIntWindow(pVCpu, pVmxTransient);
16324}
16325
16326
16327/**
16328 * Nested-guest VM-exit handler for NMI-window exiting (VMX_EXIT_NMI_WINDOW).
16329 */
16330HMVMX_EXIT_NSRC_DECL hmR0VmxExitNmiWindowNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16331{
16332 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16333
16334 if (CPUMIsGuestVmxProcCtlsSet(pVCpu, &pVCpu->cpum.GstCtx, VMX_PROC_CTLS_NMI_WINDOW_EXIT))
16335 return IEMExecVmxVmexit(pVCpu, pVmxTransient->uExitReason, 0 /* uExitQual */);
16336 return hmR0VmxExitIntWindow(pVCpu, pVmxTransient);
16337}
16338
16339
16340/**
16341 * Nested-guest VM-exit handler for task switches (VMX_EXIT_TASK_SWITCH).
16342 * Unconditional VM-exit.
16343 */
16344HMVMX_EXIT_DECL hmR0VmxExitTaskSwitchNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16345{
16346 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16347
16348 hmR0VmxReadExitQualVmcs(pVmxTransient);
16349 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16350 hmR0VmxReadIdtVectoringInfoVmcs(pVmxTransient);
16351 hmR0VmxReadIdtVectoringErrorCodeVmcs(pVmxTransient);
16352
16353 VMXVEXITINFO ExitInfo;
16354 RT_ZERO(ExitInfo);
16355 ExitInfo.uReason = pVmxTransient->uExitReason;
16356 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
16357 ExitInfo.u64Qual = pVmxTransient->uExitQual;
16358
16359 VMXVEXITEVENTINFO ExitEventInfo;
16360 RT_ZERO(ExitEventInfo);
16361 ExitEventInfo.uIdtVectoringInfo = pVmxTransient->uIdtVectoringInfo;
16362 ExitEventInfo.uIdtVectoringErrCode = pVmxTransient->uIdtVectoringErrorCode;
16363 return IEMExecVmxVmexitTaskSwitch(pVCpu, &ExitInfo, &ExitEventInfo);
16364}
16365
16366
16367/**
16368 * Nested-guest VM-exit handler for HLT (VMX_EXIT_HLT). Conditional VM-exit.
16369 */
16370HMVMX_EXIT_DECL hmR0VmxExitHltNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16371{
16372 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16373
16374 if (CPUMIsGuestVmxProcCtlsSet(pVCpu, &pVCpu->cpum.GstCtx, VMX_PROC_CTLS_HLT_EXIT))
16375 {
16376 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16377 return IEMExecVmxVmexitInstr(pVCpu, pVmxTransient->uExitReason, pVmxTransient->cbExitInstr);
16378 }
16379 return hmR0VmxExitHlt(pVCpu, pVmxTransient);
16380}
16381
16382
16383/**
16384 * Nested-guest VM-exit handler for INVLPG (VMX_EXIT_INVLPG). Conditional VM-exit.
16385 */
16386HMVMX_EXIT_DECL hmR0VmxExitInvlpgNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16387{
16388 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16389
16390 if (CPUMIsGuestVmxProcCtlsSet(pVCpu, &pVCpu->cpum.GstCtx, VMX_PROC_CTLS_INVLPG_EXIT))
16391 {
16392 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16393 hmR0VmxReadExitQualVmcs(pVmxTransient);
16394
16395 VMXVEXITINFO ExitInfo;
16396 RT_ZERO(ExitInfo);
16397 ExitInfo.uReason = pVmxTransient->uExitReason;
16398 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
16399 ExitInfo.u64Qual = pVmxTransient->uExitQual;
16400 return IEMExecVmxVmexitInstrWithInfo(pVCpu, &ExitInfo);
16401 }
16402 return hmR0VmxExitInvlpg(pVCpu, pVmxTransient);
16403}
16404
16405
16406/**
16407 * Nested-guest VM-exit handler for RDPMC (VMX_EXIT_RDPMC). Conditional VM-exit.
16408 */
16409HMVMX_EXIT_DECL hmR0VmxExitRdpmcNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16410{
16411 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16412
16413 if (CPUMIsGuestVmxProcCtlsSet(pVCpu, &pVCpu->cpum.GstCtx, VMX_PROC_CTLS_RDPMC_EXIT))
16414 {
16415 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16416 return IEMExecVmxVmexitInstr(pVCpu, pVmxTransient->uExitReason, pVmxTransient->cbExitInstr);
16417 }
16418 return hmR0VmxExitRdpmc(pVCpu, pVmxTransient);
16419}
16420
16421
16422/**
16423 * Nested-guest VM-exit handler for VMREAD (VMX_EXIT_VMREAD) and VMWRITE
16424 * (VMX_EXIT_VMWRITE). Conditional VM-exit.
16425 */
16426HMVMX_EXIT_DECL hmR0VmxExitVmreadVmwriteNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16427{
16428 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16429
16430 Assert( pVmxTransient->uExitReason == VMX_EXIT_VMREAD
16431 || pVmxTransient->uExitReason == VMX_EXIT_VMWRITE);
16432
16433 hmR0VmxReadExitInstrInfoVmcs(pVmxTransient);
16434
16435 uint8_t const iGReg = pVmxTransient->ExitInstrInfo.VmreadVmwrite.iReg2;
16436 Assert(iGReg < RT_ELEMENTS(pVCpu->cpum.GstCtx.aGRegs));
16437 uint64_t u64VmcsField = pVCpu->cpum.GstCtx.aGRegs[iGReg].u64;
16438
16439 HMVMX_CPUMCTX_ASSERT(pVCpu, CPUMCTX_EXTRN_EFER);
16440 if (!CPUMIsGuestInLongModeEx(&pVCpu->cpum.GstCtx))
16441 u64VmcsField &= UINT64_C(0xffffffff);
16442
16443 if (CPUMIsGuestVmxVmreadVmwriteInterceptSet(pVCpu, pVmxTransient->uExitReason, u64VmcsField))
16444 {
16445 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16446 hmR0VmxReadExitQualVmcs(pVmxTransient);
16447
16448 VMXVEXITINFO ExitInfo;
16449 RT_ZERO(ExitInfo);
16450 ExitInfo.uReason = pVmxTransient->uExitReason;
16451 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
16452 ExitInfo.u64Qual = pVmxTransient->uExitQual;
16453 ExitInfo.InstrInfo = pVmxTransient->ExitInstrInfo;
16454 return IEMExecVmxVmexitInstrWithInfo(pVCpu, &ExitInfo);
16455 }
16456
16457 if (pVmxTransient->uExitReason == VMX_EXIT_VMREAD)
16458 return hmR0VmxExitVmread(pVCpu, pVmxTransient);
16459 return hmR0VmxExitVmwrite(pVCpu, pVmxTransient);
16460}
16461
16462
16463/**
16464 * Nested-guest VM-exit handler for RDTSC (VMX_EXIT_RDTSC). Conditional VM-exit.
16465 */
16466HMVMX_EXIT_DECL hmR0VmxExitRdtscNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16467{
16468 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16469
16470 if (CPUMIsGuestVmxProcCtlsSet(pVCpu, &pVCpu->cpum.GstCtx, VMX_PROC_CTLS_RDTSC_EXIT))
16471 {
16472 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16473 return IEMExecVmxVmexitInstr(pVCpu, pVmxTransient->uExitReason, pVmxTransient->cbExitInstr);
16474 }
16475
16476 return hmR0VmxExitRdtsc(pVCpu, pVmxTransient);
16477}
16478
16479
16480/**
16481 * Nested-guest VM-exit handler for control-register accesses (VMX_EXIT_MOV_CRX).
16482 * Conditional VM-exit.
16483 */
16484HMVMX_EXIT_DECL hmR0VmxExitMovCRxNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16485{
16486 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16487
16488 hmR0VmxReadExitQualVmcs(pVmxTransient);
16489 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16490
16491 VBOXSTRICTRC rcStrict;
16492 uint32_t const uAccessType = VMX_EXIT_QUAL_CRX_ACCESS(pVmxTransient->uExitQual);
16493 switch (uAccessType)
16494 {
16495 case VMX_EXIT_QUAL_CRX_ACCESS_WRITE:
16496 {
16497 uint8_t const iCrReg = VMX_EXIT_QUAL_CRX_REGISTER(pVmxTransient->uExitQual);
16498 uint8_t const iGReg = VMX_EXIT_QUAL_CRX_GENREG(pVmxTransient->uExitQual);
16499 Assert(iGReg < RT_ELEMENTS(pVCpu->cpum.GstCtx.aGRegs));
16500 uint64_t const uNewCrX = pVCpu->cpum.GstCtx.aGRegs[iGReg].u64;
16501
16502 bool fIntercept;
16503 switch (iCrReg)
16504 {
16505 case 0:
16506 case 4:
16507 fIntercept = CPUMIsGuestVmxMovToCr0Cr4InterceptSet(pVCpu, &pVCpu->cpum.GstCtx, iCrReg, uNewCrX);
16508 break;
16509
16510 case 3:
16511 fIntercept = CPUMIsGuestVmxMovToCr3InterceptSet(pVCpu, uNewCrX);
16512 break;
16513
16514 case 8:
16515 fIntercept = CPUMIsGuestVmxProcCtlsSet(pVCpu, &pVCpu->cpum.GstCtx, VMX_PROC_CTLS_CR8_LOAD_EXIT);
16516 break;
16517
16518 default:
16519 fIntercept = false;
16520 break;
16521 }
16522 if (fIntercept)
16523 {
16524 VMXVEXITINFO ExitInfo;
16525 RT_ZERO(ExitInfo);
16526 ExitInfo.uReason = pVmxTransient->uExitReason;
16527 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
16528 ExitInfo.u64Qual = pVmxTransient->uExitQual;
16529 rcStrict = IEMExecVmxVmexitInstrWithInfo(pVCpu, &ExitInfo);
16530 }
16531 else
16532 rcStrict = hmR0VmxExitMovToCrX(pVCpu, pVmxTransient->pVmcsInfo, pVmxTransient->cbExitInstr, iGReg, iCrReg);
16533 break;
16534 }
16535
16536 case VMX_EXIT_QUAL_CRX_ACCESS_READ:
16537 {
16538 /*
16539 * CR0/CR4 reads do not cause VM-exits, the read-shadow is used (subject to masking).
16540 * CR2 reads do not cause a VM-exit.
16541 * CR3 reads cause a VM-exit depending on the "CR3 store exiting" control.
16542 * CR8 reads cause a VM-exit depending on the "CR8 store exiting" control.
16543 */
16544 uint8_t const iCrReg = VMX_EXIT_QUAL_CRX_REGISTER(pVmxTransient->uExitQual);
16545 if ( iCrReg == 3
16546 || iCrReg == 8)
16547 {
16548 static const uint32_t s_auCrXReadIntercepts[] = { 0, 0, 0, VMX_PROC_CTLS_CR3_STORE_EXIT, 0,
16549 0, 0, 0, VMX_PROC_CTLS_CR8_STORE_EXIT };
16550 uint32_t const uIntercept = s_auCrXReadIntercepts[iCrReg];
16551 if (CPUMIsGuestVmxProcCtlsSet(pVCpu, &pVCpu->cpum.GstCtx, uIntercept))
16552 {
16553 VMXVEXITINFO ExitInfo;
16554 RT_ZERO(ExitInfo);
16555 ExitInfo.uReason = pVmxTransient->uExitReason;
16556 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
16557 ExitInfo.u64Qual = pVmxTransient->uExitQual;
16558 rcStrict = IEMExecVmxVmexitInstrWithInfo(pVCpu, &ExitInfo);
16559 }
16560 else
16561 {
16562 uint8_t const iGReg = VMX_EXIT_QUAL_CRX_GENREG(pVmxTransient->uExitQual);
16563 rcStrict = hmR0VmxExitMovFromCrX(pVCpu, pVmxTransient->pVmcsInfo, pVmxTransient->cbExitInstr, iGReg, iCrReg);
16564 }
16565 }
16566 else
16567 {
16568 AssertMsgFailed(("MOV from CR%d VM-exit must not happen\n", iCrReg));
16569 HMVMX_UNEXPECTED_EXIT_RET(pVCpu, iCrReg);
16570 }
16571 break;
16572 }
16573
16574 case VMX_EXIT_QUAL_CRX_ACCESS_CLTS:
16575 {
16576 PCVMXVVMCS pVmcsNstGst = pVCpu->cpum.GstCtx.hwvirt.vmx.CTX_SUFF(pVmcs);
16577 Assert(pVmcsNstGst);
16578 uint64_t const uGstHostMask = pVmcsNstGst->u64Cr0Mask.u;
16579 uint64_t const uReadShadow = pVmcsNstGst->u64Cr0ReadShadow.u;
16580 if ( (uGstHostMask & X86_CR0_TS)
16581 && (uReadShadow & X86_CR0_TS))
16582 {
16583 VMXVEXITINFO ExitInfo;
16584 RT_ZERO(ExitInfo);
16585 ExitInfo.uReason = pVmxTransient->uExitReason;
16586 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
16587 ExitInfo.u64Qual = pVmxTransient->uExitQual;
16588 rcStrict = IEMExecVmxVmexitInstrWithInfo(pVCpu, &ExitInfo);
16589 }
16590 else
16591 rcStrict = hmR0VmxExitClts(pVCpu, pVmxTransient->pVmcsInfo, pVmxTransient->cbExitInstr);
16592 break;
16593 }
16594
16595 case VMX_EXIT_QUAL_CRX_ACCESS_LMSW: /* LMSW (Load Machine-Status Word into CR0) */
16596 {
16597 RTGCPTR GCPtrEffDst;
16598 uint16_t const uNewMsw = VMX_EXIT_QUAL_CRX_LMSW_DATA(pVmxTransient->uExitQual);
16599 bool const fMemOperand = VMX_EXIT_QUAL_CRX_LMSW_OP_MEM(pVmxTransient->uExitQual);
16600 if (fMemOperand)
16601 {
16602 hmR0VmxReadGuestLinearAddrVmcs(pVmxTransient);
16603 GCPtrEffDst = pVmxTransient->uGuestLinearAddr;
16604 }
16605 else
16606 GCPtrEffDst = NIL_RTGCPTR;
16607
16608 if (CPUMIsGuestVmxLmswInterceptSet(pVCpu, &pVCpu->cpum.GstCtx, uNewMsw))
16609 {
16610 VMXVEXITINFO ExitInfo;
16611 RT_ZERO(ExitInfo);
16612 ExitInfo.uReason = pVmxTransient->uExitReason;
16613 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
16614 ExitInfo.u64GuestLinearAddr = GCPtrEffDst;
16615 ExitInfo.u64Qual = pVmxTransient->uExitQual;
16616 rcStrict = IEMExecVmxVmexitInstrWithInfo(pVCpu, &ExitInfo);
16617 }
16618 else
16619 rcStrict = hmR0VmxExitLmsw(pVCpu, pVmxTransient->pVmcsInfo, pVmxTransient->cbExitInstr, uNewMsw, GCPtrEffDst);
16620 break;
16621 }
16622
16623 default:
16624 {
16625 AssertMsgFailed(("Unrecognized Mov CRX access type %#x\n", uAccessType));
16626 HMVMX_UNEXPECTED_EXIT_RET(pVCpu, uAccessType);
16627 }
16628 }
16629
16630 if (rcStrict == VINF_IEM_RAISED_XCPT)
16631 {
16632 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_RAISED_XCPT_MASK);
16633 rcStrict = VINF_SUCCESS;
16634 }
16635 return rcStrict;
16636}
16637
16638
16639/**
16640 * Nested-guest VM-exit handler for debug-register accesses (VMX_EXIT_MOV_DRX).
16641 * Conditional VM-exit.
16642 */
16643HMVMX_EXIT_DECL hmR0VmxExitMovDRxNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16644{
16645 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16646
16647 if (CPUMIsGuestVmxProcCtlsSet(pVCpu, &pVCpu->cpum.GstCtx, VMX_PROC_CTLS_MOV_DR_EXIT))
16648 {
16649 hmR0VmxReadExitQualVmcs(pVmxTransient);
16650 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16651
16652 VMXVEXITINFO ExitInfo;
16653 RT_ZERO(ExitInfo);
16654 ExitInfo.uReason = pVmxTransient->uExitReason;
16655 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
16656 ExitInfo.u64Qual = pVmxTransient->uExitQual;
16657 return IEMExecVmxVmexitInstrWithInfo(pVCpu, &ExitInfo);
16658 }
16659 return hmR0VmxExitMovDRx(pVCpu, pVmxTransient);
16660}
16661
16662
16663/**
16664 * Nested-guest VM-exit handler for I/O instructions (VMX_EXIT_IO_INSTR).
16665 * Conditional VM-exit.
16666 */
16667HMVMX_EXIT_DECL hmR0VmxExitIoInstrNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16668{
16669 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16670
16671 hmR0VmxReadExitQualVmcs(pVmxTransient);
16672
16673 uint32_t const uIOPort = VMX_EXIT_QUAL_IO_PORT(pVmxTransient->uExitQual);
16674 uint8_t const uIOSize = VMX_EXIT_QUAL_IO_SIZE(pVmxTransient->uExitQual);
16675 AssertReturn(uIOSize <= 3 && uIOSize != 2, VERR_VMX_IPE_1);
16676
16677 static uint32_t const s_aIOSizes[4] = { 1, 2, 0, 4 }; /* Size of the I/O accesses in bytes. */
16678 uint8_t const cbAccess = s_aIOSizes[uIOSize];
16679 if (CPUMIsGuestVmxIoInterceptSet(pVCpu, uIOPort, cbAccess))
16680 {
16681 /*
16682 * IN/OUT instruction:
16683 * - Provides VM-exit instruction length.
16684 *
16685 * INS/OUTS instruction:
16686 * - Provides VM-exit instruction length.
16687 * - Provides Guest-linear address.
16688 * - Optionally provides VM-exit instruction info (depends on CPU feature).
16689 */
16690 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
16691 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16692
16693 /* Make sure we don't use stale/uninitialized VMX-transient info. below. */
16694 pVmxTransient->ExitInstrInfo.u = 0;
16695 pVmxTransient->uGuestLinearAddr = 0;
16696
16697 bool const fVmxInsOutsInfo = pVM->cpum.ro.GuestFeatures.fVmxInsOutInfo;
16698 bool const fIOString = VMX_EXIT_QUAL_IO_IS_STRING(pVmxTransient->uExitQual);
16699 if (fIOString)
16700 {
16701 hmR0VmxReadGuestLinearAddrVmcs(pVmxTransient);
16702 if (fVmxInsOutsInfo)
16703 {
16704 Assert(RT_BF_GET(pVM->hm.s.vmx.Msrs.u64Basic, VMX_BF_BASIC_VMCS_INS_OUTS)); /* Paranoia. */
16705 hmR0VmxReadExitInstrInfoVmcs(pVmxTransient);
16706 }
16707 }
16708
16709 VMXVEXITINFO ExitInfo;
16710 RT_ZERO(ExitInfo);
16711 ExitInfo.uReason = pVmxTransient->uExitReason;
16712 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
16713 ExitInfo.u64Qual = pVmxTransient->uExitQual;
16714 ExitInfo.InstrInfo = pVmxTransient->ExitInstrInfo;
16715 ExitInfo.u64GuestLinearAddr = pVmxTransient->uGuestLinearAddr;
16716 return IEMExecVmxVmexitInstrWithInfo(pVCpu, &ExitInfo);
16717 }
16718 return hmR0VmxExitIoInstr(pVCpu, pVmxTransient);
16719}
16720
16721
16722/**
16723 * Nested-guest VM-exit handler for RDMSR (VMX_EXIT_RDMSR).
16724 */
16725HMVMX_EXIT_DECL hmR0VmxExitRdmsrNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16726{
16727 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16728
16729 uint32_t fMsrpm;
16730 if (CPUMIsGuestVmxProcCtlsSet(pVCpu, &pVCpu->cpum.GstCtx, VMX_PROC_CTLS_USE_MSR_BITMAPS))
16731 fMsrpm = CPUMGetVmxMsrPermission(pVCpu->cpum.GstCtx.hwvirt.vmx.CTX_SUFF(pvMsrBitmap), pVCpu->cpum.GstCtx.ecx);
16732 else
16733 fMsrpm = VMXMSRPM_EXIT_RD;
16734
16735 if (fMsrpm & VMXMSRPM_EXIT_RD)
16736 {
16737 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16738 return IEMExecVmxVmexitInstr(pVCpu, pVmxTransient->uExitReason, pVmxTransient->cbExitInstr);
16739 }
16740 return hmR0VmxExitRdmsr(pVCpu, pVmxTransient);
16741}
16742
16743
16744/**
16745 * Nested-guest VM-exit handler for WRMSR (VMX_EXIT_WRMSR).
16746 */
16747HMVMX_EXIT_DECL hmR0VmxExitWrmsrNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16748{
16749 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16750
16751 uint32_t fMsrpm;
16752 if (CPUMIsGuestVmxProcCtlsSet(pVCpu, &pVCpu->cpum.GstCtx, VMX_PROC_CTLS_USE_MSR_BITMAPS))
16753 fMsrpm = CPUMGetVmxMsrPermission(pVCpu->cpum.GstCtx.hwvirt.vmx.CTX_SUFF(pvMsrBitmap), pVCpu->cpum.GstCtx.ecx);
16754 else
16755 fMsrpm = VMXMSRPM_EXIT_WR;
16756
16757 if (fMsrpm & VMXMSRPM_EXIT_WR)
16758 {
16759 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16760 return IEMExecVmxVmexitInstr(pVCpu, pVmxTransient->uExitReason, pVmxTransient->cbExitInstr);
16761 }
16762 return hmR0VmxExitWrmsr(pVCpu, pVmxTransient);
16763}
16764
16765
16766/**
16767 * Nested-guest VM-exit handler for MWAIT (VMX_EXIT_MWAIT). Conditional VM-exit.
16768 */
16769HMVMX_EXIT_DECL hmR0VmxExitMwaitNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16770{
16771 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16772
16773 if (CPUMIsGuestVmxProcCtlsSet(pVCpu, &pVCpu->cpum.GstCtx, VMX_PROC_CTLS_MWAIT_EXIT))
16774 {
16775 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16776 return IEMExecVmxVmexitInstr(pVCpu, pVmxTransient->uExitReason, pVmxTransient->cbExitInstr);
16777 }
16778 return hmR0VmxExitMwait(pVCpu, pVmxTransient);
16779}
16780
16781
16782/**
16783 * Nested-guest VM-exit handler for monitor-trap-flag (VMX_EXIT_MTF). Conditional
16784 * VM-exit.
16785 */
16786HMVMX_EXIT_DECL hmR0VmxExitMtfNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16787{
16788 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16789
16790 /** @todo NSTVMX: Should consider debugging nested-guests using VM debugger. */
16791 hmR0VmxReadGuestPendingDbgXctps(pVmxTransient);
16792 VMXVEXITINFO ExitInfo;
16793 RT_ZERO(ExitInfo);
16794 ExitInfo.uReason = pVmxTransient->uExitReason;
16795 ExitInfo.u64GuestPendingDbgXcpts = pVmxTransient->uGuestPendingDbgXcpts;
16796 return IEMExecVmxVmexitTrapLike(pVCpu, &ExitInfo);
16797}
16798
16799
16800/**
16801 * Nested-guest VM-exit handler for MONITOR (VMX_EXIT_MONITOR). Conditional VM-exit.
16802 */
16803HMVMX_EXIT_DECL hmR0VmxExitMonitorNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16804{
16805 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16806
16807 if (CPUMIsGuestVmxProcCtlsSet(pVCpu, &pVCpu->cpum.GstCtx, VMX_PROC_CTLS_MONITOR_EXIT))
16808 {
16809 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16810 return IEMExecVmxVmexitInstr(pVCpu, pVmxTransient->uExitReason, pVmxTransient->cbExitInstr);
16811 }
16812 return hmR0VmxExitMonitor(pVCpu, pVmxTransient);
16813}
16814
16815
16816/**
16817 * Nested-guest VM-exit handler for PAUSE (VMX_EXIT_PAUSE). Conditional VM-exit.
16818 */
16819HMVMX_EXIT_DECL hmR0VmxExitPauseNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16820{
16821 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16822
16823 /** @todo NSTVMX: Think about this more. Does the outer guest need to intercept
16824 * PAUSE when executing a nested-guest? If it does not, we would not need
16825 * to check for the intercepts here. Just call VM-exit... */
16826
16827 /* The CPU would have already performed the necessary CPL checks for PAUSE-loop exiting. */
16828 if ( CPUMIsGuestVmxProcCtlsSet(pVCpu, &pVCpu->cpum.GstCtx, VMX_PROC_CTLS_PAUSE_EXIT)
16829 || CPUMIsGuestVmxProcCtls2Set(pVCpu, &pVCpu->cpum.GstCtx, VMX_PROC_CTLS2_PAUSE_LOOP_EXIT))
16830 {
16831 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16832 return IEMExecVmxVmexitInstr(pVCpu, pVmxTransient->uExitReason, pVmxTransient->cbExitInstr);
16833 }
16834 return hmR0VmxExitPause(pVCpu, pVmxTransient);
16835}
16836
16837
16838/**
16839 * Nested-guest VM-exit handler for when the TPR value is lowered below the
16840 * specified threshold (VMX_EXIT_TPR_BELOW_THRESHOLD). Conditional VM-exit.
16841 */
16842HMVMX_EXIT_NSRC_DECL hmR0VmxExitTprBelowThresholdNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16843{
16844 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16845
16846 if (CPUMIsGuestVmxProcCtlsSet(pVCpu, &pVCpu->cpum.GstCtx, VMX_PROC_CTLS_USE_TPR_SHADOW))
16847 {
16848 hmR0VmxReadGuestPendingDbgXctps(pVmxTransient);
16849 VMXVEXITINFO ExitInfo;
16850 RT_ZERO(ExitInfo);
16851 ExitInfo.uReason = pVmxTransient->uExitReason;
16852 ExitInfo.u64GuestPendingDbgXcpts = pVmxTransient->uGuestPendingDbgXcpts;
16853 return IEMExecVmxVmexitTrapLike(pVCpu, &ExitInfo);
16854 }
16855 return hmR0VmxExitTprBelowThreshold(pVCpu, pVmxTransient);
16856}
16857
16858
16859/**
16860 * Nested-guest VM-exit handler for APIC access (VMX_EXIT_APIC_ACCESS). Conditional
16861 * VM-exit.
16862 */
16863HMVMX_EXIT_DECL hmR0VmxExitApicAccessNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16864{
16865 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16866
16867 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16868 hmR0VmxReadIdtVectoringInfoVmcs(pVmxTransient);
16869 hmR0VmxReadIdtVectoringErrorCodeVmcs(pVmxTransient);
16870 hmR0VmxReadExitQualVmcs(pVmxTransient);
16871
16872 Assert(CPUMIsGuestVmxProcCtls2Set(pVCpu, &pVCpu->cpum.GstCtx, VMX_PROC_CTLS2_VIRT_APIC_ACCESS));
16873
16874 Log4Func(("at offset %#x type=%u\n", VMX_EXIT_QUAL_APIC_ACCESS_OFFSET(pVmxTransient->uExitQual),
16875 VMX_EXIT_QUAL_APIC_ACCESS_TYPE(pVmxTransient->uExitQual)));
16876
16877 VMXVEXITINFO ExitInfo;
16878 RT_ZERO(ExitInfo);
16879 ExitInfo.uReason = pVmxTransient->uExitReason;
16880 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
16881 ExitInfo.u64Qual = pVmxTransient->uExitQual;
16882
16883 VMXVEXITEVENTINFO ExitEventInfo;
16884 RT_ZERO(ExitEventInfo);
16885 ExitEventInfo.uIdtVectoringInfo = pVmxTransient->uIdtVectoringInfo;
16886 ExitEventInfo.uIdtVectoringErrCode = pVmxTransient->uIdtVectoringErrorCode;
16887 return IEMExecVmxVmexitApicAccess(pVCpu, &ExitInfo, &ExitEventInfo);
16888}
16889
16890
16891/**
16892 * Nested-guest VM-exit handler for APIC write emulation (VMX_EXIT_APIC_WRITE).
16893 * Conditional VM-exit.
16894 */
16895HMVMX_EXIT_DECL hmR0VmxExitApicWriteNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16896{
16897 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16898
16899 Assert(CPUMIsGuestVmxProcCtls2Set(pVCpu, &pVCpu->cpum.GstCtx, VMX_PROC_CTLS2_APIC_REG_VIRT));
16900 hmR0VmxReadExitQualVmcs(pVmxTransient);
16901 return IEMExecVmxVmexit(pVCpu, pVmxTransient->uExitReason, pVmxTransient->uExitQual);
16902}
16903
16904
16905/**
16906 * Nested-guest VM-exit handler for virtualized EOI (VMX_EXIT_VIRTUALIZED_EOI).
16907 * Conditional VM-exit.
16908 */
16909HMVMX_EXIT_DECL hmR0VmxExitVirtEoiNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16910{
16911 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16912
16913 Assert(CPUMIsGuestVmxProcCtls2Set(pVCpu, &pVCpu->cpum.GstCtx, VMX_PROC_CTLS2_VIRT_INT_DELIVERY));
16914 hmR0VmxReadExitQualVmcs(pVmxTransient);
16915 return IEMExecVmxVmexit(pVCpu, pVmxTransient->uExitReason, pVmxTransient->uExitQual);
16916}
16917
16918
16919/**
16920 * Nested-guest VM-exit handler for RDTSCP (VMX_EXIT_RDTSCP). Conditional VM-exit.
16921 */
16922HMVMX_EXIT_DECL hmR0VmxExitRdtscpNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16923{
16924 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16925
16926 if (CPUMIsGuestVmxProcCtlsSet(pVCpu, &pVCpu->cpum.GstCtx, VMX_PROC_CTLS_RDTSC_EXIT))
16927 {
16928 Assert(CPUMIsGuestVmxProcCtls2Set(pVCpu, &pVCpu->cpum.GstCtx, VMX_PROC_CTLS2_RDTSCP));
16929 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16930 return IEMExecVmxVmexitInstr(pVCpu, pVmxTransient->uExitReason, pVmxTransient->cbExitInstr);
16931 }
16932 return hmR0VmxExitRdtscp(pVCpu, pVmxTransient);
16933}
16934
16935
16936/**
16937 * Nested-guest VM-exit handler for WBINVD (VMX_EXIT_WBINVD). Conditional VM-exit.
16938 */
16939HMVMX_EXIT_NSRC_DECL hmR0VmxExitWbinvdNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16940{
16941 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16942
16943 if (CPUMIsGuestVmxProcCtls2Set(pVCpu, &pVCpu->cpum.GstCtx, VMX_PROC_CTLS2_WBINVD_EXIT))
16944 {
16945 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16946 return IEMExecVmxVmexitInstr(pVCpu, pVmxTransient->uExitReason, pVmxTransient->cbExitInstr);
16947 }
16948 return hmR0VmxExitWbinvd(pVCpu, pVmxTransient);
16949}
16950
16951
16952/**
16953 * Nested-guest VM-exit handler for INVPCID (VMX_EXIT_INVPCID). Conditional VM-exit.
16954 */
16955HMVMX_EXIT_DECL hmR0VmxExitInvpcidNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16956{
16957 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16958
16959 if (CPUMIsGuestVmxProcCtlsSet(pVCpu, &pVCpu->cpum.GstCtx, VMX_PROC_CTLS_INVLPG_EXIT))
16960 {
16961 Assert(CPUMIsGuestVmxProcCtls2Set(pVCpu, &pVCpu->cpum.GstCtx, VMX_PROC_CTLS2_INVPCID));
16962 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
16963 hmR0VmxReadExitQualVmcs(pVmxTransient);
16964 hmR0VmxReadExitInstrInfoVmcs(pVmxTransient);
16965
16966 VMXVEXITINFO ExitInfo;
16967 RT_ZERO(ExitInfo);
16968 ExitInfo.uReason = pVmxTransient->uExitReason;
16969 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
16970 ExitInfo.u64Qual = pVmxTransient->uExitQual;
16971 ExitInfo.InstrInfo = pVmxTransient->ExitInstrInfo;
16972 return IEMExecVmxVmexitInstrWithInfo(pVCpu, &ExitInfo);
16973 }
16974 return hmR0VmxExitInvpcid(pVCpu, pVmxTransient);
16975}
16976
16977
16978/**
16979 * Nested-guest VM-exit handler for invalid-guest state
16980 * (VMX_EXIT_ERR_INVALID_GUEST_STATE). Error VM-exit.
16981 */
16982HMVMX_EXIT_DECL hmR0VmxExitErrInvalidGuestStateNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
16983{
16984 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
16985
16986 /*
16987 * Currently this should never happen because we fully emulate VMLAUNCH/VMRESUME in IEM.
16988 * So if it does happen, it indicates a bug possibly in the hardware-assisted VMX code.
16989 * Handle it like it's in an invalid guest state of the outer guest.
16990 *
16991 * When the fast path is implemented, this should be changed to cause the corresponding
16992 * nested-guest VM-exit.
16993 */
16994 return hmR0VmxExitErrInvalidGuestState(pVCpu, pVmxTransient);
16995}
16996
16997
16998/**
16999 * Nested-guest VM-exit handler for instructions that cause VM-exits uncondtionally
17000 * and only provide the instruction length.
17001 *
17002 * Unconditional VM-exit.
17003 */
17004HMVMX_EXIT_DECL hmR0VmxExitInstrNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
17005{
17006 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
17007
17008#ifdef VBOX_STRICT
17009 PCCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
17010 switch (pVmxTransient->uExitReason)
17011 {
17012 case VMX_EXIT_ENCLS:
17013 Assert(CPUMIsGuestVmxProcCtls2Set(pVCpu, pCtx, VMX_PROC_CTLS2_ENCLS_EXIT));
17014 break;
17015
17016 case VMX_EXIT_VMFUNC:
17017 Assert(CPUMIsGuestVmxProcCtls2Set(pVCpu, pCtx, VMX_PROC_CTLS2_VMFUNC));
17018 break;
17019 }
17020#endif
17021
17022 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
17023 return IEMExecVmxVmexitInstr(pVCpu, pVmxTransient->uExitReason, pVmxTransient->cbExitInstr);
17024}
17025
17026
17027/**
17028 * Nested-guest VM-exit handler for instructions that provide instruction length as
17029 * well as more information.
17030 *
17031 * Unconditional VM-exit.
17032 */
17033HMVMX_EXIT_DECL hmR0VmxExitInstrWithInfoNested(PVMCPUCC pVCpu, PVMXTRANSIENT pVmxTransient)
17034{
17035 HMVMX_VALIDATE_NESTED_EXIT_HANDLER_PARAMS(pVCpu, pVmxTransient);
17036
17037#ifdef VBOX_STRICT
17038 PCCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
17039 switch (pVmxTransient->uExitReason)
17040 {
17041 case VMX_EXIT_GDTR_IDTR_ACCESS:
17042 case VMX_EXIT_LDTR_TR_ACCESS:
17043 Assert(CPUMIsGuestVmxProcCtls2Set(pVCpu, pCtx, VMX_PROC_CTLS2_DESC_TABLE_EXIT));
17044 break;
17045
17046 case VMX_EXIT_RDRAND:
17047 Assert(CPUMIsGuestVmxProcCtls2Set(pVCpu, pCtx, VMX_PROC_CTLS2_RDRAND_EXIT));
17048 break;
17049
17050 case VMX_EXIT_RDSEED:
17051 Assert(CPUMIsGuestVmxProcCtls2Set(pVCpu, pCtx, VMX_PROC_CTLS2_RDSEED_EXIT));
17052 break;
17053
17054 case VMX_EXIT_XSAVES:
17055 case VMX_EXIT_XRSTORS:
17056 /** @todo NSTVMX: Verify XSS-bitmap. */
17057 Assert(CPUMIsGuestVmxProcCtls2Set(pVCpu, pCtx, VMX_PROC_CTLS2_XSAVES_XRSTORS));
17058 break;
17059
17060 case VMX_EXIT_UMWAIT:
17061 case VMX_EXIT_TPAUSE:
17062 Assert(CPUMIsGuestVmxProcCtlsSet(pVCpu, pCtx, VMX_PROC_CTLS_RDTSC_EXIT));
17063 Assert(CPUMIsGuestVmxProcCtls2Set(pVCpu, pCtx, VMX_PROC_CTLS2_USER_WAIT_PAUSE));
17064 break;
17065 }
17066#endif
17067
17068 hmR0VmxReadExitInstrLenVmcs(pVmxTransient);
17069 hmR0VmxReadExitQualVmcs(pVmxTransient);
17070 hmR0VmxReadExitInstrInfoVmcs(pVmxTransient);
17071
17072 VMXVEXITINFO ExitInfo;
17073 RT_ZERO(ExitInfo);
17074 ExitInfo.uReason = pVmxTransient->uExitReason;
17075 ExitInfo.cbInstr = pVmxTransient->cbExitInstr;
17076 ExitInfo.u64Qual = pVmxTransient->uExitQual;
17077 ExitInfo.InstrInfo = pVmxTransient->ExitInstrInfo;
17078 return IEMExecVmxVmexitInstrWithInfo(pVCpu, &ExitInfo);
17079}
17080
17081/** @} */
17082#endif /* VBOX_WITH_NESTED_HWVIRT_VMX */
17083
Note: See TracBrowser for help on using the repository browser.

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