VirtualBox

source: vbox/trunk/src/VBox/VMM/VMMAll/NEMAllNativeTemplate-win.cpp.h@ 91815

最後變更 在這個檔案從91815是 91702,由 vboxsync 提交於 3 年 前

VMM/NEM: More stats. Played with using WHvMapGpaRange again, but much too slow to use on a per-page basis. bugref:10118

  • 屬性 svn:eol-style 設為 native
  • 屬性 svn:keywords 設為 Author Date Id Revision
檔案大小: 236.7 KB
 
1/* $Id: NEMAllNativeTemplate-win.cpp.h 91702 2021-10-12 21:15:19Z vboxsync $ */
2/** @file
3 * NEM - Native execution manager, Windows code template ring-0/3.
4 */
5
6/*
7 * Copyright (C) 2018-2020 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.alldomusa.eu.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* Defined Constants And Macros *
21*********************************************************************************************************************************/
22/** Copy back a segment from hyper-V. */
23#define NEM_WIN_COPY_BACK_SEG(a_Dst, a_Src) \
24 do { \
25 (a_Dst).u64Base = (a_Src).Base; \
26 (a_Dst).u32Limit = (a_Src).Limit; \
27 (a_Dst).ValidSel = (a_Dst).Sel = (a_Src).Selector; \
28 (a_Dst).Attr.u = (a_Src).Attributes; \
29 (a_Dst).fFlags = CPUMSELREG_FLAGS_VALID; \
30 } while (0)
31
32/** @def NEMWIN_ASSERT_MSG_REG_VAL
33 * Asserts the correctness of a register value in a message/context.
34 */
35#if 0
36# define NEMWIN_NEED_GET_REGISTER
37# if defined(IN_RING0) || defined(NEM_WIN_USE_HYPERCALLS_FOR_REGISTERS)
38# define NEMWIN_ASSERT_MSG_REG_VAL(a_pVCpu, a_enmReg, a_Expr, a_Msg) \
39 do { \
40 HV_REGISTER_VALUE TmpVal; \
41 nemHCWinGetRegister(a_pVCpu, a_enmReg, &TmpVal); \
42 AssertMsg(a_Expr, a_Msg); \
43 } while (0)
44# else
45# define NEMWIN_ASSERT_MSG_REG_VAL(a_pVCpu, a_enmReg, a_Expr, a_Msg) \
46 do { \
47 WHV_REGISTER_VALUE TmpVal; \
48 nemR3WinGetRegister(a_pVCpu, a_enmReg, &TmpVal); \
49 AssertMsg(a_Expr, a_Msg); \
50 } while (0)
51# endif
52#else
53# define NEMWIN_ASSERT_MSG_REG_VAL(a_pVCpu, a_enmReg, a_Expr, a_Msg) do { } while (0)
54#endif
55
56/** @def NEMWIN_ASSERT_MSG_REG_VAL
57 * Asserts the correctness of a 64-bit register value in a message/context.
58 */
59#define NEMWIN_ASSERT_MSG_REG_VAL64(a_pVCpu, a_enmReg, a_u64Val) \
60 NEMWIN_ASSERT_MSG_REG_VAL(a_pVCpu, a_enmReg, (a_u64Val) == TmpVal.Reg64, \
61 (#a_u64Val "=%#RX64, expected %#RX64\n", (a_u64Val), TmpVal.Reg64))
62/** @def NEMWIN_ASSERT_MSG_REG_VAL
63 * Asserts the correctness of a segment register value in a message/context.
64 */
65#define NEMWIN_ASSERT_MSG_REG_SEG(a_pVCpu, a_enmReg, a_SReg) \
66 NEMWIN_ASSERT_MSG_REG_VAL(a_pVCpu, a_enmReg, \
67 (a_SReg).Base == TmpVal.Segment.Base \
68 && (a_SReg).Limit == TmpVal.Segment.Limit \
69 && (a_SReg).Selector == TmpVal.Segment.Selector \
70 && (a_SReg).Attributes == TmpVal.Segment.Attributes, \
71 ( #a_SReg "=%#RX16 {%#RX64 LB %#RX32,%#RX16} expected %#RX16 {%#RX64 LB %#RX32,%#RX16}\n", \
72 (a_SReg).Selector, (a_SReg).Base, (a_SReg).Limit, (a_SReg).Attributes, \
73 TmpVal.Segment.Selector, TmpVal.Segment.Base, TmpVal.Segment.Limit, TmpVal.Segment.Attributes))
74
75
76/*********************************************************************************************************************************
77* Global Variables *
78*********************************************************************************************************************************/
79/** NEM_WIN_PAGE_STATE_XXX names. */
80NEM_TMPL_STATIC const char * const g_apszPageStates[4] = { "not-set", "unmapped", "readable", "writable" };
81
82/** HV_INTERCEPT_ACCESS_TYPE names. */
83static const char * const g_apszHvInterceptAccessTypes[4] = { "read", "write", "exec", "!undefined!" };
84
85
86/*********************************************************************************************************************************
87* Internal Functions *
88*********************************************************************************************************************************/
89NEM_TMPL_STATIC int nemHCNativeSetPhysPage(PVMCC pVM, PVMCPUCC pVCpu, RTGCPHYS GCPhysSrc, RTGCPHYS GCPhysDst,
90 uint32_t fPageProt, uint8_t *pu2State, bool fBackingChanged);
91
92
93
94#ifdef NEM_WIN_USE_HYPERCALLS_FOR_PAGES
95
96/**
97 * Wrapper around VMMR0_DO_NEM_MAP_PAGES for a single page.
98 *
99 * @returns VBox status code.
100 * @param pVM The cross context VM structure.
101 * @param pVCpu The cross context virtual CPU structure of the caller.
102 * @param GCPhysSrc The source page. Does not need to be page aligned.
103 * @param GCPhysDst The destination page. Same as @a GCPhysSrc except for
104 * when A20 is disabled.
105 * @param fFlags HV_MAP_GPA_XXX.
106 */
107DECLINLINE(int) nemHCWinHypercallMapPage(PVMCC pVM, PVMCPUCC pVCpu, RTGCPHYS GCPhysSrc, RTGCPHYS GCPhysDst, uint32_t fFlags)
108{
109#ifdef IN_RING0
110 /** @todo optimize further, caller generally has the physical address. */
111 return nemR0WinMapPages(pVM, pVCpu,
112 GCPhysSrc & ~(RTGCPHYS)X86_PAGE_OFFSET_MASK,
113 GCPhysDst & ~(RTGCPHYS)X86_PAGE_OFFSET_MASK,
114 1, fFlags);
115#else
116 pVCpu->nem.s.Hypercall.MapPages.GCPhysSrc = GCPhysSrc & ~(RTGCPHYS)X86_PAGE_OFFSET_MASK;
117 pVCpu->nem.s.Hypercall.MapPages.GCPhysDst = GCPhysDst & ~(RTGCPHYS)X86_PAGE_OFFSET_MASK;
118 pVCpu->nem.s.Hypercall.MapPages.cPages = 1;
119 pVCpu->nem.s.Hypercall.MapPages.fFlags = fFlags;
120 return VMMR3CallR0Emt(pVM, pVCpu, VMMR0_DO_NEM_MAP_PAGES, 0, NULL);
121#endif
122}
123
124
125/**
126 * Wrapper around VMMR0_DO_NEM_UNMAP_PAGES for a single page.
127 *
128 * @returns VBox status code.
129 * @param pVM The cross context VM structure.
130 * @param pVCpu The cross context virtual CPU structure of the caller.
131 * @param GCPhys The page to unmap. Does not need to be page aligned.
132 */
133DECLINLINE(int) nemHCWinHypercallUnmapPage(PVMCC pVM, PVMCPUCC pVCpu, RTGCPHYS GCPhys)
134{
135# ifdef IN_RING0
136 return nemR0WinUnmapPages(pVM, pVCpu, GCPhys & ~(RTGCPHYS)X86_PAGE_OFFSET_MASK, 1);
137# else
138 pVCpu->nem.s.Hypercall.UnmapPages.GCPhys = GCPhys & ~(RTGCPHYS)X86_PAGE_OFFSET_MASK;
139 pVCpu->nem.s.Hypercall.UnmapPages.cPages = 1;
140 return VMMR3CallR0Emt(pVM, pVCpu, VMMR0_DO_NEM_UNMAP_PAGES, 0, NULL);
141# endif
142}
143
144#endif /* NEM_WIN_USE_HYPERCALLS_FOR_PAGES */
145#ifndef IN_RING0
146
147NEM_TMPL_STATIC int nemHCWinCopyStateToHyperV(PVMCC pVM, PVMCPUCC pVCpu)
148{
149# if defined(NEM_WIN_USE_HYPERCALLS_FOR_REGISTERS) || defined(NEM_WIN_WITH_RING0_RUNLOOP)
150# if !defined(NEM_WIN_USE_HYPERCALLS_FOR_REGISTERS) && defined(NEM_WIN_WITH_RING0_RUNLOOP)
151 if (pVM->nem.s.fUseRing0Runloop)
152# endif
153 {
154 int rc = VMMR3CallR0Emt(pVM, pVCpu, VMMR0_DO_NEM_EXPORT_STATE, 0, NULL);
155 AssertLogRelRCReturn(rc, rc);
156 return rc;
157 }
158# endif
159# ifndef NEM_WIN_USE_HYPERCALLS_FOR_REGISTERS
160
161 /*
162 * The following is very similar to what nemR0WinExportState() does.
163 */
164 WHV_REGISTER_NAME aenmNames[128];
165 WHV_REGISTER_VALUE aValues[128];
166
167 uint64_t const fWhat = ~pVCpu->cpum.GstCtx.fExtrn & (CPUMCTX_EXTRN_ALL | CPUMCTX_EXTRN_NEM_WIN_MASK);
168 if ( !fWhat
169 && pVCpu->nem.s.fCurrentInterruptWindows == pVCpu->nem.s.fDesiredInterruptWindows)
170 return VINF_SUCCESS;
171 uintptr_t iReg = 0;
172
173# define ADD_REG64(a_enmName, a_uValue) do { \
174 aenmNames[iReg] = (a_enmName); \
175 aValues[iReg].Reg128.High64 = 0; \
176 aValues[iReg].Reg64 = (a_uValue); \
177 iReg++; \
178 } while (0)
179# define ADD_REG128(a_enmName, a_uValueLo, a_uValueHi) do { \
180 aenmNames[iReg] = (a_enmName); \
181 aValues[iReg].Reg128.Low64 = (a_uValueLo); \
182 aValues[iReg].Reg128.High64 = (a_uValueHi); \
183 iReg++; \
184 } while (0)
185
186 /* GPRs */
187 if (fWhat & CPUMCTX_EXTRN_GPRS_MASK)
188 {
189 if (fWhat & CPUMCTX_EXTRN_RAX)
190 ADD_REG64(WHvX64RegisterRax, pVCpu->cpum.GstCtx.rax);
191 if (fWhat & CPUMCTX_EXTRN_RCX)
192 ADD_REG64(WHvX64RegisterRcx, pVCpu->cpum.GstCtx.rcx);
193 if (fWhat & CPUMCTX_EXTRN_RDX)
194 ADD_REG64(WHvX64RegisterRdx, pVCpu->cpum.GstCtx.rdx);
195 if (fWhat & CPUMCTX_EXTRN_RBX)
196 ADD_REG64(WHvX64RegisterRbx, pVCpu->cpum.GstCtx.rbx);
197 if (fWhat & CPUMCTX_EXTRN_RSP)
198 ADD_REG64(WHvX64RegisterRsp, pVCpu->cpum.GstCtx.rsp);
199 if (fWhat & CPUMCTX_EXTRN_RBP)
200 ADD_REG64(WHvX64RegisterRbp, pVCpu->cpum.GstCtx.rbp);
201 if (fWhat & CPUMCTX_EXTRN_RSI)
202 ADD_REG64(WHvX64RegisterRsi, pVCpu->cpum.GstCtx.rsi);
203 if (fWhat & CPUMCTX_EXTRN_RDI)
204 ADD_REG64(WHvX64RegisterRdi, pVCpu->cpum.GstCtx.rdi);
205 if (fWhat & CPUMCTX_EXTRN_R8_R15)
206 {
207 ADD_REG64(WHvX64RegisterR8, pVCpu->cpum.GstCtx.r8);
208 ADD_REG64(WHvX64RegisterR9, pVCpu->cpum.GstCtx.r9);
209 ADD_REG64(WHvX64RegisterR10, pVCpu->cpum.GstCtx.r10);
210 ADD_REG64(WHvX64RegisterR11, pVCpu->cpum.GstCtx.r11);
211 ADD_REG64(WHvX64RegisterR12, pVCpu->cpum.GstCtx.r12);
212 ADD_REG64(WHvX64RegisterR13, pVCpu->cpum.GstCtx.r13);
213 ADD_REG64(WHvX64RegisterR14, pVCpu->cpum.GstCtx.r14);
214 ADD_REG64(WHvX64RegisterR15, pVCpu->cpum.GstCtx.r15);
215 }
216 }
217
218 /* RIP & Flags */
219 if (fWhat & CPUMCTX_EXTRN_RIP)
220 ADD_REG64(WHvX64RegisterRip, pVCpu->cpum.GstCtx.rip);
221 if (fWhat & CPUMCTX_EXTRN_RFLAGS)
222 ADD_REG64(WHvX64RegisterRflags, pVCpu->cpum.GstCtx.rflags.u);
223
224 /* Segments */
225# define ADD_SEG(a_enmName, a_SReg) \
226 do { \
227 aenmNames[iReg] = a_enmName; \
228 aValues[iReg].Segment.Base = (a_SReg).u64Base; \
229 aValues[iReg].Segment.Limit = (a_SReg).u32Limit; \
230 aValues[iReg].Segment.Selector = (a_SReg).Sel; \
231 aValues[iReg].Segment.Attributes = (a_SReg).Attr.u; \
232 iReg++; \
233 } while (0)
234 if (fWhat & CPUMCTX_EXTRN_SREG_MASK)
235 {
236 if (fWhat & CPUMCTX_EXTRN_ES)
237 ADD_SEG(WHvX64RegisterEs, pVCpu->cpum.GstCtx.es);
238 if (fWhat & CPUMCTX_EXTRN_CS)
239 ADD_SEG(WHvX64RegisterCs, pVCpu->cpum.GstCtx.cs);
240 if (fWhat & CPUMCTX_EXTRN_SS)
241 ADD_SEG(WHvX64RegisterSs, pVCpu->cpum.GstCtx.ss);
242 if (fWhat & CPUMCTX_EXTRN_DS)
243 ADD_SEG(WHvX64RegisterDs, pVCpu->cpum.GstCtx.ds);
244 if (fWhat & CPUMCTX_EXTRN_FS)
245 ADD_SEG(WHvX64RegisterFs, pVCpu->cpum.GstCtx.fs);
246 if (fWhat & CPUMCTX_EXTRN_GS)
247 ADD_SEG(WHvX64RegisterGs, pVCpu->cpum.GstCtx.gs);
248 }
249
250 /* Descriptor tables & task segment. */
251 if (fWhat & CPUMCTX_EXTRN_TABLE_MASK)
252 {
253 if (fWhat & CPUMCTX_EXTRN_LDTR)
254 ADD_SEG(WHvX64RegisterLdtr, pVCpu->cpum.GstCtx.ldtr);
255 if (fWhat & CPUMCTX_EXTRN_TR)
256 ADD_SEG(WHvX64RegisterTr, pVCpu->cpum.GstCtx.tr);
257 if (fWhat & CPUMCTX_EXTRN_IDTR)
258 {
259 aenmNames[iReg] = WHvX64RegisterIdtr;
260 aValues[iReg].Table.Limit = pVCpu->cpum.GstCtx.idtr.cbIdt;
261 aValues[iReg].Table.Base = pVCpu->cpum.GstCtx.idtr.pIdt;
262 iReg++;
263 }
264 if (fWhat & CPUMCTX_EXTRN_GDTR)
265 {
266 aenmNames[iReg] = WHvX64RegisterGdtr;
267 aValues[iReg].Table.Limit = pVCpu->cpum.GstCtx.gdtr.cbGdt;
268 aValues[iReg].Table.Base = pVCpu->cpum.GstCtx.gdtr.pGdt;
269 iReg++;
270 }
271 }
272
273 /* Control registers. */
274 if (fWhat & CPUMCTX_EXTRN_CR_MASK)
275 {
276 if (fWhat & CPUMCTX_EXTRN_CR0)
277 ADD_REG64(WHvX64RegisterCr0, pVCpu->cpum.GstCtx.cr0);
278 if (fWhat & CPUMCTX_EXTRN_CR2)
279 ADD_REG64(WHvX64RegisterCr2, pVCpu->cpum.GstCtx.cr2);
280 if (fWhat & CPUMCTX_EXTRN_CR3)
281 ADD_REG64(WHvX64RegisterCr3, pVCpu->cpum.GstCtx.cr3);
282 if (fWhat & CPUMCTX_EXTRN_CR4)
283 ADD_REG64(WHvX64RegisterCr4, pVCpu->cpum.GstCtx.cr4);
284 }
285 if (fWhat & CPUMCTX_EXTRN_APIC_TPR)
286 ADD_REG64(WHvX64RegisterCr8, CPUMGetGuestCR8(pVCpu));
287
288 /* Debug registers. */
289/** @todo fixme. Figure out what the hyper-v version of KVM_SET_GUEST_DEBUG would be. */
290 if (fWhat & CPUMCTX_EXTRN_DR0_DR3)
291 {
292 ADD_REG64(WHvX64RegisterDr0, pVCpu->cpum.GstCtx.dr[0]); // CPUMGetHyperDR0(pVCpu));
293 ADD_REG64(WHvX64RegisterDr1, pVCpu->cpum.GstCtx.dr[1]); // CPUMGetHyperDR1(pVCpu));
294 ADD_REG64(WHvX64RegisterDr2, pVCpu->cpum.GstCtx.dr[2]); // CPUMGetHyperDR2(pVCpu));
295 ADD_REG64(WHvX64RegisterDr3, pVCpu->cpum.GstCtx.dr[3]); // CPUMGetHyperDR3(pVCpu));
296 }
297 if (fWhat & CPUMCTX_EXTRN_DR6)
298 ADD_REG64(WHvX64RegisterDr6, pVCpu->cpum.GstCtx.dr[6]); // CPUMGetHyperDR6(pVCpu));
299 if (fWhat & CPUMCTX_EXTRN_DR7)
300 ADD_REG64(WHvX64RegisterDr7, pVCpu->cpum.GstCtx.dr[7]); // CPUMGetHyperDR7(pVCpu));
301
302 /* Floating point state. */
303 if (fWhat & CPUMCTX_EXTRN_X87)
304 {
305 ADD_REG128(WHvX64RegisterFpMmx0, pVCpu->cpum.GstCtx.XState.x87.aRegs[0].au64[0], pVCpu->cpum.GstCtx.XState.x87.aRegs[0].au64[1]);
306 ADD_REG128(WHvX64RegisterFpMmx1, pVCpu->cpum.GstCtx.XState.x87.aRegs[1].au64[0], pVCpu->cpum.GstCtx.XState.x87.aRegs[1].au64[1]);
307 ADD_REG128(WHvX64RegisterFpMmx2, pVCpu->cpum.GstCtx.XState.x87.aRegs[2].au64[0], pVCpu->cpum.GstCtx.XState.x87.aRegs[2].au64[1]);
308 ADD_REG128(WHvX64RegisterFpMmx3, pVCpu->cpum.GstCtx.XState.x87.aRegs[3].au64[0], pVCpu->cpum.GstCtx.XState.x87.aRegs[3].au64[1]);
309 ADD_REG128(WHvX64RegisterFpMmx4, pVCpu->cpum.GstCtx.XState.x87.aRegs[4].au64[0], pVCpu->cpum.GstCtx.XState.x87.aRegs[4].au64[1]);
310 ADD_REG128(WHvX64RegisterFpMmx5, pVCpu->cpum.GstCtx.XState.x87.aRegs[5].au64[0], pVCpu->cpum.GstCtx.XState.x87.aRegs[5].au64[1]);
311 ADD_REG128(WHvX64RegisterFpMmx6, pVCpu->cpum.GstCtx.XState.x87.aRegs[6].au64[0], pVCpu->cpum.GstCtx.XState.x87.aRegs[6].au64[1]);
312 ADD_REG128(WHvX64RegisterFpMmx7, pVCpu->cpum.GstCtx.XState.x87.aRegs[7].au64[0], pVCpu->cpum.GstCtx.XState.x87.aRegs[7].au64[1]);
313
314 aenmNames[iReg] = WHvX64RegisterFpControlStatus;
315 aValues[iReg].FpControlStatus.FpControl = pVCpu->cpum.GstCtx.XState.x87.FCW;
316 aValues[iReg].FpControlStatus.FpStatus = pVCpu->cpum.GstCtx.XState.x87.FSW;
317 aValues[iReg].FpControlStatus.FpTag = pVCpu->cpum.GstCtx.XState.x87.FTW;
318 aValues[iReg].FpControlStatus.Reserved = pVCpu->cpum.GstCtx.XState.x87.FTW >> 8;
319 aValues[iReg].FpControlStatus.LastFpOp = pVCpu->cpum.GstCtx.XState.x87.FOP;
320 aValues[iReg].FpControlStatus.LastFpRip = (pVCpu->cpum.GstCtx.XState.x87.FPUIP)
321 | ((uint64_t)pVCpu->cpum.GstCtx.XState.x87.CS << 32)
322 | ((uint64_t)pVCpu->cpum.GstCtx.XState.x87.Rsrvd1 << 48);
323 iReg++;
324
325 aenmNames[iReg] = WHvX64RegisterXmmControlStatus;
326 aValues[iReg].XmmControlStatus.LastFpRdp = (pVCpu->cpum.GstCtx.XState.x87.FPUDP)
327 | ((uint64_t)pVCpu->cpum.GstCtx.XState.x87.DS << 32)
328 | ((uint64_t)pVCpu->cpum.GstCtx.XState.x87.Rsrvd2 << 48);
329 aValues[iReg].XmmControlStatus.XmmStatusControl = pVCpu->cpum.GstCtx.XState.x87.MXCSR;
330 aValues[iReg].XmmControlStatus.XmmStatusControlMask = pVCpu->cpum.GstCtx.XState.x87.MXCSR_MASK; /** @todo ??? (Isn't this an output field?) */
331 iReg++;
332 }
333
334 /* Vector state. */
335 if (fWhat & CPUMCTX_EXTRN_SSE_AVX)
336 {
337 ADD_REG128(WHvX64RegisterXmm0, pVCpu->cpum.GstCtx.XState.x87.aXMM[ 0].uXmm.s.Lo, pVCpu->cpum.GstCtx.XState.x87.aXMM[ 0].uXmm.s.Hi);
338 ADD_REG128(WHvX64RegisterXmm1, pVCpu->cpum.GstCtx.XState.x87.aXMM[ 1].uXmm.s.Lo, pVCpu->cpum.GstCtx.XState.x87.aXMM[ 1].uXmm.s.Hi);
339 ADD_REG128(WHvX64RegisterXmm2, pVCpu->cpum.GstCtx.XState.x87.aXMM[ 2].uXmm.s.Lo, pVCpu->cpum.GstCtx.XState.x87.aXMM[ 2].uXmm.s.Hi);
340 ADD_REG128(WHvX64RegisterXmm3, pVCpu->cpum.GstCtx.XState.x87.aXMM[ 3].uXmm.s.Lo, pVCpu->cpum.GstCtx.XState.x87.aXMM[ 3].uXmm.s.Hi);
341 ADD_REG128(WHvX64RegisterXmm4, pVCpu->cpum.GstCtx.XState.x87.aXMM[ 4].uXmm.s.Lo, pVCpu->cpum.GstCtx.XState.x87.aXMM[ 4].uXmm.s.Hi);
342 ADD_REG128(WHvX64RegisterXmm5, pVCpu->cpum.GstCtx.XState.x87.aXMM[ 5].uXmm.s.Lo, pVCpu->cpum.GstCtx.XState.x87.aXMM[ 5].uXmm.s.Hi);
343 ADD_REG128(WHvX64RegisterXmm6, pVCpu->cpum.GstCtx.XState.x87.aXMM[ 6].uXmm.s.Lo, pVCpu->cpum.GstCtx.XState.x87.aXMM[ 6].uXmm.s.Hi);
344 ADD_REG128(WHvX64RegisterXmm7, pVCpu->cpum.GstCtx.XState.x87.aXMM[ 7].uXmm.s.Lo, pVCpu->cpum.GstCtx.XState.x87.aXMM[ 7].uXmm.s.Hi);
345 ADD_REG128(WHvX64RegisterXmm8, pVCpu->cpum.GstCtx.XState.x87.aXMM[ 8].uXmm.s.Lo, pVCpu->cpum.GstCtx.XState.x87.aXMM[ 8].uXmm.s.Hi);
346 ADD_REG128(WHvX64RegisterXmm9, pVCpu->cpum.GstCtx.XState.x87.aXMM[ 9].uXmm.s.Lo, pVCpu->cpum.GstCtx.XState.x87.aXMM[ 9].uXmm.s.Hi);
347 ADD_REG128(WHvX64RegisterXmm10, pVCpu->cpum.GstCtx.XState.x87.aXMM[10].uXmm.s.Lo, pVCpu->cpum.GstCtx.XState.x87.aXMM[10].uXmm.s.Hi);
348 ADD_REG128(WHvX64RegisterXmm11, pVCpu->cpum.GstCtx.XState.x87.aXMM[11].uXmm.s.Lo, pVCpu->cpum.GstCtx.XState.x87.aXMM[11].uXmm.s.Hi);
349 ADD_REG128(WHvX64RegisterXmm12, pVCpu->cpum.GstCtx.XState.x87.aXMM[12].uXmm.s.Lo, pVCpu->cpum.GstCtx.XState.x87.aXMM[12].uXmm.s.Hi);
350 ADD_REG128(WHvX64RegisterXmm13, pVCpu->cpum.GstCtx.XState.x87.aXMM[13].uXmm.s.Lo, pVCpu->cpum.GstCtx.XState.x87.aXMM[13].uXmm.s.Hi);
351 ADD_REG128(WHvX64RegisterXmm14, pVCpu->cpum.GstCtx.XState.x87.aXMM[14].uXmm.s.Lo, pVCpu->cpum.GstCtx.XState.x87.aXMM[14].uXmm.s.Hi);
352 ADD_REG128(WHvX64RegisterXmm15, pVCpu->cpum.GstCtx.XState.x87.aXMM[15].uXmm.s.Lo, pVCpu->cpum.GstCtx.XState.x87.aXMM[15].uXmm.s.Hi);
353 }
354
355 /* MSRs */
356 // WHvX64RegisterTsc - don't touch
357 if (fWhat & CPUMCTX_EXTRN_EFER)
358 ADD_REG64(WHvX64RegisterEfer, pVCpu->cpum.GstCtx.msrEFER);
359 if (fWhat & CPUMCTX_EXTRN_KERNEL_GS_BASE)
360 ADD_REG64(WHvX64RegisterKernelGsBase, pVCpu->cpum.GstCtx.msrKERNELGSBASE);
361 if (fWhat & CPUMCTX_EXTRN_SYSENTER_MSRS)
362 {
363 ADD_REG64(WHvX64RegisterSysenterCs, pVCpu->cpum.GstCtx.SysEnter.cs);
364 ADD_REG64(WHvX64RegisterSysenterEip, pVCpu->cpum.GstCtx.SysEnter.eip);
365 ADD_REG64(WHvX64RegisterSysenterEsp, pVCpu->cpum.GstCtx.SysEnter.esp);
366 }
367 if (fWhat & CPUMCTX_EXTRN_SYSCALL_MSRS)
368 {
369 ADD_REG64(WHvX64RegisterStar, pVCpu->cpum.GstCtx.msrSTAR);
370 ADD_REG64(WHvX64RegisterLstar, pVCpu->cpum.GstCtx.msrLSTAR);
371 ADD_REG64(WHvX64RegisterCstar, pVCpu->cpum.GstCtx.msrCSTAR);
372 ADD_REG64(WHvX64RegisterSfmask, pVCpu->cpum.GstCtx.msrSFMASK);
373 }
374 if (fWhat & CPUMCTX_EXTRN_OTHER_MSRS)
375 {
376 ADD_REG64(WHvX64RegisterApicBase, APICGetBaseMsrNoCheck(pVCpu));
377 ADD_REG64(WHvX64RegisterPat, pVCpu->cpum.GstCtx.msrPAT);
378#if 0 /** @todo check if WHvX64RegisterMsrMtrrCap works here... */
379 ADD_REG64(WHvX64RegisterMsrMtrrCap, CPUMGetGuestIa32MtrrCap(pVCpu));
380#endif
381 PCPUMCTXMSRS pCtxMsrs = CPUMQueryGuestCtxMsrsPtr(pVCpu);
382 ADD_REG64(WHvX64RegisterMsrMtrrDefType, pCtxMsrs->msr.MtrrDefType);
383 ADD_REG64(WHvX64RegisterMsrMtrrFix64k00000, pCtxMsrs->msr.MtrrFix64K_00000);
384 ADD_REG64(WHvX64RegisterMsrMtrrFix16k80000, pCtxMsrs->msr.MtrrFix16K_80000);
385 ADD_REG64(WHvX64RegisterMsrMtrrFix16kA0000, pCtxMsrs->msr.MtrrFix16K_A0000);
386 ADD_REG64(WHvX64RegisterMsrMtrrFix4kC0000, pCtxMsrs->msr.MtrrFix4K_C0000);
387 ADD_REG64(WHvX64RegisterMsrMtrrFix4kC8000, pCtxMsrs->msr.MtrrFix4K_C8000);
388 ADD_REG64(WHvX64RegisterMsrMtrrFix4kD0000, pCtxMsrs->msr.MtrrFix4K_D0000);
389 ADD_REG64(WHvX64RegisterMsrMtrrFix4kD8000, pCtxMsrs->msr.MtrrFix4K_D8000);
390 ADD_REG64(WHvX64RegisterMsrMtrrFix4kE0000, pCtxMsrs->msr.MtrrFix4K_E0000);
391 ADD_REG64(WHvX64RegisterMsrMtrrFix4kE8000, pCtxMsrs->msr.MtrrFix4K_E8000);
392 ADD_REG64(WHvX64RegisterMsrMtrrFix4kF0000, pCtxMsrs->msr.MtrrFix4K_F0000);
393 ADD_REG64(WHvX64RegisterMsrMtrrFix4kF8000, pCtxMsrs->msr.MtrrFix4K_F8000);
394 ADD_REG64(WHvX64RegisterTscAux, pCtxMsrs->msr.TscAux);
395#if 0 /** @todo these registers aren't available? Might explain something.. .*/
396 const CPUMCPUVENDOR enmCpuVendor = CPUMGetHostCpuVendor(pVM);
397 if (enmCpuVendor != CPUMCPUVENDOR_AMD)
398 {
399 ADD_REG64(HvX64RegisterIa32MiscEnable, pCtxMsrs->msr.MiscEnable);
400 ADD_REG64(HvX64RegisterIa32FeatureControl, CPUMGetGuestIa32FeatureControl(pVCpu));
401 }
402#endif
403 }
404
405 /* event injection (clear it). */
406 if (fWhat & CPUMCTX_EXTRN_NEM_WIN_EVENT_INJECT)
407 ADD_REG64(WHvRegisterPendingInterruption, 0);
408
409 /* Interruptibility state. This can get a little complicated since we get
410 half of the state via HV_X64_VP_EXECUTION_STATE. */
411 if ( (fWhat & (CPUMCTX_EXTRN_NEM_WIN_INHIBIT_INT | CPUMCTX_EXTRN_NEM_WIN_INHIBIT_NMI))
412 == (CPUMCTX_EXTRN_NEM_WIN_INHIBIT_INT | CPUMCTX_EXTRN_NEM_WIN_INHIBIT_NMI) )
413 {
414 ADD_REG64(WHvRegisterInterruptState, 0);
415 if ( VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS)
416 && EMGetInhibitInterruptsPC(pVCpu) == pVCpu->cpum.GstCtx.rip)
417 aValues[iReg - 1].InterruptState.InterruptShadow = 1;
418 if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_BLOCK_NMIS))
419 aValues[iReg - 1].InterruptState.NmiMasked = 1;
420 }
421 else if (fWhat & CPUMCTX_EXTRN_NEM_WIN_INHIBIT_INT)
422 {
423 if ( pVCpu->nem.s.fLastInterruptShadow
424 || ( VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS)
425 && EMGetInhibitInterruptsPC(pVCpu) == pVCpu->cpum.GstCtx.rip))
426 {
427 ADD_REG64(WHvRegisterInterruptState, 0);
428 if ( VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS)
429 && EMGetInhibitInterruptsPC(pVCpu) == pVCpu->cpum.GstCtx.rip)
430 aValues[iReg - 1].InterruptState.InterruptShadow = 1;
431 /** @todo Retrieve NMI state, currently assuming it's zero. (yes this may happen on I/O) */
432 //if (VMCPU_FF_IS_ANY_SET(pVCpu, VMCPU_FF_BLOCK_NMIS))
433 // aValues[iReg - 1].InterruptState.NmiMasked = 1;
434 }
435 }
436 else
437 Assert(!(fWhat & CPUMCTX_EXTRN_NEM_WIN_INHIBIT_NMI));
438
439 /* Interrupt windows. Always set if active as Hyper-V seems to be forgetful. */
440 uint8_t const fDesiredIntWin = pVCpu->nem.s.fDesiredInterruptWindows;
441 if ( fDesiredIntWin
442 || pVCpu->nem.s.fCurrentInterruptWindows != fDesiredIntWin)
443 {
444 pVCpu->nem.s.fCurrentInterruptWindows = pVCpu->nem.s.fDesiredInterruptWindows;
445 Log8(("Setting WHvX64RegisterDeliverabilityNotifications, fDesiredIntWin=%X\n", fDesiredIntWin));
446 ADD_REG64(WHvX64RegisterDeliverabilityNotifications, fDesiredIntWin);
447 Assert(aValues[iReg - 1].DeliverabilityNotifications.NmiNotification == RT_BOOL(fDesiredIntWin & NEM_WIN_INTW_F_NMI));
448 Assert(aValues[iReg - 1].DeliverabilityNotifications.InterruptNotification == RT_BOOL(fDesiredIntWin & NEM_WIN_INTW_F_REGULAR));
449 Assert(aValues[iReg - 1].DeliverabilityNotifications.InterruptPriority == (unsigned)((fDesiredIntWin & NEM_WIN_INTW_F_PRIO_MASK) >> NEM_WIN_INTW_F_PRIO_SHIFT));
450 }
451
452 /// @todo WHvRegisterPendingEvent
453
454 /*
455 * Set the registers.
456 */
457 Assert(iReg < RT_ELEMENTS(aValues));
458 Assert(iReg < RT_ELEMENTS(aenmNames));
459# ifdef NEM_WIN_INTERCEPT_NT_IO_CTLS
460 Log12(("Calling WHvSetVirtualProcessorRegisters(%p, %u, %p, %u, %p)\n",
461 pVM->nem.s.hPartition, pVCpu->idCpu, aenmNames, iReg, aValues));
462# endif
463 HRESULT hrc = WHvSetVirtualProcessorRegisters(pVM->nem.s.hPartition, pVCpu->idCpu, aenmNames, iReg, aValues);
464 if (SUCCEEDED(hrc))
465 {
466 pVCpu->cpum.GstCtx.fExtrn |= CPUMCTX_EXTRN_ALL | CPUMCTX_EXTRN_NEM_WIN_MASK | CPUMCTX_EXTRN_KEEPER_NEM;
467 return VINF_SUCCESS;
468 }
469 AssertLogRelMsgFailed(("WHvSetVirtualProcessorRegisters(%p, %u,,%u,) -> %Rhrc (Last=%#x/%u)\n",
470 pVM->nem.s.hPartition, pVCpu->idCpu, iReg,
471 hrc, RTNtLastStatusValue(), RTNtLastErrorValue()));
472 return VERR_INTERNAL_ERROR;
473
474# undef ADD_REG64
475# undef ADD_REG128
476# undef ADD_SEG
477
478# endif /* !NEM_WIN_USE_HYPERCALLS_FOR_REGISTERS */
479}
480
481
482NEM_TMPL_STATIC int nemHCWinCopyStateFromHyperV(PVMCC pVM, PVMCPUCC pVCpu, uint64_t fWhat)
483{
484# if defined(NEM_WIN_USE_HYPERCALLS_FOR_REGISTERS) || defined(NEM_WIN_WITH_RING0_RUNLOOP)
485# if !defined(NEM_WIN_USE_HYPERCALLS_FOR_REGISTERS) && defined(NEM_WIN_WITH_RING0_RUNLOOP)
486 if (pVM->nem.s.fUseRing0Runloop)
487# endif
488 {
489 /* See NEMR0ImportState */
490 int rc = VMMR3CallR0Emt(pVM, pVCpu, VMMR0_DO_NEM_IMPORT_STATE, fWhat, NULL);
491 if (RT_SUCCESS(rc))
492 return rc;
493 if (rc == VERR_NEM_FLUSH_TLB)
494 {
495 rc = PGMFlushTLB(pVCpu, pVCpu->cpum.GstCtx.cr3, true /*fGlobal*/, false /*fPdpesMapped*/);
496 return rc;
497 }
498 AssertLogRelRCReturn(rc, rc);
499 return rc;
500 }
501# endif
502# ifndef NEM_WIN_USE_HYPERCALLS_FOR_REGISTERS
503 WHV_REGISTER_NAME aenmNames[128];
504
505 fWhat &= pVCpu->cpum.GstCtx.fExtrn;
506 uintptr_t iReg = 0;
507
508 /* GPRs */
509 if (fWhat & CPUMCTX_EXTRN_GPRS_MASK)
510 {
511 if (fWhat & CPUMCTX_EXTRN_RAX)
512 aenmNames[iReg++] = WHvX64RegisterRax;
513 if (fWhat & CPUMCTX_EXTRN_RCX)
514 aenmNames[iReg++] = WHvX64RegisterRcx;
515 if (fWhat & CPUMCTX_EXTRN_RDX)
516 aenmNames[iReg++] = WHvX64RegisterRdx;
517 if (fWhat & CPUMCTX_EXTRN_RBX)
518 aenmNames[iReg++] = WHvX64RegisterRbx;
519 if (fWhat & CPUMCTX_EXTRN_RSP)
520 aenmNames[iReg++] = WHvX64RegisterRsp;
521 if (fWhat & CPUMCTX_EXTRN_RBP)
522 aenmNames[iReg++] = WHvX64RegisterRbp;
523 if (fWhat & CPUMCTX_EXTRN_RSI)
524 aenmNames[iReg++] = WHvX64RegisterRsi;
525 if (fWhat & CPUMCTX_EXTRN_RDI)
526 aenmNames[iReg++] = WHvX64RegisterRdi;
527 if (fWhat & CPUMCTX_EXTRN_R8_R15)
528 {
529 aenmNames[iReg++] = WHvX64RegisterR8;
530 aenmNames[iReg++] = WHvX64RegisterR9;
531 aenmNames[iReg++] = WHvX64RegisterR10;
532 aenmNames[iReg++] = WHvX64RegisterR11;
533 aenmNames[iReg++] = WHvX64RegisterR12;
534 aenmNames[iReg++] = WHvX64RegisterR13;
535 aenmNames[iReg++] = WHvX64RegisterR14;
536 aenmNames[iReg++] = WHvX64RegisterR15;
537 }
538 }
539
540 /* RIP & Flags */
541 if (fWhat & CPUMCTX_EXTRN_RIP)
542 aenmNames[iReg++] = WHvX64RegisterRip;
543 if (fWhat & CPUMCTX_EXTRN_RFLAGS)
544 aenmNames[iReg++] = WHvX64RegisterRflags;
545
546 /* Segments */
547 if (fWhat & CPUMCTX_EXTRN_SREG_MASK)
548 {
549 if (fWhat & CPUMCTX_EXTRN_ES)
550 aenmNames[iReg++] = WHvX64RegisterEs;
551 if (fWhat & CPUMCTX_EXTRN_CS)
552 aenmNames[iReg++] = WHvX64RegisterCs;
553 if (fWhat & CPUMCTX_EXTRN_SS)
554 aenmNames[iReg++] = WHvX64RegisterSs;
555 if (fWhat & CPUMCTX_EXTRN_DS)
556 aenmNames[iReg++] = WHvX64RegisterDs;
557 if (fWhat & CPUMCTX_EXTRN_FS)
558 aenmNames[iReg++] = WHvX64RegisterFs;
559 if (fWhat & CPUMCTX_EXTRN_GS)
560 aenmNames[iReg++] = WHvX64RegisterGs;
561 }
562
563 /* Descriptor tables. */
564 if (fWhat & CPUMCTX_EXTRN_TABLE_MASK)
565 {
566 if (fWhat & CPUMCTX_EXTRN_LDTR)
567 aenmNames[iReg++] = WHvX64RegisterLdtr;
568 if (fWhat & CPUMCTX_EXTRN_TR)
569 aenmNames[iReg++] = WHvX64RegisterTr;
570 if (fWhat & CPUMCTX_EXTRN_IDTR)
571 aenmNames[iReg++] = WHvX64RegisterIdtr;
572 if (fWhat & CPUMCTX_EXTRN_GDTR)
573 aenmNames[iReg++] = WHvX64RegisterGdtr;
574 }
575
576 /* Control registers. */
577 if (fWhat & CPUMCTX_EXTRN_CR_MASK)
578 {
579 if (fWhat & CPUMCTX_EXTRN_CR0)
580 aenmNames[iReg++] = WHvX64RegisterCr0;
581 if (fWhat & CPUMCTX_EXTRN_CR2)
582 aenmNames[iReg++] = WHvX64RegisterCr2;
583 if (fWhat & CPUMCTX_EXTRN_CR3)
584 aenmNames[iReg++] = WHvX64RegisterCr3;
585 if (fWhat & CPUMCTX_EXTRN_CR4)
586 aenmNames[iReg++] = WHvX64RegisterCr4;
587 }
588 if (fWhat & CPUMCTX_EXTRN_APIC_TPR)
589 aenmNames[iReg++] = WHvX64RegisterCr8;
590
591 /* Debug registers. */
592 if (fWhat & CPUMCTX_EXTRN_DR7)
593 aenmNames[iReg++] = WHvX64RegisterDr7;
594 if (fWhat & CPUMCTX_EXTRN_DR0_DR3)
595 {
596 if (!(fWhat & CPUMCTX_EXTRN_DR7) && (pVCpu->cpum.GstCtx.fExtrn & CPUMCTX_EXTRN_DR7))
597 {
598 fWhat |= CPUMCTX_EXTRN_DR7;
599 aenmNames[iReg++] = WHvX64RegisterDr7;
600 }
601 aenmNames[iReg++] = WHvX64RegisterDr0;
602 aenmNames[iReg++] = WHvX64RegisterDr1;
603 aenmNames[iReg++] = WHvX64RegisterDr2;
604 aenmNames[iReg++] = WHvX64RegisterDr3;
605 }
606 if (fWhat & CPUMCTX_EXTRN_DR6)
607 aenmNames[iReg++] = WHvX64RegisterDr6;
608
609 /* Floating point state. */
610 if (fWhat & CPUMCTX_EXTRN_X87)
611 {
612 aenmNames[iReg++] = WHvX64RegisterFpMmx0;
613 aenmNames[iReg++] = WHvX64RegisterFpMmx1;
614 aenmNames[iReg++] = WHvX64RegisterFpMmx2;
615 aenmNames[iReg++] = WHvX64RegisterFpMmx3;
616 aenmNames[iReg++] = WHvX64RegisterFpMmx4;
617 aenmNames[iReg++] = WHvX64RegisterFpMmx5;
618 aenmNames[iReg++] = WHvX64RegisterFpMmx6;
619 aenmNames[iReg++] = WHvX64RegisterFpMmx7;
620 aenmNames[iReg++] = WHvX64RegisterFpControlStatus;
621 }
622 if (fWhat & (CPUMCTX_EXTRN_X87 | CPUMCTX_EXTRN_SSE_AVX))
623 aenmNames[iReg++] = WHvX64RegisterXmmControlStatus;
624
625 /* Vector state. */
626 if (fWhat & CPUMCTX_EXTRN_SSE_AVX)
627 {
628 aenmNames[iReg++] = WHvX64RegisterXmm0;
629 aenmNames[iReg++] = WHvX64RegisterXmm1;
630 aenmNames[iReg++] = WHvX64RegisterXmm2;
631 aenmNames[iReg++] = WHvX64RegisterXmm3;
632 aenmNames[iReg++] = WHvX64RegisterXmm4;
633 aenmNames[iReg++] = WHvX64RegisterXmm5;
634 aenmNames[iReg++] = WHvX64RegisterXmm6;
635 aenmNames[iReg++] = WHvX64RegisterXmm7;
636 aenmNames[iReg++] = WHvX64RegisterXmm8;
637 aenmNames[iReg++] = WHvX64RegisterXmm9;
638 aenmNames[iReg++] = WHvX64RegisterXmm10;
639 aenmNames[iReg++] = WHvX64RegisterXmm11;
640 aenmNames[iReg++] = WHvX64RegisterXmm12;
641 aenmNames[iReg++] = WHvX64RegisterXmm13;
642 aenmNames[iReg++] = WHvX64RegisterXmm14;
643 aenmNames[iReg++] = WHvX64RegisterXmm15;
644 }
645
646 /* MSRs */
647 // WHvX64RegisterTsc - don't touch
648 if (fWhat & CPUMCTX_EXTRN_EFER)
649 aenmNames[iReg++] = WHvX64RegisterEfer;
650 if (fWhat & CPUMCTX_EXTRN_KERNEL_GS_BASE)
651 aenmNames[iReg++] = WHvX64RegisterKernelGsBase;
652 if (fWhat & CPUMCTX_EXTRN_SYSENTER_MSRS)
653 {
654 aenmNames[iReg++] = WHvX64RegisterSysenterCs;
655 aenmNames[iReg++] = WHvX64RegisterSysenterEip;
656 aenmNames[iReg++] = WHvX64RegisterSysenterEsp;
657 }
658 if (fWhat & CPUMCTX_EXTRN_SYSCALL_MSRS)
659 {
660 aenmNames[iReg++] = WHvX64RegisterStar;
661 aenmNames[iReg++] = WHvX64RegisterLstar;
662 aenmNames[iReg++] = WHvX64RegisterCstar;
663 aenmNames[iReg++] = WHvX64RegisterSfmask;
664 }
665
666//#ifdef LOG_ENABLED
667// const CPUMCPUVENDOR enmCpuVendor = CPUMGetHostCpuVendor(pVM);
668//#endif
669 if (fWhat & CPUMCTX_EXTRN_OTHER_MSRS)
670 {
671 aenmNames[iReg++] = WHvX64RegisterApicBase; /// @todo APIC BASE
672 aenmNames[iReg++] = WHvX64RegisterPat;
673#if 0 /*def LOG_ENABLED*/ /** @todo Check if WHvX64RegisterMsrMtrrCap works... */
674 aenmNames[iReg++] = WHvX64RegisterMsrMtrrCap;
675#endif
676 aenmNames[iReg++] = WHvX64RegisterMsrMtrrDefType;
677 aenmNames[iReg++] = WHvX64RegisterMsrMtrrFix64k00000;
678 aenmNames[iReg++] = WHvX64RegisterMsrMtrrFix16k80000;
679 aenmNames[iReg++] = WHvX64RegisterMsrMtrrFix16kA0000;
680 aenmNames[iReg++] = WHvX64RegisterMsrMtrrFix4kC0000;
681 aenmNames[iReg++] = WHvX64RegisterMsrMtrrFix4kC8000;
682 aenmNames[iReg++] = WHvX64RegisterMsrMtrrFix4kD0000;
683 aenmNames[iReg++] = WHvX64RegisterMsrMtrrFix4kD8000;
684 aenmNames[iReg++] = WHvX64RegisterMsrMtrrFix4kE0000;
685 aenmNames[iReg++] = WHvX64RegisterMsrMtrrFix4kE8000;
686 aenmNames[iReg++] = WHvX64RegisterMsrMtrrFix4kF0000;
687 aenmNames[iReg++] = WHvX64RegisterMsrMtrrFix4kF8000;
688 aenmNames[iReg++] = WHvX64RegisterTscAux;
689 /** @todo look for HvX64RegisterIa32MiscEnable and HvX64RegisterIa32FeatureControl? */
690//#ifdef LOG_ENABLED
691// if (enmCpuVendor != CPUMCPUVENDOR_AMD)
692// aenmNames[iReg++] = HvX64RegisterIa32FeatureControl;
693//#endif
694 }
695
696 /* Interruptibility. */
697 if (fWhat & (CPUMCTX_EXTRN_NEM_WIN_INHIBIT_INT | CPUMCTX_EXTRN_NEM_WIN_INHIBIT_NMI))
698 {
699 aenmNames[iReg++] = WHvRegisterInterruptState;
700 aenmNames[iReg++] = WHvX64RegisterRip;
701 }
702
703 /* event injection */
704 aenmNames[iReg++] = WHvRegisterPendingInterruption;
705 aenmNames[iReg++] = WHvRegisterPendingEvent0; /** @todo renamed to WHvRegisterPendingEvent */
706
707 size_t const cRegs = iReg;
708 Assert(cRegs < RT_ELEMENTS(aenmNames));
709
710 /*
711 * Get the registers.
712 */
713 WHV_REGISTER_VALUE aValues[128];
714 RT_ZERO(aValues);
715 Assert(RT_ELEMENTS(aValues) >= cRegs);
716 Assert(RT_ELEMENTS(aenmNames) >= cRegs);
717# ifdef NEM_WIN_INTERCEPT_NT_IO_CTLS
718 Log12(("Calling WHvGetVirtualProcessorRegisters(%p, %u, %p, %u, %p)\n",
719 pVM->nem.s.hPartition, pVCpu->idCpu, aenmNames, cRegs, aValues));
720# endif
721 HRESULT hrc = WHvGetVirtualProcessorRegisters(pVM->nem.s.hPartition, pVCpu->idCpu, aenmNames, (uint32_t)cRegs, aValues);
722 AssertLogRelMsgReturn(SUCCEEDED(hrc),
723 ("WHvGetVirtualProcessorRegisters(%p, %u,,%u,) -> %Rhrc (Last=%#x/%u)\n",
724 pVM->nem.s.hPartition, pVCpu->idCpu, cRegs, hrc, RTNtLastStatusValue(), RTNtLastErrorValue())
725 , VERR_NEM_GET_REGISTERS_FAILED);
726
727 iReg = 0;
728# define GET_REG64(a_DstVar, a_enmName) do { \
729 Assert(aenmNames[iReg] == (a_enmName)); \
730 (a_DstVar) = aValues[iReg].Reg64; \
731 iReg++; \
732 } while (0)
733# define GET_REG64_LOG7(a_DstVar, a_enmName, a_szLogName) do { \
734 Assert(aenmNames[iReg] == (a_enmName)); \
735 if ((a_DstVar) != aValues[iReg].Reg64) \
736 Log7(("NEM/%u: " a_szLogName " changed %RX64 -> %RX64\n", pVCpu->idCpu, (a_DstVar), aValues[iReg].Reg64)); \
737 (a_DstVar) = aValues[iReg].Reg64; \
738 iReg++; \
739 } while (0)
740# define GET_REG128(a_DstVarLo, a_DstVarHi, a_enmName) do { \
741 Assert(aenmNames[iReg] == a_enmName); \
742 (a_DstVarLo) = aValues[iReg].Reg128.Low64; \
743 (a_DstVarHi) = aValues[iReg].Reg128.High64; \
744 iReg++; \
745 } while (0)
746# define GET_SEG(a_SReg, a_enmName) do { \
747 Assert(aenmNames[iReg] == (a_enmName)); \
748 NEM_WIN_COPY_BACK_SEG(a_SReg, aValues[iReg].Segment); \
749 iReg++; \
750 } while (0)
751
752 /* GPRs */
753 if (fWhat & CPUMCTX_EXTRN_GPRS_MASK)
754 {
755 if (fWhat & CPUMCTX_EXTRN_RAX)
756 GET_REG64(pVCpu->cpum.GstCtx.rax, WHvX64RegisterRax);
757 if (fWhat & CPUMCTX_EXTRN_RCX)
758 GET_REG64(pVCpu->cpum.GstCtx.rcx, WHvX64RegisterRcx);
759 if (fWhat & CPUMCTX_EXTRN_RDX)
760 GET_REG64(pVCpu->cpum.GstCtx.rdx, WHvX64RegisterRdx);
761 if (fWhat & CPUMCTX_EXTRN_RBX)
762 GET_REG64(pVCpu->cpum.GstCtx.rbx, WHvX64RegisterRbx);
763 if (fWhat & CPUMCTX_EXTRN_RSP)
764 GET_REG64(pVCpu->cpum.GstCtx.rsp, WHvX64RegisterRsp);
765 if (fWhat & CPUMCTX_EXTRN_RBP)
766 GET_REG64(pVCpu->cpum.GstCtx.rbp, WHvX64RegisterRbp);
767 if (fWhat & CPUMCTX_EXTRN_RSI)
768 GET_REG64(pVCpu->cpum.GstCtx.rsi, WHvX64RegisterRsi);
769 if (fWhat & CPUMCTX_EXTRN_RDI)
770 GET_REG64(pVCpu->cpum.GstCtx.rdi, WHvX64RegisterRdi);
771 if (fWhat & CPUMCTX_EXTRN_R8_R15)
772 {
773 GET_REG64(pVCpu->cpum.GstCtx.r8, WHvX64RegisterR8);
774 GET_REG64(pVCpu->cpum.GstCtx.r9, WHvX64RegisterR9);
775 GET_REG64(pVCpu->cpum.GstCtx.r10, WHvX64RegisterR10);
776 GET_REG64(pVCpu->cpum.GstCtx.r11, WHvX64RegisterR11);
777 GET_REG64(pVCpu->cpum.GstCtx.r12, WHvX64RegisterR12);
778 GET_REG64(pVCpu->cpum.GstCtx.r13, WHvX64RegisterR13);
779 GET_REG64(pVCpu->cpum.GstCtx.r14, WHvX64RegisterR14);
780 GET_REG64(pVCpu->cpum.GstCtx.r15, WHvX64RegisterR15);
781 }
782 }
783
784 /* RIP & Flags */
785 if (fWhat & CPUMCTX_EXTRN_RIP)
786 GET_REG64(pVCpu->cpum.GstCtx.rip, WHvX64RegisterRip);
787 if (fWhat & CPUMCTX_EXTRN_RFLAGS)
788 GET_REG64(pVCpu->cpum.GstCtx.rflags.u, WHvX64RegisterRflags);
789
790 /* Segments */
791 if (fWhat & CPUMCTX_EXTRN_SREG_MASK)
792 {
793 if (fWhat & CPUMCTX_EXTRN_ES)
794 GET_SEG(pVCpu->cpum.GstCtx.es, WHvX64RegisterEs);
795 if (fWhat & CPUMCTX_EXTRN_CS)
796 GET_SEG(pVCpu->cpum.GstCtx.cs, WHvX64RegisterCs);
797 if (fWhat & CPUMCTX_EXTRN_SS)
798 GET_SEG(pVCpu->cpum.GstCtx.ss, WHvX64RegisterSs);
799 if (fWhat & CPUMCTX_EXTRN_DS)
800 GET_SEG(pVCpu->cpum.GstCtx.ds, WHvX64RegisterDs);
801 if (fWhat & CPUMCTX_EXTRN_FS)
802 GET_SEG(pVCpu->cpum.GstCtx.fs, WHvX64RegisterFs);
803 if (fWhat & CPUMCTX_EXTRN_GS)
804 GET_SEG(pVCpu->cpum.GstCtx.gs, WHvX64RegisterGs);
805 }
806
807 /* Descriptor tables and the task segment. */
808 if (fWhat & CPUMCTX_EXTRN_TABLE_MASK)
809 {
810 if (fWhat & CPUMCTX_EXTRN_LDTR)
811 GET_SEG(pVCpu->cpum.GstCtx.ldtr, WHvX64RegisterLdtr);
812
813 if (fWhat & CPUMCTX_EXTRN_TR)
814 {
815 /* AMD-V likes loading TR with in AVAIL state, whereas intel insists on BUSY. So,
816 avoid to trigger sanity assertions around the code, always fix this. */
817 GET_SEG(pVCpu->cpum.GstCtx.tr, WHvX64RegisterTr);
818 switch (pVCpu->cpum.GstCtx.tr.Attr.n.u4Type)
819 {
820 case X86_SEL_TYPE_SYS_386_TSS_BUSY:
821 case X86_SEL_TYPE_SYS_286_TSS_BUSY:
822 break;
823 case X86_SEL_TYPE_SYS_386_TSS_AVAIL:
824 pVCpu->cpum.GstCtx.tr.Attr.n.u4Type = X86_SEL_TYPE_SYS_386_TSS_BUSY;
825 break;
826 case X86_SEL_TYPE_SYS_286_TSS_AVAIL:
827 pVCpu->cpum.GstCtx.tr.Attr.n.u4Type = X86_SEL_TYPE_SYS_286_TSS_BUSY;
828 break;
829 }
830 }
831 if (fWhat & CPUMCTX_EXTRN_IDTR)
832 {
833 Assert(aenmNames[iReg] == WHvX64RegisterIdtr);
834 pVCpu->cpum.GstCtx.idtr.cbIdt = aValues[iReg].Table.Limit;
835 pVCpu->cpum.GstCtx.idtr.pIdt = aValues[iReg].Table.Base;
836 iReg++;
837 }
838 if (fWhat & CPUMCTX_EXTRN_GDTR)
839 {
840 Assert(aenmNames[iReg] == WHvX64RegisterGdtr);
841 pVCpu->cpum.GstCtx.gdtr.cbGdt = aValues[iReg].Table.Limit;
842 pVCpu->cpum.GstCtx.gdtr.pGdt = aValues[iReg].Table.Base;
843 iReg++;
844 }
845 }
846
847 /* Control registers. */
848 bool fMaybeChangedMode = false;
849 bool fUpdateCr3 = false;
850 if (fWhat & CPUMCTX_EXTRN_CR_MASK)
851 {
852 if (fWhat & CPUMCTX_EXTRN_CR0)
853 {
854 Assert(aenmNames[iReg] == WHvX64RegisterCr0);
855 if (pVCpu->cpum.GstCtx.cr0 != aValues[iReg].Reg64)
856 {
857 CPUMSetGuestCR0(pVCpu, aValues[iReg].Reg64);
858 fMaybeChangedMode = true;
859 }
860 iReg++;
861 }
862 if (fWhat & CPUMCTX_EXTRN_CR2)
863 GET_REG64(pVCpu->cpum.GstCtx.cr2, WHvX64RegisterCr2);
864 if (fWhat & CPUMCTX_EXTRN_CR3)
865 {
866 if (pVCpu->cpum.GstCtx.cr3 != aValues[iReg].Reg64)
867 {
868 CPUMSetGuestCR3(pVCpu, aValues[iReg].Reg64);
869 fUpdateCr3 = true;
870 }
871 iReg++;
872 }
873 if (fWhat & CPUMCTX_EXTRN_CR4)
874 {
875 if (pVCpu->cpum.GstCtx.cr4 != aValues[iReg].Reg64)
876 {
877 CPUMSetGuestCR4(pVCpu, aValues[iReg].Reg64);
878 fMaybeChangedMode = true;
879 }
880 iReg++;
881 }
882 }
883 if (fWhat & CPUMCTX_EXTRN_APIC_TPR)
884 {
885 Assert(aenmNames[iReg] == WHvX64RegisterCr8);
886 APICSetTpr(pVCpu, (uint8_t)aValues[iReg].Reg64 << 4);
887 iReg++;
888 }
889
890 /* Debug registers. */
891 if (fWhat & CPUMCTX_EXTRN_DR7)
892 {
893 Assert(aenmNames[iReg] == WHvX64RegisterDr7);
894 if (pVCpu->cpum.GstCtx.dr[7] != aValues[iReg].Reg64)
895 CPUMSetGuestDR7(pVCpu, aValues[iReg].Reg64);
896 pVCpu->cpum.GstCtx.fExtrn &= ~CPUMCTX_EXTRN_DR7; /* Hack alert! Avoids asserting when processing CPUMCTX_EXTRN_DR0_DR3. */
897 iReg++;
898 }
899 if (fWhat & CPUMCTX_EXTRN_DR0_DR3)
900 {
901 Assert(aenmNames[iReg] == WHvX64RegisterDr0);
902 Assert(aenmNames[iReg+3] == WHvX64RegisterDr3);
903 if (pVCpu->cpum.GstCtx.dr[0] != aValues[iReg].Reg64)
904 CPUMSetGuestDR0(pVCpu, aValues[iReg].Reg64);
905 iReg++;
906 if (pVCpu->cpum.GstCtx.dr[1] != aValues[iReg].Reg64)
907 CPUMSetGuestDR1(pVCpu, aValues[iReg].Reg64);
908 iReg++;
909 if (pVCpu->cpum.GstCtx.dr[2] != aValues[iReg].Reg64)
910 CPUMSetGuestDR2(pVCpu, aValues[iReg].Reg64);
911 iReg++;
912 if (pVCpu->cpum.GstCtx.dr[3] != aValues[iReg].Reg64)
913 CPUMSetGuestDR3(pVCpu, aValues[iReg].Reg64);
914 iReg++;
915 }
916 if (fWhat & CPUMCTX_EXTRN_DR6)
917 {
918 Assert(aenmNames[iReg] == WHvX64RegisterDr6);
919 if (pVCpu->cpum.GstCtx.dr[6] != aValues[iReg].Reg64)
920 CPUMSetGuestDR6(pVCpu, aValues[iReg].Reg64);
921 iReg++;
922 }
923
924 /* Floating point state. */
925 if (fWhat & CPUMCTX_EXTRN_X87)
926 {
927 GET_REG128(pVCpu->cpum.GstCtx.XState.x87.aRegs[0].au64[0], pVCpu->cpum.GstCtx.XState.x87.aRegs[0].au64[1], WHvX64RegisterFpMmx0);
928 GET_REG128(pVCpu->cpum.GstCtx.XState.x87.aRegs[1].au64[0], pVCpu->cpum.GstCtx.XState.x87.aRegs[1].au64[1], WHvX64RegisterFpMmx1);
929 GET_REG128(pVCpu->cpum.GstCtx.XState.x87.aRegs[2].au64[0], pVCpu->cpum.GstCtx.XState.x87.aRegs[2].au64[1], WHvX64RegisterFpMmx2);
930 GET_REG128(pVCpu->cpum.GstCtx.XState.x87.aRegs[3].au64[0], pVCpu->cpum.GstCtx.XState.x87.aRegs[3].au64[1], WHvX64RegisterFpMmx3);
931 GET_REG128(pVCpu->cpum.GstCtx.XState.x87.aRegs[4].au64[0], pVCpu->cpum.GstCtx.XState.x87.aRegs[4].au64[1], WHvX64RegisterFpMmx4);
932 GET_REG128(pVCpu->cpum.GstCtx.XState.x87.aRegs[5].au64[0], pVCpu->cpum.GstCtx.XState.x87.aRegs[5].au64[1], WHvX64RegisterFpMmx5);
933 GET_REG128(pVCpu->cpum.GstCtx.XState.x87.aRegs[6].au64[0], pVCpu->cpum.GstCtx.XState.x87.aRegs[6].au64[1], WHvX64RegisterFpMmx6);
934 GET_REG128(pVCpu->cpum.GstCtx.XState.x87.aRegs[7].au64[0], pVCpu->cpum.GstCtx.XState.x87.aRegs[7].au64[1], WHvX64RegisterFpMmx7);
935
936 Assert(aenmNames[iReg] == WHvX64RegisterFpControlStatus);
937 pVCpu->cpum.GstCtx.XState.x87.FCW = aValues[iReg].FpControlStatus.FpControl;
938 pVCpu->cpum.GstCtx.XState.x87.FSW = aValues[iReg].FpControlStatus.FpStatus;
939 pVCpu->cpum.GstCtx.XState.x87.FTW = aValues[iReg].FpControlStatus.FpTag
940 /*| (aValues[iReg].FpControlStatus.Reserved << 8)*/;
941 pVCpu->cpum.GstCtx.XState.x87.FOP = aValues[iReg].FpControlStatus.LastFpOp;
942 pVCpu->cpum.GstCtx.XState.x87.FPUIP = (uint32_t)aValues[iReg].FpControlStatus.LastFpRip;
943 pVCpu->cpum.GstCtx.XState.x87.CS = (uint16_t)(aValues[iReg].FpControlStatus.LastFpRip >> 32);
944 pVCpu->cpum.GstCtx.XState.x87.Rsrvd1 = (uint16_t)(aValues[iReg].FpControlStatus.LastFpRip >> 48);
945 iReg++;
946 }
947
948 if (fWhat & (CPUMCTX_EXTRN_X87 | CPUMCTX_EXTRN_SSE_AVX))
949 {
950 Assert(aenmNames[iReg] == WHvX64RegisterXmmControlStatus);
951 if (fWhat & CPUMCTX_EXTRN_X87)
952 {
953 pVCpu->cpum.GstCtx.XState.x87.FPUDP = (uint32_t)aValues[iReg].XmmControlStatus.LastFpRdp;
954 pVCpu->cpum.GstCtx.XState.x87.DS = (uint16_t)(aValues[iReg].XmmControlStatus.LastFpRdp >> 32);
955 pVCpu->cpum.GstCtx.XState.x87.Rsrvd2 = (uint16_t)(aValues[iReg].XmmControlStatus.LastFpRdp >> 48);
956 }
957 pVCpu->cpum.GstCtx.XState.x87.MXCSR = aValues[iReg].XmmControlStatus.XmmStatusControl;
958 pVCpu->cpum.GstCtx.XState.x87.MXCSR_MASK = aValues[iReg].XmmControlStatus.XmmStatusControlMask; /** @todo ??? (Isn't this an output field?) */
959 iReg++;
960 }
961
962 /* Vector state. */
963 if (fWhat & CPUMCTX_EXTRN_SSE_AVX)
964 {
965 GET_REG128(pVCpu->cpum.GstCtx.XState.x87.aXMM[ 0].uXmm.s.Lo, pVCpu->cpum.GstCtx.XState.x87.aXMM[ 0].uXmm.s.Hi, WHvX64RegisterXmm0);
966 GET_REG128(pVCpu->cpum.GstCtx.XState.x87.aXMM[ 1].uXmm.s.Lo, pVCpu->cpum.GstCtx.XState.x87.aXMM[ 1].uXmm.s.Hi, WHvX64RegisterXmm1);
967 GET_REG128(pVCpu->cpum.GstCtx.XState.x87.aXMM[ 2].uXmm.s.Lo, pVCpu->cpum.GstCtx.XState.x87.aXMM[ 2].uXmm.s.Hi, WHvX64RegisterXmm2);
968 GET_REG128(pVCpu->cpum.GstCtx.XState.x87.aXMM[ 3].uXmm.s.Lo, pVCpu->cpum.GstCtx.XState.x87.aXMM[ 3].uXmm.s.Hi, WHvX64RegisterXmm3);
969 GET_REG128(pVCpu->cpum.GstCtx.XState.x87.aXMM[ 4].uXmm.s.Lo, pVCpu->cpum.GstCtx.XState.x87.aXMM[ 4].uXmm.s.Hi, WHvX64RegisterXmm4);
970 GET_REG128(pVCpu->cpum.GstCtx.XState.x87.aXMM[ 5].uXmm.s.Lo, pVCpu->cpum.GstCtx.XState.x87.aXMM[ 5].uXmm.s.Hi, WHvX64RegisterXmm5);
971 GET_REG128(pVCpu->cpum.GstCtx.XState.x87.aXMM[ 6].uXmm.s.Lo, pVCpu->cpum.GstCtx.XState.x87.aXMM[ 6].uXmm.s.Hi, WHvX64RegisterXmm6);
972 GET_REG128(pVCpu->cpum.GstCtx.XState.x87.aXMM[ 7].uXmm.s.Lo, pVCpu->cpum.GstCtx.XState.x87.aXMM[ 7].uXmm.s.Hi, WHvX64RegisterXmm7);
973 GET_REG128(pVCpu->cpum.GstCtx.XState.x87.aXMM[ 8].uXmm.s.Lo, pVCpu->cpum.GstCtx.XState.x87.aXMM[ 8].uXmm.s.Hi, WHvX64RegisterXmm8);
974 GET_REG128(pVCpu->cpum.GstCtx.XState.x87.aXMM[ 9].uXmm.s.Lo, pVCpu->cpum.GstCtx.XState.x87.aXMM[ 9].uXmm.s.Hi, WHvX64RegisterXmm9);
975 GET_REG128(pVCpu->cpum.GstCtx.XState.x87.aXMM[10].uXmm.s.Lo, pVCpu->cpum.GstCtx.XState.x87.aXMM[10].uXmm.s.Hi, WHvX64RegisterXmm10);
976 GET_REG128(pVCpu->cpum.GstCtx.XState.x87.aXMM[11].uXmm.s.Lo, pVCpu->cpum.GstCtx.XState.x87.aXMM[11].uXmm.s.Hi, WHvX64RegisterXmm11);
977 GET_REG128(pVCpu->cpum.GstCtx.XState.x87.aXMM[12].uXmm.s.Lo, pVCpu->cpum.GstCtx.XState.x87.aXMM[12].uXmm.s.Hi, WHvX64RegisterXmm12);
978 GET_REG128(pVCpu->cpum.GstCtx.XState.x87.aXMM[13].uXmm.s.Lo, pVCpu->cpum.GstCtx.XState.x87.aXMM[13].uXmm.s.Hi, WHvX64RegisterXmm13);
979 GET_REG128(pVCpu->cpum.GstCtx.XState.x87.aXMM[14].uXmm.s.Lo, pVCpu->cpum.GstCtx.XState.x87.aXMM[14].uXmm.s.Hi, WHvX64RegisterXmm14);
980 GET_REG128(pVCpu->cpum.GstCtx.XState.x87.aXMM[15].uXmm.s.Lo, pVCpu->cpum.GstCtx.XState.x87.aXMM[15].uXmm.s.Hi, WHvX64RegisterXmm15);
981 }
982
983 /* MSRs */
984 // WHvX64RegisterTsc - don't touch
985 if (fWhat & CPUMCTX_EXTRN_EFER)
986 {
987 Assert(aenmNames[iReg] == WHvX64RegisterEfer);
988 if (aValues[iReg].Reg64 != pVCpu->cpum.GstCtx.msrEFER)
989 {
990 Log7(("NEM/%u: MSR EFER changed %RX64 -> %RX64\n", pVCpu->idCpu, pVCpu->cpum.GstCtx.msrEFER, aValues[iReg].Reg64));
991 if ((aValues[iReg].Reg64 ^ pVCpu->cpum.GstCtx.msrEFER) & MSR_K6_EFER_NXE)
992 PGMNotifyNxeChanged(pVCpu, RT_BOOL(aValues[iReg].Reg64 & MSR_K6_EFER_NXE));
993 pVCpu->cpum.GstCtx.msrEFER = aValues[iReg].Reg64;
994 fMaybeChangedMode = true;
995 }
996 iReg++;
997 }
998 if (fWhat & CPUMCTX_EXTRN_KERNEL_GS_BASE)
999 GET_REG64_LOG7(pVCpu->cpum.GstCtx.msrKERNELGSBASE, WHvX64RegisterKernelGsBase, "MSR KERNEL_GS_BASE");
1000 if (fWhat & CPUMCTX_EXTRN_SYSENTER_MSRS)
1001 {
1002 GET_REG64_LOG7(pVCpu->cpum.GstCtx.SysEnter.cs, WHvX64RegisterSysenterCs, "MSR SYSENTER.CS");
1003 GET_REG64_LOG7(pVCpu->cpum.GstCtx.SysEnter.eip, WHvX64RegisterSysenterEip, "MSR SYSENTER.EIP");
1004 GET_REG64_LOG7(pVCpu->cpum.GstCtx.SysEnter.esp, WHvX64RegisterSysenterEsp, "MSR SYSENTER.ESP");
1005 }
1006 if (fWhat & CPUMCTX_EXTRN_SYSCALL_MSRS)
1007 {
1008 GET_REG64_LOG7(pVCpu->cpum.GstCtx.msrSTAR, WHvX64RegisterStar, "MSR STAR");
1009 GET_REG64_LOG7(pVCpu->cpum.GstCtx.msrLSTAR, WHvX64RegisterLstar, "MSR LSTAR");
1010 GET_REG64_LOG7(pVCpu->cpum.GstCtx.msrCSTAR, WHvX64RegisterCstar, "MSR CSTAR");
1011 GET_REG64_LOG7(pVCpu->cpum.GstCtx.msrSFMASK, WHvX64RegisterSfmask, "MSR SFMASK");
1012 }
1013 if (fWhat & CPUMCTX_EXTRN_OTHER_MSRS)
1014 {
1015 Assert(aenmNames[iReg] == WHvX64RegisterApicBase);
1016 const uint64_t uOldBase = APICGetBaseMsrNoCheck(pVCpu);
1017 if (aValues[iReg].Reg64 != uOldBase)
1018 {
1019 Log7(("NEM/%u: MSR APICBase changed %RX64 -> %RX64 (%RX64)\n",
1020 pVCpu->idCpu, uOldBase, aValues[iReg].Reg64, aValues[iReg].Reg64 ^ uOldBase));
1021 int rc2 = APICSetBaseMsr(pVCpu, aValues[iReg].Reg64);
1022 AssertLogRelMsg(rc2 == VINF_SUCCESS, ("%Rrc %RX64\n", rc2, aValues[iReg].Reg64));
1023 }
1024 iReg++;
1025
1026 GET_REG64_LOG7(pVCpu->cpum.GstCtx.msrPAT, WHvX64RegisterPat, "MSR PAT");
1027#if 0 /*def LOG_ENABLED*/ /** @todo something's wrong with HvX64RegisterMtrrCap? (AMD) */
1028 GET_REG64_LOG7(pVCpu->cpum.GstCtx.msrPAT, WHvX64RegisterMsrMtrrCap);
1029#endif
1030 PCPUMCTXMSRS pCtxMsrs = CPUMQueryGuestCtxMsrsPtr(pVCpu);
1031 GET_REG64_LOG7(pCtxMsrs->msr.MtrrDefType, WHvX64RegisterMsrMtrrDefType, "MSR MTRR_DEF_TYPE");
1032 GET_REG64_LOG7(pCtxMsrs->msr.MtrrFix64K_00000, WHvX64RegisterMsrMtrrFix64k00000, "MSR MTRR_FIX_64K_00000");
1033 GET_REG64_LOG7(pCtxMsrs->msr.MtrrFix16K_80000, WHvX64RegisterMsrMtrrFix16k80000, "MSR MTRR_FIX_16K_80000");
1034 GET_REG64_LOG7(pCtxMsrs->msr.MtrrFix16K_A0000, WHvX64RegisterMsrMtrrFix16kA0000, "MSR MTRR_FIX_16K_A0000");
1035 GET_REG64_LOG7(pCtxMsrs->msr.MtrrFix4K_C0000, WHvX64RegisterMsrMtrrFix4kC0000, "MSR MTRR_FIX_4K_C0000");
1036 GET_REG64_LOG7(pCtxMsrs->msr.MtrrFix4K_C8000, WHvX64RegisterMsrMtrrFix4kC8000, "MSR MTRR_FIX_4K_C8000");
1037 GET_REG64_LOG7(pCtxMsrs->msr.MtrrFix4K_D0000, WHvX64RegisterMsrMtrrFix4kD0000, "MSR MTRR_FIX_4K_D0000");
1038 GET_REG64_LOG7(pCtxMsrs->msr.MtrrFix4K_D8000, WHvX64RegisterMsrMtrrFix4kD8000, "MSR MTRR_FIX_4K_D8000");
1039 GET_REG64_LOG7(pCtxMsrs->msr.MtrrFix4K_E0000, WHvX64RegisterMsrMtrrFix4kE0000, "MSR MTRR_FIX_4K_E0000");
1040 GET_REG64_LOG7(pCtxMsrs->msr.MtrrFix4K_E8000, WHvX64RegisterMsrMtrrFix4kE8000, "MSR MTRR_FIX_4K_E8000");
1041 GET_REG64_LOG7(pCtxMsrs->msr.MtrrFix4K_F0000, WHvX64RegisterMsrMtrrFix4kF0000, "MSR MTRR_FIX_4K_F0000");
1042 GET_REG64_LOG7(pCtxMsrs->msr.MtrrFix4K_F8000, WHvX64RegisterMsrMtrrFix4kF8000, "MSR MTRR_FIX_4K_F8000");
1043 GET_REG64_LOG7(pCtxMsrs->msr.TscAux, WHvX64RegisterTscAux, "MSR TSC_AUX");
1044 /** @todo look for HvX64RegisterIa32MiscEnable and HvX64RegisterIa32FeatureControl? */
1045 }
1046
1047 /* Interruptibility. */
1048 if (fWhat & (CPUMCTX_EXTRN_NEM_WIN_INHIBIT_INT | CPUMCTX_EXTRN_NEM_WIN_INHIBIT_NMI))
1049 {
1050 Assert(aenmNames[iReg] == WHvRegisterInterruptState);
1051 Assert(aenmNames[iReg + 1] == WHvX64RegisterRip);
1052
1053 if (!(pVCpu->cpum.GstCtx.fExtrn & CPUMCTX_EXTRN_NEM_WIN_INHIBIT_INT))
1054 {
1055 pVCpu->nem.s.fLastInterruptShadow = aValues[iReg].InterruptState.InterruptShadow;
1056 if (aValues[iReg].InterruptState.InterruptShadow)
1057 EMSetInhibitInterruptsPC(pVCpu, aValues[iReg + 1].Reg64);
1058 else
1059 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS);
1060 }
1061
1062 if (!(pVCpu->cpum.GstCtx.fExtrn & CPUMCTX_EXTRN_NEM_WIN_INHIBIT_NMI))
1063 {
1064 if (aValues[iReg].InterruptState.NmiMasked)
1065 VMCPU_FF_SET(pVCpu, VMCPU_FF_BLOCK_NMIS);
1066 else
1067 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_BLOCK_NMIS);
1068 }
1069
1070 fWhat |= CPUMCTX_EXTRN_NEM_WIN_INHIBIT_INT | CPUMCTX_EXTRN_NEM_WIN_INHIBIT_NMI;
1071 iReg += 2;
1072 }
1073
1074 /* Event injection. */
1075 /// @todo WHvRegisterPendingInterruption
1076 Assert(aenmNames[iReg] == WHvRegisterPendingInterruption);
1077 if (aValues[iReg].PendingInterruption.InterruptionPending)
1078 {
1079 Log7(("PendingInterruption: type=%u vector=%#x errcd=%RTbool/%#x instr-len=%u nested=%u\n",
1080 aValues[iReg].PendingInterruption.InterruptionType, aValues[iReg].PendingInterruption.InterruptionVector,
1081 aValues[iReg].PendingInterruption.DeliverErrorCode, aValues[iReg].PendingInterruption.ErrorCode,
1082 aValues[iReg].PendingInterruption.InstructionLength, aValues[iReg].PendingInterruption.NestedEvent));
1083 AssertMsg((aValues[iReg].PendingInterruption.AsUINT64 & UINT64_C(0xfc00)) == 0,
1084 ("%#RX64\n", aValues[iReg].PendingInterruption.AsUINT64));
1085 }
1086
1087 /// @todo WHvRegisterPendingEvent0 (renamed to WHvRegisterPendingEvent).
1088
1089 /* Almost done, just update extrn flags and maybe change PGM mode. */
1090 pVCpu->cpum.GstCtx.fExtrn &= ~fWhat;
1091 if (!(pVCpu->cpum.GstCtx.fExtrn & (CPUMCTX_EXTRN_ALL | (CPUMCTX_EXTRN_NEM_WIN_MASK & ~CPUMCTX_EXTRN_NEM_WIN_EVENT_INJECT))))
1092 pVCpu->cpum.GstCtx.fExtrn = 0;
1093
1094 /* Typical. */
1095 if (!fMaybeChangedMode && !fUpdateCr3)
1096 return VINF_SUCCESS;
1097
1098 /*
1099 * Slow.
1100 */
1101 if (fMaybeChangedMode)
1102 {
1103 int rc = PGMChangeMode(pVCpu, pVCpu->cpum.GstCtx.cr0, pVCpu->cpum.GstCtx.cr4, pVCpu->cpum.GstCtx.msrEFER);
1104 AssertMsgReturn(rc == VINF_SUCCESS, ("rc=%Rrc\n", rc), RT_FAILURE_NP(rc) ? rc : VERR_NEM_IPE_1);
1105 }
1106
1107 if (fUpdateCr3)
1108 {
1109 int rc = PGMUpdateCR3(pVCpu, pVCpu->cpum.GstCtx.cr3, false /*fPdpesMapped*/);
1110 if (rc == VINF_SUCCESS)
1111 { /* likely */ }
1112 else
1113 AssertMsgFailedReturn(("rc=%Rrc\n", rc), RT_FAILURE_NP(rc) ? rc : VERR_NEM_IPE_2);
1114 }
1115
1116 return VINF_SUCCESS;
1117# endif /* !NEM_WIN_USE_HYPERCALLS_FOR_REGISTERS */
1118}
1119
1120#endif /* !IN_RING0 */
1121
1122
1123/**
1124 * Interface for importing state on demand (used by IEM).
1125 *
1126 * @returns VBox status code.
1127 * @param pVCpu The cross context CPU structure.
1128 * @param fWhat What to import, CPUMCTX_EXTRN_XXX.
1129 */
1130VMM_INT_DECL(int) NEMImportStateOnDemand(PVMCPUCC pVCpu, uint64_t fWhat)
1131{
1132 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatImportOnDemand);
1133
1134#ifdef IN_RING0
1135# ifdef NEM_WIN_WITH_RING0_RUNLOOP
1136 return nemR0WinImportState(pVCpu->pGVM, pVCpu, &pVCpu->cpum.GstCtx, fWhat, true /*fCanUpdateCr3*/);
1137# else
1138 RT_NOREF(pVCpu, fWhat);
1139 return VERR_NOT_IMPLEMENTED;
1140# endif
1141#else
1142 return nemHCWinCopyStateFromHyperV(pVCpu->pVMR3, pVCpu, fWhat);
1143#endif
1144}
1145
1146
1147/**
1148 * Query the CPU tick counter and optionally the TSC_AUX MSR value.
1149 *
1150 * @returns VBox status code.
1151 * @param pVCpu The cross context CPU structure.
1152 * @param pcTicks Where to return the CPU tick count.
1153 * @param puAux Where to return the TSC_AUX register value.
1154 */
1155VMM_INT_DECL(int) NEMHCQueryCpuTick(PVMCPUCC pVCpu, uint64_t *pcTicks, uint32_t *puAux)
1156{
1157 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatQueryCpuTick);
1158
1159#ifdef IN_RING3
1160 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
1161 VMCPU_ASSERT_EMT_RETURN(pVCpu, VERR_VM_THREAD_NOT_EMT);
1162 AssertReturn(VM_IS_NEM_ENABLED(pVM), VERR_NEM_IPE_9);
1163
1164# if defined(NEM_WIN_USE_HYPERCALLS_FOR_REGISTERS) || defined(NEM_WIN_WITH_RING0_RUNLOOP)
1165# if !defined(NEM_WIN_USE_HYPERCALLS_FOR_REGISTERS) && defined(NEM_WIN_WITH_RING0_RUNLOOP)
1166 if (pVM->nem.s.fUseRing0Runloop)
1167# endif
1168 {
1169 /* Call ring-0 and get the values. */
1170 int rc = VMMR3CallR0Emt(pVM, pVCpu, VMMR0_DO_NEM_QUERY_CPU_TICK, 0, NULL);
1171 AssertLogRelRCReturn(rc, rc);
1172 *pcTicks = pVCpu->nem.s.Hypercall.QueryCpuTick.cTicks;
1173 if (puAux)
1174 *puAux = pVCpu->cpum.GstCtx.fExtrn & CPUMCTX_EXTRN_TSC_AUX
1175 ? pVCpu->nem.s.Hypercall.QueryCpuTick.uAux : CPUMGetGuestTscAux(pVCpu);
1176 return VINF_SUCCESS;
1177 }
1178# endif
1179# ifndef NEM_WIN_USE_HYPERCALLS_FOR_REGISTERS
1180 /* Call the offical API. */
1181 WHV_REGISTER_NAME aenmNames[2] = { WHvX64RegisterTsc, WHvX64RegisterTscAux };
1182 WHV_REGISTER_VALUE aValues[2] = { {0, 0}, {0, 0} };
1183 Assert(RT_ELEMENTS(aenmNames) == RT_ELEMENTS(aValues));
1184 HRESULT hrc = WHvGetVirtualProcessorRegisters(pVM->nem.s.hPartition, pVCpu->idCpu, aenmNames, 2, aValues);
1185 AssertLogRelMsgReturn(SUCCEEDED(hrc),
1186 ("WHvGetVirtualProcessorRegisters(%p, %u,{tsc,tsc_aux},2,) -> %Rhrc (Last=%#x/%u)\n",
1187 pVM->nem.s.hPartition, pVCpu->idCpu, hrc, RTNtLastStatusValue(), RTNtLastErrorValue())
1188 , VERR_NEM_GET_REGISTERS_FAILED);
1189 *pcTicks = aValues[0].Reg64;
1190 if (puAux)
1191 *pcTicks = pVCpu->cpum.GstCtx.fExtrn & CPUMCTX_EXTRN_TSC_AUX ? aValues[0].Reg64 : CPUMGetGuestTscAux(pVCpu);
1192 return VINF_SUCCESS;
1193# endif /* !NEM_WIN_USE_HYPERCALLS_FOR_REGISTERS */
1194#else /* IN_RING0 */
1195# ifdef NEM_WIN_WITH_RING0_RUNLOOP
1196 int rc = nemR0WinQueryCpuTick(pVCpu->pGVM, pVCpu, pcTicks, puAux);
1197 if (RT_SUCCESS(rc) && puAux && !(pVCpu->cpum.GstCtx.fExtrn & CPUMCTX_EXTRN_TSC_AUX))
1198 *puAux = CPUMGetGuestTscAux(pVCpu);
1199 return rc;
1200# else
1201 RT_NOREF(pVCpu, pcTicks, puAux);
1202 return VERR_NOT_IMPLEMENTED;
1203# endif
1204#endif /* IN_RING0 */
1205}
1206
1207
1208/**
1209 * Resumes CPU clock (TSC) on all virtual CPUs.
1210 *
1211 * This is called by TM when the VM is started, restored, resumed or similar.
1212 *
1213 * @returns VBox status code.
1214 * @param pVM The cross context VM structure.
1215 * @param pVCpu The cross context CPU structure of the calling EMT.
1216 * @param uPausedTscValue The TSC value at the time of pausing.
1217 */
1218VMM_INT_DECL(int) NEMHCResumeCpuTickOnAll(PVMCC pVM, PVMCPUCC pVCpu, uint64_t uPausedTscValue)
1219{
1220#ifdef IN_RING0
1221# ifdef NEM_WIN_WITH_RING0_RUNLOOP
1222 return nemR0WinResumeCpuTickOnAll(pVM, pVCpu, uPausedTscValue);
1223# else
1224 RT_NOREF(pVM, pVCpu, uPausedTscValue);
1225 return VERR_NOT_IMPLEMENTED;
1226# endif
1227#else /* IN_RING3 */
1228 VMCPU_ASSERT_EMT_RETURN(pVCpu, VERR_VM_THREAD_NOT_EMT);
1229 AssertReturn(VM_IS_NEM_ENABLED(pVM), VERR_NEM_IPE_9);
1230
1231# if defined(NEM_WIN_USE_HYPERCALLS_FOR_REGISTERS) || defined(NEM_WIN_WITH_RING0_RUNLOOP)
1232# if !defined(NEM_WIN_USE_HYPERCALLS_FOR_REGISTERS) && defined(NEM_WIN_WITH_RING0_RUNLOOP)
1233 if (pVM->nem.s.fUseRing0Runloop)
1234# endif
1235 {
1236 /* Call ring-0 and do it all there. */
1237 return VMMR3CallR0Emt(pVM, pVCpu, VMMR0_DO_NEM_RESUME_CPU_TICK_ON_ALL, uPausedTscValue, NULL);
1238 }
1239# endif
1240# ifndef NEM_WIN_USE_HYPERCALLS_FOR_REGISTERS
1241 /*
1242 * Call the offical API to do the job.
1243 */
1244 if (pVM->cCpus > 1)
1245 RTThreadYield(); /* Try decrease the chance that we get rescheduled in the middle. */
1246
1247 /* Start with the first CPU. */
1248 WHV_REGISTER_NAME enmName = WHvX64RegisterTsc;
1249 WHV_REGISTER_VALUE Value = {0, 0};
1250 Value.Reg64 = uPausedTscValue;
1251 uint64_t const uFirstTsc = ASMReadTSC();
1252 HRESULT hrc = WHvSetVirtualProcessorRegisters(pVM->nem.s.hPartition, 0 /*iCpu*/, &enmName, 1, &Value);
1253 AssertLogRelMsgReturn(SUCCEEDED(hrc),
1254 ("WHvSetVirtualProcessorRegisters(%p, 0,{tsc},2,%#RX64) -> %Rhrc (Last=%#x/%u)\n",
1255 pVM->nem.s.hPartition, uPausedTscValue, hrc, RTNtLastStatusValue(), RTNtLastErrorValue())
1256 , VERR_NEM_SET_TSC);
1257
1258 /* Do the other CPUs, adjusting for elapsed TSC and keeping finger crossed
1259 that we don't introduce too much drift here. */
1260 for (VMCPUID iCpu = 1; iCpu < pVM->cCpus; iCpu++)
1261 {
1262 Assert(enmName == WHvX64RegisterTsc);
1263 const uint64_t offDelta = (ASMReadTSC() - uFirstTsc);
1264 Value.Reg64 = uPausedTscValue + offDelta;
1265 hrc = WHvSetVirtualProcessorRegisters(pVM->nem.s.hPartition, iCpu, &enmName, 1, &Value);
1266 AssertLogRelMsgReturn(SUCCEEDED(hrc),
1267 ("WHvSetVirtualProcessorRegisters(%p, 0,{tsc},2,%#RX64 + %#RX64) -> %Rhrc (Last=%#x/%u)\n",
1268 pVM->nem.s.hPartition, iCpu, uPausedTscValue, offDelta, hrc, RTNtLastStatusValue(), RTNtLastErrorValue())
1269 , VERR_NEM_SET_TSC);
1270 }
1271
1272 return VINF_SUCCESS;
1273# endif /* !NEM_WIN_USE_HYPERCALLS_FOR_REGISTERS */
1274#endif /* IN_RING3 */
1275}
1276
1277#ifdef NEMWIN_NEED_GET_REGISTER
1278# if defined(IN_RING0) || defined(NEM_WIN_USE_HYPERCALLS_FOR_REGISTERS)
1279/** Worker for assertion macro. */
1280NEM_TMPL_STATIC int nemHCWinGetRegister(PVMCPUCC pVCpu, PGVMCPU pGVCpu, uint32_t enmReg, HV_REGISTER_VALUE *pRetValue)
1281{
1282 RT_ZERO(*pRetValue);
1283# ifdef IN_RING3
1284 RT_NOREF(pVCpu, pGVCpu, enmReg);
1285 return VERR_NOT_IMPLEMENTED;
1286# else
1287 NOREF(pVCpu);
1288
1289 /*
1290 * Hypercall parameters.
1291 */
1292 HV_INPUT_GET_VP_REGISTERS *pInput = (HV_INPUT_GET_VP_REGISTERS *)pGVCpu->nem.s.HypercallData.pbPage;
1293 AssertPtrReturn(pInput, VERR_INTERNAL_ERROR_3);
1294 AssertReturn(g_pfnHvlInvokeHypercall, VERR_NEM_MISSING_KERNEL_API);
1295
1296 pInput->PartitionId = pVCpu->pGVM->nemr0.s.idHvPartition;
1297 pInput->VpIndex = pVCpu->idCpu;
1298 pInput->fFlags = 0;
1299 pInput->Names[0] = (HV_REGISTER_NAME)enmReg;
1300
1301 size_t const cbInput = RT_ALIGN_Z(RT_UOFFSETOF(HV_INPUT_GET_VP_REGISTERS, Names[1]), 32);
1302 HV_REGISTER_VALUE *paValues = (HV_REGISTER_VALUE *)((uint8_t *)pInput + cbInput);
1303 RT_BZERO(paValues, sizeof(paValues[0]) * 1);
1304
1305 /*
1306 * Make the hypercall and copy out the value.
1307 */
1308 uint64_t uResult = g_pfnHvlInvokeHypercall(HV_MAKE_CALL_INFO(HvCallGetVpRegisters, 1),
1309 pGVCpu->nem.s.HypercallData.HCPhysPage,
1310 pGVCpu->nem.s.HypercallData.HCPhysPage + cbInput);
1311 AssertLogRelMsgReturn(uResult == HV_MAKE_CALL_REP_RET(1), ("uResult=%RX64 cRegs=%#x\n", uResult, 1),
1312 VERR_NEM_GET_REGISTERS_FAILED);
1313
1314 *pRetValue = paValues[0];
1315 return VINF_SUCCESS;
1316# endif
1317}
1318# else
1319/** Worker for assertion macro. */
1320NEM_TMPL_STATIC int nemR3WinGetRegister(PVMCPUCC a_pVCpu, uint32_t a_enmReg, WHV_REGISTER_VALUE pValue)
1321{
1322 RT_ZERO(*pRetValue);
1323 RT_NOREF(pVCpu, pGVCpu, enmReg);
1324 return VERR_NOT_IMPLEMENTED;
1325}
1326# endif
1327#endif
1328
1329
1330#ifdef LOG_ENABLED
1331/**
1332 * Get the virtual processor running status.
1333 */
1334DECLINLINE(VID_PROCESSOR_STATUS) nemHCWinCpuGetRunningStatus(PVMCPUCC pVCpu)
1335{
1336# ifdef IN_RING0
1337 NOREF(pVCpu);
1338 return VidProcessorStatusUndefined;
1339# else
1340 RTERRVARS Saved;
1341 RTErrVarsSave(&Saved);
1342
1343 /*
1344 * This API is disabled in release builds, it seems. On build 17101 it requires
1345 * the following patch to be enabled (windbg): eb vid+12180 0f 84 98 00 00 00
1346 */
1347 VID_PROCESSOR_STATUS enmCpuStatus = VidProcessorStatusUndefined;
1348 NTSTATUS rcNt = g_pfnVidGetVirtualProcessorRunningStatus(pVCpu->pVMR3->nem.s.hPartitionDevice, pVCpu->idCpu, &enmCpuStatus);
1349 AssertRC(rcNt);
1350
1351 RTErrVarsRestore(&Saved);
1352 return enmCpuStatus;
1353# endif
1354}
1355#endif /* LOG_ENABLED */
1356
1357
1358#if defined(NEM_WIN_USE_OUR_OWN_RUN_API) || defined(NEM_WIN_WITH_RING0_RUNLOOP)
1359# ifdef IN_RING3 /* hopefully not needed in ring-0, as we'd need KTHREADs and KeAlertThread. */
1360/**
1361 * Our own WHvCancelRunVirtualProcessor that can later be moved to ring-0.
1362 *
1363 * This is an experiment only.
1364 *
1365 * @returns VBox status code.
1366 * @param pVM The cross context VM structure.
1367 * @param pVCpu The cross context virtual CPU structure of the
1368 * calling EMT.
1369 */
1370NEM_TMPL_STATIC int nemHCWinCancelRunVirtualProcessor(PVMCC pVM, PVMCPUCC pVCpu)
1371{
1372 /*
1373 * Work the state.
1374 *
1375 * From the looks of things, we should let the EMT call VidStopVirtualProcessor.
1376 * So, we just need to modify the state and kick the EMT if it's waiting on
1377 * messages. For the latter we use QueueUserAPC / KeAlterThread.
1378 */
1379 for (;;)
1380 {
1381 VMCPUSTATE enmState = VMCPU_GET_STATE(pVCpu);
1382 switch (enmState)
1383 {
1384 case VMCPUSTATE_STARTED_EXEC_NEM:
1385 if (VMCPU_CMPXCHG_STATE(pVCpu, VMCPUSTATE_STARTED_EXEC_NEM_CANCELED, VMCPUSTATE_STARTED_EXEC_NEM))
1386 {
1387 DBGFTRACE_CUSTOM(pVM, "VMCPUSTATE_STARTED_EXEC_NEM -> CANCELED");
1388 Log8(("nemHCWinCancelRunVirtualProcessor: Switched %u to canceled state\n", pVCpu->idCpu));
1389 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatCancelChangedState);
1390 return VINF_SUCCESS;
1391 }
1392 break;
1393
1394 case VMCPUSTATE_STARTED_EXEC_NEM_WAIT:
1395 if (VMCPU_CMPXCHG_STATE(pVCpu, VMCPUSTATE_STARTED_EXEC_NEM_CANCELED, VMCPUSTATE_STARTED_EXEC_NEM_WAIT))
1396 {
1397 DBGFTRACE_CUSTOM(pVM, "VMCPUSTATE_STARTED_EXEC_NEM_WAIT -> CANCELED");
1398# ifdef IN_RING0
1399 NTSTATUS rcNt = KeAlertThread(??);
1400 DBGFTRACE_CUSTOM(pVM, "KeAlertThread -> %#x", rcNt);
1401# else
1402 NTSTATUS rcNt = NtAlertThread(pVCpu->nem.s.hNativeThreadHandle);
1403 DBGFTRACE_CUSTOM(pVM, "NtAlertThread -> %#x", rcNt);
1404# endif
1405 Log8(("nemHCWinCancelRunVirtualProcessor: Alerted %u: %#x\n", pVCpu->idCpu, rcNt));
1406 Assert(rcNt == STATUS_SUCCESS);
1407 if (NT_SUCCESS(rcNt))
1408 {
1409 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatCancelAlertedThread);
1410 return VINF_SUCCESS;
1411 }
1412 AssertLogRelMsgFailedReturn(("NtAlertThread failed: %#x\n", rcNt), RTErrConvertFromNtStatus(rcNt));
1413 }
1414 break;
1415
1416 default:
1417 return VINF_SUCCESS;
1418 }
1419
1420 ASMNopPause();
1421 RT_NOREF(pVM);
1422 }
1423}
1424# endif /* IN_RING3 */
1425#endif /* NEM_WIN_USE_OUR_OWN_RUN_API || NEM_WIN_WITH_RING0_RUNLOOP */
1426
1427
1428#ifdef LOG_ENABLED
1429/**
1430 * Logs the current CPU state.
1431 */
1432NEM_TMPL_STATIC void nemHCWinLogState(PVMCC pVM, PVMCPUCC pVCpu)
1433{
1434 if (LogIs3Enabled())
1435 {
1436# if 0 // def IN_RING3 - causes lazy state import assertions all over CPUM.
1437 char szRegs[4096];
1438 DBGFR3RegPrintf(pVM->pUVM, pVCpu->idCpu, &szRegs[0], sizeof(szRegs),
1439 "rax=%016VR{rax} rbx=%016VR{rbx} rcx=%016VR{rcx} rdx=%016VR{rdx}\n"
1440 "rsi=%016VR{rsi} rdi=%016VR{rdi} r8 =%016VR{r8} r9 =%016VR{r9}\n"
1441 "r10=%016VR{r10} r11=%016VR{r11} r12=%016VR{r12} r13=%016VR{r13}\n"
1442 "r14=%016VR{r14} r15=%016VR{r15} %VRF{rflags}\n"
1443 "rip=%016VR{rip} rsp=%016VR{rsp} rbp=%016VR{rbp}\n"
1444 "cs={%04VR{cs} base=%016VR{cs_base} limit=%08VR{cs_lim} flags=%04VR{cs_attr}} cr0=%016VR{cr0}\n"
1445 "ds={%04VR{ds} base=%016VR{ds_base} limit=%08VR{ds_lim} flags=%04VR{ds_attr}} cr2=%016VR{cr2}\n"
1446 "es={%04VR{es} base=%016VR{es_base} limit=%08VR{es_lim} flags=%04VR{es_attr}} cr3=%016VR{cr3}\n"
1447 "fs={%04VR{fs} base=%016VR{fs_base} limit=%08VR{fs_lim} flags=%04VR{fs_attr}} cr4=%016VR{cr4}\n"
1448 "gs={%04VR{gs} base=%016VR{gs_base} limit=%08VR{gs_lim} flags=%04VR{gs_attr}} cr8=%016VR{cr8}\n"
1449 "ss={%04VR{ss} base=%016VR{ss_base} limit=%08VR{ss_lim} flags=%04VR{ss_attr}}\n"
1450 "dr0=%016VR{dr0} dr1=%016VR{dr1} dr2=%016VR{dr2} dr3=%016VR{dr3}\n"
1451 "dr6=%016VR{dr6} dr7=%016VR{dr7}\n"
1452 "gdtr=%016VR{gdtr_base}:%04VR{gdtr_lim} idtr=%016VR{idtr_base}:%04VR{idtr_lim} rflags=%08VR{rflags}\n"
1453 "ldtr={%04VR{ldtr} base=%016VR{ldtr_base} limit=%08VR{ldtr_lim} flags=%08VR{ldtr_attr}}\n"
1454 "tr ={%04VR{tr} base=%016VR{tr_base} limit=%08VR{tr_lim} flags=%08VR{tr_attr}}\n"
1455 " sysenter={cs=%04VR{sysenter_cs} eip=%08VR{sysenter_eip} esp=%08VR{sysenter_esp}}\n"
1456 " efer=%016VR{efer}\n"
1457 " pat=%016VR{pat}\n"
1458 " sf_mask=%016VR{sf_mask}\n"
1459 "krnl_gs_base=%016VR{krnl_gs_base}\n"
1460 " lstar=%016VR{lstar}\n"
1461 " star=%016VR{star} cstar=%016VR{cstar}\n"
1462 "fcw=%04VR{fcw} fsw=%04VR{fsw} ftw=%04VR{ftw} mxcsr=%04VR{mxcsr} mxcsr_mask=%04VR{mxcsr_mask}\n"
1463 );
1464
1465 char szInstr[256];
1466 DBGFR3DisasInstrEx(pVM->pUVM, pVCpu->idCpu, 0, 0,
1467 DBGF_DISAS_FLAGS_CURRENT_GUEST | DBGF_DISAS_FLAGS_DEFAULT_MODE,
1468 szInstr, sizeof(szInstr), NULL);
1469 Log3(("%s%s\n", szRegs, szInstr));
1470# else
1471 /** @todo stat logging in ring-0 */
1472 RT_NOREF(pVM, pVCpu);
1473# endif
1474 }
1475}
1476#endif /* LOG_ENABLED */
1477
1478
1479/** Macro used by nemHCWinExecStateToLogStr and nemR3WinExecStateToLogStr. */
1480#define SWITCH_IT(a_szPrefix) \
1481 do \
1482 switch (u)\
1483 { \
1484 case 0x00: return a_szPrefix ""; \
1485 case 0x01: return a_szPrefix ",Pnd"; \
1486 case 0x02: return a_szPrefix ",Dbg"; \
1487 case 0x03: return a_szPrefix ",Pnd,Dbg"; \
1488 case 0x04: return a_szPrefix ",Shw"; \
1489 case 0x05: return a_szPrefix ",Pnd,Shw"; \
1490 case 0x06: return a_szPrefix ",Shw,Dbg"; \
1491 case 0x07: return a_szPrefix ",Pnd,Shw,Dbg"; \
1492 default: AssertFailedReturn("WTF?"); \
1493 } \
1494 while (0)
1495
1496#ifdef NEM_WIN_TEMPLATE_MODE_OWN_RUN_API
1497/**
1498 * Translates the execution stat bitfield into a short log string, VID version.
1499 *
1500 * @returns Read-only log string.
1501 * @param pMsgHdr The header which state to summarize.
1502 */
1503static const char *nemHCWinExecStateToLogStr(HV_X64_INTERCEPT_MESSAGE_HEADER const *pMsgHdr)
1504{
1505 unsigned u = (unsigned)pMsgHdr->ExecutionState.InterruptionPending
1506 | ((unsigned)pMsgHdr->ExecutionState.DebugActive << 1)
1507 | ((unsigned)pMsgHdr->ExecutionState.InterruptShadow << 2);
1508 if (pMsgHdr->ExecutionState.EferLma)
1509 SWITCH_IT("LM");
1510 else if (pMsgHdr->ExecutionState.Cr0Pe)
1511 SWITCH_IT("PM");
1512 else
1513 SWITCH_IT("RM");
1514}
1515#elif defined(IN_RING3)
1516/**
1517 * Translates the execution stat bitfield into a short log string, WinHv version.
1518 *
1519 * @returns Read-only log string.
1520 * @param pExitCtx The exit context which state to summarize.
1521 */
1522static const char *nemR3WinExecStateToLogStr(WHV_VP_EXIT_CONTEXT const *pExitCtx)
1523{
1524 unsigned u = (unsigned)pExitCtx->ExecutionState.InterruptionPending
1525 | ((unsigned)pExitCtx->ExecutionState.DebugActive << 1)
1526 | ((unsigned)pExitCtx->ExecutionState.InterruptShadow << 2);
1527 if (pExitCtx->ExecutionState.EferLma)
1528 SWITCH_IT("LM");
1529 else if (pExitCtx->ExecutionState.Cr0Pe)
1530 SWITCH_IT("PM");
1531 else
1532 SWITCH_IT("RM");
1533}
1534#endif /* IN_RING3 && !NEM_WIN_TEMPLATE_MODE_OWN_RUN_API */
1535#undef SWITCH_IT
1536
1537
1538#ifdef NEM_WIN_TEMPLATE_MODE_OWN_RUN_API
1539/**
1540 * Advances the guest RIP and clear EFLAGS.RF, VID version.
1541 *
1542 * This may clear VMCPU_FF_INHIBIT_INTERRUPTS.
1543 *
1544 * @param pVCpu The cross context virtual CPU structure.
1545 * @param pExitCtx The exit context.
1546 * @param cbMinInstr The minimum instruction length, or 1 if not unknown.
1547 */
1548DECLINLINE(void)
1549nemHCWinAdvanceGuestRipAndClearRF(PVMCPUCC pVCpu, HV_X64_INTERCEPT_MESSAGE_HEADER const *pMsgHdr, uint8_t cbMinInstr)
1550{
1551 Assert(!(pVCpu->cpum.GstCtx.fExtrn & (CPUMCTX_EXTRN_RIP | CPUMCTX_EXTRN_RFLAGS)));
1552
1553 /* Advance the RIP. */
1554 Assert(pMsgHdr->InstructionLength >= cbMinInstr); RT_NOREF_PV(cbMinInstr);
1555 pVCpu->cpum.GstCtx.rip += pMsgHdr->InstructionLength;
1556 pVCpu->cpum.GstCtx.rflags.Bits.u1RF = 0;
1557
1558 /* Update interrupt inhibition. */
1559 if (!VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS))
1560 { /* likely */ }
1561 else if (pVCpu->cpum.GstCtx.rip != EMGetInhibitInterruptsPC(pVCpu))
1562 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS);
1563}
1564#elif defined(IN_RING3)
1565/**
1566 * Advances the guest RIP and clear EFLAGS.RF, WinHv version.
1567 *
1568 * This may clear VMCPU_FF_INHIBIT_INTERRUPTS.
1569 *
1570 * @param pVCpu The cross context virtual CPU structure.
1571 * @param pExitCtx The exit context.
1572 * @param cbMinInstr The minimum instruction length, or 1 if not unknown.
1573 */
1574DECLINLINE(void) nemR3WinAdvanceGuestRipAndClearRF(PVMCPUCC pVCpu, WHV_VP_EXIT_CONTEXT const *pExitCtx, uint8_t cbMinInstr)
1575{
1576 Assert(!(pVCpu->cpum.GstCtx.fExtrn & (CPUMCTX_EXTRN_RIP | CPUMCTX_EXTRN_RFLAGS)));
1577
1578 /* Advance the RIP. */
1579 Assert(pExitCtx->InstructionLength >= cbMinInstr); RT_NOREF_PV(cbMinInstr);
1580 pVCpu->cpum.GstCtx.rip += pExitCtx->InstructionLength;
1581 pVCpu->cpum.GstCtx.rflags.Bits.u1RF = 0;
1582
1583 /* Update interrupt inhibition. */
1584 if (!VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS))
1585 { /* likely */ }
1586 else if (pVCpu->cpum.GstCtx.rip != EMGetInhibitInterruptsPC(pVCpu))
1587 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS);
1588}
1589#endif /* IN_RING3 && !NEM_WIN_TEMPLATE_MODE_OWN_RUN_API */
1590
1591#if defined(NEM_WIN_USE_HYPERCALLS_FOR_PAGES) || defined(IN_RING3)
1592
1593NEM_TMPL_STATIC DECLCALLBACK(int)
1594nemHCWinUnmapOnePageCallback(PVMCC pVM, PVMCPUCC pVCpu, RTGCPHYS GCPhys, uint8_t *pu2NemState, void *pvUser)
1595{
1596 RT_NOREF_PV(pvUser);
1597# ifdef NEM_WIN_USE_HYPERCALLS_FOR_PAGES
1598 int rc = nemHCWinHypercallUnmapPage(pVM, pVCpu, GCPhys);
1599 AssertRC(rc);
1600 if (RT_SUCCESS(rc))
1601# else
1602 RT_NOREF_PV(pVCpu);
1603 HRESULT hrc = WHvUnmapGpaRange(pVM->nem.s.hPartition, GCPhys, X86_PAGE_SIZE);
1604 if (SUCCEEDED(hrc))
1605# endif
1606 {
1607 Log5(("NEM GPA unmap all: %RGp (cMappedPages=%u)\n", GCPhys, pVM->nem.s.cMappedPages - 1));
1608 *pu2NemState = NEM_WIN_PAGE_STATE_UNMAPPED;
1609 STAM_REL_COUNTER_INC(&pVM->nem.s.StatUnmapPage);
1610 }
1611 else
1612 {
1613# ifdef NEM_WIN_USE_HYPERCALLS_FOR_PAGES
1614 LogRel(("nemHCWinUnmapOnePageCallback: GCPhys=%RGp rc=%Rrc\n", GCPhys, rc));
1615# else
1616 LogRel(("nemHCWinUnmapOnePageCallback: GCPhys=%RGp %s hrc=%Rhrc (%#x) Last=%#x/%u (cMappedPages=%u)\n",
1617 GCPhys, g_apszPageStates[*pu2NemState], hrc, hrc, RTNtLastStatusValue(),
1618 RTNtLastErrorValue(), pVM->nem.s.cMappedPages));
1619# endif
1620 *pu2NemState = NEM_WIN_PAGE_STATE_NOT_SET;
1621 STAM_REL_COUNTER_INC(&pVM->nem.s.StatUnmapPageFailed);
1622 }
1623 if (pVM->nem.s.cMappedPages > 0)
1624 ASMAtomicDecU32(&pVM->nem.s.cMappedPages);
1625 return VINF_SUCCESS;
1626}
1627
1628
1629/**
1630 * State to pass between nemHCWinHandleMemoryAccess / nemR3WinWHvHandleMemoryAccess
1631 * and nemHCWinHandleMemoryAccessPageCheckerCallback.
1632 */
1633typedef struct NEMHCWINHMACPCCSTATE
1634{
1635 /** Input: Write access. */
1636 bool fWriteAccess;
1637 /** Output: Set if we did something. */
1638 bool fDidSomething;
1639 /** Output: Set it we should resume. */
1640 bool fCanResume;
1641} NEMHCWINHMACPCCSTATE;
1642
1643/**
1644 * @callback_method_impl{FNPGMPHYSNEMCHECKPAGE,
1645 * Worker for nemR3WinHandleMemoryAccess; pvUser points to a
1646 * NEMHCWINHMACPCCSTATE structure. }
1647 */
1648NEM_TMPL_STATIC DECLCALLBACK(int)
1649nemHCWinHandleMemoryAccessPageCheckerCallback(PVMCC pVM, PVMCPUCC pVCpu, RTGCPHYS GCPhys, PPGMPHYSNEMPAGEINFO pInfo, void *pvUser)
1650{
1651 NEMHCWINHMACPCCSTATE *pState = (NEMHCWINHMACPCCSTATE *)pvUser;
1652 pState->fDidSomething = false;
1653 pState->fCanResume = false;
1654
1655 /* If A20 is disabled, we may need to make another query on the masked
1656 page to get the correct protection information. */
1657 uint8_t u2State = pInfo->u2NemState;
1658 RTGCPHYS GCPhysSrc;
1659 if ( pVM->nem.s.fA20Enabled
1660 || !NEM_WIN_IS_SUBJECT_TO_A20(GCPhys))
1661 GCPhysSrc = GCPhys;
1662 else
1663 {
1664 GCPhysSrc = GCPhys & ~(RTGCPHYS)RT_BIT_32(20);
1665 PGMPHYSNEMPAGEINFO Info2;
1666 int rc = PGMPhysNemPageInfoChecker(pVM, pVCpu, GCPhysSrc, pState->fWriteAccess, &Info2, NULL, NULL);
1667 AssertRCReturn(rc, rc);
1668
1669 *pInfo = Info2;
1670 pInfo->u2NemState = u2State;
1671 }
1672
1673 /*
1674 * Consolidate current page state with actual page protection and access type.
1675 * We don't really consider downgrades here, as they shouldn't happen.
1676 */
1677# ifndef NEM_WIN_USE_HYPERCALLS_FOR_PAGES
1678 /** @todo Someone at microsoft please explain:
1679 * I'm not sure WTF was going on, but I ended up in a loop if I remapped a
1680 * readonly page as writable (unmap, then map again). Specifically, this was an
1681 * issue with the big VRAM mapping at 0xe0000000 when booing DSL 4.4.1. So, in
1682 * a hope to work around that we no longer pre-map anything, just unmap stuff
1683 * and do it lazily here. And here we will first unmap, restart, and then remap
1684 * with new protection or backing.
1685 */
1686# endif
1687 int rc;
1688 switch (u2State)
1689 {
1690 case NEM_WIN_PAGE_STATE_UNMAPPED:
1691 case NEM_WIN_PAGE_STATE_NOT_SET:
1692 if (pInfo->fNemProt == NEM_PAGE_PROT_NONE)
1693 {
1694 Log4(("nemHCWinHandleMemoryAccessPageCheckerCallback: %RGp - #1\n", GCPhys));
1695 return VINF_SUCCESS;
1696 }
1697
1698 /* Don't bother remapping it if it's a write request to a non-writable page. */
1699 if ( pState->fWriteAccess
1700 && !(pInfo->fNemProt & NEM_PAGE_PROT_WRITE))
1701 {
1702 Log4(("nemHCWinHandleMemoryAccessPageCheckerCallback: %RGp - #1w\n", GCPhys));
1703 return VINF_SUCCESS;
1704 }
1705
1706 /* Map the page. */
1707 rc = nemHCNativeSetPhysPage(pVM,
1708 pVCpu,
1709 GCPhysSrc & ~(RTGCPHYS)X86_PAGE_OFFSET_MASK,
1710 GCPhys & ~(RTGCPHYS)X86_PAGE_OFFSET_MASK,
1711 pInfo->fNemProt,
1712 &u2State,
1713 true /*fBackingState*/);
1714 pInfo->u2NemState = u2State;
1715 Log4(("nemHCWinHandleMemoryAccessPageCheckerCallback: %RGp - synced => %s + %Rrc\n",
1716 GCPhys, g_apszPageStates[u2State], rc));
1717 pState->fDidSomething = true;
1718 pState->fCanResume = true;
1719 return rc;
1720
1721 case NEM_WIN_PAGE_STATE_READABLE:
1722 if ( !(pInfo->fNemProt & NEM_PAGE_PROT_WRITE)
1723 && (pInfo->fNemProt & (NEM_PAGE_PROT_READ | NEM_PAGE_PROT_EXECUTE)))
1724 {
1725 Log4(("nemHCWinHandleMemoryAccessPageCheckerCallback: %RGp - #2\n", GCPhys));
1726 return VINF_SUCCESS;
1727 }
1728
1729# ifdef NEM_WIN_USE_HYPERCALLS_FOR_PAGES
1730 /* Upgrade page to writable. */
1731/** @todo test this*/
1732 if ( (pInfo->fNemProt & NEM_PAGE_PROT_WRITE)
1733 && pState->fWriteAccess)
1734 {
1735 rc = nemHCWinHypercallMapPage(pVM, pVCpu, GCPhysSrc, GCPhys,
1736 HV_MAP_GPA_READABLE | HV_MAP_GPA_WRITABLE
1737 | HV_MAP_GPA_EXECUTABLE | HV_MAP_GPA_EXECUTABLE_AGAIN);
1738 AssertRC(rc);
1739 if (RT_SUCCESS(rc))
1740 {
1741 STAM_REL_COUNTER_INC(&pVM->nem.s.StatRemapPage);
1742 pInfo->u2NemState = NEM_WIN_PAGE_STATE_WRITABLE;
1743 pState->fDidSomething = true;
1744 pState->fCanResume = true;
1745 Log5(("NEM GPA write-upgrade/exit: %RGp (was %s, cMappedPages=%u)\n",
1746 GCPhys, g_apszPageStates[u2State], pVM->nem.s.cMappedPages));
1747 }
1748 else
1749 STAM_REL_COUNTER_INC(&pVM->nem.s.StatRemapPageFailed);
1750 }
1751 else
1752 {
1753 /* Need to emulate the acces. */
1754 AssertBreak(pInfo->fNemProt != NEM_PAGE_PROT_NONE); /* There should be no downgrades. */
1755 rc = VINF_SUCCESS;
1756 }
1757 return rc;
1758# else
1759 break;
1760# endif
1761
1762 case NEM_WIN_PAGE_STATE_WRITABLE:
1763 if (pInfo->fNemProt & NEM_PAGE_PROT_WRITE)
1764 {
1765 if (pInfo->u2OldNemState == NEM_WIN_PAGE_STATE_WRITABLE)
1766 Log4(("nemHCWinHandleMemoryAccessPageCheckerCallback: %RGp - #3a\n", GCPhys));
1767 else
1768 {
1769 pState->fCanResume = true;
1770 Log4(("nemHCWinHandleMemoryAccessPageCheckerCallback: %RGp - #3b (%s -> %s)\n",
1771 GCPhys, g_apszPageStates[pInfo->u2OldNemState], g_apszPageStates[u2State]));
1772 }
1773 return VINF_SUCCESS;
1774 }
1775# ifdef NEM_WIN_USE_HYPERCALLS_FOR_PAGES
1776 AssertFailed(); /* There should be no downgrades. */
1777# endif
1778 break;
1779
1780 default:
1781 AssertLogRelMsgFailedReturn(("u2State=%#x\n", u2State), VERR_NEM_IPE_4);
1782 }
1783
1784 /*
1785 * Unmap and restart the instruction.
1786 * If this fails, which it does every so often, just unmap everything for now.
1787 */
1788# ifdef NEM_WIN_USE_HYPERCALLS_FOR_PAGES
1789 rc = nemHCWinHypercallUnmapPage(pVM, pVCpu, GCPhys);
1790 AssertRC(rc);
1791 if (RT_SUCCESS(rc))
1792# else
1793 /** @todo figure out whether we mess up the state or if it's WHv. */
1794 HRESULT hrc = WHvUnmapGpaRange(pVM->nem.s.hPartition, GCPhys, X86_PAGE_SIZE);
1795 if (SUCCEEDED(hrc))
1796# endif
1797 {
1798 pState->fDidSomething = true;
1799 pState->fCanResume = true;
1800 pInfo->u2NemState = NEM_WIN_PAGE_STATE_UNMAPPED;
1801 STAM_REL_COUNTER_INC(&pVM->nem.s.StatUnmapPage);
1802 uint32_t cMappedPages = ASMAtomicDecU32(&pVM->nem.s.cMappedPages); NOREF(cMappedPages);
1803 Log5(("NEM GPA unmapped/exit: %RGp (was %s, cMappedPages=%u)\n", GCPhys, g_apszPageStates[u2State], cMappedPages));
1804 return VINF_SUCCESS;
1805 }
1806 STAM_REL_COUNTER_INC(&pVM->nem.s.StatUnmapPageFailed);
1807# ifdef NEM_WIN_USE_HYPERCALLS_FOR_PAGES
1808 LogRel(("nemHCWinHandleMemoryAccessPageCheckerCallback/unmap: GCPhysDst=%RGp rc=%Rrc\n", GCPhys, rc));
1809 return rc;
1810# else
1811 LogRel(("nemHCWinHandleMemoryAccessPageCheckerCallback/unmap: GCPhysDst=%RGp %s hrc=%Rhrc (%#x) Last=%#x/%u (cMappedPages=%u)\n",
1812 GCPhys, g_apszPageStates[u2State], hrc, hrc, RTNtLastStatusValue(), RTNtLastErrorValue(),
1813 pVM->nem.s.cMappedPages));
1814
1815 PGMPhysNemEnumPagesByState(pVM, pVCpu, NEM_WIN_PAGE_STATE_READABLE, nemHCWinUnmapOnePageCallback, NULL);
1816 Log(("nemHCWinHandleMemoryAccessPageCheckerCallback: Unmapped all (cMappedPages=%u)\n", pVM->nem.s.cMappedPages));
1817 STAM_REL_COUNTER_INC(&pVM->nem.s.StatUnmapAllPages);
1818
1819 pState->fDidSomething = true;
1820 pState->fCanResume = true;
1821 pInfo->u2NemState = NEM_WIN_PAGE_STATE_UNMAPPED;
1822 return VINF_SUCCESS;
1823# endif
1824}
1825
1826#endif /* defined(NEM_WIN_USE_HYPERCALLS_FOR_PAGES) || defined(IN_RING3) */
1827
1828
1829#if defined(IN_RING0) && defined(NEM_WIN_TEMPLATE_MODE_OWN_RUN_API)
1830/**
1831 * Wrapper around nemR0WinImportState that converts VERR_NEM_FLUSH_TLB
1832 * into informational status codes and logs+asserts statuses.
1833 *
1834 * @returns VBox strict status code.
1835 * @param pGVM The global (ring-0) VM structure.
1836 * @param pGVCpu The global (ring-0) per CPU structure.
1837 * @param fWhat What to import.
1838 * @param pszCaller Who is doing the importing.
1839 */
1840DECLINLINE(VBOXSTRICTRC) nemR0WinImportStateStrict(PGVM pGVM, PGVMCPU pGVCpu, uint64_t fWhat, const char *pszCaller)
1841{
1842 int rc = nemR0WinImportState(pGVM, pGVCpu, &pGVCpu->cpum.GstCtx, fWhat, true /*fCanUpdateCr3*/);
1843 if (RT_SUCCESS(rc))
1844 {
1845 Assert(rc == VINF_SUCCESS);
1846 return VINF_SUCCESS;
1847 }
1848
1849 if (rc == VERR_NEM_FLUSH_TLB)
1850 {
1851 Log4(("%s/%u: nemR0WinImportState -> %Rrc\n", pszCaller, pGVCpu->idCpu, -rc));
1852 return -rc;
1853 }
1854 RT_NOREF(pszCaller);
1855 AssertMsgFailedReturn(("%s/%u: nemR0WinImportState failed: %Rrc\n", pszCaller, pGVCpu->idCpu, rc), rc);
1856}
1857#endif /* IN_RING0 && NEM_WIN_TEMPLATE_MODE_OWN_RUN_API*/
1858
1859#if defined(NEM_WIN_TEMPLATE_MODE_OWN_RUN_API) || defined(IN_RING3)
1860/**
1861 * Wrapper around nemR0WinImportStateStrict and nemHCWinCopyStateFromHyperV.
1862 *
1863 * Unlike the wrapped APIs, this checks whether it's necessary.
1864 *
1865 * @returns VBox strict status code.
1866 * @param pVCpu The cross context per CPU structure.
1867 * @param fWhat What to import.
1868 * @param pszCaller Who is doing the importing.
1869 */
1870DECLINLINE(VBOXSTRICTRC) nemHCWinImportStateIfNeededStrict(PVMCPUCC pVCpu, uint64_t fWhat, const char *pszCaller)
1871{
1872 if (pVCpu->cpum.GstCtx.fExtrn & fWhat)
1873 {
1874# ifdef IN_RING0
1875 return nemR0WinImportStateStrict(pVCpu->pGVM, pVCpu, fWhat, pszCaller);
1876# else
1877 RT_NOREF(pszCaller);
1878 int rc = nemHCWinCopyStateFromHyperV(pVCpu->pVMR3, pVCpu, fWhat);
1879 AssertRCReturn(rc, rc);
1880# endif
1881 }
1882 return VINF_SUCCESS;
1883}
1884#endif /* NEM_WIN_TEMPLATE_MODE_OWN_RUN_API || IN_RING3 */
1885
1886#ifdef NEM_WIN_TEMPLATE_MODE_OWN_RUN_API
1887/**
1888 * Copies register state from the X64 intercept message header.
1889 *
1890 * ASSUMES no state copied yet.
1891 *
1892 * @param pVCpu The cross context per CPU structure.
1893 * @param pHdr The X64 intercept message header.
1894 * @sa nemR3WinCopyStateFromX64Header
1895 */
1896DECLINLINE(void) nemHCWinCopyStateFromX64Header(PVMCPUCC pVCpu, HV_X64_INTERCEPT_MESSAGE_HEADER const *pHdr)
1897{
1898 Assert( (pVCpu->cpum.GstCtx.fExtrn & (CPUMCTX_EXTRN_RIP | CPUMCTX_EXTRN_RFLAGS | CPUMCTX_EXTRN_CS | CPUMCTX_EXTRN_NEM_WIN_INHIBIT_INT))
1899 == (CPUMCTX_EXTRN_RIP | CPUMCTX_EXTRN_RFLAGS | CPUMCTX_EXTRN_CS | CPUMCTX_EXTRN_NEM_WIN_INHIBIT_INT));
1900 NEM_WIN_COPY_BACK_SEG(pVCpu->cpum.GstCtx.cs, pHdr->CsSegment);
1901 pVCpu->cpum.GstCtx.rip = pHdr->Rip;
1902 pVCpu->cpum.GstCtx.rflags.u = pHdr->Rflags;
1903
1904 pVCpu->nem.s.fLastInterruptShadow = pHdr->ExecutionState.InterruptShadow;
1905 if (!pHdr->ExecutionState.InterruptShadow)
1906 {
1907 if (!VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS))
1908 { /* likely */ }
1909 else
1910 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS);
1911 }
1912 else
1913 EMSetInhibitInterruptsPC(pVCpu, pHdr->Rip);
1914
1915 APICSetTpr(pVCpu, pHdr->Cr8 << 4);
1916
1917 pVCpu->cpum.GstCtx.fExtrn &= ~(CPUMCTX_EXTRN_RIP | CPUMCTX_EXTRN_RFLAGS | CPUMCTX_EXTRN_CS | CPUMCTX_EXTRN_NEM_WIN_INHIBIT_INT | CPUMCTX_EXTRN_APIC_TPR);
1918}
1919#elif defined(IN_RING3)
1920/**
1921 * Copies register state from the (common) exit context.
1922 *
1923 * ASSUMES no state copied yet.
1924 *
1925 * @param pVCpu The cross context per CPU structure.
1926 * @param pExitCtx The common exit context.
1927 * @sa nemHCWinCopyStateFromX64Header
1928 */
1929DECLINLINE(void) nemR3WinCopyStateFromX64Header(PVMCPUCC pVCpu, WHV_VP_EXIT_CONTEXT const *pExitCtx)
1930{
1931 Assert( (pVCpu->cpum.GstCtx.fExtrn & (CPUMCTX_EXTRN_RIP | CPUMCTX_EXTRN_RFLAGS | CPUMCTX_EXTRN_CS | CPUMCTX_EXTRN_NEM_WIN_INHIBIT_INT))
1932 == (CPUMCTX_EXTRN_RIP | CPUMCTX_EXTRN_RFLAGS | CPUMCTX_EXTRN_CS | CPUMCTX_EXTRN_NEM_WIN_INHIBIT_INT));
1933 NEM_WIN_COPY_BACK_SEG(pVCpu->cpum.GstCtx.cs, pExitCtx->Cs);
1934 pVCpu->cpum.GstCtx.rip = pExitCtx->Rip;
1935 pVCpu->cpum.GstCtx.rflags.u = pExitCtx->Rflags;
1936
1937 pVCpu->nem.s.fLastInterruptShadow = pExitCtx->ExecutionState.InterruptShadow;
1938 if (!pExitCtx->ExecutionState.InterruptShadow)
1939 {
1940 if (!VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS))
1941 { /* likely */ }
1942 else
1943 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS);
1944 }
1945 else
1946 EMSetInhibitInterruptsPC(pVCpu, pExitCtx->Rip);
1947
1948 APICSetTpr(pVCpu, pExitCtx->Cr8 << 4);
1949
1950 pVCpu->cpum.GstCtx.fExtrn &= ~(CPUMCTX_EXTRN_RIP | CPUMCTX_EXTRN_RFLAGS | CPUMCTX_EXTRN_CS | CPUMCTX_EXTRN_NEM_WIN_INHIBIT_INT | CPUMCTX_EXTRN_APIC_TPR);
1951}
1952#endif /* IN_RING3 && !NEM_WIN_TEMPLATE_MODE_OWN_RUN_API */
1953
1954
1955#ifdef NEM_WIN_TEMPLATE_MODE_OWN_RUN_API
1956/**
1957 * Deals with memory intercept message.
1958 *
1959 * @returns Strict VBox status code.
1960 * @param pVM The cross context VM structure.
1961 * @param pVCpu The cross context per CPU structure.
1962 * @param pMsg The message.
1963 * @sa nemR3WinHandleExitMemory
1964 */
1965NEM_TMPL_STATIC VBOXSTRICTRC
1966nemHCWinHandleMessageMemory(PVMCC pVM, PVMCPUCC pVCpu, HV_X64_MEMORY_INTERCEPT_MESSAGE const *pMsg)
1967{
1968 uint64_t const uHostTsc = ASMReadTSC();
1969 Assert( pMsg->Header.InterceptAccessType == HV_INTERCEPT_ACCESS_READ
1970 || pMsg->Header.InterceptAccessType == HV_INTERCEPT_ACCESS_WRITE
1971 || pMsg->Header.InterceptAccessType == HV_INTERCEPT_ACCESS_EXECUTE);
1972
1973 /*
1974 * Whatever we do, we must clear pending event injection upon resume.
1975 */
1976 if (pMsg->Header.ExecutionState.InterruptionPending)
1977 pVCpu->cpum.GstCtx.fExtrn &= ~CPUMCTX_EXTRN_NEM_WIN_EVENT_INJECT;
1978
1979# if 0 /* Experiment: 20K -> 34K exit/s. */
1980 if ( pMsg->Header.ExecutionState.EferLma
1981 && pMsg->Header.CsSegment.Long
1982 && pMsg->Header.InterceptAccessType == HV_INTERCEPT_ACCESS_WRITE)
1983 {
1984 if ( pMsg->Header.Rip - (uint64_t)0xf65a < (uint64_t)(0xf662 - 0xf65a)
1985 && pMsg->InstructionBytes[0] == 0x89
1986 && pMsg->InstructionBytes[1] == 0x03)
1987 {
1988 pVCpu->cpum.GstCtx.rip = pMsg->Header.Rip + 2;
1989 pVCpu->cpum.GstCtx.fExtrn &= ~CPUMCTX_EXTRN_RIP;
1990 AssertMsg(pMsg->Header.InstructionLength == 2, ("%#x\n", pMsg->Header.InstructionLength));
1991 //Log(("%RX64 msg:\n%.80Rhxd\n", pVCpu->cpum.GstCtx.rip, pMsg));
1992 return VINF_SUCCESS;
1993 }
1994 }
1995# endif
1996
1997 /*
1998 * Ask PGM for information about the given GCPhys. We need to check if we're
1999 * out of sync first.
2000 */
2001 NEMHCWINHMACPCCSTATE State = { pMsg->Header.InterceptAccessType == HV_INTERCEPT_ACCESS_WRITE, false, false };
2002 PGMPHYSNEMPAGEINFO Info;
2003 int rc = PGMPhysNemPageInfoChecker(pVM, pVCpu, pMsg->GuestPhysicalAddress, State.fWriteAccess, &Info,
2004 nemHCWinHandleMemoryAccessPageCheckerCallback, &State);
2005 if (RT_SUCCESS(rc))
2006 {
2007 if (Info.fNemProt & ( pMsg->Header.InterceptAccessType == HV_INTERCEPT_ACCESS_WRITE
2008 ? NEM_PAGE_PROT_WRITE : NEM_PAGE_PROT_READ))
2009 {
2010 if (State.fCanResume)
2011 {
2012 Log4(("MemExit/%u: %04x:%08RX64/%s: %RGp (=>%RHp) %s fProt=%u%s%s%s; restarting (%s)\n",
2013 pVCpu->idCpu, pMsg->Header.CsSegment.Selector, pMsg->Header.Rip, nemHCWinExecStateToLogStr(&pMsg->Header),
2014 pMsg->GuestPhysicalAddress, Info.HCPhys, g_apszPageStates[Info.u2NemState], Info.fNemProt,
2015 Info.fHasHandlers ? " handlers" : "", Info.fZeroPage ? " zero-pg" : "",
2016 State.fDidSomething ? "" : " no-change", g_apszHvInterceptAccessTypes[pMsg->Header.InterceptAccessType]));
2017 EMHistoryAddExit(pVCpu, EMEXIT_MAKE_FT(EMEXIT_F_KIND_NEM, NEMEXITTYPE_MEMORY_ACCESS),
2018 pMsg->Header.Rip + pMsg->Header.CsSegment.Base, uHostTsc);
2019 return VINF_SUCCESS;
2020 }
2021 }
2022 Log4(("MemExit/%u: %04x:%08RX64/%s: %RGp (=>%RHp) %s fProt=%u%s%s%s; emulating (%s)\n",
2023 pVCpu->idCpu, pMsg->Header.CsSegment.Selector, pMsg->Header.Rip, nemHCWinExecStateToLogStr(&pMsg->Header),
2024 pMsg->GuestPhysicalAddress, Info.HCPhys, g_apszPageStates[Info.u2NemState], Info.fNemProt,
2025 Info.fHasHandlers ? " handlers" : "", Info.fZeroPage ? " zero-pg" : "",
2026 State.fDidSomething ? "" : " no-change", g_apszHvInterceptAccessTypes[pMsg->Header.InterceptAccessType]));
2027 }
2028 else
2029 Log4(("MemExit/%u: %04x:%08RX64/%s: %RGp rc=%Rrc%s; emulating (%s)\n",
2030 pVCpu->idCpu, pMsg->Header.CsSegment.Selector, pMsg->Header.Rip, nemHCWinExecStateToLogStr(&pMsg->Header),
2031 pMsg->GuestPhysicalAddress, rc, State.fDidSomething ? " modified-backing" : "",
2032 g_apszHvInterceptAccessTypes[pMsg->Header.InterceptAccessType]));
2033
2034 /*
2035 * Emulate the memory access, either access handler or special memory.
2036 */
2037 PCEMEXITREC pExitRec = EMHistoryAddExit(pVCpu,
2038 pMsg->Header.InterceptAccessType == HV_INTERCEPT_ACCESS_WRITE
2039 ? EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM, EMEXITTYPE_MMIO_WRITE)
2040 : EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM, EMEXITTYPE_MMIO_READ),
2041 pMsg->Header.Rip + pMsg->Header.CsSegment.Base, uHostTsc);
2042 nemHCWinCopyStateFromX64Header(pVCpu, &pMsg->Header);
2043 VBOXSTRICTRC rcStrict;
2044# ifdef IN_RING0
2045 rcStrict = nemR0WinImportStateStrict(pVM, pVCpu,
2046 NEM_WIN_CPUMCTX_EXTRN_MASK_FOR_IEM | CPUMCTX_EXTRN_DS | CPUMCTX_EXTRN_ES, "MemExit");
2047 if (rcStrict != VINF_SUCCESS)
2048 return rcStrict;
2049# else
2050 rc = nemHCWinCopyStateFromHyperV(pVM, pVCpu, NEM_WIN_CPUMCTX_EXTRN_MASK_FOR_IEM | CPUMCTX_EXTRN_DS | CPUMCTX_EXTRN_ES);
2051 AssertRCReturn(rc, rc);
2052# endif
2053
2054 if (pMsg->Reserved1)
2055 Log(("MemExit/Reserved1=%#x\n", pMsg->Reserved1));
2056 if (pMsg->Header.ExecutionState.Reserved0 || pMsg->Header.ExecutionState.Reserved1)
2057 Log(("MemExit/Hdr/State: Reserved0=%#x Reserved1=%#x\n", pMsg->Header.ExecutionState.Reserved0, pMsg->Header.ExecutionState.Reserved1));
2058
2059 if (!pExitRec)
2060 {
2061 //if (pMsg->InstructionByteCount > 0)
2062 // Log4(("InstructionByteCount=%#x %.16Rhxs\n", pMsg->InstructionByteCount, pMsg->InstructionBytes));
2063 if (pMsg->InstructionByteCount > 0)
2064 rcStrict = IEMExecOneWithPrefetchedByPC(pVCpu, CPUMCTX2CORE(&pVCpu->cpum.GstCtx), pMsg->Header.Rip,
2065 pMsg->InstructionBytes, pMsg->InstructionByteCount);
2066 else
2067 rcStrict = IEMExecOne(pVCpu);
2068 /** @todo do we need to do anything wrt debugging here? */
2069 }
2070 else
2071 {
2072 /* Frequent access or probing. */
2073 rcStrict = EMHistoryExec(pVCpu, pExitRec, 0);
2074 Log4(("MemExit/%u: %04x:%08RX64/%s: EMHistoryExec -> %Rrc + %04x:%08RX64\n",
2075 pVCpu->idCpu, pMsg->Header.CsSegment.Selector, pMsg->Header.Rip, nemHCWinExecStateToLogStr(&pMsg->Header),
2076 VBOXSTRICTRC_VAL(rcStrict), pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip));
2077 }
2078 return rcStrict;
2079}
2080#elif defined(IN_RING3)
2081/**
2082 * Deals with memory access exits (WHvRunVpExitReasonMemoryAccess).
2083 *
2084 * @returns Strict VBox status code.
2085 * @param pVM The cross context VM structure.
2086 * @param pVCpu The cross context per CPU structure.
2087 * @param pExit The VM exit information to handle.
2088 * @sa nemHCWinHandleMessageMemory
2089 */
2090NEM_TMPL_STATIC VBOXSTRICTRC
2091nemR3WinHandleExitMemory(PVMCC pVM, PVMCPUCC pVCpu, WHV_RUN_VP_EXIT_CONTEXT const *pExit)
2092{
2093 uint64_t const uHostTsc = ASMReadTSC();
2094 Assert(pExit->MemoryAccess.AccessInfo.AccessType != 3);
2095
2096 /*
2097 * Whatever we do, we must clear pending event injection upon resume.
2098 */
2099 if (pExit->VpContext.ExecutionState.InterruptionPending)
2100 pVCpu->cpum.GstCtx.fExtrn &= ~CPUMCTX_EXTRN_NEM_WIN_EVENT_INJECT;
2101
2102 /*
2103 * Ask PGM for information about the given GCPhys. We need to check if we're
2104 * out of sync first.
2105 */
2106 NEMHCWINHMACPCCSTATE State = { pExit->MemoryAccess.AccessInfo.AccessType == WHvMemoryAccessWrite, false, false };
2107 PGMPHYSNEMPAGEINFO Info;
2108 int rc = PGMPhysNemPageInfoChecker(pVM, pVCpu, pExit->MemoryAccess.Gpa, State.fWriteAccess, &Info,
2109 nemHCWinHandleMemoryAccessPageCheckerCallback, &State);
2110 if (RT_SUCCESS(rc))
2111 {
2112 if (Info.fNemProt & ( pExit->MemoryAccess.AccessInfo.AccessType == WHvMemoryAccessWrite
2113 ? NEM_PAGE_PROT_WRITE : NEM_PAGE_PROT_READ))
2114 {
2115 if (State.fCanResume)
2116 {
2117 Log4(("MemExit/%u: %04x:%08RX64/%s: %RGp (=>%RHp) %s fProt=%u%s%s%s; restarting (%s)\n",
2118 pVCpu->idCpu, pExit->VpContext.Cs.Selector, pExit->VpContext.Rip, nemR3WinExecStateToLogStr(&pExit->VpContext),
2119 pExit->MemoryAccess.Gpa, Info.HCPhys, g_apszPageStates[Info.u2NemState], Info.fNemProt,
2120 Info.fHasHandlers ? " handlers" : "", Info.fZeroPage ? " zero-pg" : "",
2121 State.fDidSomething ? "" : " no-change", g_apszHvInterceptAccessTypes[pExit->MemoryAccess.AccessInfo.AccessType]));
2122 EMHistoryAddExit(pVCpu, EMEXIT_MAKE_FT(EMEXIT_F_KIND_NEM, NEMEXITTYPE_MEMORY_ACCESS),
2123 pExit->VpContext.Rip + pExit->VpContext.Cs.Base, uHostTsc);
2124 return VINF_SUCCESS;
2125 }
2126 }
2127 Log4(("MemExit/%u: %04x:%08RX64/%s: %RGp (=>%RHp) %s fProt=%u%s%s%s; emulating (%s)\n",
2128 pVCpu->idCpu, pExit->VpContext.Cs.Selector, pExit->VpContext.Rip, nemR3WinExecStateToLogStr(&pExit->VpContext),
2129 pExit->MemoryAccess.Gpa, Info.HCPhys, g_apszPageStates[Info.u2NemState], Info.fNemProt,
2130 Info.fHasHandlers ? " handlers" : "", Info.fZeroPage ? " zero-pg" : "",
2131 State.fDidSomething ? "" : " no-change", g_apszHvInterceptAccessTypes[pExit->MemoryAccess.AccessInfo.AccessType]));
2132 }
2133 else
2134 Log4(("MemExit/%u: %04x:%08RX64/%s: %RGp rc=%Rrc%s; emulating (%s)\n",
2135 pVCpu->idCpu, pExit->VpContext.Cs.Selector, pExit->VpContext.Rip, nemR3WinExecStateToLogStr(&pExit->VpContext),
2136 pExit->MemoryAccess.Gpa, rc, State.fDidSomething ? " modified-backing" : "",
2137 g_apszHvInterceptAccessTypes[pExit->MemoryAccess.AccessInfo.AccessType]));
2138
2139 /*
2140 * Emulate the memory access, either access handler or special memory.
2141 */
2142 PCEMEXITREC pExitRec = EMHistoryAddExit(pVCpu,
2143 pExit->MemoryAccess.AccessInfo.AccessType == WHvMemoryAccessWrite
2144 ? EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM, EMEXITTYPE_MMIO_WRITE)
2145 : EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM, EMEXITTYPE_MMIO_READ),
2146 pExit->VpContext.Rip + pExit->VpContext.Cs.Base, uHostTsc);
2147 nemR3WinCopyStateFromX64Header(pVCpu, &pExit->VpContext);
2148 rc = nemHCWinCopyStateFromHyperV(pVM, pVCpu, NEM_WIN_CPUMCTX_EXTRN_MASK_FOR_IEM | CPUMCTX_EXTRN_DS | CPUMCTX_EXTRN_ES);
2149 AssertRCReturn(rc, rc);
2150 if (pExit->VpContext.ExecutionState.Reserved0 || pExit->VpContext.ExecutionState.Reserved1)
2151 Log(("MemExit/Hdr/State: Reserved0=%#x Reserved1=%#x\n", pExit->VpContext.ExecutionState.Reserved0, pExit->VpContext.ExecutionState.Reserved1));
2152
2153 VBOXSTRICTRC rcStrict;
2154 if (!pExitRec)
2155 {
2156 //if (pMsg->InstructionByteCount > 0)
2157 // Log4(("InstructionByteCount=%#x %.16Rhxs\n", pMsg->InstructionByteCount, pMsg->InstructionBytes));
2158 if (pExit->MemoryAccess.InstructionByteCount > 0)
2159 rcStrict = IEMExecOneWithPrefetchedByPC(pVCpu, CPUMCTX2CORE(&pVCpu->cpum.GstCtx), pExit->VpContext.Rip,
2160 pExit->MemoryAccess.InstructionBytes, pExit->MemoryAccess.InstructionByteCount);
2161 else
2162 rcStrict = IEMExecOne(pVCpu);
2163 /** @todo do we need to do anything wrt debugging here? */
2164 }
2165 else
2166 {
2167 /* Frequent access or probing. */
2168 rcStrict = EMHistoryExec(pVCpu, pExitRec, 0);
2169 Log4(("MemExit/%u: %04x:%08RX64/%s: EMHistoryExec -> %Rrc + %04x:%08RX64\n",
2170 pVCpu->idCpu, pExit->VpContext.Cs.Selector, pExit->VpContext.Rip, nemR3WinExecStateToLogStr(&pExit->VpContext),
2171 VBOXSTRICTRC_VAL(rcStrict), pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip));
2172 }
2173 return rcStrict;
2174}
2175#endif /* IN_RING3 && !NEM_WIN_TEMPLATE_MODE_OWN_RUN_API */
2176
2177
2178#ifdef NEM_WIN_TEMPLATE_MODE_OWN_RUN_API
2179/**
2180 * Deals with I/O port intercept message.
2181 *
2182 * @returns Strict VBox status code.
2183 * @param pVM The cross context VM structure.
2184 * @param pVCpu The cross context per CPU structure.
2185 * @param pMsg The message.
2186 */
2187NEM_TMPL_STATIC VBOXSTRICTRC
2188nemHCWinHandleMessageIoPort(PVMCC pVM, PVMCPUCC pVCpu, HV_X64_IO_PORT_INTERCEPT_MESSAGE const *pMsg)
2189{
2190 /*
2191 * Assert message sanity.
2192 */
2193 Assert( pMsg->AccessInfo.AccessSize == 1
2194 || pMsg->AccessInfo.AccessSize == 2
2195 || pMsg->AccessInfo.AccessSize == 4);
2196 Assert( pMsg->Header.InterceptAccessType == HV_INTERCEPT_ACCESS_READ
2197 || pMsg->Header.InterceptAccessType == HV_INTERCEPT_ACCESS_WRITE);
2198 NEMWIN_ASSERT_MSG_REG_SEG( pVCpu, HvX64RegisterCs, pMsg->Header.CsSegment);
2199 NEMWIN_ASSERT_MSG_REG_VAL64(pVCpu, HvX64RegisterRip, pMsg->Header.Rip);
2200 NEMWIN_ASSERT_MSG_REG_VAL64(pVCpu, HvX64RegisterRflags, pMsg->Header.Rflags);
2201 NEMWIN_ASSERT_MSG_REG_VAL64(pVCpu, HvX64RegisterCr8, (uint64_t)pMsg->Header.Cr8);
2202 NEMWIN_ASSERT_MSG_REG_VAL64(pVCpu, HvX64RegisterRax, pMsg->Rax);
2203 if (pMsg->AccessInfo.StringOp)
2204 {
2205 NEMWIN_ASSERT_MSG_REG_SEG( pVCpu, HvX64RegisterDs, pMsg->DsSegment);
2206 NEMWIN_ASSERT_MSG_REG_SEG( pVCpu, HvX64RegisterEs, pMsg->EsSegment);
2207 NEMWIN_ASSERT_MSG_REG_VAL64(pVCpu, HvX64RegisterRcx, pMsg->Rcx);
2208 NEMWIN_ASSERT_MSG_REG_VAL64(pVCpu, HvX64RegisterRsi, pMsg->Rsi);
2209 NEMWIN_ASSERT_MSG_REG_VAL64(pVCpu, HvX64RegisterRdi, pMsg->Rdi);
2210 }
2211
2212 /*
2213 * Whatever we do, we must clear pending event injection upon resume.
2214 */
2215 if (pMsg->Header.ExecutionState.InterruptionPending)
2216 pVCpu->cpum.GstCtx.fExtrn &= ~CPUMCTX_EXTRN_NEM_WIN_EVENT_INJECT;
2217
2218 /*
2219 * Add history first to avoid two paths doing EMHistoryExec calls.
2220 */
2221 VBOXSTRICTRC rcStrict;
2222 PCEMEXITREC pExitRec = EMHistoryAddExit(pVCpu,
2223 !pMsg->AccessInfo.StringOp
2224 ? ( pMsg->Header.InterceptAccessType == HV_INTERCEPT_ACCESS_WRITE
2225 ? EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM, EMEXITTYPE_IO_PORT_WRITE)
2226 : EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM, EMEXITTYPE_IO_PORT_READ))
2227 : ( pMsg->Header.InterceptAccessType == HV_INTERCEPT_ACCESS_WRITE
2228 ? EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM, EMEXITTYPE_IO_PORT_STR_WRITE)
2229 : EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM, EMEXITTYPE_IO_PORT_STR_READ)),
2230 pMsg->Header.Rip + pMsg->Header.CsSegment.Base, ASMReadTSC());
2231 if (!pExitRec)
2232 {
2233 if (!pMsg->AccessInfo.StringOp)
2234 {
2235 /*
2236 * Simple port I/O.
2237 */
2238 static uint32_t const s_fAndMask[8] =
2239 { UINT32_MAX, UINT32_C(0xff), UINT32_C(0xffff), UINT32_MAX, UINT32_MAX, UINT32_MAX, UINT32_MAX, UINT32_MAX };
2240 uint32_t const fAndMask = s_fAndMask[pMsg->AccessInfo.AccessSize];
2241
2242 nemHCWinCopyStateFromX64Header(pVCpu, &pMsg->Header);
2243 if (pMsg->Header.InterceptAccessType == HV_INTERCEPT_ACCESS_WRITE)
2244 {
2245 rcStrict = IOMIOPortWrite(pVM, pVCpu, pMsg->PortNumber, (uint32_t)pMsg->Rax & fAndMask, pMsg->AccessInfo.AccessSize);
2246 Log4(("IOExit/%u: %04x:%08RX64/%s: OUT %#x, %#x LB %u rcStrict=%Rrc\n",
2247 pVCpu->idCpu, pMsg->Header.CsSegment.Selector, pMsg->Header.Rip, nemHCWinExecStateToLogStr(&pMsg->Header),
2248 pMsg->PortNumber, (uint32_t)pMsg->Rax & fAndMask, pMsg->AccessInfo.AccessSize, VBOXSTRICTRC_VAL(rcStrict) ));
2249 if (IOM_SUCCESS(rcStrict))
2250 nemHCWinAdvanceGuestRipAndClearRF(pVCpu, &pMsg->Header, 1);
2251# ifdef IN_RING0
2252 else if ( rcStrict == VINF_IOM_R3_IOPORT_WRITE
2253 && !pVCpu->cpum.GstCtx.rflags.Bits.u1TF
2254 /** @todo check for debug breakpoints */ )
2255 return EMRZSetPendingIoPortWrite(pVCpu, pMsg->PortNumber, pMsg->Header.InstructionLength,
2256 pMsg->AccessInfo.AccessSize, (uint32_t)pMsg->Rax & fAndMask);
2257# endif
2258 else
2259 {
2260 pVCpu->cpum.GstCtx.rax = pMsg->Rax;
2261 pVCpu->cpum.GstCtx.fExtrn &= ~CPUMCTX_EXTRN_RAX;
2262 }
2263 }
2264 else
2265 {
2266 uint32_t uValue = 0;
2267 rcStrict = IOMIOPortRead(pVM, pVCpu, pMsg->PortNumber, &uValue, pMsg->AccessInfo.AccessSize);
2268 Log4(("IOExit/%u: %04x:%08RX64/%s: IN %#x LB %u -> %#x, rcStrict=%Rrc\n",
2269 pVCpu->idCpu, pMsg->Header.CsSegment.Selector, pMsg->Header.Rip, nemHCWinExecStateToLogStr(&pMsg->Header),
2270 pMsg->PortNumber, pMsg->AccessInfo.AccessSize, uValue, VBOXSTRICTRC_VAL(rcStrict) ));
2271 if (IOM_SUCCESS(rcStrict))
2272 {
2273 if (pMsg->AccessInfo.AccessSize != 4)
2274 pVCpu->cpum.GstCtx.rax = (pMsg->Rax & ~(uint64_t)fAndMask) | (uValue & fAndMask);
2275 else
2276 pVCpu->cpum.GstCtx.rax = uValue;
2277 pVCpu->cpum.GstCtx.fExtrn &= ~CPUMCTX_EXTRN_RAX;
2278 Log4(("IOExit/%u: RAX %#RX64 -> %#RX64\n", pVCpu->idCpu, pMsg->Rax, pVCpu->cpum.GstCtx.rax));
2279 nemHCWinAdvanceGuestRipAndClearRF(pVCpu, &pMsg->Header, 1);
2280 }
2281 else
2282 {
2283 pVCpu->cpum.GstCtx.rax = pMsg->Rax;
2284 pVCpu->cpum.GstCtx.fExtrn &= ~CPUMCTX_EXTRN_RAX;
2285# ifdef IN_RING0
2286 if ( rcStrict == VINF_IOM_R3_IOPORT_READ
2287 && !pVCpu->cpum.GstCtx.rflags.Bits.u1TF
2288 /** @todo check for debug breakpoints */ )
2289 return EMRZSetPendingIoPortRead(pVCpu, pMsg->PortNumber, pMsg->Header.InstructionLength,
2290 pMsg->AccessInfo.AccessSize);
2291# endif
2292 }
2293 }
2294 }
2295 else
2296 {
2297 /*
2298 * String port I/O.
2299 */
2300 /** @todo Someone at Microsoft please explain how we can get the address mode
2301 * from the IoPortAccess.VpContext. CS.Attributes is only sufficient for
2302 * getting the default mode, it can always be overridden by a prefix. This
2303 * forces us to interpret the instruction from opcodes, which is suboptimal.
2304 * Both AMD-V and VT-x includes the address size in the exit info, at least on
2305 * CPUs that are reasonably new.
2306 *
2307 * Of course, it's possible this is an undocumented and we just need to do some
2308 * experiments to figure out how it's communicated. Alternatively, we can scan
2309 * the opcode bytes for possible evil prefixes.
2310 */
2311 nemHCWinCopyStateFromX64Header(pVCpu, &pMsg->Header);
2312 pVCpu->cpum.GstCtx.fExtrn &= ~( CPUMCTX_EXTRN_RAX | CPUMCTX_EXTRN_RCX | CPUMCTX_EXTRN_RDI | CPUMCTX_EXTRN_RSI
2313 | CPUMCTX_EXTRN_DS | CPUMCTX_EXTRN_ES);
2314 NEM_WIN_COPY_BACK_SEG(pVCpu->cpum.GstCtx.ds, pMsg->DsSegment);
2315 NEM_WIN_COPY_BACK_SEG(pVCpu->cpum.GstCtx.es, pMsg->EsSegment);
2316 pVCpu->cpum.GstCtx.rax = pMsg->Rax;
2317 pVCpu->cpum.GstCtx.rcx = pMsg->Rcx;
2318 pVCpu->cpum.GstCtx.rdi = pMsg->Rdi;
2319 pVCpu->cpum.GstCtx.rsi = pMsg->Rsi;
2320# ifdef IN_RING0
2321 rcStrict = nemR0WinImportStateStrict(pVM, pVCpu, NEM_WIN_CPUMCTX_EXTRN_MASK_FOR_IEM, "IOExit");
2322 if (rcStrict != VINF_SUCCESS)
2323 return rcStrict;
2324# else
2325 int rc = nemHCWinCopyStateFromHyperV(pVM, pVCpu, NEM_WIN_CPUMCTX_EXTRN_MASK_FOR_IEM);
2326 AssertRCReturn(rc, rc);
2327# endif
2328
2329 Log4(("IOExit/%u: %04x:%08RX64/%s: %s%s %#x LB %u (emulating)\n",
2330 pVCpu->idCpu, pMsg->Header.CsSegment.Selector, pMsg->Header.Rip, nemHCWinExecStateToLogStr(&pMsg->Header),
2331 pMsg->AccessInfo.RepPrefix ? "REP " : "",
2332 pMsg->Header.InterceptAccessType == HV_INTERCEPT_ACCESS_WRITE ? "OUTS" : "INS",
2333 pMsg->PortNumber, pMsg->AccessInfo.AccessSize ));
2334 rcStrict = IEMExecOne(pVCpu);
2335 }
2336 if (IOM_SUCCESS(rcStrict))
2337 {
2338 /*
2339 * Do debug checks.
2340 */
2341 if ( pMsg->Header.ExecutionState.DebugActive /** @todo Microsoft: Does DebugActive this only reflect DR7? */
2342 || (pMsg->Header.Rflags & X86_EFL_TF)
2343 || DBGFBpIsHwIoArmed(pVM) )
2344 {
2345 /** @todo Debugging. */
2346 }
2347 }
2348 return rcStrict;
2349 }
2350
2351 /*
2352 * Frequent exit or something needing probing.
2353 * Get state and call EMHistoryExec.
2354 */
2355 nemHCWinCopyStateFromX64Header(pVCpu, &pMsg->Header);
2356 if (!pMsg->AccessInfo.StringOp)
2357 pVCpu->cpum.GstCtx.fExtrn &= ~CPUMCTX_EXTRN_RAX;
2358 else
2359 {
2360 pVCpu->cpum.GstCtx.fExtrn &= ~( CPUMCTX_EXTRN_RAX | CPUMCTX_EXTRN_RCX | CPUMCTX_EXTRN_RDI | CPUMCTX_EXTRN_RSI
2361 | CPUMCTX_EXTRN_DS | CPUMCTX_EXTRN_ES);
2362 NEM_WIN_COPY_BACK_SEG(pVCpu->cpum.GstCtx.ds, pMsg->DsSegment);
2363 NEM_WIN_COPY_BACK_SEG(pVCpu->cpum.GstCtx.es, pMsg->EsSegment);
2364 pVCpu->cpum.GstCtx.rcx = pMsg->Rcx;
2365 pVCpu->cpum.GstCtx.rdi = pMsg->Rdi;
2366 pVCpu->cpum.GstCtx.rsi = pMsg->Rsi;
2367 }
2368 pVCpu->cpum.GstCtx.rax = pMsg->Rax;
2369
2370# ifdef IN_RING0
2371 rcStrict = nemR0WinImportStateStrict(pVM, pVCpu, NEM_WIN_CPUMCTX_EXTRN_MASK_FOR_IEM, "IOExit");
2372 if (rcStrict != VINF_SUCCESS)
2373 return rcStrict;
2374# else
2375 int rc = nemHCWinCopyStateFromHyperV(pVM, pVCpu, NEM_WIN_CPUMCTX_EXTRN_MASK_FOR_IEM);
2376 AssertRCReturn(rc, rc);
2377# endif
2378
2379 Log4(("IOExit/%u: %04x:%08RX64/%s: %s%s%s %#x LB %u -> EMHistoryExec\n",
2380 pVCpu->idCpu, pMsg->Header.CsSegment.Selector, pMsg->Header.Rip, nemHCWinExecStateToLogStr(&pMsg->Header),
2381 pMsg->AccessInfo.RepPrefix ? "REP " : "",
2382 pMsg->Header.InterceptAccessType == HV_INTERCEPT_ACCESS_WRITE ? "OUT" : "IN",
2383 pMsg->AccessInfo.StringOp ? "S" : "",
2384 pMsg->PortNumber, pMsg->AccessInfo.AccessSize));
2385 rcStrict = EMHistoryExec(pVCpu, pExitRec, 0);
2386 Log4(("IOExit/%u: %04x:%08RX64/%s: EMHistoryExec -> %Rrc + %04x:%08RX64\n",
2387 pVCpu->idCpu, pMsg->Header.CsSegment.Selector, pMsg->Header.Rip, nemHCWinExecStateToLogStr(&pMsg->Header),
2388 VBOXSTRICTRC_VAL(rcStrict), pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip));
2389 return rcStrict;
2390}
2391#elif defined(IN_RING3)
2392/**
2393 * Deals with I/O port access exits (WHvRunVpExitReasonX64IoPortAccess).
2394 *
2395 * @returns Strict VBox status code.
2396 * @param pVM The cross context VM structure.
2397 * @param pVCpu The cross context per CPU structure.
2398 * @param pExit The VM exit information to handle.
2399 * @sa nemHCWinHandleMessageIoPort
2400 */
2401NEM_TMPL_STATIC VBOXSTRICTRC nemR3WinHandleExitIoPort(PVMCC pVM, PVMCPUCC pVCpu, WHV_RUN_VP_EXIT_CONTEXT const *pExit)
2402{
2403 Assert( pExit->IoPortAccess.AccessInfo.AccessSize == 1
2404 || pExit->IoPortAccess.AccessInfo.AccessSize == 2
2405 || pExit->IoPortAccess.AccessInfo.AccessSize == 4);
2406
2407 /*
2408 * Whatever we do, we must clear pending event injection upon resume.
2409 */
2410 if (pExit->VpContext.ExecutionState.InterruptionPending)
2411 pVCpu->cpum.GstCtx.fExtrn &= ~CPUMCTX_EXTRN_NEM_WIN_EVENT_INJECT;
2412
2413 /*
2414 * Add history first to avoid two paths doing EMHistoryExec calls.
2415 */
2416 PCEMEXITREC pExitRec = EMHistoryAddExit(pVCpu,
2417 !pExit->IoPortAccess.AccessInfo.StringOp
2418 ? ( pExit->MemoryAccess.AccessInfo.AccessType == WHvMemoryAccessWrite
2419 ? EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM, EMEXITTYPE_IO_PORT_WRITE)
2420 : EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM, EMEXITTYPE_IO_PORT_READ))
2421 : ( pExit->MemoryAccess.AccessInfo.AccessType == WHvMemoryAccessWrite
2422 ? EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM, EMEXITTYPE_IO_PORT_STR_WRITE)
2423 : EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM, EMEXITTYPE_IO_PORT_STR_READ)),
2424 pExit->VpContext.Rip + pExit->VpContext.Cs.Base, ASMReadTSC());
2425 if (!pExitRec)
2426 {
2427 VBOXSTRICTRC rcStrict;
2428 if (!pExit->IoPortAccess.AccessInfo.StringOp)
2429 {
2430 /*
2431 * Simple port I/O.
2432 */
2433 static uint32_t const s_fAndMask[8] =
2434 { UINT32_MAX, UINT32_C(0xff), UINT32_C(0xffff), UINT32_MAX, UINT32_MAX, UINT32_MAX, UINT32_MAX, UINT32_MAX };
2435 uint32_t const fAndMask = s_fAndMask[pExit->IoPortAccess.AccessInfo.AccessSize];
2436 if (pExit->IoPortAccess.AccessInfo.IsWrite)
2437 {
2438 rcStrict = IOMIOPortWrite(pVM, pVCpu, pExit->IoPortAccess.PortNumber,
2439 (uint32_t)pExit->IoPortAccess.Rax & fAndMask,
2440 pExit->IoPortAccess.AccessInfo.AccessSize);
2441 Log4(("IOExit/%u: %04x:%08RX64/%s: OUT %#x, %#x LB %u rcStrict=%Rrc\n",
2442 pVCpu->idCpu, pExit->VpContext.Cs.Selector, pExit->VpContext.Rip, nemR3WinExecStateToLogStr(&pExit->VpContext),
2443 pExit->IoPortAccess.PortNumber, (uint32_t)pExit->IoPortAccess.Rax & fAndMask,
2444 pExit->IoPortAccess.AccessInfo.AccessSize, VBOXSTRICTRC_VAL(rcStrict) ));
2445 if (IOM_SUCCESS(rcStrict))
2446 {
2447 nemR3WinCopyStateFromX64Header(pVCpu, &pExit->VpContext);
2448 nemR3WinAdvanceGuestRipAndClearRF(pVCpu, &pExit->VpContext, 1);
2449 }
2450 }
2451 else
2452 {
2453 uint32_t uValue = 0;
2454 rcStrict = IOMIOPortRead(pVM, pVCpu, pExit->IoPortAccess.PortNumber, &uValue,
2455 pExit->IoPortAccess.AccessInfo.AccessSize);
2456 Log4(("IOExit/%u: %04x:%08RX64/%s: IN %#x LB %u -> %#x, rcStrict=%Rrc\n",
2457 pVCpu->idCpu, pExit->VpContext.Cs.Selector, pExit->VpContext.Rip, nemR3WinExecStateToLogStr(&pExit->VpContext),
2458 pExit->IoPortAccess.PortNumber, pExit->IoPortAccess.AccessInfo.AccessSize, uValue, VBOXSTRICTRC_VAL(rcStrict) ));
2459 if (IOM_SUCCESS(rcStrict))
2460 {
2461 if (pExit->IoPortAccess.AccessInfo.AccessSize != 4)
2462 pVCpu->cpum.GstCtx.rax = (pExit->IoPortAccess.Rax & ~(uint64_t)fAndMask) | (uValue & fAndMask);
2463 else
2464 pVCpu->cpum.GstCtx.rax = uValue;
2465 pVCpu->cpum.GstCtx.fExtrn &= ~CPUMCTX_EXTRN_RAX;
2466 Log4(("IOExit/%u: RAX %#RX64 -> %#RX64\n", pVCpu->idCpu, pExit->IoPortAccess.Rax, pVCpu->cpum.GstCtx.rax));
2467 nemR3WinCopyStateFromX64Header(pVCpu, &pExit->VpContext);
2468 nemR3WinAdvanceGuestRipAndClearRF(pVCpu, &pExit->VpContext, 1);
2469 }
2470 }
2471 }
2472 else
2473 {
2474 /*
2475 * String port I/O.
2476 */
2477 /** @todo Someone at Microsoft please explain how we can get the address mode
2478 * from the IoPortAccess.VpContext. CS.Attributes is only sufficient for
2479 * getting the default mode, it can always be overridden by a prefix. This
2480 * forces us to interpret the instruction from opcodes, which is suboptimal.
2481 * Both AMD-V and VT-x includes the address size in the exit info, at least on
2482 * CPUs that are reasonably new.
2483 *
2484 * Of course, it's possible this is an undocumented and we just need to do some
2485 * experiments to figure out how it's communicated. Alternatively, we can scan
2486 * the opcode bytes for possible evil prefixes.
2487 */
2488 nemR3WinCopyStateFromX64Header(pVCpu, &pExit->VpContext);
2489 pVCpu->cpum.GstCtx.fExtrn &= ~( CPUMCTX_EXTRN_RAX | CPUMCTX_EXTRN_RCX | CPUMCTX_EXTRN_RDI | CPUMCTX_EXTRN_RSI
2490 | CPUMCTX_EXTRN_DS | CPUMCTX_EXTRN_ES);
2491 NEM_WIN_COPY_BACK_SEG(pVCpu->cpum.GstCtx.ds, pExit->IoPortAccess.Ds);
2492 NEM_WIN_COPY_BACK_SEG(pVCpu->cpum.GstCtx.es, pExit->IoPortAccess.Es);
2493 pVCpu->cpum.GstCtx.rax = pExit->IoPortAccess.Rax;
2494 pVCpu->cpum.GstCtx.rcx = pExit->IoPortAccess.Rcx;
2495 pVCpu->cpum.GstCtx.rdi = pExit->IoPortAccess.Rdi;
2496 pVCpu->cpum.GstCtx.rsi = pExit->IoPortAccess.Rsi;
2497 int rc = nemHCWinCopyStateFromHyperV(pVM, pVCpu, NEM_WIN_CPUMCTX_EXTRN_MASK_FOR_IEM);
2498 AssertRCReturn(rc, rc);
2499
2500 Log4(("IOExit/%u: %04x:%08RX64/%s: %s%s %#x LB %u (emulating)\n",
2501 pVCpu->idCpu, pExit->VpContext.Cs.Selector, pExit->VpContext.Rip, nemR3WinExecStateToLogStr(&pExit->VpContext),
2502 pExit->IoPortAccess.AccessInfo.RepPrefix ? "REP " : "",
2503 pExit->IoPortAccess.AccessInfo.IsWrite ? "OUTS" : "INS",
2504 pExit->IoPortAccess.PortNumber, pExit->IoPortAccess.AccessInfo.AccessSize ));
2505 rcStrict = IEMExecOne(pVCpu);
2506 }
2507 if (IOM_SUCCESS(rcStrict))
2508 {
2509 /*
2510 * Do debug checks.
2511 */
2512 if ( pExit->VpContext.ExecutionState.DebugActive /** @todo Microsoft: Does DebugActive this only reflect DR7? */
2513 || (pExit->VpContext.Rflags & X86_EFL_TF)
2514 || DBGFBpIsHwIoArmed(pVM) )
2515 {
2516 /** @todo Debugging. */
2517 }
2518 }
2519 return rcStrict;
2520 }
2521
2522 /*
2523 * Frequent exit or something needing probing.
2524 * Get state and call EMHistoryExec.
2525 */
2526 nemR3WinCopyStateFromX64Header(pVCpu, &pExit->VpContext);
2527 if (!pExit->IoPortAccess.AccessInfo.StringOp)
2528 pVCpu->cpum.GstCtx.fExtrn &= ~CPUMCTX_EXTRN_RAX;
2529 else
2530 {
2531 pVCpu->cpum.GstCtx.fExtrn &= ~( CPUMCTX_EXTRN_RAX | CPUMCTX_EXTRN_RCX | CPUMCTX_EXTRN_RDI | CPUMCTX_EXTRN_RSI
2532 | CPUMCTX_EXTRN_DS | CPUMCTX_EXTRN_ES);
2533 NEM_WIN_COPY_BACK_SEG(pVCpu->cpum.GstCtx.ds, pExit->IoPortAccess.Ds);
2534 NEM_WIN_COPY_BACK_SEG(pVCpu->cpum.GstCtx.es, pExit->IoPortAccess.Es);
2535 pVCpu->cpum.GstCtx.rcx = pExit->IoPortAccess.Rcx;
2536 pVCpu->cpum.GstCtx.rdi = pExit->IoPortAccess.Rdi;
2537 pVCpu->cpum.GstCtx.rsi = pExit->IoPortAccess.Rsi;
2538 }
2539 pVCpu->cpum.GstCtx.rax = pExit->IoPortAccess.Rax;
2540 int rc = nemHCWinCopyStateFromHyperV(pVM, pVCpu, NEM_WIN_CPUMCTX_EXTRN_MASK_FOR_IEM);
2541 AssertRCReturn(rc, rc);
2542 Log4(("IOExit/%u: %04x:%08RX64/%s: %s%s%s %#x LB %u -> EMHistoryExec\n",
2543 pVCpu->idCpu, pExit->VpContext.Cs.Selector, pExit->VpContext.Rip, nemR3WinExecStateToLogStr(&pExit->VpContext),
2544 pExit->IoPortAccess.AccessInfo.RepPrefix ? "REP " : "",
2545 pExit->IoPortAccess.AccessInfo.IsWrite ? "OUT" : "IN",
2546 pExit->IoPortAccess.AccessInfo.StringOp ? "S" : "",
2547 pExit->IoPortAccess.PortNumber, pExit->IoPortAccess.AccessInfo.AccessSize));
2548 VBOXSTRICTRC rcStrict = EMHistoryExec(pVCpu, pExitRec, 0);
2549 Log4(("IOExit/%u: %04x:%08RX64/%s: EMHistoryExec -> %Rrc + %04x:%08RX64\n",
2550 pVCpu->idCpu, pExit->VpContext.Cs.Selector, pExit->VpContext.Rip, nemR3WinExecStateToLogStr(&pExit->VpContext),
2551 VBOXSTRICTRC_VAL(rcStrict), pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip));
2552 return rcStrict;
2553}
2554#endif /* IN_RING3 && !NEM_WIN_TEMPLATE_MODE_OWN_RUN_API */
2555
2556
2557#ifdef NEM_WIN_TEMPLATE_MODE_OWN_RUN_API
2558/**
2559 * Deals with interrupt window message.
2560 *
2561 * @returns Strict VBox status code.
2562 * @param pVM The cross context VM structure.
2563 * @param pVCpu The cross context per CPU structure.
2564 * @param pMsg The message.
2565 * @sa nemR3WinHandleExitInterruptWindow
2566 */
2567NEM_TMPL_STATIC VBOXSTRICTRC
2568nemHCWinHandleMessageInterruptWindow(PVMCC pVM, PVMCPUCC pVCpu, HV_X64_INTERRUPT_WINDOW_MESSAGE const *pMsg)
2569{
2570 /*
2571 * Assert message sanity.
2572 */
2573 Assert( pMsg->Header.InterceptAccessType == HV_INTERCEPT_ACCESS_EXECUTE
2574 || pMsg->Header.InterceptAccessType == HV_INTERCEPT_ACCESS_READ // READ & WRITE are probably not used here
2575 || pMsg->Header.InterceptAccessType == HV_INTERCEPT_ACCESS_WRITE);
2576 AssertMsg(pMsg->Type == HvX64PendingInterrupt || pMsg->Type == HvX64PendingNmi, ("%#x\n", pMsg->Type));
2577
2578 /*
2579 * Just copy the state we've got and handle it in the loop for now.
2580 */
2581 EMHistoryAddExit(pVCpu, EMEXIT_MAKE_FT(EMEXIT_F_KIND_NEM, NEMEXITTYPE_INTTERRUPT_WINDOW),
2582 pMsg->Header.Rip + pMsg->Header.CsSegment.Base, ASMReadTSC());
2583
2584 nemHCWinCopyStateFromX64Header(pVCpu, &pMsg->Header);
2585 Log4(("IntWinExit/%u: %04x:%08RX64/%s: %u IF=%d InterruptShadow=%d\n",
2586 pVCpu->idCpu, pMsg->Header.CsSegment.Selector, pMsg->Header.Rip, nemHCWinExecStateToLogStr(&pMsg->Header),
2587 pMsg->Type, RT_BOOL(pMsg->Header.Rflags & X86_EFL_IF), pMsg->Header.ExecutionState.InterruptShadow));
2588
2589 /** @todo call nemHCWinHandleInterruptFF */
2590 RT_NOREF(pVM);
2591 return VINF_SUCCESS;
2592}
2593#elif defined(IN_RING3)
2594/**
2595 * Deals with interrupt window exits (WHvRunVpExitReasonX64InterruptWindow).
2596 *
2597 * @returns Strict VBox status code.
2598 * @param pVM The cross context VM structure.
2599 * @param pVCpu The cross context per CPU structure.
2600 * @param pExit The VM exit information to handle.
2601 * @sa nemHCWinHandleMessageInterruptWindow
2602 */
2603NEM_TMPL_STATIC VBOXSTRICTRC nemR3WinHandleExitInterruptWindow(PVMCC pVM, PVMCPUCC pVCpu, WHV_RUN_VP_EXIT_CONTEXT const *pExit)
2604{
2605 /*
2606 * Assert message sanity.
2607 */
2608 AssertMsg( pExit->InterruptWindow.DeliverableType == WHvX64PendingInterrupt
2609 || pExit->InterruptWindow.DeliverableType == WHvX64PendingNmi,
2610 ("%#x\n", pExit->InterruptWindow.DeliverableType));
2611
2612 /*
2613 * Just copy the state we've got and handle it in the loop for now.
2614 */
2615 EMHistoryAddExit(pVCpu, EMEXIT_MAKE_FT(EMEXIT_F_KIND_NEM, NEMEXITTYPE_INTTERRUPT_WINDOW),
2616 pExit->VpContext.Rip + pExit->VpContext.Cs.Base, ASMReadTSC());
2617
2618 nemR3WinCopyStateFromX64Header(pVCpu, &pExit->VpContext);
2619 Log4(("IntWinExit/%u: %04x:%08RX64/%s: %u IF=%d InterruptShadow=%d CR8=%#x\n",
2620 pVCpu->idCpu, pExit->VpContext.Cs.Selector, pExit->VpContext.Rip, nemR3WinExecStateToLogStr(&pExit->VpContext),
2621 pExit->InterruptWindow.DeliverableType, RT_BOOL(pExit->VpContext.Rflags & X86_EFL_IF),
2622 pExit->VpContext.ExecutionState.InterruptShadow, pExit->VpContext.Cr8));
2623
2624 /** @todo call nemHCWinHandleInterruptFF */
2625 RT_NOREF(pVM);
2626 return VINF_SUCCESS;
2627}
2628#endif /* IN_RING3 && !NEM_WIN_TEMPLATE_MODE_OWN_RUN_API */
2629
2630
2631#ifdef NEM_WIN_TEMPLATE_MODE_OWN_RUN_API
2632/**
2633 * Deals with CPUID intercept message.
2634 *
2635 * @returns Strict VBox status code.
2636 * @param pVM The cross context VM structure.
2637 * @param pVCpu The cross context per CPU structure.
2638 * @param pMsg The message.
2639 * @sa nemR3WinHandleExitCpuId
2640 */
2641NEM_TMPL_STATIC VBOXSTRICTRC nemHCWinHandleMessageCpuId(PVMCC pVM, PVMCPUCC pVCpu, HV_X64_CPUID_INTERCEPT_MESSAGE const *pMsg)
2642{
2643 /* Check message register value sanity. */
2644 NEMWIN_ASSERT_MSG_REG_SEG( pVCpu, HvX64RegisterCs, pMsg->Header.CsSegment);
2645 NEMWIN_ASSERT_MSG_REG_VAL64(pVCpu, HvX64RegisterRip, pMsg->Header.Rip);
2646 NEMWIN_ASSERT_MSG_REG_VAL64(pVCpu, HvX64RegisterRflags, pMsg->Header.Rflags);
2647 NEMWIN_ASSERT_MSG_REG_VAL64(pVCpu, HvX64RegisterCr8, (uint64_t)pMsg->Header.Cr8);
2648 NEMWIN_ASSERT_MSG_REG_VAL64(pVCpu, HvX64RegisterRax, pMsg->Rax);
2649 NEMWIN_ASSERT_MSG_REG_VAL64(pVCpu, HvX64RegisterRcx, pMsg->Rcx);
2650 NEMWIN_ASSERT_MSG_REG_VAL64(pVCpu, HvX64RegisterRdx, pMsg->Rdx);
2651 NEMWIN_ASSERT_MSG_REG_VAL64(pVCpu, HvX64RegisterRbx, pMsg->Rbx);
2652
2653 /* Do exit history. */
2654 PCEMEXITREC pExitRec = EMHistoryAddExit(pVCpu, EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM, EMEXITTYPE_CPUID),
2655 pMsg->Header.Rip + pMsg->Header.CsSegment.Base, ASMReadTSC());
2656 if (!pExitRec)
2657 {
2658 /*
2659 * Soak up state and execute the instruction.
2660 *
2661 * Note! If this grows slightly more complicated, combine into an IEMExecDecodedCpuId
2662 * function and make everyone use it.
2663 */
2664 /** @todo Combine implementations into IEMExecDecodedCpuId as this will
2665 * only get weirder with nested VT-x and AMD-V support. */
2666 nemHCWinCopyStateFromX64Header(pVCpu, &pMsg->Header);
2667
2668 /* Copy in the low register values (top is always cleared). */
2669 pVCpu->cpum.GstCtx.rax = (uint32_t)pMsg->Rax;
2670 pVCpu->cpum.GstCtx.rcx = (uint32_t)pMsg->Rcx;
2671 pVCpu->cpum.GstCtx.rdx = (uint32_t)pMsg->Rdx;
2672 pVCpu->cpum.GstCtx.rbx = (uint32_t)pMsg->Rbx;
2673 pVCpu->cpum.GstCtx.fExtrn &= ~(CPUMCTX_EXTRN_RAX | CPUMCTX_EXTRN_RCX | CPUMCTX_EXTRN_RDX | CPUMCTX_EXTRN_RBX);
2674
2675 /* Get the correct values. */
2676 CPUMGetGuestCpuId(pVCpu, pVCpu->cpum.GstCtx.eax, pVCpu->cpum.GstCtx.ecx,
2677 &pVCpu->cpum.GstCtx.eax, &pVCpu->cpum.GstCtx.ebx, &pVCpu->cpum.GstCtx.ecx, &pVCpu->cpum.GstCtx.edx);
2678
2679 Log4(("CpuIdExit/%u: %04x:%08RX64/%s: rax=%08RX64 / rcx=%08RX64 / rdx=%08RX64 / rbx=%08RX64 -> %08RX32 / %08RX32 / %08RX32 / %08RX32 (hv: %08RX64 / %08RX64 / %08RX64 / %08RX64)\n",
2680 pVCpu->idCpu, pMsg->Header.CsSegment.Selector, pMsg->Header.Rip, nemHCWinExecStateToLogStr(&pMsg->Header),
2681 pMsg->Rax, pMsg->Rcx, pMsg->Rdx, pMsg->Rbx,
2682 pVCpu->cpum.GstCtx.eax, pVCpu->cpum.GstCtx.ecx, pVCpu->cpum.GstCtx.edx, pVCpu->cpum.GstCtx.ebx,
2683 pMsg->DefaultResultRax, pMsg->DefaultResultRcx, pMsg->DefaultResultRdx, pMsg->DefaultResultRbx));
2684
2685 /* Move RIP and we're done. */
2686 nemHCWinAdvanceGuestRipAndClearRF(pVCpu, &pMsg->Header, 2);
2687
2688 return VINF_SUCCESS;
2689 }
2690
2691 /*
2692 * Frequent exit or something needing probing.
2693 * Get state and call EMHistoryExec.
2694 */
2695 nemHCWinCopyStateFromX64Header(pVCpu, &pMsg->Header);
2696 pVCpu->cpum.GstCtx.rax = pMsg->Rax;
2697 pVCpu->cpum.GstCtx.rcx = pMsg->Rcx;
2698 pVCpu->cpum.GstCtx.rdx = pMsg->Rdx;
2699 pVCpu->cpum.GstCtx.rbx = pMsg->Rbx;
2700 pVCpu->cpum.GstCtx.fExtrn &= ~(CPUMCTX_EXTRN_RAX | CPUMCTX_EXTRN_RCX | CPUMCTX_EXTRN_RDX | CPUMCTX_EXTRN_RBX);
2701 Log4(("CpuIdExit/%u: %04x:%08RX64/%s: rax=%08RX64 / rcx=%08RX64 / rdx=%08RX64 / rbx=%08RX64 (hv: %08RX64 / %08RX64 / %08RX64 / %08RX64) ==> EMHistoryExec\n",
2702 pVCpu->idCpu, pMsg->Header.CsSegment.Selector, pMsg->Header.Rip, nemHCWinExecStateToLogStr(&pMsg->Header),
2703 pMsg->Rax, pMsg->Rcx, pMsg->Rdx, pMsg->Rbx,
2704 pMsg->DefaultResultRax, pMsg->DefaultResultRcx, pMsg->DefaultResultRdx, pMsg->DefaultResultRbx));
2705# ifdef IN_RING0
2706 VBOXSTRICTRC rcStrict = nemR0WinImportStateStrict(pVM, pVCpu, NEM_WIN_CPUMCTX_EXTRN_MASK_FOR_IEM, "CpuIdExit");
2707 if (rcStrict != VINF_SUCCESS)
2708 return rcStrict;
2709 RT_NOREF(pVM);
2710# else
2711 int rc = nemHCWinCopyStateFromHyperV(pVM, pVCpu, NEM_WIN_CPUMCTX_EXTRN_MASK_FOR_IEM);
2712 AssertRCReturn(rc, rc);
2713# endif
2714 VBOXSTRICTRC rcStrictExec = EMHistoryExec(pVCpu, pExitRec, 0);
2715 Log4(("CpuIdExit/%u: %04x:%08RX64/%s: EMHistoryExec -> %Rrc + %04x:%08RX64\n",
2716 pVCpu->idCpu, pMsg->Header.CsSegment.Selector, pMsg->Header.Rip, nemHCWinExecStateToLogStr(&pMsg->Header),
2717 VBOXSTRICTRC_VAL(rcStrictExec), pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip));
2718 return rcStrictExec;
2719}
2720#elif defined(IN_RING3)
2721/**
2722 * Deals with CPUID exits (WHvRunVpExitReasonX64Cpuid).
2723 *
2724 * @returns Strict VBox status code.
2725 * @param pVM The cross context VM structure.
2726 * @param pVCpu The cross context per CPU structure.
2727 * @param pExit The VM exit information to handle.
2728 * @sa nemHCWinHandleMessageCpuId
2729 */
2730NEM_TMPL_STATIC VBOXSTRICTRC
2731nemR3WinHandleExitCpuId(PVMCC pVM, PVMCPUCC pVCpu, WHV_RUN_VP_EXIT_CONTEXT const *pExit)
2732{
2733 PCEMEXITREC pExitRec = EMHistoryAddExit(pVCpu, EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM, EMEXITTYPE_CPUID),
2734 pExit->VpContext.Rip + pExit->VpContext.Cs.Base, ASMReadTSC());
2735 if (!pExitRec)
2736 {
2737 /*
2738 * Soak up state and execute the instruction.
2739 *
2740 * Note! If this grows slightly more complicated, combine into an IEMExecDecodedCpuId
2741 * function and make everyone use it.
2742 */
2743 /** @todo Combine implementations into IEMExecDecodedCpuId as this will
2744 * only get weirder with nested VT-x and AMD-V support. */
2745 nemR3WinCopyStateFromX64Header(pVCpu, &pExit->VpContext);
2746
2747 /* Copy in the low register values (top is always cleared). */
2748 pVCpu->cpum.GstCtx.rax = (uint32_t)pExit->CpuidAccess.Rax;
2749 pVCpu->cpum.GstCtx.rcx = (uint32_t)pExit->CpuidAccess.Rcx;
2750 pVCpu->cpum.GstCtx.rdx = (uint32_t)pExit->CpuidAccess.Rdx;
2751 pVCpu->cpum.GstCtx.rbx = (uint32_t)pExit->CpuidAccess.Rbx;
2752 pVCpu->cpum.GstCtx.fExtrn &= ~(CPUMCTX_EXTRN_RAX | CPUMCTX_EXTRN_RCX | CPUMCTX_EXTRN_RDX | CPUMCTX_EXTRN_RBX);
2753
2754 /* Get the correct values. */
2755 CPUMGetGuestCpuId(pVCpu, pVCpu->cpum.GstCtx.eax, pVCpu->cpum.GstCtx.ecx,
2756 &pVCpu->cpum.GstCtx.eax, &pVCpu->cpum.GstCtx.ebx, &pVCpu->cpum.GstCtx.ecx, &pVCpu->cpum.GstCtx.edx);
2757
2758 Log4(("CpuIdExit/%u: %04x:%08RX64/%s: rax=%08RX64 / rcx=%08RX64 / rdx=%08RX64 / rbx=%08RX64 -> %08RX32 / %08RX32 / %08RX32 / %08RX32 (hv: %08RX64 / %08RX64 / %08RX64 / %08RX64)\n",
2759 pVCpu->idCpu, pExit->VpContext.Cs.Selector, pExit->VpContext.Rip, nemR3WinExecStateToLogStr(&pExit->VpContext),
2760 pExit->CpuidAccess.Rax, pExit->CpuidAccess.Rcx, pExit->CpuidAccess.Rdx, pExit->CpuidAccess.Rbx,
2761 pVCpu->cpum.GstCtx.eax, pVCpu->cpum.GstCtx.ecx, pVCpu->cpum.GstCtx.edx, pVCpu->cpum.GstCtx.ebx,
2762 pExit->CpuidAccess.DefaultResultRax, pExit->CpuidAccess.DefaultResultRcx, pExit->CpuidAccess.DefaultResultRdx, pExit->CpuidAccess.DefaultResultRbx));
2763
2764 /* Move RIP and we're done. */
2765 nemR3WinAdvanceGuestRipAndClearRF(pVCpu, &pExit->VpContext, 2);
2766
2767 RT_NOREF_PV(pVM);
2768 return VINF_SUCCESS;
2769 }
2770
2771 /*
2772 * Frequent exit or something needing probing.
2773 * Get state and call EMHistoryExec.
2774 */
2775 nemR3WinCopyStateFromX64Header(pVCpu, &pExit->VpContext);
2776 pVCpu->cpum.GstCtx.rax = pExit->CpuidAccess.Rax;
2777 pVCpu->cpum.GstCtx.rcx = pExit->CpuidAccess.Rcx;
2778 pVCpu->cpum.GstCtx.rdx = pExit->CpuidAccess.Rdx;
2779 pVCpu->cpum.GstCtx.rbx = pExit->CpuidAccess.Rbx;
2780 pVCpu->cpum.GstCtx.fExtrn &= ~(CPUMCTX_EXTRN_RAX | CPUMCTX_EXTRN_RCX | CPUMCTX_EXTRN_RDX | CPUMCTX_EXTRN_RBX);
2781 Log4(("CpuIdExit/%u: %04x:%08RX64/%s: rax=%08RX64 / rcx=%08RX64 / rdx=%08RX64 / rbx=%08RX64 (hv: %08RX64 / %08RX64 / %08RX64 / %08RX64) ==> EMHistoryExec\n",
2782 pVCpu->idCpu, pExit->VpContext.Cs.Selector, pExit->VpContext.Rip, nemR3WinExecStateToLogStr(&pExit->VpContext),
2783 pExit->CpuidAccess.Rax, pExit->CpuidAccess.Rcx, pExit->CpuidAccess.Rdx, pExit->CpuidAccess.Rbx,
2784 pExit->CpuidAccess.DefaultResultRax, pExit->CpuidAccess.DefaultResultRcx, pExit->CpuidAccess.DefaultResultRdx, pExit->CpuidAccess.DefaultResultRbx));
2785 int rc = nemHCWinCopyStateFromHyperV(pVM, pVCpu, NEM_WIN_CPUMCTX_EXTRN_MASK_FOR_IEM);
2786 AssertRCReturn(rc, rc);
2787 VBOXSTRICTRC rcStrict = EMHistoryExec(pVCpu, pExitRec, 0);
2788 Log4(("CpuIdExit/%u: %04x:%08RX64/%s: EMHistoryExec -> %Rrc + %04x:%08RX64\n",
2789 pVCpu->idCpu, pExit->VpContext.Cs.Selector, pExit->VpContext.Rip, nemR3WinExecStateToLogStr(&pExit->VpContext),
2790 VBOXSTRICTRC_VAL(rcStrict), pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip));
2791 return rcStrict;
2792}
2793#endif /* IN_RING3 && !NEM_WIN_TEMPLATE_MODE_OWN_RUN_API */
2794
2795
2796#ifdef NEM_WIN_TEMPLATE_MODE_OWN_RUN_API
2797/**
2798 * Deals with MSR intercept message.
2799 *
2800 * @returns Strict VBox status code.
2801 * @param pVCpu The cross context per CPU structure.
2802 * @param pMsg The message.
2803 * @sa nemR3WinHandleExitMsr
2804 */
2805NEM_TMPL_STATIC VBOXSTRICTRC nemHCWinHandleMessageMsr(PVMCPUCC pVCpu, HV_X64_MSR_INTERCEPT_MESSAGE const *pMsg)
2806{
2807 /*
2808 * A wee bit of sanity first.
2809 */
2810 Assert( pMsg->Header.InterceptAccessType == HV_INTERCEPT_ACCESS_READ
2811 || pMsg->Header.InterceptAccessType == HV_INTERCEPT_ACCESS_WRITE);
2812 NEMWIN_ASSERT_MSG_REG_SEG( pVCpu, HvX64RegisterCs, pMsg->Header.CsSegment);
2813 NEMWIN_ASSERT_MSG_REG_VAL64(pVCpu, HvX64RegisterRip, pMsg->Header.Rip);
2814 NEMWIN_ASSERT_MSG_REG_VAL64(pVCpu, HvX64RegisterRflags, pMsg->Header.Rflags);
2815 NEMWIN_ASSERT_MSG_REG_VAL64(pVCpu, HvX64RegisterCr8, (uint64_t)pMsg->Header.Cr8);
2816 NEMWIN_ASSERT_MSG_REG_VAL64(pVCpu, HvX64RegisterRax, pMsg->Rax);
2817 NEMWIN_ASSERT_MSG_REG_VAL64(pVCpu, HvX64RegisterRdx, pMsg->Rdx);
2818
2819 /*
2820 * Check CPL as that's common to both RDMSR and WRMSR.
2821 */
2822 VBOXSTRICTRC rcStrict;
2823 if (pMsg->Header.ExecutionState.Cpl == 0)
2824 {
2825 /*
2826 * Get all the MSR state. Since we're getting EFER, we also need to
2827 * get CR0, CR4 and CR3.
2828 */
2829 PCEMEXITREC pExitRec = EMHistoryAddExit(pVCpu,
2830 pMsg->Header.InterceptAccessType == HV_INTERCEPT_ACCESS_WRITE
2831 ? EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM, EMEXITTYPE_MSR_WRITE)
2832 : EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM, EMEXITTYPE_MSR_READ),
2833 pMsg->Header.Rip + pMsg->Header.CsSegment.Base, ASMReadTSC());
2834
2835 nemHCWinCopyStateFromX64Header(pVCpu, &pMsg->Header);
2836 rcStrict = nemHCWinImportStateIfNeededStrict(pVCpu,
2837 (!pExitRec ? 0 : IEM_CPUMCTX_EXTRN_MUST_MASK)
2838 | CPUMCTX_EXTRN_ALL_MSRS | CPUMCTX_EXTRN_CR0
2839 | CPUMCTX_EXTRN_CR3 | CPUMCTX_EXTRN_CR4,
2840 "MSRs");
2841 if (rcStrict == VINF_SUCCESS)
2842 {
2843 if (!pExitRec)
2844 {
2845 /*
2846 * Handle writes.
2847 */
2848 if (pMsg->Header.InterceptAccessType == HV_INTERCEPT_ACCESS_WRITE)
2849 {
2850 rcStrict = CPUMSetGuestMsr(pVCpu, pMsg->MsrNumber, RT_MAKE_U64((uint32_t)pMsg->Rax, (uint32_t)pMsg->Rdx));
2851 Log4(("MsrExit/%u: %04x:%08RX64/%s: WRMSR %08x, %08x:%08x -> %Rrc\n",
2852 pVCpu->idCpu, pMsg->Header.CsSegment.Selector, pMsg->Header.Rip, nemHCWinExecStateToLogStr(&pMsg->Header),
2853 pMsg->MsrNumber, (uint32_t)pMsg->Rax, (uint32_t)pMsg->Rdx, VBOXSTRICTRC_VAL(rcStrict) ));
2854 if (rcStrict == VINF_SUCCESS)
2855 {
2856 nemHCWinAdvanceGuestRipAndClearRF(pVCpu, &pMsg->Header, 2);
2857 return VINF_SUCCESS;
2858 }
2859# ifndef IN_RING3
2860 /* move to ring-3 and handle the trap/whatever there, as we want to LogRel this. */
2861 if (rcStrict == VERR_CPUM_RAISE_GP_0)
2862 rcStrict = VINF_CPUM_R3_MSR_WRITE;
2863 return rcStrict;
2864# else
2865 LogRel(("MsrExit/%u: %04x:%08RX64/%s: WRMSR %08x, %08x:%08x -> %Rrc!\n",
2866 pVCpu->idCpu, pMsg->Header.CsSegment.Selector, pMsg->Header.Rip, nemHCWinExecStateToLogStr(&pMsg->Header),
2867 pMsg->MsrNumber, (uint32_t)pMsg->Rax, (uint32_t)pMsg->Rdx, VBOXSTRICTRC_VAL(rcStrict) ));
2868# endif
2869 }
2870 /*
2871 * Handle reads.
2872 */
2873 else
2874 {
2875 uint64_t uValue = 0;
2876 rcStrict = CPUMQueryGuestMsr(pVCpu, pMsg->MsrNumber, &uValue);
2877 Log4(("MsrExit/%u: %04x:%08RX64/%s: RDMSR %08x -> %08RX64 / %Rrc\n",
2878 pVCpu->idCpu, pMsg->Header.CsSegment.Selector, pMsg->Header.Rip, nemHCWinExecStateToLogStr(&pMsg->Header),
2879 pMsg->MsrNumber, uValue, VBOXSTRICTRC_VAL(rcStrict) ));
2880 if (rcStrict == VINF_SUCCESS)
2881 {
2882 pVCpu->cpum.GstCtx.rax = (uint32_t)uValue;
2883 pVCpu->cpum.GstCtx.rdx = uValue >> 32;
2884 pVCpu->cpum.GstCtx.fExtrn &= ~(CPUMCTX_EXTRN_RAX | CPUMCTX_EXTRN_RDX);
2885 nemHCWinAdvanceGuestRipAndClearRF(pVCpu, &pMsg->Header, 2);
2886 return VINF_SUCCESS;
2887 }
2888# ifndef IN_RING3
2889 /* move to ring-3 and handle the trap/whatever there, as we want to LogRel this. */
2890 if (rcStrict == VERR_CPUM_RAISE_GP_0)
2891 rcStrict = VINF_CPUM_R3_MSR_READ;
2892 return rcStrict;
2893# else
2894 LogRel(("MsrExit/%u: %04x:%08RX64/%s: RDMSR %08x -> %08RX64 / %Rrc\n",
2895 pVCpu->idCpu, pMsg->Header.CsSegment.Selector, pMsg->Header.Rip, nemHCWinExecStateToLogStr(&pMsg->Header),
2896 pMsg->MsrNumber, uValue, VBOXSTRICTRC_VAL(rcStrict) ));
2897# endif
2898 }
2899 }
2900 else
2901 {
2902 /*
2903 * Handle frequent exit or something needing probing.
2904 */
2905 Log4(("MsrExit/%u: %04x:%08RX64/%s: %sMSR %#08x\n",
2906 pVCpu->idCpu, pMsg->Header.CsSegment.Selector, pMsg->Header.Rip, nemHCWinExecStateToLogStr(&pMsg->Header),
2907 pMsg->Header.InterceptAccessType == HV_INTERCEPT_ACCESS_WRITE ? "WR" : "RD", pMsg->MsrNumber));
2908 rcStrict = EMHistoryExec(pVCpu, pExitRec, 0);
2909 Log4(("MsrExit/%u: %04x:%08RX64/%s: EMHistoryExec -> %Rrc + %04x:%08RX64\n",
2910 pVCpu->idCpu, pMsg->Header.CsSegment.Selector, pMsg->Header.Rip, nemHCWinExecStateToLogStr(&pMsg->Header),
2911 VBOXSTRICTRC_VAL(rcStrict), pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip));
2912 return rcStrict;
2913 }
2914 }
2915 else
2916 {
2917 LogRel(("MsrExit/%u: %04x:%08RX64/%s: %sMSR %08x -> %Rrc - msr state import\n",
2918 pVCpu->idCpu, pMsg->Header.CsSegment.Selector, pMsg->Header.Rip, nemHCWinExecStateToLogStr(&pMsg->Header),
2919 pMsg->Header.InterceptAccessType == HV_INTERCEPT_ACCESS_WRITE ? "WR" : "RD",
2920 pMsg->MsrNumber, VBOXSTRICTRC_VAL(rcStrict) ));
2921 return rcStrict;
2922 }
2923 }
2924 else if (pMsg->Header.InterceptAccessType == HV_INTERCEPT_ACCESS_WRITE)
2925 Log4(("MsrExit/%u: %04x:%08RX64/%s: CPL %u -> #GP(0); WRMSR %08x, %08x:%08x\n",
2926 pVCpu->idCpu, pMsg->Header.CsSegment.Selector, pMsg->Header.Rip, nemHCWinExecStateToLogStr(&pMsg->Header),
2927 pMsg->Header.ExecutionState.Cpl, pMsg->MsrNumber, (uint32_t)pMsg->Rax, (uint32_t)pMsg->Rdx ));
2928 else
2929 Log4(("MsrExit/%u: %04x:%08RX64/%s: CPL %u -> #GP(0); RDMSR %08x\n",
2930 pVCpu->idCpu, pMsg->Header.CsSegment.Selector, pMsg->Header.Rip, nemHCWinExecStateToLogStr(&pMsg->Header),
2931 pMsg->Header.ExecutionState.Cpl, pMsg->MsrNumber));
2932
2933 /*
2934 * If we get down here, we're supposed to #GP(0).
2935 */
2936 rcStrict = nemHCWinImportStateIfNeededStrict(pVCpu, NEM_WIN_CPUMCTX_EXTRN_MASK_FOR_IEM | CPUMCTX_EXTRN_ALL_MSRS, "MSR");
2937 if (rcStrict == VINF_SUCCESS)
2938 {
2939 rcStrict = IEMInjectTrap(pVCpu, X86_XCPT_GP, TRPM_TRAP, 0, 0, 0);
2940 if (rcStrict == VINF_IEM_RAISED_XCPT)
2941 rcStrict = VINF_SUCCESS;
2942 else if (rcStrict != VINF_SUCCESS)
2943 Log4(("MsrExit/%u: Injecting #GP(0) failed: %Rrc\n", VBOXSTRICTRC_VAL(rcStrict) ));
2944 }
2945 return rcStrict;
2946}
2947#elif defined(IN_RING3)
2948/**
2949 * Deals with MSR access exits (WHvRunVpExitReasonX64MsrAccess).
2950 *
2951 * @returns Strict VBox status code.
2952 * @param pVM The cross context VM structure.
2953 * @param pVCpu The cross context per CPU structure.
2954 * @param pExit The VM exit information to handle.
2955 * @sa nemHCWinHandleMessageMsr
2956 */
2957NEM_TMPL_STATIC VBOXSTRICTRC nemR3WinHandleExitMsr(PVMCC pVM, PVMCPUCC pVCpu, WHV_RUN_VP_EXIT_CONTEXT const *pExit)
2958{
2959 /*
2960 * Check CPL as that's common to both RDMSR and WRMSR.
2961 */
2962 VBOXSTRICTRC rcStrict;
2963 if (pExit->VpContext.ExecutionState.Cpl == 0)
2964 {
2965 /*
2966 * Get all the MSR state. Since we're getting EFER, we also need to
2967 * get CR0, CR4 and CR3.
2968 */
2969 PCEMEXITREC pExitRec = EMHistoryAddExit(pVCpu,
2970 pExit->MsrAccess.AccessInfo.IsWrite
2971 ? EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM, EMEXITTYPE_MSR_WRITE)
2972 : EMEXIT_MAKE_FT(EMEXIT_F_KIND_EM, EMEXITTYPE_MSR_READ),
2973 pExit->VpContext.Rip + pExit->VpContext.Cs.Base, ASMReadTSC());
2974 nemR3WinCopyStateFromX64Header(pVCpu, &pExit->VpContext);
2975 rcStrict = nemHCWinImportStateIfNeededStrict(pVCpu,
2976 (!pExitRec ? 0 : IEM_CPUMCTX_EXTRN_MUST_MASK)
2977 | CPUMCTX_EXTRN_ALL_MSRS | CPUMCTX_EXTRN_CR0
2978 | CPUMCTX_EXTRN_CR3 | CPUMCTX_EXTRN_CR4,
2979 "MSRs");
2980 if (rcStrict == VINF_SUCCESS)
2981 {
2982 if (!pExitRec)
2983 {
2984 /*
2985 * Handle writes.
2986 */
2987 if (pExit->MsrAccess.AccessInfo.IsWrite)
2988 {
2989 rcStrict = CPUMSetGuestMsr(pVCpu, pExit->MsrAccess.MsrNumber,
2990 RT_MAKE_U64((uint32_t)pExit->MsrAccess.Rax, (uint32_t)pExit->MsrAccess.Rdx));
2991 Log4(("MsrExit/%u: %04x:%08RX64/%s: WRMSR %08x, %08x:%08x -> %Rrc\n", pVCpu->idCpu, pExit->VpContext.Cs.Selector,
2992 pExit->VpContext.Rip, nemR3WinExecStateToLogStr(&pExit->VpContext), pExit->MsrAccess.MsrNumber,
2993 (uint32_t)pExit->MsrAccess.Rax, (uint32_t)pExit->MsrAccess.Rdx, VBOXSTRICTRC_VAL(rcStrict) ));
2994 if (rcStrict == VINF_SUCCESS)
2995 {
2996 nemR3WinAdvanceGuestRipAndClearRF(pVCpu, &pExit->VpContext, 2);
2997 return VINF_SUCCESS;
2998 }
2999 LogRel(("MsrExit/%u: %04x:%08RX64/%s: WRMSR %08x, %08x:%08x -> %Rrc!\n", pVCpu->idCpu,
3000 pExit->VpContext.Cs.Selector, pExit->VpContext.Rip, nemR3WinExecStateToLogStr(&pExit->VpContext),
3001 pExit->MsrAccess.MsrNumber, (uint32_t)pExit->MsrAccess.Rax, (uint32_t)pExit->MsrAccess.Rdx,
3002 VBOXSTRICTRC_VAL(rcStrict) ));
3003 }
3004 /*
3005 * Handle reads.
3006 */
3007 else
3008 {
3009 uint64_t uValue = 0;
3010 rcStrict = CPUMQueryGuestMsr(pVCpu, pExit->MsrAccess.MsrNumber, &uValue);
3011 Log4(("MsrExit/%u: %04x:%08RX64/%s: RDMSR %08x -> %08RX64 / %Rrc\n", pVCpu->idCpu,
3012 pExit->VpContext.Cs.Selector, pExit->VpContext.Rip, nemR3WinExecStateToLogStr(&pExit->VpContext),
3013 pExit->MsrAccess.MsrNumber, uValue, VBOXSTRICTRC_VAL(rcStrict) ));
3014 if (rcStrict == VINF_SUCCESS)
3015 {
3016 pVCpu->cpum.GstCtx.rax = (uint32_t)uValue;
3017 pVCpu->cpum.GstCtx.rdx = uValue >> 32;
3018 pVCpu->cpum.GstCtx.fExtrn &= ~(CPUMCTX_EXTRN_RAX | CPUMCTX_EXTRN_RDX);
3019 nemR3WinAdvanceGuestRipAndClearRF(pVCpu, &pExit->VpContext, 2);
3020 return VINF_SUCCESS;
3021 }
3022 LogRel(("MsrExit/%u: %04x:%08RX64/%s: RDMSR %08x -> %08RX64 / %Rrc\n", pVCpu->idCpu, pExit->VpContext.Cs.Selector,
3023 pExit->VpContext.Rip, nemR3WinExecStateToLogStr(&pExit->VpContext), pExit->MsrAccess.MsrNumber,
3024 uValue, VBOXSTRICTRC_VAL(rcStrict) ));
3025 }
3026 }
3027 else
3028 {
3029 /*
3030 * Handle frequent exit or something needing probing.
3031 */
3032 Log4(("MsrExit/%u: %04x:%08RX64/%s: %sMSR %#08x\n",
3033 pVCpu->idCpu, pExit->VpContext.Cs.Selector, pExit->VpContext.Rip, nemR3WinExecStateToLogStr(&pExit->VpContext),
3034 pExit->MsrAccess.AccessInfo.IsWrite ? "WR" : "RD", pExit->MsrAccess.MsrNumber));
3035 rcStrict = EMHistoryExec(pVCpu, pExitRec, 0);
3036 Log4(("MsrExit/%u: %04x:%08RX64/%s: EMHistoryExec -> %Rrc + %04x:%08RX64\n",
3037 pVCpu->idCpu, pExit->VpContext.Cs.Selector, pExit->VpContext.Rip, nemR3WinExecStateToLogStr(&pExit->VpContext),
3038 VBOXSTRICTRC_VAL(rcStrict), pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip));
3039 return rcStrict;
3040 }
3041 }
3042 else
3043 {
3044 LogRel(("MsrExit/%u: %04x:%08RX64/%s: %sMSR %08x -> %Rrc - msr state import\n",
3045 pVCpu->idCpu, pExit->VpContext.Cs.Selector, pExit->VpContext.Rip, nemR3WinExecStateToLogStr(&pExit->VpContext),
3046 pExit->MsrAccess.AccessInfo.IsWrite ? "WR" : "RD", pExit->MsrAccess.MsrNumber, VBOXSTRICTRC_VAL(rcStrict) ));
3047 return rcStrict;
3048 }
3049 }
3050 else if (pExit->MsrAccess.AccessInfo.IsWrite)
3051 Log4(("MsrExit/%u: %04x:%08RX64/%s: CPL %u -> #GP(0); WRMSR %08x, %08x:%08x\n", pVCpu->idCpu, pExit->VpContext.Cs.Selector,
3052 pExit->VpContext.Rip, nemR3WinExecStateToLogStr(&pExit->VpContext), pExit->VpContext.ExecutionState.Cpl,
3053 pExit->MsrAccess.MsrNumber, (uint32_t)pExit->MsrAccess.Rax, (uint32_t)pExit->MsrAccess.Rdx ));
3054 else
3055 Log4(("MsrExit/%u: %04x:%08RX64/%s: CPL %u -> #GP(0); RDMSR %08x\n", pVCpu->idCpu, pExit->VpContext.Cs.Selector,
3056 pExit->VpContext.Rip, nemR3WinExecStateToLogStr(&pExit->VpContext), pExit->VpContext.ExecutionState.Cpl,
3057 pExit->MsrAccess.MsrNumber));
3058
3059 /*
3060 * If we get down here, we're supposed to #GP(0).
3061 */
3062 rcStrict = nemHCWinImportStateIfNeededStrict(pVCpu, NEM_WIN_CPUMCTX_EXTRN_MASK_FOR_IEM | CPUMCTX_EXTRN_ALL_MSRS, "MSR");
3063 if (rcStrict == VINF_SUCCESS)
3064 {
3065 rcStrict = IEMInjectTrap(pVCpu, X86_XCPT_GP, TRPM_TRAP, 0, 0, 0);
3066 if (rcStrict == VINF_IEM_RAISED_XCPT)
3067 rcStrict = VINF_SUCCESS;
3068 else if (rcStrict != VINF_SUCCESS)
3069 Log4(("MsrExit/%u: Injecting #GP(0) failed: %Rrc\n", VBOXSTRICTRC_VAL(rcStrict) ));
3070 }
3071
3072 RT_NOREF_PV(pVM);
3073 return rcStrict;
3074}
3075#endif /* IN_RING3 && !NEM_WIN_TEMPLATE_MODE_OWN_RUN_API */
3076
3077
3078/**
3079 * Worker for nemHCWinHandleMessageException & nemR3WinHandleExitException that
3080 * checks if the given opcodes are of interest at all.
3081 *
3082 * @returns true if interesting, false if not.
3083 * @param cbOpcodes Number of opcode bytes available.
3084 * @param pbOpcodes The opcode bytes.
3085 * @param f64BitMode Whether we're in 64-bit mode.
3086 */
3087DECLINLINE(bool) nemHcWinIsInterestingUndefinedOpcode(uint8_t cbOpcodes, uint8_t const *pbOpcodes, bool f64BitMode)
3088{
3089 /*
3090 * Currently only interested in VMCALL and VMMCALL.
3091 */
3092 while (cbOpcodes >= 3)
3093 {
3094 switch (pbOpcodes[0])
3095 {
3096 case 0x0f:
3097 switch (pbOpcodes[1])
3098 {
3099 case 0x01:
3100 switch (pbOpcodes[2])
3101 {
3102 case 0xc1: /* 0f 01 c1 VMCALL */
3103 return true;
3104 case 0xd9: /* 0f 01 d9 VMMCALL */
3105 return true;
3106 default:
3107 break;
3108 }
3109 break;
3110 }
3111 break;
3112
3113 default:
3114 return false;
3115
3116 /* prefixes */
3117 case 0x40: case 0x41: case 0x42: case 0x43: case 0x44: case 0x45: case 0x46: case 0x47:
3118 case 0x48: case 0x49: case 0x4a: case 0x4b: case 0x4c: case 0x4d: case 0x4e: case 0x4f:
3119 if (!f64BitMode)
3120 return false;
3121 RT_FALL_THRU();
3122 case X86_OP_PRF_CS:
3123 case X86_OP_PRF_SS:
3124 case X86_OP_PRF_DS:
3125 case X86_OP_PRF_ES:
3126 case X86_OP_PRF_FS:
3127 case X86_OP_PRF_GS:
3128 case X86_OP_PRF_SIZE_OP:
3129 case X86_OP_PRF_SIZE_ADDR:
3130 case X86_OP_PRF_LOCK:
3131 case X86_OP_PRF_REPZ:
3132 case X86_OP_PRF_REPNZ:
3133 cbOpcodes--;
3134 pbOpcodes++;
3135 continue;
3136 }
3137 break;
3138 }
3139 return false;
3140}
3141
3142
3143#ifdef NEM_WIN_TEMPLATE_MODE_OWN_RUN_API
3144/**
3145 * Copies state included in a exception intercept message.
3146 *
3147 * @param pVCpu The cross context per CPU structure.
3148 * @param pMsg The message.
3149 * @param fClearXcpt Clear pending exception.
3150 */
3151DECLINLINE(void)
3152nemHCWinCopyStateFromExceptionMessage(PVMCPUCC pVCpu, HV_X64_EXCEPTION_INTERCEPT_MESSAGE const *pMsg, bool fClearXcpt)
3153{
3154 nemHCWinCopyStateFromX64Header(pVCpu, &pMsg->Header);
3155 pVCpu->cpum.GstCtx.fExtrn &= ~( CPUMCTX_EXTRN_GPRS_MASK | CPUMCTX_EXTRN_SS | CPUMCTX_EXTRN_DS
3156 | (fClearXcpt ? CPUMCTX_EXTRN_NEM_WIN_EVENT_INJECT : 0) );
3157 pVCpu->cpum.GstCtx.rax = pMsg->Rax;
3158 pVCpu->cpum.GstCtx.rcx = pMsg->Rcx;
3159 pVCpu->cpum.GstCtx.rdx = pMsg->Rdx;
3160 pVCpu->cpum.GstCtx.rbx = pMsg->Rbx;
3161 pVCpu->cpum.GstCtx.rsp = pMsg->Rsp;
3162 pVCpu->cpum.GstCtx.rbp = pMsg->Rbp;
3163 pVCpu->cpum.GstCtx.rsi = pMsg->Rsi;
3164 pVCpu->cpum.GstCtx.rdi = pMsg->Rdi;
3165 pVCpu->cpum.GstCtx.r8 = pMsg->R8;
3166 pVCpu->cpum.GstCtx.r9 = pMsg->R9;
3167 pVCpu->cpum.GstCtx.r10 = pMsg->R10;
3168 pVCpu->cpum.GstCtx.r11 = pMsg->R11;
3169 pVCpu->cpum.GstCtx.r12 = pMsg->R12;
3170 pVCpu->cpum.GstCtx.r13 = pMsg->R13;
3171 pVCpu->cpum.GstCtx.r14 = pMsg->R14;
3172 pVCpu->cpum.GstCtx.r15 = pMsg->R15;
3173 NEM_WIN_COPY_BACK_SEG(pVCpu->cpum.GstCtx.ds, pMsg->DsSegment);
3174 NEM_WIN_COPY_BACK_SEG(pVCpu->cpum.GstCtx.ss, pMsg->SsSegment);
3175}
3176#elif defined(IN_RING3)
3177/**
3178 * Copies state included in a exception intercept exit.
3179 *
3180 * @param pVCpu The cross context per CPU structure.
3181 * @param pExit The VM exit information.
3182 * @param fClearXcpt Clear pending exception.
3183 */
3184DECLINLINE(void) nemR3WinCopyStateFromExceptionMessage(PVMCPUCC pVCpu, WHV_RUN_VP_EXIT_CONTEXT const *pExit, bool fClearXcpt)
3185{
3186 nemR3WinCopyStateFromX64Header(pVCpu, &pExit->VpContext);
3187 if (fClearXcpt)
3188 pVCpu->cpum.GstCtx.fExtrn &= ~CPUMCTX_EXTRN_NEM_WIN_EVENT_INJECT;
3189}
3190#endif /* IN_RING3 && !NEM_WIN_TEMPLATE_MODE_OWN_RUN_API */
3191
3192
3193/**
3194 * Advances the guest RIP by the number of bytes specified in @a cb.
3195 *
3196 * @param pVCpu The cross context virtual CPU structure.
3197 * @param cb RIP increment value in bytes.
3198 */
3199DECLINLINE(void) nemHcWinAdvanceRip(PVMCPUCC pVCpu, uint32_t cb)
3200{
3201 PCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
3202 pCtx->rip += cb;
3203
3204 /* Update interrupt shadow. */
3205 if ( VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS)
3206 && pCtx->rip != EMGetInhibitInterruptsPC(pVCpu))
3207 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS);
3208}
3209
3210
3211/**
3212 * Hacks its way around the lovely mesa driver's backdoor accesses.
3213 *
3214 * @sa hmR0VmxHandleMesaDrvGp
3215 * @sa hmR0SvmHandleMesaDrvGp
3216 */
3217static int nemHcWinHandleMesaDrvGp(PVMCPUCC pVCpu, PCPUMCTX pCtx)
3218{
3219 Assert(!(pCtx->fExtrn & (CPUMCTX_EXTRN_RIP | CPUMCTX_EXTRN_CS | CPUMCTX_EXTRN_RFLAGS | CPUMCTX_EXTRN_GPRS_MASK)));
3220 RT_NOREF(pCtx);
3221
3222 /* For now we'll just skip the instruction. */
3223 nemHcWinAdvanceRip(pVCpu, 1);
3224 return VINF_SUCCESS;
3225}
3226
3227
3228/**
3229 * Checks if the \#GP'ing instruction is the mesa driver doing it's lovely
3230 * backdoor logging w/o checking what it is running inside.
3231 *
3232 * This recognizes an "IN EAX,DX" instruction executed in flat ring-3, with the
3233 * backdoor port and magic numbers loaded in registers.
3234 *
3235 * @returns true if it is, false if it isn't.
3236 * @sa hmR0VmxIsMesaDrvGp
3237 * @sa hmR0SvmIsMesaDrvGp
3238 */
3239DECLINLINE(bool) nemHcWinIsMesaDrvGp(PVMCPUCC pVCpu, PCPUMCTX pCtx, const uint8_t *pbInsn, uint32_t cbInsn)
3240{
3241 /* #GP(0) is already checked by caller. */
3242
3243 /* Check magic and port. */
3244 Assert(!(pCtx->fExtrn & (CPUMCTX_EXTRN_RDX | CPUMCTX_EXTRN_RAX)));
3245 if (pCtx->dx != UINT32_C(0x5658))
3246 return false;
3247 if (pCtx->rax != UINT32_C(0x564d5868))
3248 return false;
3249
3250 /* Flat ring-3 CS. */
3251 if (CPUMGetGuestCPL(pVCpu) != 3)
3252 return false;
3253 if (pCtx->cs.u64Base != 0)
3254 return false;
3255
3256 /* 0xed: IN eAX,dx */
3257 if (cbInsn < 1) /* Play safe (shouldn't happen). */
3258 {
3259 uint8_t abInstr[1];
3260 int rc = PGMPhysSimpleReadGCPtr(pVCpu, abInstr, pCtx->rip, sizeof(abInstr));
3261 if (RT_FAILURE(rc))
3262 return false;
3263 if (abInstr[0] != 0xed)
3264 return false;
3265 }
3266 else
3267 {
3268 if (pbInsn[0] != 0xed)
3269 return false;
3270 }
3271
3272 return true;
3273}
3274
3275
3276#ifdef NEM_WIN_TEMPLATE_MODE_OWN_RUN_API
3277/**
3278 * Deals with exception intercept message (HvMessageTypeX64ExceptionIntercept).
3279 *
3280 * @returns Strict VBox status code.
3281 * @param pVCpu The cross context per CPU structure.
3282 * @param pMsg The message.
3283 * @sa nemR3WinHandleExitMsr
3284 */
3285NEM_TMPL_STATIC VBOXSTRICTRC
3286nemHCWinHandleMessageException(PVMCPUCC pVCpu, HV_X64_EXCEPTION_INTERCEPT_MESSAGE const *pMsg)
3287{
3288 /*
3289 * Assert sanity.
3290 */
3291 Assert( pMsg->Header.InterceptAccessType == HV_INTERCEPT_ACCESS_READ
3292 || pMsg->Header.InterceptAccessType == HV_INTERCEPT_ACCESS_WRITE
3293 || pMsg->Header.InterceptAccessType == HV_INTERCEPT_ACCESS_EXECUTE);
3294 NEMWIN_ASSERT_MSG_REG_SEG( pVCpu, HvX64RegisterCs, pMsg->Header.CsSegment);
3295 NEMWIN_ASSERT_MSG_REG_VAL64(pVCpu, HvX64RegisterRip, pMsg->Header.Rip);
3296 NEMWIN_ASSERT_MSG_REG_VAL64(pVCpu, HvX64RegisterRflags, pMsg->Header.Rflags);
3297 NEMWIN_ASSERT_MSG_REG_VAL64(pVCpu, HvX64RegisterCr8, (uint64_t)pMsg->Header.Cr8);
3298 NEMWIN_ASSERT_MSG_REG_SEG( pVCpu, HvX64RegisterDs, pMsg->DsSegment);
3299 NEMWIN_ASSERT_MSG_REG_SEG( pVCpu, HvX64RegisterSs, pMsg->SsSegment);
3300 NEMWIN_ASSERT_MSG_REG_VAL64(pVCpu, HvX64RegisterRax, pMsg->Rax);
3301 NEMWIN_ASSERT_MSG_REG_VAL64(pVCpu, HvX64RegisterRcx, pMsg->Rcx);
3302 NEMWIN_ASSERT_MSG_REG_VAL64(pVCpu, HvX64RegisterRdx, pMsg->Rdx);
3303 NEMWIN_ASSERT_MSG_REG_VAL64(pVCpu, HvX64RegisterRbx, pMsg->Rbx);
3304 NEMWIN_ASSERT_MSG_REG_VAL64(pVCpu, HvX64RegisterRsp, pMsg->Rsp);
3305 NEMWIN_ASSERT_MSG_REG_VAL64(pVCpu, HvX64RegisterRbp, pMsg->Rbp);
3306 NEMWIN_ASSERT_MSG_REG_VAL64(pVCpu, HvX64RegisterRsi, pMsg->Rsi);
3307 NEMWIN_ASSERT_MSG_REG_VAL64(pVCpu, HvX64RegisterRdi, pMsg->Rdi);
3308 NEMWIN_ASSERT_MSG_REG_VAL64(pVCpu, HvX64RegisterR8, pMsg->R8);
3309 NEMWIN_ASSERT_MSG_REG_VAL64(pVCpu, HvX64RegisterR9, pMsg->R9);
3310 NEMWIN_ASSERT_MSG_REG_VAL64(pVCpu, HvX64RegisterR10, pMsg->R10);
3311 NEMWIN_ASSERT_MSG_REG_VAL64(pVCpu, HvX64RegisterR11, pMsg->R11);
3312 NEMWIN_ASSERT_MSG_REG_VAL64(pVCpu, HvX64RegisterR12, pMsg->R12);
3313 NEMWIN_ASSERT_MSG_REG_VAL64(pVCpu, HvX64RegisterR13, pMsg->R13);
3314 NEMWIN_ASSERT_MSG_REG_VAL64(pVCpu, HvX64RegisterR14, pMsg->R14);
3315 NEMWIN_ASSERT_MSG_REG_VAL64(pVCpu, HvX64RegisterR15, pMsg->R15);
3316
3317 /*
3318 * Get most of the register state since we'll end up making IEM inject the
3319 * event. The exception isn't normally flaged as a pending event, so duh.
3320 *
3321 * Note! We can optimize this later with event injection.
3322 */
3323 Log4(("XcptExit/%u: %04x:%08RX64/%s: %x errcd=%#x parm=%RX64\n",
3324 pVCpu->idCpu, pMsg->Header.CsSegment.Selector, pMsg->Header.Rip, nemHCWinExecStateToLogStr(&pMsg->Header),
3325 pMsg->ExceptionVector, pMsg->ErrorCode, pMsg->ExceptionParameter));
3326 nemHCWinCopyStateFromExceptionMessage(pVCpu, pMsg, true /*fClearXcpt*/);
3327 uint64_t fWhat = NEM_WIN_CPUMCTX_EXTRN_MASK_FOR_IEM;
3328 if (pMsg->ExceptionVector == X86_XCPT_DB)
3329 fWhat |= CPUMCTX_EXTRN_DR0_DR3 | CPUMCTX_EXTRN_DR7 | CPUMCTX_EXTRN_DR6;
3330 VBOXSTRICTRC rcStrict = nemHCWinImportStateIfNeededStrict(pVCpu, fWhat, "Xcpt");
3331 if (rcStrict != VINF_SUCCESS)
3332 return rcStrict;
3333
3334 /*
3335 * Handle the intercept.
3336 */
3337 TRPMEVENT enmEvtType = TRPM_TRAP;
3338 switch (pMsg->ExceptionVector)
3339 {
3340 /*
3341 * We get undefined opcodes on VMMCALL(AMD) & VMCALL(Intel) instructions
3342 * and need to turn them over to GIM.
3343 *
3344 * Note! We do not check fGIMTrapXcptUD here ASSUMING that GIM only wants
3345 * #UD for handling non-native hypercall instructions. (IEM will
3346 * decode both and let the GIM provider decide whether to accept it.)
3347 */
3348 case X86_XCPT_UD:
3349 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatExitExceptionUd);
3350 EMHistoryAddExit(pVCpu, EMEXIT_MAKE_FT(EMEXIT_F_KIND_NEM, NEMEXITTYPE_XCPT_UD),
3351 pMsg->Header.Rip + pMsg->Header.CsSegment.Base, ASMReadTSC());
3352
3353 if (nemHcWinIsInterestingUndefinedOpcode(pMsg->InstructionByteCount, pMsg->InstructionBytes,
3354 pMsg->Header.ExecutionState.EferLma && pMsg->Header.CsSegment.Long ))
3355 {
3356 rcStrict = IEMExecOneWithPrefetchedByPC(pVCpu, CPUMCTX2CORE(&pVCpu->cpum.GstCtx), pMsg->Header.Rip,
3357 pMsg->InstructionBytes, pMsg->InstructionByteCount);
3358 Log4(("XcptExit/%u: %04x:%08RX64/%s: #UD -> emulated -> %Rrc\n",
3359 pVCpu->idCpu, pMsg->Header.CsSegment.Selector, pMsg->Header.Rip,
3360 nemHCWinExecStateToLogStr(&pMsg->Header), VBOXSTRICTRC_VAL(rcStrict) ));
3361 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatExitExceptionUdHandled);
3362 return rcStrict;
3363 }
3364 Log4(("XcptExit/%u: %04x:%08RX64/%s: #UD [%.*Rhxs] -> re-injected\n", pVCpu->idCpu, pMsg->Header.CsSegment.Selector,
3365 pMsg->Header.Rip, nemHCWinExecStateToLogStr(&pMsg->Header), pMsg->InstructionByteCount, pMsg->InstructionBytes ));
3366 break;
3367
3368 /*
3369 * Workaround the lovely mesa driver assuming that vmsvga means vmware
3370 * hypervisor and tries to log stuff to the host.
3371 */
3372 case X86_XCPT_GP:
3373 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatExitExceptionGp);
3374 /** @todo r=bird: Need workaround in IEM for this, right?
3375 EMHistoryAddExit(pVCpu, EMEXIT_MAKE_FT(EMEXIT_F_KIND_NEM, NEMEXITTYPE_XCPT_GP),
3376 pMsg->Header.Rip + pMsg->Header.CsSegment.Base, ASMReadTSC()); */
3377 if ( !pVCpu->hm.s.fTrapXcptGpForLovelyMesaDrv
3378 || !nemHcWinIsMesaDrvGp(pVCpu, &pVCpu->cpum.GstCtx, pMsg->InstructionBytes, pMsg->InstructionByteCount))
3379 {
3380# if 1 /** @todo Need to emulate instruction or we get a triple fault when trying to inject the #GP... */
3381 rcStrict = IEMExecOneWithPrefetchedByPC(pVCpu, CPUMCTX2CORE(&pVCpu->cpum.GstCtx), pMsg->Header.Rip,
3382 pMsg->InstructionBytes, pMsg->InstructionByteCount);
3383 Log4(("XcptExit/%u: %04x:%08RX64/%s: #GP -> emulated -> %Rrc\n",
3384 pVCpu->idCpu, pMsg->Header.CsSegment.Selector, pMsg->Header.Rip,
3385 nemHCWinExecStateToLogStr(&pMsg->Header), VBOXSTRICTRC_VAL(rcStrict) ));
3386 return rcStrict;
3387# else
3388 break;
3389# endif
3390 }
3391 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatExitExceptionGpMesa);
3392 return nemHcWinHandleMesaDrvGp(pVCpu, &pVCpu->cpum.GstCtx);
3393
3394 /*
3395 * Filter debug exceptions.
3396 */
3397 case X86_XCPT_DB:
3398 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatExitExceptionDb);
3399 EMHistoryAddExit(pVCpu, EMEXIT_MAKE_FT(EMEXIT_F_KIND_NEM, NEMEXITTYPE_XCPT_DB),
3400 pMsg->Header.Rip + pMsg->Header.CsSegment.Base, ASMReadTSC());
3401 Log4(("XcptExit/%u: %04x:%08RX64/%s: #DB - TODO\n",
3402 pVCpu->idCpu, pMsg->Header.CsSegment.Selector, pMsg->Header.Rip, nemHCWinExecStateToLogStr(&pMsg->Header) ));
3403 break;
3404
3405 case X86_XCPT_BP:
3406 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatExitExceptionBp);
3407 EMHistoryAddExit(pVCpu, EMEXIT_MAKE_FT(EMEXIT_F_KIND_NEM, NEMEXITTYPE_XCPT_BP),
3408 pMsg->Header.Rip + pMsg->Header.CsSegment.Base, ASMReadTSC());
3409 Log4(("XcptExit/%u: %04x:%08RX64/%s: #BP - TODO - %u\n", pVCpu->idCpu, pMsg->Header.CsSegment.Selector,
3410 pMsg->Header.Rip, nemHCWinExecStateToLogStr(&pMsg->Header), pMsg->Header.InstructionLength));
3411 enmEvtType = TRPM_SOFTWARE_INT; /* We're at the INT3 instruction, not after it. */
3412 break;
3413
3414 /* This shouldn't happen. */
3415 default:
3416 AssertLogRelMsgFailedReturn(("ExceptionVector=%#x\n", pMsg->ExceptionVector), VERR_IEM_IPE_6);
3417 }
3418
3419 /*
3420 * Inject it.
3421 */
3422 rcStrict = IEMInjectTrap(pVCpu, pMsg->ExceptionVector, enmEvtType, pMsg->ErrorCode,
3423 pMsg->ExceptionParameter /*??*/, pMsg->Header.InstructionLength);
3424 Log4(("XcptExit/%u: %04x:%08RX64/%s: %#u -> injected -> %Rrc\n",
3425 pVCpu->idCpu, pMsg->Header.CsSegment.Selector, pMsg->Header.Rip,
3426 nemHCWinExecStateToLogStr(&pMsg->Header), pMsg->ExceptionVector, VBOXSTRICTRC_VAL(rcStrict) ));
3427 return rcStrict;
3428}
3429#elif defined(IN_RING3)
3430/**
3431 * Deals with MSR access exits (WHvRunVpExitReasonException).
3432 *
3433 * @returns Strict VBox status code.
3434 * @param pVM The cross context VM structure.
3435 * @param pVCpu The cross context per CPU structure.
3436 * @param pExit The VM exit information to handle.
3437 * @sa nemR3WinHandleExitException
3438 */
3439NEM_TMPL_STATIC VBOXSTRICTRC nemR3WinHandleExitException(PVMCC pVM, PVMCPUCC pVCpu, WHV_RUN_VP_EXIT_CONTEXT const *pExit)
3440{
3441 /*
3442 * Get most of the register state since we'll end up making IEM inject the
3443 * event. The exception isn't normally flaged as a pending event, so duh.
3444 *
3445 * Note! We can optimize this later with event injection.
3446 */
3447 Log4(("XcptExit/%u: %04x:%08RX64/%s: %x errcd=%#x parm=%RX64\n", pVCpu->idCpu, pExit->VpContext.Cs.Selector,
3448 pExit->VpContext.Rip, nemR3WinExecStateToLogStr(&pExit->VpContext), pExit->VpException.ExceptionType,
3449 pExit->VpException.ErrorCode, pExit->VpException.ExceptionParameter ));
3450 nemR3WinCopyStateFromExceptionMessage(pVCpu, pExit, true /*fClearXcpt*/);
3451 uint64_t fWhat = NEM_WIN_CPUMCTX_EXTRN_MASK_FOR_IEM;
3452 if (pExit->VpException.ExceptionType == X86_XCPT_DB)
3453 fWhat |= CPUMCTX_EXTRN_DR0_DR3 | CPUMCTX_EXTRN_DR7 | CPUMCTX_EXTRN_DR6;
3454 VBOXSTRICTRC rcStrict = nemHCWinImportStateIfNeededStrict(pVCpu, fWhat, "Xcpt");
3455 if (rcStrict != VINF_SUCCESS)
3456 return rcStrict;
3457
3458 /*
3459 * Handle the intercept.
3460 */
3461 TRPMEVENT enmEvtType = TRPM_TRAP;
3462 switch (pExit->VpException.ExceptionType)
3463 {
3464 /*
3465 * We get undefined opcodes on VMMCALL(AMD) & VMCALL(Intel) instructions
3466 * and need to turn them over to GIM.
3467 *
3468 * Note! We do not check fGIMTrapXcptUD here ASSUMING that GIM only wants
3469 * #UD for handling non-native hypercall instructions. (IEM will
3470 * decode both and let the GIM provider decide whether to accept it.)
3471 */
3472 case X86_XCPT_UD:
3473 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatExitExceptionUd);
3474 EMHistoryAddExit(pVCpu, EMEXIT_MAKE_FT(EMEXIT_F_KIND_NEM, NEMEXITTYPE_XCPT_UD),
3475 pExit->VpContext.Rip + pExit->VpContext.Cs.Base, ASMReadTSC());
3476 if (nemHcWinIsInterestingUndefinedOpcode(pExit->VpException.InstructionByteCount, pExit->VpException.InstructionBytes,
3477 pExit->VpContext.ExecutionState.EferLma && pExit->VpContext.Cs.Long ))
3478 {
3479 rcStrict = IEMExecOneWithPrefetchedByPC(pVCpu, CPUMCTX2CORE(&pVCpu->cpum.GstCtx), pExit->VpContext.Rip,
3480 pExit->VpException.InstructionBytes,
3481 pExit->VpException.InstructionByteCount);
3482 Log4(("XcptExit/%u: %04x:%08RX64/%s: #UD -> emulated -> %Rrc\n",
3483 pVCpu->idCpu, pExit->VpContext.Cs.Selector, pExit->VpContext.Rip,
3484 nemR3WinExecStateToLogStr(&pExit->VpContext), VBOXSTRICTRC_VAL(rcStrict) ));
3485 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatExitExceptionUdHandled);
3486 return rcStrict;
3487 }
3488
3489 Log4(("XcptExit/%u: %04x:%08RX64/%s: #UD [%.*Rhxs] -> re-injected\n", pVCpu->idCpu,
3490 pExit->VpContext.Cs.Selector, pExit->VpContext.Rip, nemR3WinExecStateToLogStr(&pExit->VpContext),
3491 pExit->VpException.InstructionByteCount, pExit->VpException.InstructionBytes ));
3492 break;
3493
3494 /*
3495 * Workaround the lovely mesa driver assuming that vmsvga means vmware
3496 * hypervisor and tries to log stuff to the host.
3497 */
3498 case X86_XCPT_GP:
3499 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatExitExceptionGp);
3500 /** @todo r=bird: Need workaround in IEM for this, right?
3501 EMHistoryAddExit(pVCpu, EMEXIT_MAKE_FT(EMEXIT_F_KIND_NEM, NEMEXITTYPE_XCPT_GP),
3502 pExit->VpContext.Rip + pExit->VpContext.Cs.Base, ASMReadTSC()); */
3503 if ( !pVCpu->nem.s.fTrapXcptGpForLovelyMesaDrv
3504 || !nemHcWinIsMesaDrvGp(pVCpu, &pVCpu->cpum.GstCtx, pExit->VpException.InstructionBytes,
3505 pExit->VpException.InstructionByteCount))
3506 {
3507# if 1 /** @todo Need to emulate instruction or we get a triple fault when trying to inject the #GP... */
3508 rcStrict = IEMExecOneWithPrefetchedByPC(pVCpu, CPUMCTX2CORE(&pVCpu->cpum.GstCtx), pExit->VpContext.Rip,
3509 pExit->VpException.InstructionBytes,
3510 pExit->VpException.InstructionByteCount);
3511 Log4(("XcptExit/%u: %04x:%08RX64/%s: #GP -> emulated -> %Rrc\n",
3512 pVCpu->idCpu, pExit->VpContext.Cs.Selector, pExit->VpContext.Rip,
3513 nemR3WinExecStateToLogStr(&pExit->VpContext), VBOXSTRICTRC_VAL(rcStrict) ));
3514 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatExitExceptionUdHandled);
3515 return rcStrict;
3516# else
3517 break;
3518# endif
3519 }
3520 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatExitExceptionGpMesa);
3521 return nemHcWinHandleMesaDrvGp(pVCpu, &pVCpu->cpum.GstCtx);
3522
3523 /*
3524 * Filter debug exceptions.
3525 */
3526 case X86_XCPT_DB:
3527 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatExitExceptionDb);
3528 EMHistoryAddExit(pVCpu, EMEXIT_MAKE_FT(EMEXIT_F_KIND_NEM, NEMEXITTYPE_XCPT_DB),
3529 pExit->VpContext.Rip + pExit->VpContext.Cs.Base, ASMReadTSC());
3530 Log4(("XcptExit/%u: %04x:%08RX64/%s: #DB - TODO\n",
3531 pVCpu->idCpu, pExit->VpContext.Cs.Selector, pExit->VpContext.Rip, nemR3WinExecStateToLogStr(&pExit->VpContext) ));
3532 break;
3533
3534 case X86_XCPT_BP:
3535 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatExitExceptionBp);
3536 EMHistoryAddExit(pVCpu, EMEXIT_MAKE_FT(EMEXIT_F_KIND_NEM, NEMEXITTYPE_XCPT_BP),
3537 pExit->VpContext.Rip + pExit->VpContext.Cs.Base, ASMReadTSC());
3538 Log4(("XcptExit/%u: %04x:%08RX64/%s: #BP - TODO - %u\n", pVCpu->idCpu, pExit->VpContext.Cs.Selector,
3539 pExit->VpContext.Rip, nemR3WinExecStateToLogStr(&pExit->VpContext), pExit->VpContext.InstructionLength));
3540 enmEvtType = TRPM_SOFTWARE_INT; /* We're at the INT3 instruction, not after it. */
3541 break;
3542
3543 /* This shouldn't happen. */
3544 default:
3545 AssertLogRelMsgFailedReturn(("ExceptionType=%#x\n", pExit->VpException.ExceptionType), VERR_IEM_IPE_6);
3546 }
3547
3548 /*
3549 * Inject it.
3550 */
3551 rcStrict = IEMInjectTrap(pVCpu, pExit->VpException.ExceptionType, enmEvtType, pExit->VpException.ErrorCode,
3552 pExit->VpException.ExceptionParameter /*??*/, pExit->VpContext.InstructionLength);
3553 Log4(("XcptExit/%u: %04x:%08RX64/%s: %#u -> injected -> %Rrc\n",
3554 pVCpu->idCpu, pExit->VpContext.Cs.Selector, pExit->VpContext.Rip,
3555 nemR3WinExecStateToLogStr(&pExit->VpContext), pExit->VpException.ExceptionType, VBOXSTRICTRC_VAL(rcStrict) ));
3556
3557 RT_NOREF_PV(pVM);
3558 return rcStrict;
3559}
3560#endif /* IN_RING3 && !NEM_WIN_TEMPLATE_MODE_OWN_RUN_API */
3561
3562
3563#ifdef NEM_WIN_TEMPLATE_MODE_OWN_RUN_API
3564/**
3565 * Deals with unrecoverable exception (triple fault).
3566 *
3567 * Seen WRMSR 0x201 (IA32_MTRR_PHYSMASK0) writes from grub / debian9 ending up
3568 * here too. So we'll leave it to IEM to decide.
3569 *
3570 * @returns Strict VBox status code.
3571 * @param pVCpu The cross context per CPU structure.
3572 * @param pMsgHdr The message header.
3573 * @sa nemR3WinHandleExitUnrecoverableException
3574 */
3575NEM_TMPL_STATIC VBOXSTRICTRC
3576nemHCWinHandleMessageUnrecoverableException(PVMCPUCC pVCpu, HV_X64_INTERCEPT_MESSAGE_HEADER const *pMsgHdr)
3577{
3578 /* Check message register value sanity. */
3579 NEMWIN_ASSERT_MSG_REG_SEG( pVCpu, HvX64RegisterCs, pMsgHdr->CsSegment);
3580 NEMWIN_ASSERT_MSG_REG_VAL64(pVCpu, HvX64RegisterRip, pMsgHdr->Rip);
3581 NEMWIN_ASSERT_MSG_REG_VAL64(pVCpu, HvX64RegisterRflags, pMsgHdr->Rflags);
3582 NEMWIN_ASSERT_MSG_REG_VAL64(pVCpu, HvX64RegisterCr8, (uint64_t)pMsgHdr->Cr8);
3583
3584# if 0
3585 /*
3586 * Just copy the state we've got and handle it in the loop for now.
3587 */
3588 nemHCWinCopyStateFromX64Header(pVCpu, pMsgHdr);
3589 Log(("TripleExit/%u: %04x:%08RX64/%s: RFL=%#RX64 -> VINF_EM_TRIPLE_FAULT\n",
3590 pVCpu->idCpu, pMsgHdr->CsSegment.Selector, pMsgHdr->Rip, nemHCWinExecStateToLogStr(&pMsg->Header), pMsgHdr->Rflags));
3591 return VINF_EM_TRIPLE_FAULT;
3592# else
3593 /*
3594 * Let IEM decide whether this is really it.
3595 */
3596 EMHistoryAddExit(pVCpu, EMEXIT_MAKE_FT(EMEXIT_F_KIND_NEM, NEMEXITTYPE_UNRECOVERABLE_EXCEPTION),
3597 pMsgHdr->Rip + pMsgHdr->CsSegment.Base, ASMReadTSC());
3598 nemHCWinCopyStateFromX64Header(pVCpu, pMsgHdr);
3599 VBOXSTRICTRC rcStrict = nemHCWinImportStateIfNeededStrict(pVCpu, NEM_WIN_CPUMCTX_EXTRN_MASK_FOR_IEM | CPUMCTX_EXTRN_ALL, "TripleExit");
3600 if (rcStrict == VINF_SUCCESS)
3601 {
3602 rcStrict = IEMExecOne(pVCpu);
3603 if (rcStrict == VINF_SUCCESS)
3604 {
3605 Log(("UnrecovExit/%u: %04x:%08RX64/%s: RFL=%#RX64 -> VINF_SUCCESS\n", pVCpu->idCpu, pMsgHdr->CsSegment.Selector,
3606 pMsgHdr->Rip, nemHCWinExecStateToLogStr(pMsgHdr), pMsgHdr->Rflags ));
3607 pVCpu->cpum.GstCtx.fExtrn &= ~CPUMCTX_EXTRN_NEM_WIN_EVENT_INJECT; /* Make sure to reset pending #DB(0). */
3608 return VINF_SUCCESS;
3609 }
3610 if (rcStrict == VINF_EM_TRIPLE_FAULT)
3611 Log(("UnrecovExit/%u: %04x:%08RX64/%s: RFL=%#RX64 -> VINF_EM_TRIPLE_FAULT!\n", pVCpu->idCpu, pMsgHdr->CsSegment.Selector,
3612 pMsgHdr->Rip, nemHCWinExecStateToLogStr(pMsgHdr), pMsgHdr->Rflags, VBOXSTRICTRC_VAL(rcStrict) ));
3613 else
3614 Log(("UnrecovExit/%u: %04x:%08RX64/%s: RFL=%#RX64 -> %Rrc (IEMExecOne)\n", pVCpu->idCpu, pMsgHdr->CsSegment.Selector,
3615 pMsgHdr->Rip, nemHCWinExecStateToLogStr(pMsgHdr), pMsgHdr->Rflags, VBOXSTRICTRC_VAL(rcStrict) ));
3616 }
3617 else
3618 Log(("UnrecovExit/%u: %04x:%08RX64/%s: RFL=%#RX64 -> %Rrc (state import)\n", pVCpu->idCpu, pMsgHdr->CsSegment.Selector,
3619 pMsgHdr->Rip, nemHCWinExecStateToLogStr(pMsgHdr), pMsgHdr->Rflags, VBOXSTRICTRC_VAL(rcStrict) ));
3620 return rcStrict;
3621# endif
3622}
3623#elif defined(IN_RING3)
3624/**
3625 * Deals with MSR access exits (WHvRunVpExitReasonUnrecoverableException).
3626 *
3627 * @returns Strict VBox status code.
3628 * @param pVM The cross context VM structure.
3629 * @param pVCpu The cross context per CPU structure.
3630 * @param pExit The VM exit information to handle.
3631 * @sa nemHCWinHandleMessageUnrecoverableException
3632 */
3633NEM_TMPL_STATIC VBOXSTRICTRC nemR3WinHandleExitUnrecoverableException(PVMCC pVM, PVMCPUCC pVCpu, WHV_RUN_VP_EXIT_CONTEXT const *pExit)
3634{
3635# if 0
3636 /*
3637 * Just copy the state we've got and handle it in the loop for now.
3638 */
3639 nemR3WinCopyStateFromX64Header(pVCpu, &pExit->VpContext);
3640 Log(("TripleExit/%u: %04x:%08RX64/%s: RFL=%#RX64 -> VINF_EM_TRIPLE_FAULT\n", pVCpu->idCpu, pExit->VpContext.Cs.Selector,
3641 pExit->VpContext.Rip, nemR3WinExecStateToLogStr(&pExit->VpContext), pExit->VpContext.Rflags));
3642 RT_NOREF_PV(pVM);
3643 return VINF_EM_TRIPLE_FAULT;
3644# else
3645 /*
3646 * Let IEM decide whether this is really it.
3647 */
3648 EMHistoryAddExit(pVCpu, EMEXIT_MAKE_FT(EMEXIT_F_KIND_NEM, NEMEXITTYPE_UNRECOVERABLE_EXCEPTION),
3649 pExit->VpContext.Rip + pExit->VpContext.Cs.Base, ASMReadTSC());
3650 nemR3WinCopyStateFromX64Header(pVCpu, &pExit->VpContext);
3651 VBOXSTRICTRC rcStrict = nemHCWinImportStateIfNeededStrict(pVCpu, NEM_WIN_CPUMCTX_EXTRN_MASK_FOR_IEM | CPUMCTX_EXTRN_ALL, "TripleExit");
3652 if (rcStrict == VINF_SUCCESS)
3653 {
3654 rcStrict = IEMExecOne(pVCpu);
3655 if (rcStrict == VINF_SUCCESS)
3656 {
3657 Log(("UnrecovExit/%u: %04x:%08RX64/%s: RFL=%#RX64 -> VINF_SUCCESS\n", pVCpu->idCpu, pExit->VpContext.Cs.Selector,
3658 pExit->VpContext.Rip, nemR3WinExecStateToLogStr(&pExit->VpContext), pExit->VpContext.Rflags));
3659 pVCpu->cpum.GstCtx.fExtrn &= ~CPUMCTX_EXTRN_NEM_WIN_EVENT_INJECT; /* Make sure to reset pending #DB(0). */
3660 return VINF_SUCCESS;
3661 }
3662 if (rcStrict == VINF_EM_TRIPLE_FAULT)
3663 Log(("UnrecovExit/%u: %04x:%08RX64/%s: RFL=%#RX64 -> VINF_EM_TRIPLE_FAULT!\n", pVCpu->idCpu, pExit->VpContext.Cs.Selector,
3664 pExit->VpContext.Rip, nemR3WinExecStateToLogStr(&pExit->VpContext), pExit->VpContext.Rflags, VBOXSTRICTRC_VAL(rcStrict) ));
3665 else
3666 Log(("UnrecovExit/%u: %04x:%08RX64/%s: RFL=%#RX64 -> %Rrc (IEMExecOne)\n", pVCpu->idCpu, pExit->VpContext.Cs.Selector,
3667 pExit->VpContext.Rip, nemR3WinExecStateToLogStr(&pExit->VpContext), pExit->VpContext.Rflags, VBOXSTRICTRC_VAL(rcStrict) ));
3668 }
3669 else
3670 Log(("UnrecovExit/%u: %04x:%08RX64/%s: RFL=%#RX64 -> %Rrc (state import)\n", pVCpu->idCpu, pExit->VpContext.Cs.Selector,
3671 pExit->VpContext.Rip, nemR3WinExecStateToLogStr(&pExit->VpContext), pExit->VpContext.Rflags, VBOXSTRICTRC_VAL(rcStrict) ));
3672 RT_NOREF_PV(pVM);
3673 return rcStrict;
3674# endif
3675
3676}
3677#endif /* IN_RING3 && !NEM_WIN_TEMPLATE_MODE_OWN_RUN_API */
3678
3679
3680#ifdef NEM_WIN_TEMPLATE_MODE_OWN_RUN_API
3681/**
3682 * Handles messages (VM exits).
3683 *
3684 * @returns Strict VBox status code.
3685 * @param pVM The cross context VM structure.
3686 * @param pVCpu The cross context per CPU structure.
3687 * @param pMappingHeader The message slot mapping.
3688 * @sa nemR3WinHandleExit
3689 */
3690NEM_TMPL_STATIC VBOXSTRICTRC
3691nemHCWinHandleMessage(PVMCC pVM, PVMCPUCC pVCpu, VID_MESSAGE_MAPPING_HEADER volatile *pMappingHeader)
3692{
3693 if (pMappingHeader->enmVidMsgType == VidMessageHypervisorMessage)
3694 {
3695 AssertMsg(pMappingHeader->cbMessage == HV_MESSAGE_SIZE, ("%#x\n", pMappingHeader->cbMessage));
3696 HV_MESSAGE const *pMsg = (HV_MESSAGE const *)(pMappingHeader + 1);
3697 switch (pMsg->Header.MessageType)
3698 {
3699 case HvMessageTypeUnmappedGpa:
3700 Assert(pMsg->Header.PayloadSize == RT_UOFFSETOF(HV_X64_MEMORY_INTERCEPT_MESSAGE, DsSegment));
3701 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatExitMemUnmapped);
3702 return nemHCWinHandleMessageMemory(pVM, pVCpu, &pMsg->X64MemoryIntercept);
3703
3704 case HvMessageTypeGpaIntercept:
3705 Assert(pMsg->Header.PayloadSize == RT_UOFFSETOF(HV_X64_MEMORY_INTERCEPT_MESSAGE, DsSegment));
3706 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatExitMemIntercept);
3707 return nemHCWinHandleMessageMemory(pVM, pVCpu, &pMsg->X64MemoryIntercept);
3708
3709 case HvMessageTypeX64IoPortIntercept:
3710 Assert(pMsg->Header.PayloadSize == sizeof(pMsg->X64IoPortIntercept));
3711 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatExitPortIo);
3712 return nemHCWinHandleMessageIoPort(pVM, pVCpu, &pMsg->X64IoPortIntercept);
3713
3714 case HvMessageTypeX64Halt:
3715 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatExitHalt);
3716 EMHistoryAddExit(pVCpu, EMEXIT_MAKE_FT(EMEXIT_F_KIND_NEM, NEMEXITTYPE_HALT),
3717 pMsg->X64InterceptHeader.Rip + pMsg->X64InterceptHeader.CsSegment.Base, ASMReadTSC());
3718 Log4(("HaltExit\n"));
3719 return VINF_EM_HALT;
3720
3721 case HvMessageTypeX64InterruptWindow:
3722 Assert(pMsg->Header.PayloadSize == sizeof(pMsg->X64InterruptWindow));
3723 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatExitInterruptWindow);
3724 return nemHCWinHandleMessageInterruptWindow(pVM, pVCpu, &pMsg->X64InterruptWindow);
3725
3726 case HvMessageTypeX64CpuidIntercept:
3727 Assert(pMsg->Header.PayloadSize == sizeof(pMsg->X64CpuIdIntercept));
3728 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatExitCpuId);
3729 return nemHCWinHandleMessageCpuId(pVM, pVCpu, &pMsg->X64CpuIdIntercept);
3730
3731 case HvMessageTypeX64MsrIntercept:
3732 Assert(pMsg->Header.PayloadSize == sizeof(pMsg->X64MsrIntercept));
3733 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatExitMsr);
3734 return nemHCWinHandleMessageMsr(pVCpu, &pMsg->X64MsrIntercept);
3735
3736 case HvMessageTypeX64ExceptionIntercept:
3737 Assert(pMsg->Header.PayloadSize == sizeof(pMsg->X64ExceptionIntercept));
3738 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatExitException);
3739 return nemHCWinHandleMessageException(pVCpu, &pMsg->X64ExceptionIntercept);
3740
3741 case HvMessageTypeUnrecoverableException:
3742 Assert(pMsg->Header.PayloadSize == sizeof(pMsg->X64InterceptHeader));
3743 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatExitUnrecoverable);
3744 return nemHCWinHandleMessageUnrecoverableException(pVCpu, &pMsg->X64InterceptHeader);
3745
3746 case HvMessageTypeInvalidVpRegisterValue:
3747 case HvMessageTypeUnsupportedFeature:
3748 case HvMessageTypeTlbPageSizeMismatch:
3749 LogRel(("Unimplemented msg:\n%.*Rhxd\n", (int)sizeof(*pMsg), pMsg));
3750 AssertLogRelMsgFailedReturn(("Message type %#x not implemented!\n%.32Rhxd\n", pMsg->Header.MessageType, pMsg),
3751 VERR_NEM_IPE_3);
3752
3753 case HvMessageTypeX64ApicEoi:
3754 case HvMessageTypeX64LegacyFpError:
3755 case HvMessageTypeX64RegisterIntercept:
3756 case HvMessageTypeApicEoi:
3757 case HvMessageTypeFerrAsserted:
3758 case HvMessageTypeEventLogBufferComplete:
3759 case HvMessageTimerExpired:
3760 LogRel(("Unexpected msg:\n%.*Rhxd\n", (int)sizeof(*pMsg), pMsg));
3761 AssertLogRelMsgFailedReturn(("Unexpected message on CPU #%u: %#x\n", pVCpu->idCpu, pMsg->Header.MessageType),
3762 VERR_NEM_IPE_3);
3763
3764 default:
3765 LogRel(("Unknown msg:\n%.*Rhxd\n", (int)sizeof(*pMsg), pMsg));
3766 AssertLogRelMsgFailedReturn(("Unknown message on CPU #%u: %#x\n", pVCpu->idCpu, pMsg->Header.MessageType),
3767 VERR_NEM_IPE_3);
3768 }
3769 }
3770 else
3771 AssertLogRelMsgFailedReturn(("Unexpected VID message type on CPU #%u: %#x LB %u\n",
3772 pVCpu->idCpu, pMappingHeader->enmVidMsgType, pMappingHeader->cbMessage),
3773 VERR_NEM_IPE_4);
3774}
3775#elif defined(IN_RING3)
3776/**
3777 * Handles VM exits.
3778 *
3779 * @returns Strict VBox status code.
3780 * @param pVM The cross context VM structure.
3781 * @param pVCpu The cross context per CPU structure.
3782 * @param pExit The VM exit information to handle.
3783 * @sa nemHCWinHandleMessage
3784 */
3785NEM_TMPL_STATIC VBOXSTRICTRC nemR3WinHandleExit(PVMCC pVM, PVMCPUCC pVCpu, WHV_RUN_VP_EXIT_CONTEXT const *pExit)
3786{
3787 switch (pExit->ExitReason)
3788 {
3789 case WHvRunVpExitReasonMemoryAccess:
3790 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatExitMemUnmapped);
3791 return nemR3WinHandleExitMemory(pVM, pVCpu, pExit);
3792
3793 case WHvRunVpExitReasonX64IoPortAccess:
3794 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatExitPortIo);
3795 return nemR3WinHandleExitIoPort(pVM, pVCpu, pExit);
3796
3797 case WHvRunVpExitReasonX64Halt:
3798 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatExitHalt);
3799 EMHistoryAddExit(pVCpu, EMEXIT_MAKE_FT(EMEXIT_F_KIND_NEM, NEMEXITTYPE_HALT),
3800 pExit->VpContext.Rip + pExit->VpContext.Cs.Base, ASMReadTSC());
3801 Log4(("HaltExit/%u\n", pVCpu->idCpu));
3802 return VINF_EM_HALT;
3803
3804 case WHvRunVpExitReasonCanceled:
3805 Log4(("CanceledExit/%u\n", pVCpu->idCpu));
3806 return VINF_SUCCESS;
3807
3808 case WHvRunVpExitReasonX64InterruptWindow:
3809 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatExitInterruptWindow);
3810 return nemR3WinHandleExitInterruptWindow(pVM, pVCpu, pExit);
3811
3812 case WHvRunVpExitReasonX64Cpuid:
3813 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatExitCpuId);
3814 return nemR3WinHandleExitCpuId(pVM, pVCpu, pExit);
3815
3816 case WHvRunVpExitReasonX64MsrAccess:
3817 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatExitMsr);
3818 return nemR3WinHandleExitMsr(pVM, pVCpu, pExit);
3819
3820 case WHvRunVpExitReasonException:
3821 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatExitException);
3822 return nemR3WinHandleExitException(pVM, pVCpu, pExit);
3823
3824 case WHvRunVpExitReasonUnrecoverableException:
3825 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatExitUnrecoverable);
3826 return nemR3WinHandleExitUnrecoverableException(pVM, pVCpu, pExit);
3827
3828 case WHvRunVpExitReasonUnsupportedFeature:
3829 case WHvRunVpExitReasonInvalidVpRegisterValue:
3830 LogRel(("Unimplemented exit:\n%.*Rhxd\n", (int)sizeof(*pExit), pExit));
3831 AssertLogRelMsgFailedReturn(("Unexpected exit on CPU #%u: %#x\n%.32Rhxd\n",
3832 pVCpu->idCpu, pExit->ExitReason, pExit), VERR_NEM_IPE_3);
3833
3834 /* Undesired exits: */
3835 case WHvRunVpExitReasonNone:
3836 default:
3837 LogRel(("Unknown exit:\n%.*Rhxd\n", (int)sizeof(*pExit), pExit));
3838 AssertLogRelMsgFailedReturn(("Unknown exit on CPU #%u: %#x!\n", pVCpu->idCpu, pExit->ExitReason), VERR_NEM_IPE_3);
3839 }
3840}
3841#endif /* IN_RING3 && !NEM_WIN_TEMPLATE_MODE_OWN_RUN_API */
3842
3843
3844#if defined(IN_RING0) && defined(NEM_WIN_WITH_RING0_RUNLOOP)
3845/**
3846 * Perform an I/O control operation on the partition handle (VID.SYS),
3847 * restarting on alert-like behaviour.
3848 *
3849 * @returns NT status code.
3850 * @param pGVM The ring-0 VM structure.
3851 * @param pGVCpu The global (ring-0) per CPU structure.
3852 * @param fFlags The wait flags.
3853 * @param cMillies The timeout in milliseconds
3854 */
3855static NTSTATUS nemR0NtPerformIoCtlMessageSlotHandleAndGetNext(PGVM pGVM, PGVMCPU pGVCpu, uint32_t fFlags, uint32_t cMillies)
3856{
3857 pGVCpu->nem.s.uIoCtlBuf.MsgSlotHandleAndGetNext.iCpu = pGVCpu->idCpu;
3858 pGVCpu->nem.s.uIoCtlBuf.MsgSlotHandleAndGetNext.fFlags = fFlags;
3859 pGVCpu->nem.s.uIoCtlBuf.MsgSlotHandleAndGetNext.cMillies = cMillies;
3860 NTSTATUS rcNt = nemR0NtPerformIoControl(pGVM, pGVCpu, pGVM->nemr0.s.IoCtlMessageSlotHandleAndGetNext.uFunction,
3861 &pGVCpu->nem.s.uIoCtlBuf.MsgSlotHandleAndGetNext,
3862 pGVM->nemr0.s.IoCtlMessageSlotHandleAndGetNext.cbInput,
3863 NULL, 0);
3864 if (rcNt == STATUS_SUCCESS)
3865 { /* likely */ }
3866 /*
3867 * Generally, if we get down here, we have been interrupted between ACK'ing
3868 * a message and waiting for the next due to a NtAlertThread call. So, we
3869 * should stop ACK'ing the previous message and get on waiting on the next.
3870 * See similar stuff in nemHCWinRunGC().
3871 */
3872 else if ( rcNt == STATUS_TIMEOUT
3873 || rcNt == STATUS_ALERTED /* just in case */
3874 || rcNt == STATUS_KERNEL_APC /* just in case */
3875 || rcNt == STATUS_USER_APC /* just in case */)
3876 {
3877 DBGFTRACE_CUSTOM(pGVCpu->CTX_SUFF(pVM), "IoCtlMessageSlotHandleAndGetNextRestart/1 %#x (f=%#x)", rcNt, fFlags);
3878 STAM_REL_COUNTER_INC(&pGVCpu->nem.s.StatStopCpuPendingAlerts);
3879 Assert(fFlags & VID_MSHAGN_F_GET_NEXT_MESSAGE);
3880
3881 pGVCpu->nem.s.uIoCtlBuf.MsgSlotHandleAndGetNext.iCpu = pGVCpu->idCpu;
3882 pGVCpu->nem.s.uIoCtlBuf.MsgSlotHandleAndGetNext.fFlags = fFlags & ~VID_MSHAGN_F_HANDLE_MESSAGE;
3883 pGVCpu->nem.s.uIoCtlBuf.MsgSlotHandleAndGetNext.cMillies = cMillies;
3884 rcNt = nemR0NtPerformIoControl(pGVM, pGVCpu, pGVM->nemr0.s.IoCtlMessageSlotHandleAndGetNext.uFunction,
3885 &pGVCpu->nem.s.uIoCtlBuf.MsgSlotHandleAndGetNext,
3886 pGVM->nemr0.s.IoCtlMessageSlotHandleAndGetNext.cbInput,
3887 NULL, 0);
3888 DBGFTRACE_CUSTOM(pGVM, "IoCtlMessageSlotHandleAndGetNextRestart/2 %#x", rcNt);
3889 }
3890 return rcNt;
3891}
3892#endif /* IN_RING0 */
3893
3894
3895#ifdef NEM_WIN_TEMPLATE_MODE_OWN_RUN_API
3896/**
3897 * Worker for nemHCWinRunGC that stops the execution on the way out.
3898 *
3899 * The CPU was running the last time we checked, no there are no messages that
3900 * needs being marked handled/whatever. Caller checks this.
3901 *
3902 * @returns rcStrict on success, error status on failure.
3903 * @param pVM The cross context VM structure.
3904 * @param pVCpu The cross context per CPU structure.
3905 * @param rcStrict The nemHCWinRunGC return status. This is a little
3906 * bit unnecessary, except in internal error cases,
3907 * since we won't need to stop the CPU if we took an
3908 * exit.
3909 * @param pMappingHeader The message slot mapping.
3910 */
3911NEM_TMPL_STATIC VBOXSTRICTRC nemHCWinStopCpu(PVMCC pVM, PVMCPUCC pVCpu, VBOXSTRICTRC rcStrict,
3912 VID_MESSAGE_MAPPING_HEADER volatile *pMappingHeader)
3913{
3914# ifdef DBGFTRACE_ENABLED
3915 HV_MESSAGE const volatile *pMsgForTrace = (HV_MESSAGE const volatile *)(pMappingHeader + 1);
3916# endif
3917
3918 /*
3919 * Try stopping the processor. If we're lucky we manage to do this before it
3920 * does another VM exit.
3921 */
3922 DBGFTRACE_CUSTOM(pVM, "nemStop#0");
3923# ifdef IN_RING0
3924 pVCpu->nem.s.uIoCtlBuf.idCpu = pVCpu->idCpu;
3925 NTSTATUS rcNt = nemR0NtPerformIoControl(pVM, pVCpu, pVM->nemr0.s.IoCtlStopVirtualProcessor.uFunction,
3926 &pVCpu->nem.s.uIoCtlBuf.idCpu, sizeof(pVCpu->nem.s.uIoCtlBuf.idCpu),
3927 NULL, 0);
3928 if (NT_SUCCESS(rcNt))
3929 {
3930 DBGFTRACE_CUSTOM(pVM, "nemStop#0: okay (%#x)", rcNt);
3931 Log8(("nemHCWinStopCpu: Stopping CPU succeeded (cpu status %u)\n", nemHCWinCpuGetRunningStatus(pVCpu) ));
3932 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatStopCpuSuccess);
3933 return rcStrict;
3934 }
3935# else
3936 BOOL fRet = VidStopVirtualProcessor(pVM->nem.s.hPartitionDevice, pVCpu->idCpu);
3937 if (fRet)
3938 {
3939 DBGFTRACE_CUSTOM(pVM, "nemStop#0: okay");
3940 Log8(("nemHCWinStopCpu: Stopping CPU succeeded (cpu status %u)\n", nemHCWinCpuGetRunningStatus(pVCpu) ));
3941 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatStopCpuSuccess);
3942 return rcStrict;
3943 }
3944# endif
3945
3946 /*
3947 * Dang. The CPU stopped by itself and we got a couple of message to deal with.
3948 */
3949# ifdef IN_RING0
3950 DBGFTRACE_CUSTOM(pVM, "nemStop#0: pending (%#x)", rcNt);
3951 AssertLogRelMsgReturn(rcNt == ERROR_VID_STOP_PENDING, ("rcNt=%#x\n", rcNt),
3952 RT_SUCCESS(rcStrict) ? VERR_NEM_IPE_5 : rcStrict);
3953# else
3954 DWORD dwErr = RTNtLastErrorValue();
3955 DBGFTRACE_CUSTOM(pVM, "nemStop#0: pending (%#x)", dwErr);
3956 AssertLogRelMsgReturn(dwErr == ERROR_VID_STOP_PENDING, ("dwErr=%#u (%#x)\n", dwErr, dwErr),
3957 RT_SUCCESS(rcStrict) ? VERR_NEM_IPE_5 : rcStrict);
3958# endif
3959 Log8(("nemHCWinStopCpu: Stopping CPU #%u pending...\n", pVCpu->idCpu));
3960 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatStopCpuPending);
3961
3962 /*
3963 * First message: Exit or similar, sometimes VidMessageStopRequestComplete.
3964 * Note! We can safely ASSUME that rcStrict isn't an important information one.
3965 */
3966# ifdef IN_RING0
3967 rcNt = nemR0NtPerformIoCtlMessageSlotHandleAndGetNext(pVM, pVCpu, VID_MSHAGN_F_GET_NEXT_MESSAGE, 30000 /*ms*/);
3968 DBGFTRACE_CUSTOM(pVM, "nemStop#1: %#x / %#x %#x %#x", rcNt, pMappingHeader->enmVidMsgType, pMappingHeader->cbMessage,
3969 pMsgForTrace->Header.MessageType);
3970 AssertLogRelMsgReturn(rcNt == STATUS_SUCCESS,
3971 ("1st VidMessageSlotHandleAndGetNext after ERROR_VID_STOP_PENDING failed: %#x\n", rcNt),
3972 RT_SUCCESS(rcStrict) ? VERR_NEM_IPE_5 : rcStrict);
3973# else
3974 BOOL fWait = g_pfnVidMessageSlotHandleAndGetNext(pVM->nem.s.hPartitionDevice, pVCpu->idCpu,
3975 VID_MSHAGN_F_GET_NEXT_MESSAGE, 30000 /*ms*/);
3976 DBGFTRACE_CUSTOM(pVM, "nemStop#1: %d+%#x / %#x %#x %#x", fWait, RTNtLastErrorValue(), pMappingHeader->enmVidMsgType,
3977 pMappingHeader->cbMessage, pMsgForTrace->Header.MessageType);
3978 AssertLogRelMsgReturn(fWait, ("1st VidMessageSlotHandleAndGetNext after ERROR_VID_STOP_PENDING failed: %u\n", RTNtLastErrorValue()),
3979 RT_SUCCESS(rcStrict) ? VERR_NEM_IPE_5 : rcStrict);
3980# endif
3981
3982 VID_MESSAGE_TYPE enmVidMsgType = pMappingHeader->enmVidMsgType;
3983 if (enmVidMsgType != VidMessageStopRequestComplete)
3984 {
3985 VBOXSTRICTRC rcStrict2 = nemHCWinHandleMessage(pVM, pVCpu, pMappingHeader);
3986 if (rcStrict2 != VINF_SUCCESS && RT_SUCCESS(rcStrict))
3987 rcStrict = rcStrict2;
3988 DBGFTRACE_CUSTOM(pVM, "nemStop#1: handled %#x -> %d", pMsgForTrace->Header.MessageType, VBOXSTRICTRC_VAL(rcStrict));
3989
3990 /*
3991 * Mark it as handled and get the stop request completed message, then mark
3992 * that as handled too. CPU is back into fully stopped stated then.
3993 */
3994# ifdef IN_RING0
3995 rcNt = nemR0NtPerformIoCtlMessageSlotHandleAndGetNext(pVM, pVCpu,
3996 VID_MSHAGN_F_HANDLE_MESSAGE | VID_MSHAGN_F_GET_NEXT_MESSAGE,
3997 30000 /*ms*/);
3998 DBGFTRACE_CUSTOM(pVM, "nemStop#2: %#x / %#x %#x %#x", rcNt, pMappingHeader->enmVidMsgType, pMappingHeader->cbMessage,
3999 pMsgForTrace->Header.MessageType);
4000 AssertLogRelMsgReturn(rcNt == STATUS_SUCCESS,
4001 ("2nd VidMessageSlotHandleAndGetNext after ERROR_VID_STOP_PENDING failed: %#x\n", rcNt),
4002 RT_SUCCESS(rcStrict) ? VERR_NEM_IPE_5 : rcStrict);
4003# else
4004 fWait = g_pfnVidMessageSlotHandleAndGetNext(pVM->nem.s.hPartitionDevice, pVCpu->idCpu,
4005 VID_MSHAGN_F_HANDLE_MESSAGE | VID_MSHAGN_F_GET_NEXT_MESSAGE, 30000 /*ms*/);
4006 DBGFTRACE_CUSTOM(pVM, "nemStop#2: %d+%#x / %#x %#x %#x", fWait, RTNtLastErrorValue(), pMappingHeader->enmVidMsgType,
4007 pMappingHeader->cbMessage, pMsgForTrace->Header.MessageType);
4008 AssertLogRelMsgReturn(fWait, ("2nd VidMessageSlotHandleAndGetNext after ERROR_VID_STOP_PENDING failed: %u\n", RTNtLastErrorValue()),
4009 RT_SUCCESS(rcStrict) ? VERR_NEM_IPE_5 : rcStrict);
4010# endif
4011
4012 /* It should be a stop request completed message. */
4013 enmVidMsgType = pMappingHeader->enmVidMsgType;
4014 AssertLogRelMsgReturn(enmVidMsgType == VidMessageStopRequestComplete,
4015 ("Unexpected 2nd message following ERROR_VID_STOP_PENDING: %#x LB %#x\n",
4016 enmVidMsgType, pMappingHeader->cbMessage),
4017 RT_SUCCESS(rcStrict) ? VERR_NEM_IPE_5 : rcStrict);
4018
4019 /*
4020 * Mark the VidMessageStopRequestComplete message as handled.
4021 */
4022# ifdef IN_RING0
4023 rcNt = nemR0NtPerformIoCtlMessageSlotHandleAndGetNext(pVM, pVCpu, VID_MSHAGN_F_HANDLE_MESSAGE, 30000 /*ms*/);
4024 DBGFTRACE_CUSTOM(pVM, "nemStop#3: %#x / %#x %#x %#x", rcNt, pMappingHeader->enmVidMsgType,
4025 pMsgForTrace->Header.MessageType, pMappingHeader->cbMessage, pMsgForTrace->Header.MessageType);
4026 AssertLogRelMsgReturn(rcNt == STATUS_SUCCESS,
4027 ("3rd VidMessageSlotHandleAndGetNext after ERROR_VID_STOP_PENDING failed: %#x\n", rcNt),
4028 RT_SUCCESS(rcStrict) ? VERR_NEM_IPE_5 : rcStrict);
4029# else
4030 fWait = g_pfnVidMessageSlotHandleAndGetNext(pVM->nem.s.hPartitionDevice, pVCpu->idCpu, VID_MSHAGN_F_HANDLE_MESSAGE, 30000 /*ms*/);
4031 DBGFTRACE_CUSTOM(pVM, "nemStop#3: %d+%#x / %#x %#x %#x", fWait, RTNtLastErrorValue(), pMappingHeader->enmVidMsgType,
4032 pMsgForTrace->Header.MessageType, pMappingHeader->cbMessage, pMsgForTrace->Header.MessageType);
4033 AssertLogRelMsgReturn(fWait, ("3rd VidMessageSlotHandleAndGetNext after ERROR_VID_STOP_PENDING failed: %u\n", RTNtLastErrorValue()),
4034 RT_SUCCESS(rcStrict) ? VERR_NEM_IPE_5 : rcStrict);
4035# endif
4036 Log8(("nemHCWinStopCpu: Stopped the CPU (rcStrict=%Rrc)\n", VBOXSTRICTRC_VAL(rcStrict) ));
4037 }
4038 else
4039 {
4040 /** @todo I'm not so sure about this now... */
4041 DBGFTRACE_CUSTOM(pVM, "nemStop#9: %#x %#x %#x", pMappingHeader->enmVidMsgType,
4042 pMappingHeader->cbMessage, pMsgForTrace->Header.MessageType);
4043 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatStopCpuPendingOdd);
4044 Log8(("nemHCWinStopCpu: Stopped the CPU (rcStrict=%Rrc) - 1st VidMessageSlotHandleAndGetNext got VidMessageStopRequestComplete.\n",
4045 VBOXSTRICTRC_VAL(rcStrict) ));
4046 }
4047 return rcStrict;
4048}
4049#endif /* NEM_WIN_TEMPLATE_MODE_OWN_RUN_API */
4050
4051#if defined(NEM_WIN_TEMPLATE_MODE_OWN_RUN_API) || defined(IN_RING3)
4052
4053/**
4054 * Deals with pending interrupt related force flags, may inject interrupt.
4055 *
4056 * @returns VBox strict status code.
4057 * @param pVM The cross context VM structure.
4058 * @param pVCpu The cross context per CPU structure.
4059 * @param pfInterruptWindows Where to return interrupt window flags.
4060 */
4061NEM_TMPL_STATIC VBOXSTRICTRC nemHCWinHandleInterruptFF(PVMCC pVM, PVMCPUCC pVCpu, uint8_t *pfInterruptWindows)
4062{
4063 Assert(!TRPMHasTrap(pVCpu));
4064 RT_NOREF_PV(pVM);
4065
4066 /*
4067 * First update APIC. We ASSUME this won't need TPR/CR8.
4068 */
4069 if (VMCPU_FF_TEST_AND_CLEAR(pVCpu, VMCPU_FF_UPDATE_APIC))
4070 {
4071 APICUpdatePendingInterrupts(pVCpu);
4072 if (!VMCPU_FF_IS_ANY_SET(pVCpu, VMCPU_FF_INTERRUPT_APIC | VMCPU_FF_INTERRUPT_PIC
4073 | VMCPU_FF_INTERRUPT_NMI | VMCPU_FF_INTERRUPT_SMI))
4074 return VINF_SUCCESS;
4075 }
4076
4077 /*
4078 * We don't currently implement SMIs.
4079 */
4080 AssertReturn(!VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_INTERRUPT_SMI), VERR_NEM_IPE_0);
4081
4082 /*
4083 * Check if we've got the minimum of state required for deciding whether we
4084 * can inject interrupts and NMIs. If we don't have it, get all we might require
4085 * for injection via IEM.
4086 */
4087 bool const fPendingNmi = VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_INTERRUPT_NMI);
4088 uint64_t fNeedExtrn = CPUMCTX_EXTRN_NEM_WIN_INHIBIT_INT | CPUMCTX_EXTRN_RIP | CPUMCTX_EXTRN_RFLAGS
4089 | (fPendingNmi ? CPUMCTX_EXTRN_NEM_WIN_INHIBIT_NMI : 0);
4090 if (pVCpu->cpum.GstCtx.fExtrn & fNeedExtrn)
4091 {
4092 VBOXSTRICTRC rcStrict = nemHCWinImportStateIfNeededStrict(pVCpu, NEM_WIN_CPUMCTX_EXTRN_MASK_FOR_IEM_XCPT, "IntFF");
4093 if (rcStrict != VINF_SUCCESS)
4094 return rcStrict;
4095 }
4096 bool const fInhibitInterrupts = VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS)
4097 && EMGetInhibitInterruptsPC(pVCpu) == pVCpu->cpum.GstCtx.rip;
4098
4099 /*
4100 * NMI? Try deliver it first.
4101 */
4102 if (fPendingNmi)
4103 {
4104 if ( !fInhibitInterrupts
4105 && !VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_BLOCK_NMIS))
4106 {
4107 VBOXSTRICTRC rcStrict = nemHCWinImportStateIfNeededStrict(pVCpu, NEM_WIN_CPUMCTX_EXTRN_MASK_FOR_IEM_XCPT, "NMI");
4108 if (rcStrict == VINF_SUCCESS)
4109 {
4110 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INTERRUPT_NMI);
4111 rcStrict = IEMInjectTrap(pVCpu, X86_XCPT_NMI, TRPM_HARDWARE_INT, 0, 0, 0);
4112 Log8(("Injected NMI on %u (%d)\n", pVCpu->idCpu, VBOXSTRICTRC_VAL(rcStrict) ));
4113 }
4114 return rcStrict;
4115 }
4116 *pfInterruptWindows |= NEM_WIN_INTW_F_NMI;
4117 Log8(("NMI window pending on %u\n", pVCpu->idCpu));
4118 }
4119
4120 /*
4121 * APIC or PIC interrupt?
4122 */
4123 if (VMCPU_FF_IS_ANY_SET(pVCpu, VMCPU_FF_INTERRUPT_APIC | VMCPU_FF_INTERRUPT_PIC))
4124 {
4125 if ( !fInhibitInterrupts
4126 && pVCpu->cpum.GstCtx.rflags.Bits.u1IF)
4127 {
4128 AssertCompile(NEM_WIN_CPUMCTX_EXTRN_MASK_FOR_IEM_XCPT & CPUMCTX_EXTRN_APIC_TPR);
4129 VBOXSTRICTRC rcStrict = nemHCWinImportStateIfNeededStrict(pVCpu, NEM_WIN_CPUMCTX_EXTRN_MASK_FOR_IEM_XCPT, "NMI");
4130 if (rcStrict == VINF_SUCCESS)
4131 {
4132 uint8_t bInterrupt;
4133 int rc = PDMGetInterrupt(pVCpu, &bInterrupt);
4134 if (RT_SUCCESS(rc))
4135 {
4136 rcStrict = IEMInjectTrap(pVCpu, bInterrupt, TRPM_HARDWARE_INT, 0, 0, 0);
4137 Log8(("Injected interrupt %#x on %u (%d)\n", bInterrupt, pVCpu->idCpu, VBOXSTRICTRC_VAL(rcStrict) ));
4138 }
4139 else if (rc == VERR_APIC_INTR_MASKED_BY_TPR)
4140 {
4141 *pfInterruptWindows |= ((bInterrupt >> 4) << NEM_WIN_INTW_F_PRIO_SHIFT) | NEM_WIN_INTW_F_REGULAR;
4142 Log8(("VERR_APIC_INTR_MASKED_BY_TPR: *pfInterruptWindows=%#x\n", *pfInterruptWindows));
4143 }
4144 else
4145 Log8(("PDMGetInterrupt failed -> %d\n", rc));
4146 }
4147 return rcStrict;
4148 }
4149 else if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_INTERRUPT_APIC) && !VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_INTERRUPT_PIC))
4150 {
4151 /* If only an APIC interrupt is pending, we need to know its priority. Otherwise we'll
4152 * likely get pointless deliverability notifications with IF=1 but TPR still too high.
4153 */
4154 bool fPendingIntr;
4155 uint8_t u8Tpr, u8PendingIntr;
4156 int rc = APICGetTpr(pVCpu, &u8Tpr, &fPendingIntr, &u8PendingIntr);
4157 AssertRC(rc);
4158 *pfInterruptWindows |= (u8PendingIntr >> 4) << NEM_WIN_INTW_F_PRIO_SHIFT;
4159 }
4160 *pfInterruptWindows |= NEM_WIN_INTW_F_REGULAR;
4161 Log8(("Interrupt window pending on %u\n", pVCpu->idCpu));
4162 }
4163
4164 return VINF_SUCCESS;
4165}
4166
4167
4168/**
4169 * Inner NEM runloop for windows.
4170 *
4171 * @returns Strict VBox status code.
4172 * @param pVM The cross context VM structure.
4173 * @param pVCpu The cross context per CPU structure.
4174 */
4175NEM_TMPL_STATIC VBOXSTRICTRC nemHCWinRunGC(PVMCC pVM, PVMCPUCC pVCpu)
4176{
4177 LogFlow(("NEM/%u: %04x:%08RX64 efl=%#08RX64 <=\n", pVCpu->idCpu, pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip, pVCpu->cpum.GstCtx.rflags));
4178# ifdef LOG_ENABLED
4179 if (LogIs3Enabled())
4180 nemHCWinLogState(pVM, pVCpu);
4181# endif
4182
4183 /*
4184 * Try switch to NEM runloop state.
4185 */
4186 if (VMCPU_CMPXCHG_STATE(pVCpu, VMCPUSTATE_STARTED_EXEC_NEM, VMCPUSTATE_STARTED))
4187 { /* likely */ }
4188 else
4189 {
4190 VMCPU_CMPXCHG_STATE(pVCpu, VMCPUSTATE_STARTED_EXEC_NEM, VMCPUSTATE_STARTED_EXEC_NEM_CANCELED);
4191 LogFlow(("NEM/%u: returning immediately because canceled\n", pVCpu->idCpu));
4192 return VINF_SUCCESS;
4193 }
4194
4195 /*
4196 * The run loop.
4197 *
4198 * Current approach to state updating to use the sledgehammer and sync
4199 * everything every time. This will be optimized later.
4200 */
4201# ifdef NEM_WIN_TEMPLATE_MODE_OWN_RUN_API
4202 VID_MESSAGE_MAPPING_HEADER volatile *pMappingHeader = (VID_MESSAGE_MAPPING_HEADER volatile *)pVCpu->nem.s.pvMsgSlotMapping;
4203# endif
4204 const bool fSingleStepping = DBGFIsStepping(pVCpu);
4205// const uint32_t fCheckVmFFs = !fSingleStepping ? VM_FF_HP_R0_PRE_HM_MASK
4206// : VM_FF_HP_R0_PRE_HM_STEP_MASK;
4207// const uint32_t fCheckCpuFFs = !fSingleStepping ? VMCPU_FF_HP_R0_PRE_HM_MASK : VMCPU_FF_HP_R0_PRE_HM_STEP_MASK;
4208 VBOXSTRICTRC rcStrict = VINF_SUCCESS;
4209 for (unsigned iLoop = 0;; iLoop++)
4210 {
4211# ifndef NEM_WIN_USE_HYPERCALLS_FOR_PAGES
4212 /*
4213 * Hack alert!
4214 */
4215 uint32_t const cMappedPages = pVM->nem.s.cMappedPages;
4216 if (cMappedPages < pVM->nem.s.cMaxMappedPages)
4217 { /* likely*/ }
4218 else
4219 {
4220 PGMPhysNemEnumPagesByState(pVM, pVCpu, NEM_WIN_PAGE_STATE_READABLE, nemHCWinUnmapOnePageCallback, NULL);
4221 Log(("nemHCWinRunGC: Unmapped all; cMappedPages=%u -> %u\n", cMappedPages, pVM->nem.s.cMappedPages));
4222 STAM_REL_COUNTER_INC(&pVM->nem.s.StatUnmapAllPages);
4223 }
4224# endif
4225
4226 /*
4227 * Pending interrupts or such? Need to check and deal with this prior
4228 * to the state syncing.
4229 */
4230 pVCpu->nem.s.fDesiredInterruptWindows = 0;
4231 if (VMCPU_FF_IS_ANY_SET(pVCpu, VMCPU_FF_INTERRUPT_APIC | VMCPU_FF_UPDATE_APIC | VMCPU_FF_INTERRUPT_PIC
4232 | VMCPU_FF_INTERRUPT_NMI | VMCPU_FF_INTERRUPT_SMI))
4233 {
4234# ifdef NEM_WIN_TEMPLATE_MODE_OWN_RUN_API
4235 /* Make sure the CPU isn't executing. */
4236 if (pVCpu->nem.s.fHandleAndGetFlags == VID_MSHAGN_F_GET_NEXT_MESSAGE)
4237 {
4238 pVCpu->nem.s.fHandleAndGetFlags = 0;
4239 rcStrict = nemHCWinStopCpu(pVM, pVCpu, rcStrict, pMappingHeader);
4240 if (rcStrict == VINF_SUCCESS)
4241 { /* likely */ }
4242 else
4243 {
4244 LogFlow(("NEM/%u: breaking: nemHCWinStopCpu -> %Rrc\n", pVCpu->idCpu, VBOXSTRICTRC_VAL(rcStrict) ));
4245 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatBreakOnStatus);
4246 break;
4247 }
4248 }
4249# endif
4250
4251 /* Try inject interrupt. */
4252 rcStrict = nemHCWinHandleInterruptFF(pVM, pVCpu, &pVCpu->nem.s.fDesiredInterruptWindows);
4253 if (rcStrict == VINF_SUCCESS)
4254 { /* likely */ }
4255 else
4256 {
4257 LogFlow(("NEM/%u: breaking: nemHCWinHandleInterruptFF -> %Rrc\n", pVCpu->idCpu, VBOXSTRICTRC_VAL(rcStrict) ));
4258 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatBreakOnStatus);
4259 break;
4260 }
4261 }
4262
4263 /*
4264 * Ensure that hyper-V has the whole state.
4265 * (We always update the interrupt windows settings when active as hyper-V seems
4266 * to forget about it after an exit.)
4267 */
4268 if ( (pVCpu->cpum.GstCtx.fExtrn & (CPUMCTX_EXTRN_ALL | CPUMCTX_EXTRN_NEM_WIN_MASK))
4269 != (CPUMCTX_EXTRN_ALL | CPUMCTX_EXTRN_NEM_WIN_MASK)
4270 || ( ( pVCpu->nem.s.fDesiredInterruptWindows
4271 || pVCpu->nem.s.fCurrentInterruptWindows != pVCpu->nem.s.fDesiredInterruptWindows)
4272# ifdef NEM_WIN_TEMPLATE_MODE_OWN_RUN_API
4273 && pVCpu->nem.s.fHandleAndGetFlags != VID_MSHAGN_F_GET_NEXT_MESSAGE /* not running */
4274# endif
4275 )
4276 )
4277 {
4278# ifdef NEM_WIN_TEMPLATE_MODE_OWN_RUN_API
4279 AssertMsg(pVCpu->nem.s.fHandleAndGetFlags != VID_MSHAGN_F_GET_NEXT_MESSAGE /* not running */,
4280 ("%#x fExtrn=%#RX64 (%#RX64) fDesiredInterruptWindows=%d fCurrentInterruptWindows=%#x vs %#x\n",
4281 pVCpu->nem.s.fHandleAndGetFlags, pVCpu->cpum.GstCtx.fExtrn, ~pVCpu->cpum.GstCtx.fExtrn & (CPUMCTX_EXTRN_ALL | CPUMCTX_EXTRN_NEM_WIN_MASK),
4282 pVCpu->nem.s.fDesiredInterruptWindows, pVCpu->nem.s.fCurrentInterruptWindows, pVCpu->nem.s.fDesiredInterruptWindows));
4283# endif
4284# ifdef IN_RING0
4285 int rc2 = nemR0WinExportState(pVM, pVCpu, &pVCpu->cpum.GstCtx);
4286# else
4287 int rc2 = nemHCWinCopyStateToHyperV(pVM, pVCpu);
4288# endif
4289 AssertRCReturn(rc2, rc2);
4290 }
4291
4292 /*
4293 * Poll timers and run for a bit.
4294 *
4295 * With the VID approach (ring-0 or ring-3) we can specify a timeout here,
4296 * so we take the time of the next timer event and uses that as a deadline.
4297 * The rounding heuristics are "tuned" so that rhel5 (1K timer) will boot fine.
4298 */
4299 /** @todo See if we cannot optimize this TMTimerPollGIP by only redoing
4300 * the whole polling job when timers have changed... */
4301 uint64_t offDeltaIgnored;
4302 uint64_t const nsNextTimerEvt = TMTimerPollGIP(pVM, pVCpu, &offDeltaIgnored); NOREF(nsNextTimerEvt);
4303 if ( !VM_FF_IS_ANY_SET(pVM, VM_FF_EMT_RENDEZVOUS | VM_FF_TM_VIRTUAL_SYNC)
4304 && !VMCPU_FF_IS_ANY_SET(pVCpu, VMCPU_FF_HM_TO_R3_MASK))
4305 {
4306# ifdef NEM_WIN_TEMPLATE_MODE_OWN_RUN_API
4307 if (pVCpu->nem.s.fHandleAndGetFlags)
4308 { /* Very likely that the CPU does NOT need starting (pending msg, running). */ }
4309 else
4310 {
4311# ifdef IN_RING0
4312 pVCpu->nem.s.uIoCtlBuf.idCpu = pVCpu->idCpu;
4313 NTSTATUS rcNt = nemR0NtPerformIoControl(pVM, pVCpu, pVM->nemr0.s.IoCtlStartVirtualProcessor.uFunction,
4314 &pVCpu->nem.s.uIoCtlBuf.idCpu, sizeof(pVCpu->nem.s.uIoCtlBuf.idCpu),
4315 NULL, 0);
4316 LogFlow(("NEM/%u: IoCtlStartVirtualProcessor -> %#x\n", pVCpu->idCpu, rcNt));
4317 AssertLogRelMsgReturn(NT_SUCCESS(rcNt), ("VidStartVirtualProcessor failed for CPU #%u: %#x\n", pVCpu->idCpu, rcNt),
4318 VERR_NEM_IPE_5);
4319# else
4320 AssertLogRelMsgReturn(g_pfnVidStartVirtualProcessor(pVM->nem.s.hPartitionDevice, pVCpu->idCpu),
4321 ("VidStartVirtualProcessor failed for CPU #%u: %u (%#x, rcNt=%#x)\n",
4322 pVCpu->idCpu, RTNtLastErrorValue(), RTNtLastErrorValue(), RTNtLastStatusValue()),
4323 VERR_NEM_IPE_5);
4324# endif
4325 pVCpu->nem.s.fHandleAndGetFlags = VID_MSHAGN_F_GET_NEXT_MESSAGE;
4326 }
4327# endif /* NEM_WIN_TEMPLATE_MODE_OWN_RUN_API */
4328
4329 if (VMCPU_CMPXCHG_STATE(pVCpu, VMCPUSTATE_STARTED_EXEC_NEM_WAIT, VMCPUSTATE_STARTED_EXEC_NEM))
4330 {
4331# ifdef NEM_WIN_TEMPLATE_MODE_OWN_RUN_API
4332 uint64_t const nsNow = RTTimeNanoTS();
4333 int64_t const cNsNextTimerEvt = nsNow - nsNextTimerEvt;
4334 uint32_t cMsWait;
4335 if (cNsNextTimerEvt < 100000 /* ns */)
4336 cMsWait = 0;
4337 else if ((uint64_t)cNsNextTimerEvt < RT_NS_1SEC)
4338 {
4339 if ((uint32_t)cNsNextTimerEvt < 2*RT_NS_1MS)
4340 cMsWait = 1;
4341 else
4342 cMsWait = ((uint32_t)cNsNextTimerEvt - 100000 /*ns*/) / RT_NS_1MS;
4343 }
4344 else
4345 cMsWait = RT_MS_1SEC;
4346# ifdef IN_RING0
4347 pVCpu->nem.s.uIoCtlBuf.MsgSlotHandleAndGetNext.iCpu = pVCpu->idCpu;
4348 pVCpu->nem.s.uIoCtlBuf.MsgSlotHandleAndGetNext.fFlags = pVCpu->nem.s.fHandleAndGetFlags;
4349 pVCpu->nem.s.uIoCtlBuf.MsgSlotHandleAndGetNext.cMillies = cMsWait;
4350 NTSTATUS rcNt = nemR0NtPerformIoControl(pVM, pVCpu, pVM->nemr0.s.IoCtlMessageSlotHandleAndGetNext.uFunction,
4351 &pVCpu->nem.s.uIoCtlBuf.MsgSlotHandleAndGetNext,
4352 pVM->nemr0.s.IoCtlMessageSlotHandleAndGetNext.cbInput,
4353 NULL, 0);
4354 VMCPU_CMPXCHG_STATE(pVCpu, VMCPUSTATE_STARTED_EXEC_NEM, VMCPUSTATE_STARTED_EXEC_NEM_WAIT);
4355 if (rcNt == STATUS_SUCCESS)
4356# else
4357 BOOL fRet = VidMessageSlotHandleAndGetNext(pVM->nem.s.hPartitionDevice, pVCpu->idCpu,
4358 pVCpu->nem.s.fHandleAndGetFlags, cMsWait);
4359 VMCPU_CMPXCHG_STATE(pVCpu, VMCPUSTATE_STARTED_EXEC_NEM, VMCPUSTATE_STARTED_EXEC_NEM_WAIT);
4360 if (fRet)
4361# endif
4362# else
4363 WHV_RUN_VP_EXIT_CONTEXT ExitReason;
4364 RT_ZERO(ExitReason);
4365 LogFlow(("NEM/%u: Entry @ %04X:%08RX64 IF=%d (~~may be stale~~)\n", pVCpu->idCpu, pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip, pVCpu->cpum.GstCtx.rflags.Bits.u1IF));
4366 TMNotifyStartOfExecution(pVM, pVCpu);
4367 HRESULT hrc = WHvRunVirtualProcessor(pVM->nem.s.hPartition, pVCpu->idCpu, &ExitReason, sizeof(ExitReason));
4368 VMCPU_CMPXCHG_STATE(pVCpu, VMCPUSTATE_STARTED_EXEC_NEM, VMCPUSTATE_STARTED_EXEC_NEM_WAIT);
4369 TMNotifyEndOfExecution(pVM, pVCpu, ASMReadTSC());
4370 LogFlow(("NEM/%u: Exit @ %04X:%08RX64 IF=%d CR8=%#x \n", pVCpu->idCpu, ExitReason.VpContext.Cs.Selector, ExitReason.VpContext.Rip, RT_BOOL(ExitReason.VpContext.Rflags & X86_EFL_IF), ExitReason.VpContext.Cr8));
4371 if (SUCCEEDED(hrc))
4372# endif
4373 {
4374 /*
4375 * Deal with the message.
4376 */
4377# ifdef NEM_WIN_TEMPLATE_MODE_OWN_RUN_API
4378 rcStrict = nemHCWinHandleMessage(pVM, pVCpu, pMappingHeader);
4379 pVCpu->nem.s.fHandleAndGetFlags |= VID_MSHAGN_F_HANDLE_MESSAGE;
4380# else
4381 rcStrict = nemR3WinHandleExit(pVM, pVCpu, &ExitReason);
4382# endif
4383 if (rcStrict == VINF_SUCCESS)
4384 { /* hopefully likely */ }
4385 else
4386 {
4387 LogFlow(("NEM/%u: breaking: nemHCWinHandleMessage -> %Rrc\n", pVCpu->idCpu, VBOXSTRICTRC_VAL(rcStrict) ));
4388 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatBreakOnStatus);
4389 break;
4390 }
4391 }
4392 else
4393 {
4394# ifdef NEM_WIN_TEMPLATE_MODE_OWN_RUN_API
4395
4396 /* VID.SYS merges STATUS_ALERTED and STATUS_USER_APC into STATUS_TIMEOUT,
4397 so after NtAlertThread we end up here with a STATUS_TIMEOUT. And yeah,
4398 the error code conversion is into WAIT_XXX, i.e. NT status codes. */
4399# ifndef IN_RING0
4400 DWORD rcNt = GetLastError();
4401# endif
4402 LogFlow(("NEM/%u: VidMessageSlotHandleAndGetNext -> %#x\n", pVCpu->idCpu, rcNt));
4403 AssertLogRelMsgReturn( rcNt == STATUS_TIMEOUT
4404 || rcNt == STATUS_ALERTED /* just in case */
4405 || rcNt == STATUS_USER_APC /* ditto */
4406 || rcNt == STATUS_KERNEL_APC /* ditto */
4407 , ("VidMessageSlotHandleAndGetNext failed for CPU #%u: %#x (%u)\n",
4408 pVCpu->idCpu, rcNt, rcNt),
4409 VERR_NEM_IPE_0);
4410 pVCpu->nem.s.fHandleAndGetFlags = VID_MSHAGN_F_GET_NEXT_MESSAGE;
4411 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatGetMsgTimeout);
4412# else
4413 AssertLogRelMsgFailedReturn(("WHvRunVirtualProcessor failed for CPU #%u: %#x (%u)\n",
4414 pVCpu->idCpu, hrc, GetLastError()),
4415 VERR_NEM_IPE_0);
4416# endif
4417 }
4418
4419 /*
4420 * If no relevant FFs are pending, loop.
4421 */
4422 if ( !VM_FF_IS_ANY_SET( pVM, !fSingleStepping ? VM_FF_HP_R0_PRE_HM_MASK : VM_FF_HP_R0_PRE_HM_STEP_MASK)
4423 && !VMCPU_FF_IS_ANY_SET(pVCpu, !fSingleStepping ? VMCPU_FF_HP_R0_PRE_HM_MASK : VMCPU_FF_HP_R0_PRE_HM_STEP_MASK) )
4424 continue;
4425
4426 /** @todo Try handle pending flags, not just return to EM loops. Take care
4427 * not to set important RCs here unless we've handled a message. */
4428 LogFlow(("NEM/%u: breaking: pending FF (%#x / %#RX64)\n",
4429 pVCpu->idCpu, pVM->fGlobalForcedActions, (uint64_t)pVCpu->fLocalForcedActions));
4430 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatBreakOnFFPost);
4431 }
4432 else
4433 {
4434 LogFlow(("NEM/%u: breaking: canceled %d (pre exec)\n", pVCpu->idCpu, VMCPU_GET_STATE(pVCpu) ));
4435 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatBreakOnCancel);
4436 }
4437 }
4438 else
4439 {
4440 LogFlow(("NEM/%u: breaking: pending FF (pre exec)\n", pVCpu->idCpu));
4441 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatBreakOnFFPre);
4442 }
4443 break;
4444 } /* the run loop */
4445
4446
4447 /*
4448 * If the CPU is running, make sure to stop it before we try sync back the
4449 * state and return to EM. We don't sync back the whole state if we can help it.
4450 */
4451# ifdef NEM_WIN_TEMPLATE_MODE_OWN_RUN_API
4452 if (pVCpu->nem.s.fHandleAndGetFlags == VID_MSHAGN_F_GET_NEXT_MESSAGE)
4453 {
4454 pVCpu->nem.s.fHandleAndGetFlags = 0;
4455 rcStrict = nemHCWinStopCpu(pVM, pVCpu, rcStrict, pMappingHeader);
4456 }
4457# endif
4458
4459 if (!VMCPU_CMPXCHG_STATE(pVCpu, VMCPUSTATE_STARTED, VMCPUSTATE_STARTED_EXEC_NEM))
4460 VMCPU_CMPXCHG_STATE(pVCpu, VMCPUSTATE_STARTED, VMCPUSTATE_STARTED_EXEC_NEM_CANCELED);
4461
4462 if (pVCpu->cpum.GstCtx.fExtrn & (CPUMCTX_EXTRN_ALL | (CPUMCTX_EXTRN_NEM_WIN_MASK & ~CPUMCTX_EXTRN_NEM_WIN_EVENT_INJECT)))
4463 {
4464 /* Try anticipate what we might need. */
4465 uint64_t fImport = IEM_CPUMCTX_EXTRN_MUST_MASK | CPUMCTX_EXTRN_NEM_WIN_INHIBIT_INT | CPUMCTX_EXTRN_NEM_WIN_INHIBIT_NMI;
4466 if ( (rcStrict >= VINF_EM_FIRST && rcStrict <= VINF_EM_LAST)
4467 || RT_FAILURE(rcStrict))
4468 fImport = CPUMCTX_EXTRN_ALL | (CPUMCTX_EXTRN_NEM_WIN_MASK & ~CPUMCTX_EXTRN_NEM_WIN_EVENT_INJECT);
4469# ifdef IN_RING0 /* Ring-3 I/O port access optimizations: */
4470 else if ( rcStrict == VINF_IOM_R3_IOPORT_COMMIT_WRITE
4471 || rcStrict == VINF_EM_PENDING_R3_IOPORT_WRITE)
4472 fImport = CPUMCTX_EXTRN_RIP | CPUMCTX_EXTRN_CS | CPUMCTX_EXTRN_RFLAGS | CPUMCTX_EXTRN_NEM_WIN_INHIBIT_INT;
4473 else if (rcStrict == VINF_EM_PENDING_R3_IOPORT_READ)
4474 fImport = CPUMCTX_EXTRN_RAX | CPUMCTX_EXTRN_RIP | CPUMCTX_EXTRN_CS | CPUMCTX_EXTRN_RFLAGS | CPUMCTX_EXTRN_NEM_WIN_INHIBIT_INT;
4475# endif
4476 else if (VMCPU_FF_IS_ANY_SET(pVCpu, VMCPU_FF_INTERRUPT_PIC | VMCPU_FF_INTERRUPT_APIC
4477 | VMCPU_FF_INTERRUPT_NMI | VMCPU_FF_INTERRUPT_SMI))
4478 fImport |= IEM_CPUMCTX_EXTRN_XCPT_MASK;
4479
4480 if (pVCpu->cpum.GstCtx.fExtrn & fImport)
4481 {
4482# ifdef IN_RING0
4483 int rc2 = nemR0WinImportState(pVM, pVCpu, &pVCpu->cpum.GstCtx, fImport | CPUMCTX_EXTRN_NEM_WIN_EVENT_INJECT,
4484 true /*fCanUpdateCr3*/);
4485 if (RT_SUCCESS(rc2))
4486 pVCpu->cpum.GstCtx.fExtrn &= ~fImport;
4487 else if (rc2 == VERR_NEM_FLUSH_TLB)
4488 {
4489 pVCpu->cpum.GstCtx.fExtrn &= ~fImport;
4490 if (rcStrict == VINF_SUCCESS || rcStrict == -rc2)
4491 rcStrict = -rc2;
4492 else
4493 {
4494 pVCpu->nem.s.rcPending = -rc2;
4495 LogFlow(("NEM/%u: rcPending=%Rrc (rcStrict=%Rrc)\n", pVCpu->idCpu, rc2, VBOXSTRICTRC_VAL(rcStrict) ));
4496 }
4497 }
4498# else
4499 int rc2 = nemHCWinCopyStateFromHyperV(pVM, pVCpu, fImport | CPUMCTX_EXTRN_NEM_WIN_EVENT_INJECT);
4500 if (RT_SUCCESS(rc2))
4501 pVCpu->cpum.GstCtx.fExtrn &= ~fImport;
4502# endif
4503 else if (RT_SUCCESS(rcStrict))
4504 rcStrict = rc2;
4505 if (!(pVCpu->cpum.GstCtx.fExtrn & (CPUMCTX_EXTRN_ALL | (CPUMCTX_EXTRN_NEM_WIN_MASK & ~CPUMCTX_EXTRN_NEM_WIN_EVENT_INJECT))))
4506 pVCpu->cpum.GstCtx.fExtrn = 0;
4507 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatImportOnReturn);
4508 }
4509 else
4510 {
4511 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatImportOnReturnSkipped);
4512 pVCpu->cpum.GstCtx.fExtrn &= ~CPUMCTX_EXTRN_NEM_WIN_EVENT_INJECT;
4513 }
4514 }
4515 else
4516 {
4517 STAM_REL_COUNTER_INC(&pVCpu->nem.s.StatImportOnReturnSkipped);
4518 pVCpu->cpum.GstCtx.fExtrn = 0;
4519 }
4520
4521 LogFlow(("NEM/%u: %04x:%08RX64 efl=%#08RX64 => %Rrc\n",
4522 pVCpu->idCpu, pVCpu->cpum.GstCtx.cs.Sel, pVCpu->cpum.GstCtx.rip, pVCpu->cpum.GstCtx.rflags, VBOXSTRICTRC_VAL(rcStrict) ));
4523 return rcStrict;
4524}
4525
4526#endif /* defined(NEM_WIN_TEMPLATE_MODE_OWN_RUN_API) || defined(IN_RING3) */
4527#if defined(NEM_WIN_USE_HYPERCALLS_FOR_PAGES) || defined(IN_RING3)
4528
4529/**
4530 * @callback_method_impl{FNPGMPHYSNEMCHECKPAGE}
4531 */
4532NEM_TMPL_STATIC DECLCALLBACK(int) nemHCWinUnsetForA20CheckerCallback(PVMCC pVM, PVMCPUCC pVCpu, RTGCPHYS GCPhys,
4533 PPGMPHYSNEMPAGEINFO pInfo, void *pvUser)
4534{
4535 /* We'll just unmap the memory. */
4536 if (pInfo->u2NemState > NEM_WIN_PAGE_STATE_UNMAPPED)
4537 {
4538# ifdef NEM_WIN_USE_HYPERCALLS_FOR_PAGES
4539 int rc = nemHCWinHypercallUnmapPage(pVM, pVCpu, GCPhys);
4540 AssertRC(rc);
4541 if (RT_SUCCESS(rc))
4542# else
4543 HRESULT hrc = WHvUnmapGpaRange(pVM->nem.s.hPartition, GCPhys, X86_PAGE_SIZE);
4544 if (SUCCEEDED(hrc))
4545# endif
4546 {
4547 STAM_REL_COUNTER_INC(&pVM->nem.s.StatUnmapPage);
4548 uint32_t cMappedPages = ASMAtomicDecU32(&pVM->nem.s.cMappedPages); NOREF(cMappedPages);
4549 Log5(("NEM GPA unmapped/A20: %RGp (was %s, cMappedPages=%u)\n", GCPhys, g_apszPageStates[pInfo->u2NemState], cMappedPages));
4550 pInfo->u2NemState = NEM_WIN_PAGE_STATE_UNMAPPED;
4551 }
4552 else
4553 {
4554 STAM_REL_COUNTER_INC(&pVM->nem.s.StatUnmapPageFailed);
4555# ifdef NEM_WIN_USE_HYPERCALLS_FOR_PAGES
4556 LogRel(("nemHCWinUnsetForA20CheckerCallback/unmap: GCPhys=%RGp rc=%Rrc\n", GCPhys, rc));
4557 return rc;
4558# else
4559 LogRel(("nemHCWinUnsetForA20CheckerCallback/unmap: GCPhys=%RGp hrc=%Rhrc (%#x) Last=%#x/%u\n",
4560 GCPhys, hrc, hrc, RTNtLastStatusValue(), RTNtLastErrorValue()));
4561 return VERR_NEM_IPE_2;
4562# endif
4563 }
4564 }
4565 RT_NOREF(pVCpu, pvUser);
4566 return VINF_SUCCESS;
4567}
4568
4569
4570/**
4571 * Unmaps a page from Hyper-V for the purpose of emulating A20 gate behavior.
4572 *
4573 * @returns The PGMPhysNemQueryPageInfo result.
4574 * @param pVM The cross context VM structure.
4575 * @param pVCpu The cross context virtual CPU structure.
4576 * @param GCPhys The page to unmap.
4577 */
4578NEM_TMPL_STATIC int nemHCWinUnmapPageForA20Gate(PVMCC pVM, PVMCPUCC pVCpu, RTGCPHYS GCPhys)
4579{
4580 PGMPHYSNEMPAGEINFO Info;
4581 return PGMPhysNemPageInfoChecker(pVM, pVCpu, GCPhys, false /*fMakeWritable*/, &Info,
4582 nemHCWinUnsetForA20CheckerCallback, NULL);
4583}
4584
4585#endif /* defined(NEM_WIN_USE_HYPERCALLS_FOR_PAGES) || defined(IN_RING3) */
4586
4587void nemHCNativeNotifyHandlerPhysicalRegister(PVMCC pVM, PGMPHYSHANDLERKIND enmKind, RTGCPHYS GCPhys, RTGCPHYS cb)
4588{
4589 Log5(("nemHCNativeNotifyHandlerPhysicalRegister: %RGp LB %RGp enmKind=%d\n", GCPhys, cb, enmKind));
4590 NOREF(pVM); NOREF(enmKind); NOREF(GCPhys); NOREF(cb);
4591}
4592
4593
4594void nemHCNativeNotifyHandlerPhysicalDeregister(PVMCC pVM, PGMPHYSHANDLERKIND enmKind, RTGCPHYS GCPhys, RTGCPHYS cb,
4595 int fRestoreAsRAM, bool fRestoreAsRAM2)
4596{
4597 Log5(("nemHCNativeNotifyHandlerPhysicalDeregister: %RGp LB %RGp enmKind=%d fRestoreAsRAM=%d fRestoreAsRAM2=%d\n",
4598 GCPhys, cb, enmKind, fRestoreAsRAM, fRestoreAsRAM2));
4599 NOREF(pVM); NOREF(enmKind); NOREF(GCPhys); NOREF(cb); NOREF(fRestoreAsRAM); NOREF(fRestoreAsRAM2);
4600}
4601
4602
4603void nemHCNativeNotifyHandlerPhysicalModify(PVMCC pVM, PGMPHYSHANDLERKIND enmKind, RTGCPHYS GCPhysOld,
4604 RTGCPHYS GCPhysNew, RTGCPHYS cb, bool fRestoreAsRAM)
4605{
4606 Log5(("nemHCNativeNotifyHandlerPhysicalModify: %RGp LB %RGp -> %RGp enmKind=%d fRestoreAsRAM=%d\n",
4607 GCPhysOld, cb, GCPhysNew, enmKind, fRestoreAsRAM));
4608 NOREF(pVM); NOREF(enmKind); NOREF(GCPhysOld); NOREF(GCPhysNew); NOREF(cb); NOREF(fRestoreAsRAM);
4609}
4610
4611
4612#if defined(NEM_WIN_USE_HYPERCALLS_FOR_PAGES) || defined(IN_RING3)
4613/**
4614 * Worker that maps pages into Hyper-V.
4615 *
4616 * This is used by the PGM physical page notifications as well as the memory
4617 * access VMEXIT handlers.
4618 *
4619 * @returns VBox status code.
4620 * @param pVM The cross context VM structure.
4621 * @param pVCpu The cross context virtual CPU structure of the
4622 * calling EMT.
4623 * @param GCPhysSrc The source page address.
4624 * @param GCPhysDst The hyper-V destination page. This may differ from
4625 * GCPhysSrc when A20 is disabled.
4626 * @param fPageProt NEM_PAGE_PROT_XXX.
4627 * @param pu2State Our page state (input/output).
4628 * @param fBackingChanged Set if the page backing is being changed.
4629 * @thread EMT(pVCpu)
4630 */
4631NEM_TMPL_STATIC int nemHCNativeSetPhysPage(PVMCC pVM, PVMCPUCC pVCpu, RTGCPHYS GCPhysSrc, RTGCPHYS GCPhysDst,
4632 uint32_t fPageProt, uint8_t *pu2State, bool fBackingChanged)
4633{
4634# ifdef NEM_WIN_USE_HYPERCALLS_FOR_PAGES
4635 /*
4636 * When using the hypercalls instead of the ring-3 APIs, we don't need to
4637 * unmap memory before modifying it. We still want to track the state though,
4638 * since unmap will fail when called an unmapped page and we don't want to redo
4639 * upgrades/downgrades.
4640 */
4641 uint8_t const u2OldState = *pu2State;
4642 int rc;
4643 if (fPageProt == NEM_PAGE_PROT_NONE)
4644 {
4645 if (u2OldState > NEM_WIN_PAGE_STATE_UNMAPPED)
4646 {
4647 rc = nemHCWinHypercallUnmapPage(pVM, pVCpu, GCPhysDst);
4648 if (RT_SUCCESS(rc))
4649 {
4650 *pu2State = NEM_WIN_PAGE_STATE_UNMAPPED;
4651 STAM_REL_COUNTER_INC(&pVM->nem.s.StatUnmapPage);
4652 uint32_t cMappedPages = ASMAtomicDecU32(&pVM->nem.s.cMappedPages); NOREF(cMappedPages);
4653 Log5(("NEM GPA unmapped/set: %RGp (was %s, cMappedPages=%u)\n", GCPhysDst, g_apszPageStates[u2OldState], cMappedPages));
4654 }
4655 else
4656 {
4657 STAM_REL_COUNTER_INC(&pVM->nem.s.StatUnmapPageFailed);
4658 AssertLogRelMsgFailed(("nemHCNativeSetPhysPage/unmap: GCPhysDst=%RGp rc=%Rrc\n", GCPhysDst, rc));
4659 }
4660 }
4661 else
4662 rc = VINF_SUCCESS;
4663 }
4664 else if (fPageProt & NEM_PAGE_PROT_WRITE)
4665 {
4666 if (u2OldState != NEM_WIN_PAGE_STATE_WRITABLE || fBackingChanged)
4667 {
4668 rc = nemHCWinHypercallMapPage(pVM, pVCpu, GCPhysSrc, GCPhysDst,
4669 HV_MAP_GPA_READABLE | HV_MAP_GPA_WRITABLE
4670 | HV_MAP_GPA_EXECUTABLE | HV_MAP_GPA_EXECUTABLE_AGAIN);
4671 if (RT_SUCCESS(rc))
4672 {
4673 *pu2State = NEM_WIN_PAGE_STATE_WRITABLE;
4674 STAM_REL_COUNTER_INC(&pVM->nem.s.StatMapPage);
4675 uint32_t cMappedPages = u2OldState <= NEM_WIN_PAGE_STATE_UNMAPPED
4676 ? ASMAtomicIncU32(&pVM->nem.s.cMappedPages) : pVM->nem.s.cMappedPages;
4677 Log5(("NEM GPA writable/set: %RGp (was %s, cMappedPages=%u)\n", GCPhysDst, g_apszPageStates[u2OldState], cMappedPages));
4678 NOREF(cMappedPages);
4679 }
4680 else
4681 {
4682 STAM_REL_COUNTER_INC(&pVM->nem.s.StatMapPageFailed);
4683 AssertLogRelMsgFailed(("nemHCNativeSetPhysPage/writable: GCPhysDst=%RGp rc=%Rrc\n", GCPhysDst, rc));
4684 }
4685 }
4686 else
4687 rc = VINF_SUCCESS;
4688 }
4689 else
4690 {
4691 if (u2OldState != NEM_WIN_PAGE_STATE_READABLE || fBackingChanged)
4692 {
4693 rc = nemHCWinHypercallMapPage(pVM, pVCpu, GCPhysSrc, GCPhysDst,
4694 HV_MAP_GPA_READABLE | HV_MAP_GPA_EXECUTABLE | HV_MAP_GPA_EXECUTABLE_AGAIN);
4695 if (RT_SUCCESS(rc))
4696 {
4697 *pu2State = NEM_WIN_PAGE_STATE_READABLE;
4698 STAM_REL_COUNTER_INC(&pVM->nem.s.StatMapPage);
4699 uint32_t cMappedPages = u2OldState <= NEM_WIN_PAGE_STATE_UNMAPPED
4700 ? ASMAtomicIncU32(&pVM->nem.s.cMappedPages) : pVM->nem.s.cMappedPages;
4701 Log5(("NEM GPA read+exec/set: %RGp (was %s, cMappedPages=%u)\n", GCPhysDst, g_apszPageStates[u2OldState], cMappedPages));
4702 NOREF(cMappedPages);
4703 }
4704 else
4705 {
4706 STAM_REL_COUNTER_INC(&pVM->nem.s.StatMapPageFailed);
4707 AssertLogRelMsgFailed(("nemHCNativeSetPhysPage/writable: GCPhysDst=%RGp rc=%Rrc\n", GCPhysDst, rc));
4708 }
4709 }
4710 else
4711 rc = VINF_SUCCESS;
4712 }
4713
4714 return VINF_SUCCESS;
4715
4716# else /* !NEM_WIN_USE_HYPERCALLS_FOR_PAGES */
4717 /*
4718 * Looks like we need to unmap a page before we can change the backing
4719 * or even modify the protection. This is going to be *REALLY* efficient.
4720 * PGM lends us two bits to keep track of the state here.
4721 */
4722 RT_NOREF(pVCpu);
4723 uint8_t const u2OldState = *pu2State;
4724 uint8_t const u2NewState = fPageProt & NEM_PAGE_PROT_WRITE ? NEM_WIN_PAGE_STATE_WRITABLE
4725 : fPageProt & NEM_PAGE_PROT_READ ? NEM_WIN_PAGE_STATE_READABLE : NEM_WIN_PAGE_STATE_UNMAPPED;
4726 if ( fBackingChanged
4727 || u2NewState != u2OldState)
4728 {
4729 if (u2OldState > NEM_WIN_PAGE_STATE_UNMAPPED)
4730 {
4731# ifdef NEM_WIN_USE_HYPERCALLS_FOR_PAGES
4732 int rc = nemHCWinHypercallUnmapPage(pVM, pVCpu, GCPhysDst);
4733 AssertRC(rc);
4734 if (RT_SUCCESS(rc))
4735 {
4736 *pu2State = NEM_WIN_PAGE_STATE_UNMAPPED;
4737 STAM_REL_COUNTER_INC(&pVM->nem.s.StatUnmapPage);
4738 uint32_t cMappedPages = ASMAtomicDecU32(&pVM->nem.s.cMappedPages); NOREF(cMappedPages);
4739 if (u2NewState == NEM_WIN_PAGE_STATE_UNMAPPED)
4740 {
4741 Log5(("NEM GPA unmapped/set: %RGp (was %s, cMappedPages=%u)\n",
4742 GCPhysDst, g_apszPageStates[u2OldState], cMappedPages));
4743 return VINF_SUCCESS;
4744 }
4745 }
4746 else
4747 {
4748 STAM_REL_COUNTER_INC(&pVM->nem.s.StatUnmapPageFailed);
4749 LogRel(("nemHCNativeSetPhysPage/unmap: GCPhysDst=%RGp rc=%Rrc\n", GCPhysDst, rc));
4750 return rc;
4751 }
4752# else
4753 HRESULT hrc = WHvUnmapGpaRange(pVM->nem.s.hPartition, GCPhysDst, X86_PAGE_SIZE);
4754 if (SUCCEEDED(hrc))
4755 {
4756 *pu2State = NEM_WIN_PAGE_STATE_UNMAPPED;
4757 STAM_REL_COUNTER_INC(&pVM->nem.s.StatUnmapPage);
4758 uint32_t cMappedPages = ASMAtomicDecU32(&pVM->nem.s.cMappedPages); NOREF(cMappedPages);
4759 if (u2NewState == NEM_WIN_PAGE_STATE_UNMAPPED)
4760 {
4761 Log5(("NEM GPA unmapped/set: %RGp (was %s, cMappedPages=%u)\n",
4762 GCPhysDst, g_apszPageStates[u2OldState], cMappedPages));
4763 return VINF_SUCCESS;
4764 }
4765 }
4766 else
4767 {
4768 STAM_REL_COUNTER_INC(&pVM->nem.s.StatUnmapPageFailed);
4769 LogRel(("nemHCNativeSetPhysPage/unmap: GCPhysDst=%RGp hrc=%Rhrc (%#x) Last=%#x/%u\n",
4770 GCPhysDst, hrc, hrc, RTNtLastStatusValue(), RTNtLastErrorValue()));
4771 return VERR_NEM_INIT_FAILED;
4772 }
4773# endif
4774 }
4775 }
4776
4777 /*
4778 * Writeable mapping?
4779 */
4780 if (fPageProt & NEM_PAGE_PROT_WRITE)
4781 {
4782# ifdef NEM_WIN_USE_HYPERCALLS_FOR_PAGES
4783 int rc = nemHCWinHypercallMapPage(pVM, pVCpu, GCPhysSrc, GCPhysDst,
4784 HV_MAP_GPA_READABLE | HV_MAP_GPA_WRITABLE
4785 | HV_MAP_GPA_EXECUTABLE | HV_MAP_GPA_EXECUTABLE_AGAIN);
4786 AssertRC(rc);
4787 if (RT_SUCCESS(rc))
4788 {
4789 *pu2State = NEM_WIN_PAGE_STATE_WRITABLE;
4790 STAM_REL_COUNTER_INC(&pVM->nem.s.StatMapPage);
4791 uint32_t cMappedPages = ASMAtomicIncU32(&pVM->nem.s.cMappedPages); NOREF(cMappedPages);
4792 Log5(("NEM GPA mapped/set: %RGp %s (was %s, cMappedPages=%u)\n",
4793 GCPhysDst, g_apszPageStates[u2NewState], g_apszPageStates[u2OldState], cMappedPages));
4794 return VINF_SUCCESS;
4795 }
4796 STAM_REL_COUNTER_INC(&pVM->nem.s.StatMapPageFailed);
4797 LogRel(("nemHCNativeSetPhysPage/writable: GCPhysDst=%RGp rc=%Rrc\n", GCPhysDst, rc));
4798 return rc;
4799# else
4800 void *pvPage;
4801 int rc = nemR3NativeGCPhys2R3PtrWriteable(pVM, GCPhysSrc, &pvPage);
4802 if (RT_SUCCESS(rc))
4803 {
4804 HRESULT hrc = WHvMapGpaRange(pVM->nem.s.hPartition, pvPage, GCPhysDst, X86_PAGE_SIZE,
4805 WHvMapGpaRangeFlagRead | WHvMapGpaRangeFlagExecute | WHvMapGpaRangeFlagWrite);
4806 if (SUCCEEDED(hrc))
4807 {
4808 *pu2State = NEM_WIN_PAGE_STATE_WRITABLE;
4809 STAM_REL_COUNTER_INC(&pVM->nem.s.StatMapPage);
4810 uint32_t cMappedPages = ASMAtomicIncU32(&pVM->nem.s.cMappedPages); NOREF(cMappedPages);
4811 Log5(("NEM GPA mapped/set: %RGp %s (was %s, cMappedPages=%u)\n",
4812 GCPhysDst, g_apszPageStates[u2NewState], g_apszPageStates[u2OldState], cMappedPages));
4813 return VINF_SUCCESS;
4814 }
4815 STAM_REL_COUNTER_INC(&pVM->nem.s.StatMapPageFailed);
4816 LogRel(("nemHCNativeSetPhysPage/writable: GCPhysDst=%RGp hrc=%Rhrc (%#x) Last=%#x/%u\n",
4817 GCPhysDst, hrc, hrc, RTNtLastStatusValue(), RTNtLastErrorValue()));
4818 return VERR_NEM_INIT_FAILED;
4819 }
4820 LogRel(("nemHCNativeSetPhysPage/writable: GCPhysSrc=%RGp rc=%Rrc\n", GCPhysSrc, rc));
4821 return rc;
4822# endif
4823 }
4824
4825 if (fPageProt & NEM_PAGE_PROT_READ)
4826 {
4827# ifdef NEM_WIN_USE_HYPERCALLS_FOR_PAGES
4828 int rc = nemHCWinHypercallMapPage(pVM, pVCpu, GCPhysSrc, GCPhysDst,
4829 HV_MAP_GPA_READABLE | HV_MAP_GPA_EXECUTABLE | HV_MAP_GPA_EXECUTABLE_AGAIN);
4830 AssertRC(rc);
4831 if (RT_SUCCESS(rc))
4832 {
4833 *pu2State = NEM_WIN_PAGE_STATE_READABLE;
4834 STAM_REL_COUNTER_INC(&pVM->nem.s.StatMapPage);
4835 uint32_t cMappedPages = ASMAtomicIncU32(&pVM->nem.s.cMappedPages); NOREF(cMappedPages);
4836 Log5(("NEM GPA mapped/set: %RGp %s (was %s, cMappedPages=%u)\n",
4837 GCPhysDst, g_apszPageStates[u2NewState], g_apszPageStates[u2OldState], cMappedPages));
4838 return VINF_SUCCESS;
4839 }
4840 STAM_REL_COUNTER_INC(&pVM->nem.s.StatMapPageFailed);
4841 LogRel(("nemHCNativeSetPhysPage/readonly: GCPhysDst=%RGp rc=%Rrc\n", GCPhysDst, rc));
4842 return rc;
4843# else
4844 const void *pvPage;
4845 int rc = nemR3NativeGCPhys2R3PtrReadOnly(pVM, GCPhysSrc, &pvPage);
4846 if (RT_SUCCESS(rc))
4847 {
4848 HRESULT hrc = WHvMapGpaRange(pVM->nem.s.hPartition, (void *)pvPage, GCPhysDst, X86_PAGE_SIZE,
4849 WHvMapGpaRangeFlagRead | WHvMapGpaRangeFlagExecute);
4850 if (SUCCEEDED(hrc))
4851 {
4852 *pu2State = NEM_WIN_PAGE_STATE_READABLE;
4853 STAM_REL_COUNTER_INC(&pVM->nem.s.StatMapPage);
4854 uint32_t cMappedPages = ASMAtomicIncU32(&pVM->nem.s.cMappedPages); NOREF(cMappedPages);
4855 Log5(("NEM GPA mapped/set: %RGp %s (was %s, cMappedPages=%u)\n",
4856 GCPhysDst, g_apszPageStates[u2NewState], g_apszPageStates[u2OldState], cMappedPages));
4857 return VINF_SUCCESS;
4858 }
4859 STAM_REL_COUNTER_INC(&pVM->nem.s.StatMapPageFailed);
4860 LogRel(("nemHCNativeSetPhysPage/readonly: GCPhysDst=%RGp hrc=%Rhrc (%#x) Last=%#x/%u\n",
4861 GCPhysDst, hrc, hrc, RTNtLastStatusValue(), RTNtLastErrorValue()));
4862 return VERR_NEM_INIT_FAILED;
4863 }
4864 LogRel(("nemHCNativeSetPhysPage/readonly: GCPhysSrc=%RGp rc=%Rrc\n", GCPhysSrc, rc));
4865 return rc;
4866# endif
4867 }
4868
4869 /* We already unmapped it above. */
4870 *pu2State = NEM_WIN_PAGE_STATE_UNMAPPED;
4871 return VINF_SUCCESS;
4872# endif /* !NEM_WIN_USE_HYPERCALLS_FOR_PAGES */
4873}
4874#endif /* defined(NEM_WIN_USE_HYPERCALLS_FOR_PAGES) || defined(IN_RING3) */
4875
4876
4877NEM_TMPL_STATIC int nemHCJustUnmapPageFromHyperV(PVMCC pVM, RTGCPHYS GCPhysDst, uint8_t *pu2State)
4878{
4879 if (*pu2State <= NEM_WIN_PAGE_STATE_UNMAPPED)
4880 {
4881 Log5(("nemHCJustUnmapPageFromHyperV: %RGp == unmapped\n", GCPhysDst));
4882 *pu2State = NEM_WIN_PAGE_STATE_UNMAPPED;
4883 return VINF_SUCCESS;
4884 }
4885
4886#if defined(NEM_WIN_USE_HYPERCALLS_FOR_PAGES)
4887 PVMCPUCC pVCpu = VMMGetCpu(pVM);
4888 int rc = nemHCWinHypercallUnmapPage(pVM, pVCpu, GCPhysDst);
4889 AssertRC(rc);
4890 if (RT_SUCCESS(rc))
4891 {
4892 STAM_REL_COUNTER_INC(&pVM->nem.s.StatUnmapPage);
4893 uint32_t cMappedPages = ASMAtomicDecU32(&pVM->nem.s.cMappedPages); NOREF(cMappedPages);
4894 Log5(("NEM GPA unmapped/just: %RGp (was %s, cMappedPages=%u)\n", GCPhysDst, g_apszPageStates[*pu2State], cMappedPages));
4895 *pu2State = NEM_WIN_PAGE_STATE_UNMAPPED;
4896 return VINF_SUCCESS;
4897 }
4898 STAM_REL_COUNTER_INC(&pVM->nem.s.StatUnmapPageFailed);
4899 LogRel(("nemHCJustUnmapPageFromHyperV/unmap: GCPhysDst=%RGp rc=%Rrc\n", GCPhysDst, rc));
4900 return rc;
4901
4902#elif defined(IN_RING3)
4903 HRESULT hrc = WHvUnmapGpaRange(pVM->nem.s.hPartition, GCPhysDst & ~(RTGCPHYS)X86_PAGE_OFFSET_MASK, X86_PAGE_SIZE);
4904 if (SUCCEEDED(hrc))
4905 {
4906 STAM_REL_COUNTER_INC(&pVM->nem.s.StatUnmapPage);
4907 uint32_t cMappedPages = ASMAtomicDecU32(&pVM->nem.s.cMappedPages); NOREF(cMappedPages);
4908 *pu2State = NEM_WIN_PAGE_STATE_UNMAPPED;
4909 Log5(("nemHCJustUnmapPageFromHyperV: %RGp => unmapped (total %u)\n", GCPhysDst, cMappedPages));
4910 return VINF_SUCCESS;
4911 }
4912 STAM_REL_COUNTER_INC(&pVM->nem.s.StatUnmapPageFailed);
4913 LogRel(("nemHCJustUnmapPageFromHyperV(%RGp): failed! hrc=%Rhrc (%#x) Last=%#x/%u\n",
4914 GCPhysDst, hrc, hrc, RTNtLastStatusValue(), RTNtLastErrorValue()));
4915 return VERR_NEM_IPE_6;
4916#else
4917 RT_NOREF(pVM, GCPhysDst, pu2State);
4918 LogRel(("nemHCJustUnmapPageFromHyperV(%RGp): Why are we here?!?\n", GCPhysDst));
4919 return VERR_NEM_IPE_6;
4920#endif
4921}
4922
4923
4924int nemHCNativeNotifyPhysPageAllocated(PVMCC pVM, RTGCPHYS GCPhys, RTHCPHYS HCPhys, uint32_t fPageProt,
4925 PGMPAGETYPE enmType, uint8_t *pu2State)
4926{
4927 Log5(("nemHCNativeNotifyPhysPageAllocated: %RGp HCPhys=%RHp fPageProt=%#x enmType=%d *pu2State=%d\n",
4928 GCPhys, HCPhys, fPageProt, enmType, *pu2State));
4929 RT_NOREF_PV(HCPhys); RT_NOREF_PV(enmType);
4930
4931 int rc;
4932#ifdef NEM_WIN_USE_HYPERCALLS_FOR_PAGES
4933 PVMCPUCC pVCpu = VMMGetCpu(pVM);
4934 if ( pVM->nem.s.fA20Enabled
4935 || !NEM_WIN_IS_RELEVANT_TO_A20(GCPhys))
4936 rc = nemHCNativeSetPhysPage(pVM, pVCpu, GCPhys, GCPhys, fPageProt, pu2State, true /*fBackingChanged*/);
4937 else
4938 {
4939 /* To keep effort at a minimum, we unmap the HMA page alias and resync it lazily when needed. */
4940 rc = nemHCWinUnmapPageForA20Gate(pVM, pVCpu, GCPhys | RT_BIT_32(20));
4941 if (!NEM_WIN_IS_SUBJECT_TO_A20(GCPhys) && RT_SUCCESS(rc))
4942 rc = nemHCNativeSetPhysPage(pVM, pVCpu, GCPhys, GCPhys, fPageProt, pu2State, true /*fBackingChanged*/);
4943
4944 }
4945#else
4946 RT_NOREF_PV(fPageProt);
4947 if ( pVM->nem.s.fA20Enabled
4948 || !NEM_WIN_IS_RELEVANT_TO_A20(GCPhys))
4949 rc = nemHCJustUnmapPageFromHyperV(pVM, GCPhys, pu2State);
4950 else if (!NEM_WIN_IS_SUBJECT_TO_A20(GCPhys))
4951 rc = nemHCJustUnmapPageFromHyperV(pVM, GCPhys, pu2State);
4952 else
4953 rc = VINF_SUCCESS; /* ignore since we've got the alias page at this address. */
4954#endif
4955 return rc;
4956}
4957
4958
4959void nemHCNativeNotifyPhysPageProtChanged(PVMCC pVM, RTGCPHYS GCPhys, RTHCPHYS HCPhys, uint32_t fPageProt,
4960 PGMPAGETYPE enmType, uint8_t *pu2State)
4961{
4962 Log5(("nemHCNativeNotifyPhysPageProtChanged: %RGp HCPhys=%RHp fPageProt=%#x enmType=%d *pu2State=%d\n",
4963 GCPhys, HCPhys, fPageProt, enmType, *pu2State));
4964 RT_NOREF_PV(HCPhys); RT_NOREF_PV(enmType);
4965
4966#ifdef NEM_WIN_USE_HYPERCALLS_FOR_PAGES
4967 PVMCPUCC pVCpu = VMMGetCpu(pVM);
4968 if ( pVM->nem.s.fA20Enabled
4969 || !NEM_WIN_IS_RELEVANT_TO_A20(GCPhys))
4970 nemHCNativeSetPhysPage(pVM, pVCpu, GCPhys, GCPhys, fPageProt, pu2State, false /*fBackingChanged*/);
4971 else
4972 {
4973 /* To keep effort at a minimum, we unmap the HMA page alias and resync it lazily when needed. */
4974 nemHCWinUnmapPageForA20Gate(pVM, pVCpu, GCPhys | RT_BIT_32(20));
4975 if (!NEM_WIN_IS_SUBJECT_TO_A20(GCPhys))
4976 nemHCNativeSetPhysPage(pVM, pVCpu, GCPhys, GCPhys, fPageProt, pu2State, false /*fBackingChanged*/);
4977 }
4978#else
4979 RT_NOREF_PV(fPageProt);
4980 if ( pVM->nem.s.fA20Enabled
4981 || !NEM_WIN_IS_RELEVANT_TO_A20(GCPhys))
4982 nemHCJustUnmapPageFromHyperV(pVM, GCPhys, pu2State);
4983 else if (!NEM_WIN_IS_SUBJECT_TO_A20(GCPhys))
4984 nemHCJustUnmapPageFromHyperV(pVM, GCPhys, pu2State);
4985 /* else: ignore since we've got the alias page at this address. */
4986#endif
4987}
4988
4989
4990void nemHCNativeNotifyPhysPageChanged(PVMCC pVM, RTGCPHYS GCPhys, RTHCPHYS HCPhysPrev, RTHCPHYS HCPhysNew,
4991 uint32_t fPageProt, PGMPAGETYPE enmType, uint8_t *pu2State)
4992{
4993 Log5(("nemHCNativeNotifyPhysPageChanged: %RGp HCPhys=%RHp->%RHp fPageProt=%#x enmType=%d *pu2State=%d\n",
4994 GCPhys, HCPhysPrev, HCPhysNew, fPageProt, enmType, *pu2State));
4995 RT_NOREF_PV(HCPhysPrev); RT_NOREF_PV(HCPhysNew); RT_NOREF_PV(enmType);
4996
4997#ifdef NEM_WIN_USE_HYPERCALLS_FOR_PAGES
4998 PVMCPUCC pVCpu = VMMGetCpu(pVM);
4999 if ( pVM->nem.s.fA20Enabled
5000 || !NEM_WIN_IS_RELEVANT_TO_A20(GCPhys))
5001 nemHCNativeSetPhysPage(pVM, pVCpu, GCPhys, GCPhys, fPageProt, pu2State, true /*fBackingChanged*/);
5002 else
5003 {
5004 /* To keep effort at a minimum, we unmap the HMA page alias and resync it lazily when needed. */
5005 nemHCWinUnmapPageForA20Gate(pVM, pVCpu, GCPhys | RT_BIT_32(20));
5006 if (!NEM_WIN_IS_SUBJECT_TO_A20(GCPhys))
5007 nemHCNativeSetPhysPage(pVM, pVCpu, GCPhys, GCPhys, fPageProt, pu2State, true /*fBackingChanged*/);
5008 }
5009#else
5010 RT_NOREF_PV(fPageProt);
5011 if ( pVM->nem.s.fA20Enabled
5012 || !NEM_WIN_IS_RELEVANT_TO_A20(GCPhys))
5013 nemHCJustUnmapPageFromHyperV(pVM, GCPhys, pu2State);
5014 else if (!NEM_WIN_IS_SUBJECT_TO_A20(GCPhys))
5015 nemHCJustUnmapPageFromHyperV(pVM, GCPhys, pu2State);
5016 /* else: ignore since we've got the alias page at this address. */
5017#endif
5018}
5019
注意: 瀏覽 TracBrowser 來幫助您使用儲存庫瀏覽器

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