VirtualBox

source: vbox/trunk/src/VBox/VMM/VMMR0/HMR0.cpp@ 87345

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

Copyright year updates by scm.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id Revision
File size: 67.0 KB
Line 
1/* $Id: HMR0.cpp 82968 2020-02-04 10:35:17Z vboxsync $ */
2/** @file
3 * Hardware Assisted Virtualization Manager (HM) - Host Context Ring-0.
4 */
5
6/*
7 * Copyright (C) 2006-2020 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18
19/*********************************************************************************************************************************
20* Header Files *
21*********************************************************************************************************************************/
22#define LOG_GROUP LOG_GROUP_HM
23#define VMCPU_INCL_CPUM_GST_CTX
24#include <VBox/vmm/hm.h>
25#include <VBox/vmm/pgm.h>
26#include "HMInternal.h"
27#include <VBox/vmm/vmcc.h>
28#include <VBox/vmm/hm_svm.h>
29#include <VBox/vmm/hmvmxinline.h>
30#include <VBox/err.h>
31#include <VBox/log.h>
32#include <iprt/assert.h>
33#include <iprt/asm.h>
34#include <iprt/asm-amd64-x86.h>
35#include <iprt/cpuset.h>
36#include <iprt/mem.h>
37#include <iprt/memobj.h>
38#include <iprt/once.h>
39#include <iprt/param.h>
40#include <iprt/power.h>
41#include <iprt/string.h>
42#include <iprt/thread.h>
43#include <iprt/x86.h>
44#include "HMVMXR0.h"
45#include "HMSVMR0.h"
46
47
48/*********************************************************************************************************************************
49* Internal Functions *
50*********************************************************************************************************************************/
51static DECLCALLBACK(void) hmR0EnableCpuCallback(RTCPUID idCpu, void *pvUser1, void *pvUser2);
52static DECLCALLBACK(void) hmR0DisableCpuCallback(RTCPUID idCpu, void *pvUser1, void *pvUser2);
53static DECLCALLBACK(void) hmR0InitIntelCpu(RTCPUID idCpu, void *pvUser1, void *pvUser2);
54static DECLCALLBACK(void) hmR0InitAmdCpu(RTCPUID idCpu, void *pvUser1, void *pvUser2);
55static DECLCALLBACK(void) hmR0PowerCallback(RTPOWEREVENT enmEvent, void *pvUser);
56static DECLCALLBACK(void) hmR0MpEventCallback(RTMPEVENT enmEvent, RTCPUID idCpu, void *pvData);
57
58
59/*********************************************************************************************************************************
60* Structures and Typedefs *
61*********************************************************************************************************************************/
62/**
63 * This is used to manage the status code of a RTMpOnAll in HM.
64 */
65typedef struct HMR0FIRSTRC
66{
67 /** The status code. */
68 int32_t volatile rc;
69 /** The ID of the CPU reporting the first failure. */
70 RTCPUID volatile idCpu;
71} HMR0FIRSTRC;
72/** Pointer to a first return code structure. */
73typedef HMR0FIRSTRC *PHMR0FIRSTRC;
74
75
76/*********************************************************************************************************************************
77* Global Variables *
78*********************************************************************************************************************************/
79/**
80 * Global data.
81 */
82static struct
83{
84 /** Per CPU globals. */
85 HMPHYSCPU aCpuInfo[RTCPUSET_MAX_CPUS];
86
87 /** @name Ring-0 method table for AMD-V and VT-x specific operations.
88 * @{ */
89 DECLR0CALLBACKMEMBER(int, pfnEnterSession, (PVMCPUCC pVCpu));
90 DECLR0CALLBACKMEMBER(void, pfnThreadCtxCallback, (RTTHREADCTXEVENT enmEvent, PVMCPUCC pVCpu, bool fGlobalInit));
91 DECLR0CALLBACKMEMBER(int, pfnCallRing3Callback, (PVMCPUCC pVCpu, VMMCALLRING3 enmOperation));
92 DECLR0CALLBACKMEMBER(int, pfnExportHostState, (PVMCPUCC pVCpu));
93 DECLR0CALLBACKMEMBER(VBOXSTRICTRC, pfnRunGuestCode, (PVMCPUCC pVCpu));
94 DECLR0CALLBACKMEMBER(int, pfnEnableCpu, (PHMPHYSCPU pHostCpu, PVMCC pVM, void *pvCpuPage, RTHCPHYS HCPhysCpuPage,
95 bool fEnabledByHost, PCSUPHWVIRTMSRS pHwvirtMsrs));
96 DECLR0CALLBACKMEMBER(int, pfnDisableCpu, (PHMPHYSCPU pHostCpu, void *pvCpuPage, RTHCPHYS HCPhysCpuPage));
97 DECLR0CALLBACKMEMBER(int, pfnInitVM, (PVMCC pVM));
98 DECLR0CALLBACKMEMBER(int, pfnTermVM, (PVMCC pVM));
99 DECLR0CALLBACKMEMBER(int, pfnSetupVM, (PVMCC pVM));
100 /** @} */
101
102 /** Hardware-virtualization data. */
103 struct
104 {
105 union
106 {
107 /** VT-x data. */
108 struct
109 {
110 /** Host CR4 value (set by ring-0 VMX init) */
111 uint64_t u64HostCr4;
112 /** Host EFER value (set by ring-0 VMX init) */
113 uint64_t u64HostMsrEfer;
114 /** Host SMM monitor control (used for logging/diagnostics) */
115 uint64_t u64HostSmmMonitorCtl;
116 /** Last instruction error. */
117 uint32_t ulLastInstrError;
118 /** The shift mask employed by the VMX-Preemption timer. */
119 uint8_t cPreemptTimerShift;
120 /** Padding. */
121 uint8_t abPadding[3];
122 /** Whether we're using the preemption timer or not. */
123 bool fUsePreemptTimer;
124 /** Whether we're using SUPR0EnableVTx or not. */
125 bool fUsingSUPR0EnableVTx;
126 /** Set if we've called SUPR0EnableVTx(true) and should disable it during
127 * module termination. */
128 bool fCalledSUPR0EnableVTx;
129 /** Set to by us to indicate VMX is supported by the CPU. */
130 bool fSupported;
131 } vmx;
132
133 /** AMD-V data. */
134 struct
135 {
136 /** SVM revision. */
137 uint32_t u32Rev;
138 /** SVM feature bits from cpuid 0x8000000a */
139 uint32_t u32Features;
140 /** Padding. */
141 bool afPadding[3];
142 /** Set by us to indicate SVM is supported by the CPU. */
143 bool fSupported;
144 } svm;
145 } u;
146 /** Maximum allowed ASID/VPID (inclusive). */
147 uint32_t uMaxAsid;
148 /** MSRs. */
149 SUPHWVIRTMSRS Msrs;
150 } hwvirt;
151
152 /** Last recorded error code during HM ring-0 init. */
153 int32_t rcInit;
154
155 /** If set, VT-x/AMD-V is enabled globally at init time, otherwise it's
156 * enabled and disabled each time it's used to execute guest code. */
157 bool fGlobalInit;
158 /** Indicates whether the host is suspending or not. We'll refuse a few
159 * actions when the host is being suspended to speed up the suspending and
160 * avoid trouble. */
161 bool volatile fSuspended;
162
163 /** Whether we've already initialized all CPUs.
164 * @remarks We could check the EnableAllCpusOnce state, but this is
165 * simpler and hopefully easier to understand. */
166 bool fEnabled;
167 /** Serialize initialization in HMR0EnableAllCpus. */
168 RTONCE EnableAllCpusOnce;
169} g_HmR0;
170
171
172/**
173 * Initializes a first return code structure.
174 *
175 * @param pFirstRc The structure to init.
176 */
177static void hmR0FirstRcInit(PHMR0FIRSTRC pFirstRc)
178{
179 pFirstRc->rc = VINF_SUCCESS;
180 pFirstRc->idCpu = NIL_RTCPUID;
181}
182
183
184/**
185 * Try set the status code (success ignored).
186 *
187 * @param pFirstRc The first return code structure.
188 * @param rc The status code.
189 */
190static void hmR0FirstRcSetStatus(PHMR0FIRSTRC pFirstRc, int rc)
191{
192 if ( RT_FAILURE(rc)
193 && ASMAtomicCmpXchgS32(&pFirstRc->rc, rc, VINF_SUCCESS))
194 pFirstRc->idCpu = RTMpCpuId();
195}
196
197
198/**
199 * Get the status code of a first return code structure.
200 *
201 * @returns The status code; VINF_SUCCESS or error status, no informational or
202 * warning errors.
203 * @param pFirstRc The first return code structure.
204 */
205static int hmR0FirstRcGetStatus(PHMR0FIRSTRC pFirstRc)
206{
207 return pFirstRc->rc;
208}
209
210
211#ifdef VBOX_STRICT
212# ifndef DEBUG_bird
213/**
214 * Get the CPU ID on which the failure status code was reported.
215 *
216 * @returns The CPU ID, NIL_RTCPUID if no failure was reported.
217 * @param pFirstRc The first return code structure.
218 */
219static RTCPUID hmR0FirstRcGetCpuId(PHMR0FIRSTRC pFirstRc)
220{
221 return pFirstRc->idCpu;
222}
223# endif
224#endif /* VBOX_STRICT */
225
226
227/** @name Dummy callback handlers.
228 * @{ */
229
230static DECLCALLBACK(int) hmR0DummyEnter(PVMCPUCC pVCpu)
231{
232 RT_NOREF1(pVCpu);
233 return VINF_SUCCESS;
234}
235
236static DECLCALLBACK(void) hmR0DummyThreadCtxCallback(RTTHREADCTXEVENT enmEvent, PVMCPUCC pVCpu, bool fGlobalInit)
237{
238 RT_NOREF3(enmEvent, pVCpu, fGlobalInit);
239}
240
241static DECLCALLBACK(int) hmR0DummyEnableCpu(PHMPHYSCPU pHostCpu, PVMCC pVM, void *pvCpuPage, RTHCPHYS HCPhysCpuPage,
242 bool fEnabledBySystem, PCSUPHWVIRTMSRS pHwvirtMsrs)
243{
244 RT_NOREF6(pHostCpu, pVM, pvCpuPage, HCPhysCpuPage, fEnabledBySystem, pHwvirtMsrs);
245 return VINF_SUCCESS;
246}
247
248static DECLCALLBACK(int) hmR0DummyDisableCpu(PHMPHYSCPU pHostCpu, void *pvCpuPage, RTHCPHYS HCPhysCpuPage)
249{
250 RT_NOREF3(pHostCpu, pvCpuPage, HCPhysCpuPage);
251 return VINF_SUCCESS;
252}
253
254static DECLCALLBACK(int) hmR0DummyInitVM(PVMCC pVM)
255{
256 RT_NOREF1(pVM);
257 return VINF_SUCCESS;
258}
259
260static DECLCALLBACK(int) hmR0DummyTermVM(PVMCC pVM)
261{
262 RT_NOREF1(pVM);
263 return VINF_SUCCESS;
264}
265
266static DECLCALLBACK(int) hmR0DummySetupVM(PVMCC pVM)
267{
268 RT_NOREF1(pVM);
269 return VINF_SUCCESS;
270}
271
272static DECLCALLBACK(int) hmR0DummyCallRing3Callback(PVMCPUCC pVCpu, VMMCALLRING3 enmOperation)
273{
274 RT_NOREF2(pVCpu, enmOperation);
275 return VINF_SUCCESS;
276}
277
278static DECLCALLBACK(VBOXSTRICTRC) hmR0DummyRunGuestCode(PVMCPUCC pVCpu)
279{
280 RT_NOREF(pVCpu);
281 return VINF_SUCCESS;
282}
283
284static DECLCALLBACK(int) hmR0DummyExportHostState(PVMCPUCC pVCpu)
285{
286 RT_NOREF1(pVCpu);
287 return VINF_SUCCESS;
288}
289
290/** @} */
291
292
293/**
294 * Intel specific initialization code.
295 *
296 * @returns VBox status code (will only fail if out of memory).
297 */
298static int hmR0InitIntel(void)
299{
300 /* Read this MSR now as it may be useful for error reporting when initializing VT-x fails. */
301 g_HmR0.hwvirt.Msrs.u.vmx.u64FeatCtrl = ASMRdMsr(MSR_IA32_FEATURE_CONTROL);
302
303 /*
304 * First try use native kernel API for controlling VT-x.
305 * (This is only supported by some Mac OS X kernels atm.)
306 */
307 int rc = g_HmR0.rcInit = SUPR0EnableVTx(true /* fEnable */);
308 g_HmR0.hwvirt.u.vmx.fUsingSUPR0EnableVTx = rc != VERR_NOT_SUPPORTED;
309 if (g_HmR0.hwvirt.u.vmx.fUsingSUPR0EnableVTx)
310 {
311 AssertLogRelMsg(rc == VINF_SUCCESS || rc == VERR_VMX_IN_VMX_ROOT_MODE || rc == VERR_VMX_NO_VMX, ("%Rrc\n", rc));
312 if (RT_SUCCESS(rc))
313 {
314 g_HmR0.hwvirt.u.vmx.fSupported = true;
315 rc = SUPR0EnableVTx(false /* fEnable */);
316 AssertLogRelRC(rc);
317 }
318 }
319 else
320 {
321 HMR0FIRSTRC FirstRc;
322 hmR0FirstRcInit(&FirstRc);
323 g_HmR0.rcInit = RTMpOnAll(hmR0InitIntelCpu, &FirstRc, NULL);
324 if (RT_SUCCESS(g_HmR0.rcInit))
325 g_HmR0.rcInit = hmR0FirstRcGetStatus(&FirstRc);
326 }
327
328 if (RT_SUCCESS(g_HmR0.rcInit))
329 {
330 /* Read CR4 and EFER for logging/diagnostic purposes. */
331 g_HmR0.hwvirt.u.vmx.u64HostCr4 = ASMGetCR4();
332 g_HmR0.hwvirt.u.vmx.u64HostMsrEfer = ASMRdMsr(MSR_K6_EFER);
333
334 /* Get VMX MSRs for determining VMX features we can ultimately use. */
335 SUPR0GetHwvirtMsrs(&g_HmR0.hwvirt.Msrs, SUPVTCAPS_VT_X, false /* fForce */);
336
337 /*
338 * Nested KVM workaround: Intel SDM section 34.15.5 describes that
339 * MSR_IA32_SMM_MONITOR_CTL depends on bit 49 of MSR_IA32_VMX_BASIC while
340 * table 35-2 says that this MSR is available if either VMX or SMX is supported.
341 */
342 uint64_t const uVmxBasicMsr = g_HmR0.hwvirt.Msrs.u.vmx.u64Basic;
343 if (RT_BF_GET(uVmxBasicMsr, VMX_BF_BASIC_DUAL_MON))
344 g_HmR0.hwvirt.u.vmx.u64HostSmmMonitorCtl = ASMRdMsr(MSR_IA32_SMM_MONITOR_CTL);
345
346 /* Initialize VPID - 16 bits ASID. */
347 g_HmR0.hwvirt.uMaxAsid = 0x10000; /* exclusive */
348
349 /*
350 * If the host OS has not enabled VT-x for us, try enter VMX root mode
351 * to really verify if VT-x is usable.
352 */
353 if (!g_HmR0.hwvirt.u.vmx.fUsingSUPR0EnableVTx)
354 {
355 /* Allocate a temporary VMXON region. */
356 RTR0MEMOBJ hScatchMemObj;
357 rc = RTR0MemObjAllocCont(&hScatchMemObj, PAGE_SIZE, false /* fExecutable */);
358 if (RT_FAILURE(rc))
359 {
360 LogRel(("hmR0InitIntel: RTR0MemObjAllocCont(,PAGE_SIZE,false) -> %Rrc\n", rc));
361 return rc;
362 }
363 void *pvScatchPage = RTR0MemObjAddress(hScatchMemObj);
364 RTHCPHYS const HCPhysScratchPage = RTR0MemObjGetPagePhysAddr(hScatchMemObj, 0);
365 ASMMemZeroPage(pvScatchPage);
366
367 /* Set revision dword at the beginning of the VMXON structure. */
368 *(uint32_t *)pvScatchPage = RT_BF_GET(uVmxBasicMsr, VMX_BF_BASIC_VMCS_ID);
369
370 /* Make sure we don't get rescheduled to another CPU during this probe. */
371 RTCCUINTREG const fEFlags = ASMIntDisableFlags();
372
373 /* Enable CR4.VMXE if it isn't already set. */
374 RTCCUINTREG const uOldCr4 = SUPR0ChangeCR4(X86_CR4_VMXE, RTCCUINTREG_MAX);
375
376 /*
377 * The only way of checking if we're in VMX root mode or not is to try and enter it.
378 * There is no instruction or control bit that tells us if we're in VMX root mode.
379 * Therefore, try and enter VMX root mode here.
380 */
381 rc = VMXEnable(HCPhysScratchPage);
382 if (RT_SUCCESS(rc))
383 {
384 g_HmR0.hwvirt.u.vmx.fSupported = true;
385 VMXDisable();
386 }
387 else
388 {
389 /*
390 * KVM leaves the CPU in VMX root mode. Not only is this not allowed,
391 * it will crash the host when we enter raw mode, because:
392 *
393 * (a) clearing X86_CR4_VMXE in CR4 causes a #GP (we no longer modify
394 * this bit), and
395 * (b) turning off paging causes a #GP (unavoidable when switching
396 * from long to 32 bits mode or 32 bits to PAE).
397 *
398 * They should fix their code, but until they do we simply refuse to run.
399 */
400 g_HmR0.rcInit = VERR_VMX_IN_VMX_ROOT_MODE;
401 Assert(g_HmR0.hwvirt.u.vmx.fSupported == false);
402 }
403
404 /* Restore CR4.VMXE if it wasn't set prior to us setting it above. */
405 if (!(uOldCr4 & X86_CR4_VMXE))
406 SUPR0ChangeCR4(0 /* fOrMask */, ~(uint64_t)X86_CR4_VMXE);
407
408 /* Restore interrupts. */
409 ASMSetFlags(fEFlags);
410
411 RTR0MemObjFree(hScatchMemObj, false);
412 }
413
414 if (g_HmR0.hwvirt.u.vmx.fSupported)
415 {
416 rc = VMXR0GlobalInit();
417 if (RT_FAILURE(rc))
418 g_HmR0.rcInit = rc;
419
420 /*
421 * Install the VT-x methods.
422 */
423 g_HmR0.pfnEnterSession = VMXR0Enter;
424 g_HmR0.pfnThreadCtxCallback = VMXR0ThreadCtxCallback;
425 g_HmR0.pfnCallRing3Callback = VMXR0CallRing3Callback;
426 g_HmR0.pfnExportHostState = VMXR0ExportHostState;
427 g_HmR0.pfnRunGuestCode = VMXR0RunGuestCode;
428 g_HmR0.pfnEnableCpu = VMXR0EnableCpu;
429 g_HmR0.pfnDisableCpu = VMXR0DisableCpu;
430 g_HmR0.pfnInitVM = VMXR0InitVM;
431 g_HmR0.pfnTermVM = VMXR0TermVM;
432 g_HmR0.pfnSetupVM = VMXR0SetupVM;
433
434 /*
435 * Check for the VMX-Preemption Timer and adjust for the "VMX-Preemption
436 * Timer Does Not Count Down at the Rate Specified" CPU erratum.
437 */
438 VMXCTLSMSR PinCtls;
439 PinCtls.u = g_HmR0.hwvirt.Msrs.u.vmx.u64PinCtls;
440 if (PinCtls.n.allowed1 & VMX_PIN_CTLS_PREEMPT_TIMER)
441 {
442 uint64_t const uVmxMiscMsr = g_HmR0.hwvirt.Msrs.u.vmx.u64Misc;
443 g_HmR0.hwvirt.u.vmx.fUsePreemptTimer = true;
444 g_HmR0.hwvirt.u.vmx.cPreemptTimerShift = RT_BF_GET(uVmxMiscMsr, VMX_BF_MISC_PREEMPT_TIMER_TSC);
445 if (HMIsSubjectToVmxPreemptTimerErratum())
446 g_HmR0.hwvirt.u.vmx.cPreemptTimerShift = 0; /* This is about right most of the time here. */
447 }
448 }
449 }
450#ifdef LOG_ENABLED
451 else
452 SUPR0Printf("hmR0InitIntelCpu failed with rc=%Rrc\n", g_HmR0.rcInit);
453#endif
454 return VINF_SUCCESS;
455}
456
457
458/**
459 * AMD-specific initialization code.
460 *
461 * @returns VBox status code (will only fail if out of memory).
462 */
463static int hmR0InitAmd(void)
464{
465 /* Call the global AMD-V initialization routine (should only fail in out-of-memory situations). */
466 int rc = SVMR0GlobalInit();
467 if (RT_FAILURE(rc))
468 {
469 g_HmR0.rcInit = rc;
470 return rc;
471 }
472
473 /*
474 * Install the AMD-V methods.
475 */
476 g_HmR0.pfnEnterSession = SVMR0Enter;
477 g_HmR0.pfnThreadCtxCallback = SVMR0ThreadCtxCallback;
478 g_HmR0.pfnCallRing3Callback = SVMR0CallRing3Callback;
479 g_HmR0.pfnExportHostState = SVMR0ExportHostState;
480 g_HmR0.pfnRunGuestCode = SVMR0RunGuestCode;
481 g_HmR0.pfnEnableCpu = SVMR0EnableCpu;
482 g_HmR0.pfnDisableCpu = SVMR0DisableCpu;
483 g_HmR0.pfnInitVM = SVMR0InitVM;
484 g_HmR0.pfnTermVM = SVMR0TermVM;
485 g_HmR0.pfnSetupVM = SVMR0SetupVM;
486
487 /* Query AMD features. */
488 uint32_t u32Dummy;
489 ASMCpuId(0x8000000a, &g_HmR0.hwvirt.u.svm.u32Rev, &g_HmR0.hwvirt.uMaxAsid, &u32Dummy, &g_HmR0.hwvirt.u.svm.u32Features);
490
491 /*
492 * We need to check if AMD-V has been properly initialized on all CPUs.
493 * Some BIOSes might do a poor job.
494 */
495 HMR0FIRSTRC FirstRc;
496 hmR0FirstRcInit(&FirstRc);
497 rc = RTMpOnAll(hmR0InitAmdCpu, &FirstRc, NULL);
498 AssertRC(rc);
499 if (RT_SUCCESS(rc))
500 rc = hmR0FirstRcGetStatus(&FirstRc);
501#ifndef DEBUG_bird
502 AssertMsg(rc == VINF_SUCCESS || rc == VERR_SVM_IN_USE,
503 ("hmR0InitAmdCpu failed for cpu %d with rc=%Rrc\n", hmR0FirstRcGetCpuId(&FirstRc), rc));
504#endif
505 if (RT_SUCCESS(rc))
506 {
507 SUPR0GetHwvirtMsrs(&g_HmR0.hwvirt.Msrs, SUPVTCAPS_AMD_V, false /* fForce */);
508 g_HmR0.hwvirt.u.svm.fSupported = true;
509 }
510 else
511 {
512 g_HmR0.rcInit = rc;
513 if (rc == VERR_SVM_DISABLED || rc == VERR_SVM_IN_USE)
514 rc = VINF_SUCCESS; /* Don't fail if AMD-V is disabled or in use. */
515 }
516 return rc;
517}
518
519
520/**
521 * Does global Ring-0 HM initialization (at module init).
522 *
523 * @returns VBox status code.
524 */
525VMMR0_INT_DECL(int) HMR0Init(void)
526{
527 /*
528 * Initialize the globals.
529 */
530 g_HmR0.fEnabled = false;
531 static RTONCE s_OnceInit = RTONCE_INITIALIZER;
532 g_HmR0.EnableAllCpusOnce = s_OnceInit;
533 for (unsigned i = 0; i < RT_ELEMENTS(g_HmR0.aCpuInfo); i++)
534 {
535 g_HmR0.aCpuInfo[i].idCpu = NIL_RTCPUID;
536 g_HmR0.aCpuInfo[i].hMemObj = NIL_RTR0MEMOBJ;
537 g_HmR0.aCpuInfo[i].HCPhysMemObj = NIL_RTHCPHYS;
538 g_HmR0.aCpuInfo[i].pvMemObj = NULL;
539#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
540 g_HmR0.aCpuInfo[i].n.svm.hNstGstMsrpm = NIL_RTR0MEMOBJ;
541 g_HmR0.aCpuInfo[i].n.svm.HCPhysNstGstMsrpm = NIL_RTHCPHYS;
542 g_HmR0.aCpuInfo[i].n.svm.pvNstGstMsrpm = NULL;
543#endif
544 }
545
546 /* Fill in all callbacks with placeholders. */
547 g_HmR0.pfnEnterSession = hmR0DummyEnter;
548 g_HmR0.pfnThreadCtxCallback = hmR0DummyThreadCtxCallback;
549 g_HmR0.pfnCallRing3Callback = hmR0DummyCallRing3Callback;
550 g_HmR0.pfnExportHostState = hmR0DummyExportHostState;
551 g_HmR0.pfnRunGuestCode = hmR0DummyRunGuestCode;
552 g_HmR0.pfnEnableCpu = hmR0DummyEnableCpu;
553 g_HmR0.pfnDisableCpu = hmR0DummyDisableCpu;
554 g_HmR0.pfnInitVM = hmR0DummyInitVM;
555 g_HmR0.pfnTermVM = hmR0DummyTermVM;
556 g_HmR0.pfnSetupVM = hmR0DummySetupVM;
557
558 /* Default is global VT-x/AMD-V init. */
559 g_HmR0.fGlobalInit = true;
560
561 /*
562 * Make sure aCpuInfo is big enough for all the CPUs on this system.
563 */
564 if (RTMpGetArraySize() > RT_ELEMENTS(g_HmR0.aCpuInfo))
565 {
566 LogRel(("HM: Too many real CPUs/cores/threads - %u, max %u\n", RTMpGetArraySize(), RT_ELEMENTS(g_HmR0.aCpuInfo)));
567 return VERR_TOO_MANY_CPUS;
568 }
569
570 /*
571 * Check for VT-x or AMD-V support.
572 * Return failure only in out-of-memory situations.
573 */
574 uint32_t fCaps = 0;
575 int rc = SUPR0GetVTSupport(&fCaps);
576 if (RT_SUCCESS(rc))
577 {
578 if (fCaps & SUPVTCAPS_VT_X)
579 {
580 rc = hmR0InitIntel();
581 if (RT_FAILURE(rc))
582 return rc;
583 }
584 else
585 {
586 Assert(fCaps & SUPVTCAPS_AMD_V);
587 rc = hmR0InitAmd();
588 if (RT_FAILURE(rc))
589 return rc;
590 }
591 }
592 else
593 g_HmR0.rcInit = VERR_UNSUPPORTED_CPU;
594
595 /*
596 * Register notification callbacks that we can use to disable/enable CPUs
597 * when brought offline/online or suspending/resuming.
598 */
599 if (!g_HmR0.hwvirt.u.vmx.fUsingSUPR0EnableVTx)
600 {
601 rc = RTMpNotificationRegister(hmR0MpEventCallback, NULL);
602 AssertRC(rc);
603
604 rc = RTPowerNotificationRegister(hmR0PowerCallback, NULL);
605 AssertRC(rc);
606 }
607
608 /* We return success here because module init shall not fail if HM fails to initialize. */
609 return VINF_SUCCESS;
610}
611
612
613/**
614 * Does global Ring-0 HM termination (at module termination).
615 *
616 * @returns VBox status code.
617 */
618VMMR0_INT_DECL(int) HMR0Term(void)
619{
620 int rc;
621 if ( g_HmR0.hwvirt.u.vmx.fSupported
622 && g_HmR0.hwvirt.u.vmx.fUsingSUPR0EnableVTx)
623 {
624 /*
625 * Simple if the host OS manages VT-x.
626 */
627 Assert(g_HmR0.fGlobalInit);
628
629 if (g_HmR0.hwvirt.u.vmx.fCalledSUPR0EnableVTx)
630 {
631 rc = SUPR0EnableVTx(false /* fEnable */);
632 g_HmR0.hwvirt.u.vmx.fCalledSUPR0EnableVTx = false;
633 }
634 else
635 rc = VINF_SUCCESS;
636
637 for (unsigned iCpu = 0; iCpu < RT_ELEMENTS(g_HmR0.aCpuInfo); iCpu++)
638 {
639 g_HmR0.aCpuInfo[iCpu].fConfigured = false;
640 Assert(g_HmR0.aCpuInfo[iCpu].hMemObj == NIL_RTR0MEMOBJ);
641 }
642 }
643 else
644 {
645 Assert(!g_HmR0.hwvirt.u.vmx.fSupported || !g_HmR0.hwvirt.u.vmx.fUsingSUPR0EnableVTx);
646
647 /* Doesn't really matter if this fails. */
648 rc = RTMpNotificationDeregister(hmR0MpEventCallback, NULL); AssertRC(rc);
649 rc = RTPowerNotificationDeregister(hmR0PowerCallback, NULL); AssertRC(rc);
650
651 /*
652 * Disable VT-x/AMD-V on all CPUs if we enabled it before.
653 */
654 if (g_HmR0.fGlobalInit)
655 {
656 HMR0FIRSTRC FirstRc;
657 hmR0FirstRcInit(&FirstRc);
658 rc = RTMpOnAll(hmR0DisableCpuCallback, NULL /* pvUser 1 */, &FirstRc);
659 Assert(RT_SUCCESS(rc) || rc == VERR_NOT_SUPPORTED);
660 if (RT_SUCCESS(rc))
661 rc = hmR0FirstRcGetStatus(&FirstRc);
662 }
663
664 /*
665 * Free the per-cpu pages used for VT-x and AMD-V.
666 */
667 for (unsigned i = 0; i < RT_ELEMENTS(g_HmR0.aCpuInfo); i++)
668 {
669 if (g_HmR0.aCpuInfo[i].hMemObj != NIL_RTR0MEMOBJ)
670 {
671 RTR0MemObjFree(g_HmR0.aCpuInfo[i].hMemObj, false);
672 g_HmR0.aCpuInfo[i].hMemObj = NIL_RTR0MEMOBJ;
673 g_HmR0.aCpuInfo[i].HCPhysMemObj = NIL_RTHCPHYS;
674 g_HmR0.aCpuInfo[i].pvMemObj = NULL;
675 }
676#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
677 if (g_HmR0.aCpuInfo[i].n.svm.hNstGstMsrpm != NIL_RTR0MEMOBJ)
678 {
679 RTR0MemObjFree(g_HmR0.aCpuInfo[i].n.svm.hNstGstMsrpm, false);
680 g_HmR0.aCpuInfo[i].n.svm.hNstGstMsrpm = NIL_RTR0MEMOBJ;
681 g_HmR0.aCpuInfo[i].n.svm.HCPhysNstGstMsrpm = NIL_RTHCPHYS;
682 g_HmR0.aCpuInfo[i].n.svm.pvNstGstMsrpm = NULL;
683 }
684#endif
685 }
686 }
687
688 /** @todo This needs cleaning up. There's no matching
689 * hmR0TermIntel()/hmR0TermAmd() and all the VT-x/AMD-V specific bits
690 * should move into their respective modules. */
691 /* Finally, call global VT-x/AMD-V termination. */
692 if (g_HmR0.hwvirt.u.vmx.fSupported)
693 VMXR0GlobalTerm();
694 else if (g_HmR0.hwvirt.u.svm.fSupported)
695 SVMR0GlobalTerm();
696
697 return rc;
698}
699
700
701/**
702 * Worker function used by hmR0PowerCallback() and HMR0Init() to initalize VT-x
703 * on a CPU.
704 *
705 * @param idCpu The identifier for the CPU the function is called on.
706 * @param pvUser1 Pointer to the first RC structure.
707 * @param pvUser2 Ignored.
708 */
709static DECLCALLBACK(void) hmR0InitIntelCpu(RTCPUID idCpu, void *pvUser1, void *pvUser2)
710{
711 PHMR0FIRSTRC pFirstRc = (PHMR0FIRSTRC)pvUser1;
712 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
713 Assert(idCpu == (RTCPUID)RTMpCpuIdToSetIndex(idCpu)); /** @todo fix idCpu == index assumption (rainy day) */
714 NOREF(idCpu); NOREF(pvUser2);
715
716 int rc = SUPR0GetVmxUsability(NULL /* pfIsSmxModeAmbiguous */);
717 hmR0FirstRcSetStatus(pFirstRc, rc);
718}
719
720
721/**
722 * Worker function used by hmR0PowerCallback() and HMR0Init() to initalize AMD-V
723 * on a CPU.
724 *
725 * @param idCpu The identifier for the CPU the function is called on.
726 * @param pvUser1 Pointer to the first RC structure.
727 * @param pvUser2 Ignored.
728 */
729static DECLCALLBACK(void) hmR0InitAmdCpu(RTCPUID idCpu, void *pvUser1, void *pvUser2)
730{
731 PHMR0FIRSTRC pFirstRc = (PHMR0FIRSTRC)pvUser1;
732 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
733 Assert(idCpu == (RTCPUID)RTMpCpuIdToSetIndex(idCpu)); /** @todo fix idCpu == index assumption (rainy day) */
734 NOREF(idCpu); NOREF(pvUser2);
735
736 int rc = SUPR0GetSvmUsability(true /* fInitSvm */);
737 hmR0FirstRcSetStatus(pFirstRc, rc);
738}
739
740
741/**
742 * Enable VT-x or AMD-V on the current CPU
743 *
744 * @returns VBox status code.
745 * @param pVM The cross context VM structure. Can be NULL.
746 * @param idCpu The identifier for the CPU the function is called on.
747 *
748 * @remarks Maybe called with interrupts disabled!
749 */
750static int hmR0EnableCpu(PVMCC pVM, RTCPUID idCpu)
751{
752 PHMPHYSCPU pHostCpu = &g_HmR0.aCpuInfo[idCpu];
753
754 Assert(idCpu == (RTCPUID)RTMpCpuIdToSetIndex(idCpu)); /** @todo fix idCpu == index assumption (rainy day) */
755 Assert(idCpu < RT_ELEMENTS(g_HmR0.aCpuInfo));
756 Assert(!pHostCpu->fConfigured);
757 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
758
759 pHostCpu->idCpu = idCpu;
760 /* Do NOT reset cTlbFlushes here, see @bugref{6255}. */
761
762 int rc;
763 if ( g_HmR0.hwvirt.u.vmx.fSupported
764 && g_HmR0.hwvirt.u.vmx.fUsingSUPR0EnableVTx)
765 rc = g_HmR0.pfnEnableCpu(pHostCpu, pVM, NULL /* pvCpuPage */, NIL_RTHCPHYS, true, &g_HmR0.hwvirt.Msrs);
766 else
767 {
768 AssertLogRelMsgReturn(pHostCpu->hMemObj != NIL_RTR0MEMOBJ, ("hmR0EnableCpu failed idCpu=%u.\n", idCpu), VERR_HM_IPE_1);
769 rc = g_HmR0.pfnEnableCpu(pHostCpu, pVM, pHostCpu->pvMemObj, pHostCpu->HCPhysMemObj, false, &g_HmR0.hwvirt.Msrs);
770 }
771 if (RT_SUCCESS(rc))
772 pHostCpu->fConfigured = true;
773 return rc;
774}
775
776
777/**
778 * Worker function passed to RTMpOnAll() that is to be called on all CPUs.
779 *
780 * @param idCpu The identifier for the CPU the function is called on.
781 * @param pvUser1 Opaque pointer to the VM (can be NULL!).
782 * @param pvUser2 The 2nd user argument.
783 */
784static DECLCALLBACK(void) hmR0EnableCpuCallback(RTCPUID idCpu, void *pvUser1, void *pvUser2)
785{
786 PVMCC pVM = (PVMCC)pvUser1; /* can be NULL! */
787 PHMR0FIRSTRC pFirstRc = (PHMR0FIRSTRC)pvUser2;
788 AssertReturnVoid(g_HmR0.fGlobalInit);
789 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
790 hmR0FirstRcSetStatus(pFirstRc, hmR0EnableCpu(pVM, idCpu));
791}
792
793
794/**
795 * RTOnce callback employed by HMR0EnableAllCpus.
796 *
797 * @returns VBox status code.
798 * @param pvUser Pointer to the VM.
799 */
800static DECLCALLBACK(int32_t) hmR0EnableAllCpuOnce(void *pvUser)
801{
802 PVMCC pVM = (PVMCC)pvUser;
803
804 /*
805 * Indicate that we've initialized.
806 *
807 * Note! There is a potential race between this function and the suspend
808 * notification. Kind of unlikely though, so ignored for now.
809 */
810 AssertReturn(!g_HmR0.fEnabled, VERR_HM_ALREADY_ENABLED_IPE);
811 ASMAtomicWriteBool(&g_HmR0.fEnabled, true);
812
813 /*
814 * The global init variable is set by the first VM.
815 */
816 g_HmR0.fGlobalInit = pVM->hm.s.fGlobalInit;
817
818#ifdef VBOX_STRICT
819 for (unsigned i = 0; i < RT_ELEMENTS(g_HmR0.aCpuInfo); i++)
820 {
821 Assert(g_HmR0.aCpuInfo[i].hMemObj == NIL_RTR0MEMOBJ);
822 Assert(g_HmR0.aCpuInfo[i].HCPhysMemObj == NIL_RTHCPHYS);
823 Assert(g_HmR0.aCpuInfo[i].pvMemObj == NULL);
824 Assert(!g_HmR0.aCpuInfo[i].fConfigured);
825 Assert(!g_HmR0.aCpuInfo[i].cTlbFlushes);
826 Assert(!g_HmR0.aCpuInfo[i].uCurrentAsid);
827# ifdef VBOX_WITH_NESTED_HWVIRT_SVM
828 Assert(g_HmR0.aCpuInfo[i].n.svm.hNstGstMsrpm == NIL_RTR0MEMOBJ);
829 Assert(g_HmR0.aCpuInfo[i].n.svm.HCPhysNstGstMsrpm == NIL_RTHCPHYS);
830 Assert(g_HmR0.aCpuInfo[i].n.svm.pvNstGstMsrpm == NULL);
831# endif
832 }
833#endif
834
835 int rc;
836 if ( g_HmR0.hwvirt.u.vmx.fSupported
837 && g_HmR0.hwvirt.u.vmx.fUsingSUPR0EnableVTx)
838 {
839 /*
840 * Global VT-x initialization API (only darwin for now).
841 */
842 rc = SUPR0EnableVTx(true /* fEnable */);
843 if (RT_SUCCESS(rc))
844 {
845 g_HmR0.hwvirt.u.vmx.fCalledSUPR0EnableVTx = true;
846 /* If the host provides a VT-x init API, then we'll rely on that for global init. */
847 g_HmR0.fGlobalInit = pVM->hm.s.fGlobalInit = true;
848 }
849 else
850 AssertMsgFailed(("hmR0EnableAllCpuOnce/SUPR0EnableVTx: rc=%Rrc\n", rc));
851 }
852 else
853 {
854 /*
855 * We're doing the job ourselves.
856 */
857 /* Allocate one page per cpu for the global VT-x and AMD-V pages */
858 for (unsigned i = 0; i < RT_ELEMENTS(g_HmR0.aCpuInfo); i++)
859 {
860 Assert(g_HmR0.aCpuInfo[i].hMemObj == NIL_RTR0MEMOBJ);
861#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
862 Assert(g_HmR0.aCpuInfo[i].n.svm.hNstGstMsrpm == NIL_RTR0MEMOBJ);
863#endif
864 if (RTMpIsCpuPossible(RTMpCpuIdFromSetIndex(i)))
865 {
866 /** @todo NUMA */
867 rc = RTR0MemObjAllocCont(&g_HmR0.aCpuInfo[i].hMemObj, PAGE_SIZE, false /* executable R0 mapping */);
868 AssertLogRelRCReturn(rc, rc);
869
870 g_HmR0.aCpuInfo[i].HCPhysMemObj = RTR0MemObjGetPagePhysAddr(g_HmR0.aCpuInfo[i].hMemObj, 0);
871 Assert(g_HmR0.aCpuInfo[i].HCPhysMemObj != NIL_RTHCPHYS);
872 Assert(!(g_HmR0.aCpuInfo[i].HCPhysMemObj & PAGE_OFFSET_MASK));
873
874 g_HmR0.aCpuInfo[i].pvMemObj = RTR0MemObjAddress(g_HmR0.aCpuInfo[i].hMemObj);
875 AssertPtr(g_HmR0.aCpuInfo[i].pvMemObj);
876 ASMMemZeroPage(g_HmR0.aCpuInfo[i].pvMemObj);
877
878#ifdef VBOX_WITH_NESTED_HWVIRT_SVM
879 rc = RTR0MemObjAllocCont(&g_HmR0.aCpuInfo[i].n.svm.hNstGstMsrpm, SVM_MSRPM_PAGES << X86_PAGE_4K_SHIFT,
880 false /* executable R0 mapping */);
881 AssertLogRelRCReturn(rc, rc);
882
883 g_HmR0.aCpuInfo[i].n.svm.HCPhysNstGstMsrpm = RTR0MemObjGetPagePhysAddr(g_HmR0.aCpuInfo[i].n.svm.hNstGstMsrpm, 0);
884 Assert(g_HmR0.aCpuInfo[i].n.svm.HCPhysNstGstMsrpm != NIL_RTHCPHYS);
885 Assert(!(g_HmR0.aCpuInfo[i].n.svm.HCPhysNstGstMsrpm & PAGE_OFFSET_MASK));
886
887 g_HmR0.aCpuInfo[i].n.svm.pvNstGstMsrpm = RTR0MemObjAddress(g_HmR0.aCpuInfo[i].n.svm.hNstGstMsrpm);
888 AssertPtr(g_HmR0.aCpuInfo[i].n.svm.pvNstGstMsrpm);
889 ASMMemFill32(g_HmR0.aCpuInfo[i].n.svm.pvNstGstMsrpm, SVM_MSRPM_PAGES << X86_PAGE_4K_SHIFT, UINT32_C(0xffffffff));
890#endif
891 }
892 }
893
894 rc = VINF_SUCCESS;
895 }
896
897 if ( RT_SUCCESS(rc)
898 && g_HmR0.fGlobalInit)
899 {
900 /* First time, so initialize each cpu/core. */
901 HMR0FIRSTRC FirstRc;
902 hmR0FirstRcInit(&FirstRc);
903 rc = RTMpOnAll(hmR0EnableCpuCallback, (void *)pVM, &FirstRc);
904 if (RT_SUCCESS(rc))
905 rc = hmR0FirstRcGetStatus(&FirstRc);
906 }
907
908 return rc;
909}
910
911
912/**
913 * Sets up HM on all cpus.
914 *
915 * @returns VBox status code.
916 * @param pVM The cross context VM structure.
917 */
918VMMR0_INT_DECL(int) HMR0EnableAllCpus(PVMCC pVM)
919{
920 /* Make sure we don't touch HM after we've disabled HM in preparation of a suspend. */
921 if (ASMAtomicReadBool(&g_HmR0.fSuspended))
922 return VERR_HM_SUSPEND_PENDING;
923
924 return RTOnce(&g_HmR0.EnableAllCpusOnce, hmR0EnableAllCpuOnce, pVM);
925}
926
927
928/**
929 * Disable VT-x or AMD-V on the current CPU.
930 *
931 * @returns VBox status code.
932 * @param idCpu The identifier for the CPU this function is called on.
933 *
934 * @remarks Must be called with preemption disabled.
935 */
936static int hmR0DisableCpu(RTCPUID idCpu)
937{
938 PHMPHYSCPU pHostCpu = &g_HmR0.aCpuInfo[idCpu];
939
940 Assert(!g_HmR0.hwvirt.u.vmx.fSupported || !g_HmR0.hwvirt.u.vmx.fUsingSUPR0EnableVTx);
941 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
942 Assert(idCpu == (RTCPUID)RTMpCpuIdToSetIndex(idCpu)); /** @todo fix idCpu == index assumption (rainy day) */
943 Assert(idCpu < RT_ELEMENTS(g_HmR0.aCpuInfo));
944 Assert(!pHostCpu->fConfigured || pHostCpu->hMemObj != NIL_RTR0MEMOBJ);
945 AssertRelease(idCpu == RTMpCpuId());
946
947 if (pHostCpu->hMemObj == NIL_RTR0MEMOBJ)
948 return pHostCpu->fConfigured ? VERR_NO_MEMORY : VINF_SUCCESS /* not initialized. */;
949 AssertPtr(pHostCpu->pvMemObj);
950 Assert(pHostCpu->HCPhysMemObj != NIL_RTHCPHYS);
951
952 int rc;
953 if (pHostCpu->fConfigured)
954 {
955 rc = g_HmR0.pfnDisableCpu(pHostCpu, pHostCpu->pvMemObj, pHostCpu->HCPhysMemObj);
956 AssertRCReturn(rc, rc);
957
958 pHostCpu->fConfigured = false;
959 pHostCpu->idCpu = NIL_RTCPUID;
960 }
961 else
962 rc = VINF_SUCCESS; /* nothing to do */
963 return rc;
964}
965
966
967/**
968 * Worker function passed to RTMpOnAll() that is to be called on the target
969 * CPUs.
970 *
971 * @param idCpu The identifier for the CPU the function is called on.
972 * @param pvUser1 The 1st user argument.
973 * @param pvUser2 Opaque pointer to the FirstRc.
974 */
975static DECLCALLBACK(void) hmR0DisableCpuCallback(RTCPUID idCpu, void *pvUser1, void *pvUser2)
976{
977 PHMR0FIRSTRC pFirstRc = (PHMR0FIRSTRC)pvUser2; NOREF(pvUser1);
978 AssertReturnVoid(g_HmR0.fGlobalInit);
979 hmR0FirstRcSetStatus(pFirstRc, hmR0DisableCpu(idCpu));
980}
981
982
983/**
984 * Worker function passed to RTMpOnSpecific() that is to be called on the target
985 * CPU.
986 *
987 * @param idCpu The identifier for the CPU the function is called on.
988 * @param pvUser1 Null, not used.
989 * @param pvUser2 Null, not used.
990 */
991static DECLCALLBACK(void) hmR0DisableCpuOnSpecificCallback(RTCPUID idCpu, void *pvUser1, void *pvUser2)
992{
993 NOREF(pvUser1);
994 NOREF(pvUser2);
995 hmR0DisableCpu(idCpu);
996}
997
998
999/**
1000 * Callback function invoked when a cpu goes online or offline.
1001 *
1002 * @param enmEvent The Mp event.
1003 * @param idCpu The identifier for the CPU the function is called on.
1004 * @param pvData Opaque data (PVMCC pointer).
1005 */
1006static DECLCALLBACK(void) hmR0MpEventCallback(RTMPEVENT enmEvent, RTCPUID idCpu, void *pvData)
1007{
1008 NOREF(pvData);
1009 Assert(!g_HmR0.hwvirt.u.vmx.fSupported || !g_HmR0.hwvirt.u.vmx.fUsingSUPR0EnableVTx);
1010
1011 /*
1012 * We only care about uninitializing a CPU that is going offline. When a
1013 * CPU comes online, the initialization is done lazily in HMR0Enter().
1014 */
1015 switch (enmEvent)
1016 {
1017 case RTMPEVENT_OFFLINE:
1018 {
1019 RTTHREADPREEMPTSTATE PreemptState = RTTHREADPREEMPTSTATE_INITIALIZER;
1020 RTThreadPreemptDisable(&PreemptState);
1021 if (idCpu == RTMpCpuId())
1022 {
1023 int rc = hmR0DisableCpu(idCpu);
1024 AssertRC(rc);
1025 RTThreadPreemptRestore(&PreemptState);
1026 }
1027 else
1028 {
1029 RTThreadPreemptRestore(&PreemptState);
1030 RTMpOnSpecific(idCpu, hmR0DisableCpuOnSpecificCallback, NULL /* pvUser1 */, NULL /* pvUser2 */);
1031 }
1032 break;
1033 }
1034
1035 default:
1036 break;
1037 }
1038}
1039
1040
1041/**
1042 * Called whenever a system power state change occurs.
1043 *
1044 * @param enmEvent The Power event.
1045 * @param pvUser User argument.
1046 */
1047static DECLCALLBACK(void) hmR0PowerCallback(RTPOWEREVENT enmEvent, void *pvUser)
1048{
1049 NOREF(pvUser);
1050 Assert(!g_HmR0.hwvirt.u.vmx.fSupported || !g_HmR0.hwvirt.u.vmx.fUsingSUPR0EnableVTx);
1051
1052#ifdef LOG_ENABLED
1053 if (enmEvent == RTPOWEREVENT_SUSPEND)
1054 SUPR0Printf("hmR0PowerCallback RTPOWEREVENT_SUSPEND\n");
1055 else
1056 SUPR0Printf("hmR0PowerCallback RTPOWEREVENT_RESUME\n");
1057#endif
1058
1059 if (enmEvent == RTPOWEREVENT_SUSPEND)
1060 ASMAtomicWriteBool(&g_HmR0.fSuspended, true);
1061
1062 if (g_HmR0.fEnabled)
1063 {
1064 int rc;
1065 HMR0FIRSTRC FirstRc;
1066 hmR0FirstRcInit(&FirstRc);
1067
1068 if (enmEvent == RTPOWEREVENT_SUSPEND)
1069 {
1070 if (g_HmR0.fGlobalInit)
1071 {
1072 /* Turn off VT-x or AMD-V on all CPUs. */
1073 rc = RTMpOnAll(hmR0DisableCpuCallback, NULL /* pvUser 1 */, &FirstRc);
1074 Assert(RT_SUCCESS(rc) || rc == VERR_NOT_SUPPORTED);
1075 }
1076 /* else nothing to do here for the local init case */
1077 }
1078 else
1079 {
1080 /* Reinit the CPUs from scratch as the suspend state might have
1081 messed with the MSRs. (lousy BIOSes as usual) */
1082 if (g_HmR0.hwvirt.u.vmx.fSupported)
1083 rc = RTMpOnAll(hmR0InitIntelCpu, &FirstRc, NULL);
1084 else
1085 rc = RTMpOnAll(hmR0InitAmdCpu, &FirstRc, NULL);
1086 Assert(RT_SUCCESS(rc) || rc == VERR_NOT_SUPPORTED);
1087 if (RT_SUCCESS(rc))
1088 rc = hmR0FirstRcGetStatus(&FirstRc);
1089#ifdef LOG_ENABLED
1090 if (RT_FAILURE(rc))
1091 SUPR0Printf("hmR0PowerCallback hmR0InitXxxCpu failed with %Rc\n", rc);
1092#endif
1093 if (g_HmR0.fGlobalInit)
1094 {
1095 /* Turn VT-x or AMD-V back on on all CPUs. */
1096 rc = RTMpOnAll(hmR0EnableCpuCallback, NULL /* pVM */, &FirstRc /* output ignored */);
1097 Assert(RT_SUCCESS(rc) || rc == VERR_NOT_SUPPORTED);
1098 }
1099 /* else nothing to do here for the local init case */
1100 }
1101 }
1102
1103 if (enmEvent == RTPOWEREVENT_RESUME)
1104 ASMAtomicWriteBool(&g_HmR0.fSuspended, false);
1105}
1106
1107
1108/**
1109 * Does ring-0 per-VM HM initialization.
1110 *
1111 * This will call the CPU specific init. routine which may initialize and allocate
1112 * resources for virtual CPUs.
1113 *
1114 * @returns VBox status code.
1115 * @param pVM The cross context VM structure.
1116 *
1117 * @remarks This is called after HMR3Init(), see vmR3CreateU() and
1118 * vmR3InitRing3().
1119 */
1120VMMR0_INT_DECL(int) HMR0InitVM(PVMCC pVM)
1121{
1122 AssertReturn(pVM, VERR_INVALID_PARAMETER);
1123
1124 /* Make sure we don't touch HM after we've disabled HM in preparation of a suspend. */
1125 if (ASMAtomicReadBool(&g_HmR0.fSuspended))
1126 return VERR_HM_SUSPEND_PENDING;
1127
1128 /*
1129 * Copy globals to the VM structure.
1130 */
1131 Assert(!(pVM->hm.s.vmx.fSupported && pVM->hm.s.svm.fSupported));
1132 if (pVM->hm.s.vmx.fSupported)
1133 {
1134 pVM->hm.s.vmx.fUsePreemptTimer &= g_HmR0.hwvirt.u.vmx.fUsePreemptTimer; /* Can be overridden by CFGM in HMR3Init(). */
1135 pVM->hm.s.vmx.cPreemptTimerShift = g_HmR0.hwvirt.u.vmx.cPreemptTimerShift;
1136 pVM->hm.s.vmx.u64HostCr4 = g_HmR0.hwvirt.u.vmx.u64HostCr4;
1137 pVM->hm.s.vmx.u64HostMsrEfer = g_HmR0.hwvirt.u.vmx.u64HostMsrEfer;
1138 pVM->hm.s.vmx.u64HostSmmMonitorCtl = g_HmR0.hwvirt.u.vmx.u64HostSmmMonitorCtl;
1139 HMGetVmxMsrsFromHwvirtMsrs(&g_HmR0.hwvirt.Msrs, &pVM->hm.s.vmx.Msrs);
1140 /* If you need to tweak host MSRs for testing VMX R0 code, do it here. */
1141
1142 /* Enable VPID if supported and configured. */
1143 if (pVM->hm.s.vmx.Msrs.ProcCtls2.n.allowed1 & VMX_PROC_CTLS2_VPID)
1144 pVM->hm.s.vmx.fVpid = pVM->hm.s.vmx.fAllowVpid; /* Can be overridden by CFGM in HMR3Init(). */
1145
1146 /* Use VMCS shadowing if supported. */
1147 Assert(!pVM->hm.s.vmx.fUseVmcsShadowing);
1148 if ( pVM->cpum.ro.GuestFeatures.fVmx
1149 && (pVM->hm.s.vmx.Msrs.ProcCtls2.n.allowed1 & VMX_PROC_CTLS2_VMCS_SHADOWING))
1150 pVM->hm.s.vmx.fUseVmcsShadowing = true;
1151
1152 /* Use the VMCS controls for swapping the EFER MSR if supported. */
1153 Assert(!pVM->hm.s.vmx.fSupportsVmcsEfer);
1154 if ( (pVM->hm.s.vmx.Msrs.EntryCtls.n.allowed1 & VMX_ENTRY_CTLS_LOAD_EFER_MSR)
1155 && (pVM->hm.s.vmx.Msrs.ExitCtls.n.allowed1 & VMX_EXIT_CTLS_LOAD_EFER_MSR)
1156 && (pVM->hm.s.vmx.Msrs.ExitCtls.n.allowed1 & VMX_EXIT_CTLS_SAVE_EFER_MSR))
1157 pVM->hm.s.vmx.fSupportsVmcsEfer = true;
1158
1159#if 0
1160 /* Enable APIC register virtualization and virtual-interrupt delivery if supported. */
1161 if ( (pVM->hm.s.vmx.Msrs.ProcCtls2.n.allowed1 & VMX_PROC_CTLS2_APIC_REG_VIRT)
1162 && (pVM->hm.s.vmx.Msrs.ProcCtls2.n.allowed1 & VMX_PROC_CTLS2_VIRT_INTR_DELIVERY))
1163 pVM->hm.s.fVirtApicRegs = true;
1164
1165 /* Enable posted-interrupt processing if supported. */
1166 /** @todo Add and query IPRT API for host OS support for posted-interrupt IPI
1167 * here. */
1168 if ( (pVM->hm.s.vmx.Msrs.PinCtls.n.allowed1 & VMX_PIN_CTLS_POSTED_INT)
1169 && (pVM->hm.s.vmx.Msrs.ExitCtls.n.allowed1 & VMX_EXIT_CTLS_ACK_EXT_INT))
1170 pVM->hm.s.fPostedIntrs = true;
1171#endif
1172 }
1173 else if (pVM->hm.s.svm.fSupported)
1174 {
1175 pVM->hm.s.svm.u32Rev = g_HmR0.hwvirt.u.svm.u32Rev;
1176 pVM->hm.s.svm.u32Features = g_HmR0.hwvirt.u.svm.u32Features;
1177 pVM->hm.s.svm.u64MsrHwcr = g_HmR0.hwvirt.Msrs.u.svm.u64MsrHwcr;
1178 /* If you need to tweak host MSRs for testing SVM R0 code, do it here. */
1179 }
1180 pVM->hm.s.rcInit = g_HmR0.rcInit;
1181 pVM->hm.s.uMaxAsid = g_HmR0.hwvirt.uMaxAsid;
1182
1183 /*
1184 * Set default maximum inner loops in ring-0 before returning to ring-3.
1185 * Can be overriden using CFGM.
1186 */
1187 if (!pVM->hm.s.cMaxResumeLoops)
1188 {
1189 pVM->hm.s.cMaxResumeLoops = 1024;
1190 if (RTThreadPreemptIsPendingTrusty())
1191 pVM->hm.s.cMaxResumeLoops = 8192;
1192 }
1193
1194 /*
1195 * Initialize some per-VCPU fields.
1196 */
1197 for (VMCPUID idCpu = 0; idCpu < pVM->cCpus; idCpu++)
1198 {
1199 PVMCPUCC pVCpu = VMCC_GET_CPU(pVM, idCpu);
1200 pVCpu->hm.s.idEnteredCpu = NIL_RTCPUID;
1201 pVCpu->hm.s.idLastCpu = NIL_RTCPUID;
1202
1203 /* We'll aways increment this the first time (host uses ASID 0). */
1204 AssertReturn(!pVCpu->hm.s.uCurrentAsid, VERR_HM_IPE_3);
1205 }
1206
1207 /*
1208 * Get host kernel features that HM might need to know in order
1209 * to co-operate and function properly with the host OS (e.g. SMAP).
1210 *
1211 * Technically, we could do this as part of the pre-init VM procedure
1212 * but it shouldn't be done later than this point so we do it here.
1213 */
1214 pVM->hm.s.fHostKernelFeatures = SUPR0GetKernelFeatures();
1215
1216 /*
1217 * Call the hardware specific initialization method.
1218 */
1219 return g_HmR0.pfnInitVM(pVM);
1220}
1221
1222
1223/**
1224 * Does ring-0 per VM HM termination.
1225 *
1226 * @returns VBox status code.
1227 * @param pVM The cross context VM structure.
1228 */
1229VMMR0_INT_DECL(int) HMR0TermVM(PVMCC pVM)
1230{
1231 Log(("HMR0TermVM: %p\n", pVM));
1232 AssertReturn(pVM, VERR_INVALID_PARAMETER);
1233
1234 /*
1235 * Call the hardware specific method.
1236 *
1237 * Note! We might be preparing for a suspend, so the pfnTermVM() functions should probably not
1238 * mess with VT-x/AMD-V features on the CPU, currently all they do is free memory so this is safe.
1239 */
1240 return g_HmR0.pfnTermVM(pVM);
1241}
1242
1243
1244/**
1245 * Sets up a VT-x or AMD-V session.
1246 *
1247 * This is mostly about setting up the hardware VM state.
1248 *
1249 * @returns VBox status code.
1250 * @param pVM The cross context VM structure.
1251 */
1252VMMR0_INT_DECL(int) HMR0SetupVM(PVMCC pVM)
1253{
1254 Log(("HMR0SetupVM: %p\n", pVM));
1255 AssertReturn(pVM, VERR_INVALID_PARAMETER);
1256
1257 /* Make sure we don't touch HM after we've disabled HM in preparation of a suspend. */
1258 AssertReturn(!ASMAtomicReadBool(&g_HmR0.fSuspended), VERR_HM_SUSPEND_PENDING);
1259
1260 /* On first entry we'll sync everything. */
1261 VMCC_FOR_EACH_VMCPU_STMT(pVM, pVCpu->hm.s.fCtxChanged |= HM_CHANGED_HOST_CONTEXT | HM_CHANGED_ALL_GUEST);
1262
1263 /*
1264 * Call the hardware specific setup VM method. This requires the CPU to be
1265 * enabled for AMD-V/VT-x and preemption to be prevented.
1266 */
1267 RTTHREADPREEMPTSTATE PreemptState = RTTHREADPREEMPTSTATE_INITIALIZER;
1268 RTThreadPreemptDisable(&PreemptState);
1269 RTCPUID const idCpu = RTMpCpuId();
1270
1271 /* Enable VT-x or AMD-V if local init is required. */
1272 int rc;
1273 if (!g_HmR0.fGlobalInit)
1274 {
1275 Assert(!g_HmR0.hwvirt.u.vmx.fSupported || !g_HmR0.hwvirt.u.vmx.fUsingSUPR0EnableVTx);
1276 rc = hmR0EnableCpu(pVM, idCpu);
1277 if (RT_FAILURE(rc))
1278 {
1279 RTThreadPreemptRestore(&PreemptState);
1280 return rc;
1281 }
1282 }
1283
1284 /* Setup VT-x or AMD-V. */
1285 rc = g_HmR0.pfnSetupVM(pVM);
1286
1287 /* Disable VT-x or AMD-V if local init was done before. */
1288 if (!g_HmR0.fGlobalInit)
1289 {
1290 Assert(!g_HmR0.hwvirt.u.vmx.fSupported || !g_HmR0.hwvirt.u.vmx.fUsingSUPR0EnableVTx);
1291 int rc2 = hmR0DisableCpu(idCpu);
1292 AssertRC(rc2);
1293 }
1294
1295 RTThreadPreemptRestore(&PreemptState);
1296 return rc;
1297}
1298
1299
1300/**
1301 * Notification callback before performing a longjump to ring-3.
1302 *
1303 * @returns VBox status code.
1304 * @param pVCpu The cross context virtual CPU structure.
1305 * @param enmOperation The operation causing the ring-3 longjump.
1306 * @param pvUser User argument, currently unused, NULL.
1307 */
1308static DECLCALLBACK(int) hmR0CallRing3Callback(PVMCPUCC pVCpu, VMMCALLRING3 enmOperation, void *pvUser)
1309{
1310 RT_NOREF(pvUser);
1311 Assert(pVCpu);
1312 Assert(g_HmR0.pfnCallRing3Callback);
1313 return g_HmR0.pfnCallRing3Callback(pVCpu, enmOperation);
1314}
1315
1316
1317/**
1318 * Turns on HM on the CPU if necessary and initializes the bare minimum state
1319 * required for entering HM context.
1320 *
1321 * @returns VBox status code.
1322 * @param pVCpu The cross context virtual CPU structure.
1323 *
1324 * @remarks No-long-jump zone!!!
1325 */
1326VMMR0_INT_DECL(int) hmR0EnterCpu(PVMCPUCC pVCpu)
1327{
1328 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
1329
1330 int rc = VINF_SUCCESS;
1331 RTCPUID const idCpu = RTMpCpuId();
1332 PHMPHYSCPU pHostCpu = &g_HmR0.aCpuInfo[idCpu];
1333 AssertPtr(pHostCpu);
1334
1335 /* Enable VT-x or AMD-V if local init is required, or enable if it's a freshly onlined CPU. */
1336 if (!pHostCpu->fConfigured)
1337 rc = hmR0EnableCpu(pVCpu->CTX_SUFF(pVM), idCpu);
1338
1339 /* Register a callback to fire prior to performing a longjmp to ring-3 so HM can disable VT-x/AMD-V if needed. */
1340 VMMRZCallRing3SetNotification(pVCpu, hmR0CallRing3Callback, NULL /* pvUser */);
1341
1342 /* Reload host-state (back from ring-3/migrated CPUs) and shared guest/host bits. */
1343 if (g_HmR0.hwvirt.u.vmx.fSupported)
1344 pVCpu->hm.s.fCtxChanged |= HM_CHANGED_HOST_CONTEXT | HM_CHANGED_VMX_HOST_GUEST_SHARED_STATE;
1345 else
1346 pVCpu->hm.s.fCtxChanged |= HM_CHANGED_HOST_CONTEXT | HM_CHANGED_SVM_HOST_GUEST_SHARED_STATE;
1347
1348 Assert(pHostCpu->idCpu == idCpu && pHostCpu->idCpu != NIL_RTCPUID);
1349 pVCpu->hm.s.idEnteredCpu = idCpu;
1350 return rc;
1351}
1352
1353
1354/**
1355 * Enters the VT-x or AMD-V session.
1356 *
1357 * @returns VBox status code.
1358 * @param pVCpu The cross context virtual CPU structure.
1359 *
1360 * @remarks This is called with preemption disabled.
1361 */
1362VMMR0_INT_DECL(int) HMR0Enter(PVMCPUCC pVCpu)
1363{
1364 /* Make sure we can't enter a session after we've disabled HM in preparation of a suspend. */
1365 AssertReturn(!ASMAtomicReadBool(&g_HmR0.fSuspended), VERR_HM_SUSPEND_PENDING);
1366 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
1367
1368 /* Load the bare minimum state required for entering HM. */
1369 int rc = hmR0EnterCpu(pVCpu);
1370 if (RT_SUCCESS(rc))
1371 {
1372 if (g_HmR0.hwvirt.u.vmx.fSupported)
1373 {
1374 Assert((pVCpu->hm.s.fCtxChanged & (HM_CHANGED_HOST_CONTEXT | HM_CHANGED_VMX_HOST_GUEST_SHARED_STATE))
1375 == (HM_CHANGED_HOST_CONTEXT | HM_CHANGED_VMX_HOST_GUEST_SHARED_STATE));
1376 }
1377 else
1378 {
1379 Assert((pVCpu->hm.s.fCtxChanged & (HM_CHANGED_HOST_CONTEXT | HM_CHANGED_SVM_HOST_GUEST_SHARED_STATE))
1380 == (HM_CHANGED_HOST_CONTEXT | HM_CHANGED_SVM_HOST_GUEST_SHARED_STATE));
1381 }
1382
1383#ifdef VBOX_WITH_2X_4GB_ADDR_SPACE
1384 AssertReturn(!VMMR0ThreadCtxHookIsEnabled(pVCpu), VERR_HM_IPE_5);
1385 bool const fStartedSet = PGMR0DynMapStartOrMigrateAutoSet(pVCpu);
1386#endif
1387
1388 /* Keep track of the CPU owning the VMCS for debugging scheduling weirdness and ring-3 calls. */
1389 rc = g_HmR0.pfnEnterSession(pVCpu);
1390 AssertMsgRCReturnStmt(rc, ("rc=%Rrc pVCpu=%p\n", rc, pVCpu), pVCpu->hm.s.idEnteredCpu = NIL_RTCPUID, rc);
1391
1392 /* Exports the host-state as we may be resuming code after a longjmp and quite
1393 possibly now be scheduled on a different CPU. */
1394 rc = g_HmR0.pfnExportHostState(pVCpu);
1395 AssertMsgRCReturnStmt(rc, ("rc=%Rrc pVCpu=%p\n", rc, pVCpu), pVCpu->hm.s.idEnteredCpu = NIL_RTCPUID, rc);
1396
1397#ifdef VBOX_WITH_2X_4GB_ADDR_SPACE
1398 if (fStartedSet)
1399 PGMRZDynMapReleaseAutoSet(pVCpu);
1400#endif
1401 }
1402 return rc;
1403}
1404
1405
1406/**
1407 * Deinitializes the bare minimum state used for HM context and if necessary
1408 * disable HM on the CPU.
1409 *
1410 * @returns VBox status code.
1411 * @param pVCpu The cross context virtual CPU structure.
1412 *
1413 * @remarks No-long-jump zone!!!
1414 */
1415VMMR0_INT_DECL(int) HMR0LeaveCpu(PVMCPUCC pVCpu)
1416{
1417 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
1418 VMCPU_ASSERT_EMT_RETURN(pVCpu, VERR_HM_WRONG_CPU);
1419
1420 RTCPUID const idCpu = RTMpCpuId();
1421 PCHMPHYSCPU pHostCpu = &g_HmR0.aCpuInfo[idCpu];
1422
1423 if ( !g_HmR0.fGlobalInit
1424 && pHostCpu->fConfigured)
1425 {
1426 int rc = hmR0DisableCpu(idCpu);
1427 AssertRCReturn(rc, rc);
1428 Assert(!pHostCpu->fConfigured);
1429 Assert(pHostCpu->idCpu == NIL_RTCPUID);
1430
1431 /* For obtaining a non-zero ASID/VPID on next re-entry. */
1432 pVCpu->hm.s.idLastCpu = NIL_RTCPUID;
1433 }
1434
1435 /* Clear it while leaving HM context, hmPokeCpuForTlbFlush() relies on this. */
1436 pVCpu->hm.s.idEnteredCpu = NIL_RTCPUID;
1437
1438 /* De-register the longjmp-to-ring 3 callback now that we have reliquished hardware resources. */
1439 VMMRZCallRing3RemoveNotification(pVCpu);
1440 return VINF_SUCCESS;
1441}
1442
1443
1444/**
1445 * Thread-context hook for HM.
1446 *
1447 * @param enmEvent The thread-context event.
1448 * @param pvUser Opaque pointer to the VMCPU.
1449 */
1450VMMR0_INT_DECL(void) HMR0ThreadCtxCallback(RTTHREADCTXEVENT enmEvent, void *pvUser)
1451{
1452 PVMCPUCC pVCpu = (PVMCPUCC)pvUser;
1453 Assert(pVCpu);
1454 Assert(g_HmR0.pfnThreadCtxCallback);
1455
1456 g_HmR0.pfnThreadCtxCallback(enmEvent, pVCpu, g_HmR0.fGlobalInit);
1457}
1458
1459
1460/**
1461 * Runs guest code in a hardware accelerated VM.
1462 *
1463 * @returns Strict VBox status code. (VBOXSTRICTRC isn't used because it's
1464 * called from setjmp assembly.)
1465 * @param pVM The cross context VM structure.
1466 * @param pVCpu The cross context virtual CPU structure.
1467 *
1468 * @remarks Can be called with preemption enabled if thread-context hooks are
1469 * used!!!
1470 */
1471VMMR0_INT_DECL(int) HMR0RunGuestCode(PVMCC pVM, PVMCPUCC pVCpu)
1472{
1473 RT_NOREF(pVM);
1474
1475#ifdef VBOX_STRICT
1476 /* With thread-context hooks we would be running this code with preemption enabled. */
1477 if (!RTThreadPreemptIsEnabled(NIL_RTTHREAD))
1478 {
1479 PCHMPHYSCPU pHostCpu = &g_HmR0.aCpuInfo[RTMpCpuId()];
1480 Assert(!VMCPU_FF_IS_ANY_SET(pVCpu, VMCPU_FF_PGM_SYNC_CR3 | VMCPU_FF_PGM_SYNC_CR3_NON_GLOBAL));
1481 Assert(pHostCpu->fConfigured);
1482 AssertReturn(!ASMAtomicReadBool(&g_HmR0.fSuspended), VERR_HM_SUSPEND_PENDING);
1483 }
1484#endif
1485
1486#ifdef VBOX_WITH_2X_4GB_ADDR_SPACE
1487 AssertReturn(!VMMR0ThreadCtxHookIsEnabled(pVCpu), VERR_HM_IPE_4);
1488 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
1489 PGMRZDynMapStartAutoSet(pVCpu);
1490#endif
1491
1492 VBOXSTRICTRC rcStrict = g_HmR0.pfnRunGuestCode(pVCpu);
1493
1494#ifdef VBOX_WITH_2X_4GB_ADDR_SPACE
1495 PGMRZDynMapReleaseAutoSet(pVCpu);
1496#endif
1497 return VBOXSTRICTRC_VAL(rcStrict);
1498}
1499
1500
1501/**
1502 * Notification from CPUM that it has unloaded the guest FPU/SSE/AVX state from
1503 * the host CPU and that guest access to it must be intercepted.
1504 *
1505 * @param pVCpu The cross context virtual CPU structure of the calling EMT.
1506 */
1507VMMR0_INT_DECL(void) HMR0NotifyCpumUnloadedGuestFpuState(PVMCPUCC pVCpu)
1508{
1509 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_GUEST_CR0);
1510}
1511
1512
1513/**
1514 * Notification from CPUM that it has modified the host CR0 (because of FPU).
1515 *
1516 * @param pVCpu The cross context virtual CPU structure of the calling EMT.
1517 */
1518VMMR0_INT_DECL(void) HMR0NotifyCpumModifiedHostCr0(PVMCPUCC pVCpu)
1519{
1520 ASMAtomicUoOrU64(&pVCpu->hm.s.fCtxChanged, HM_CHANGED_HOST_CONTEXT);
1521}
1522
1523
1524/**
1525 * Returns suspend status of the host.
1526 *
1527 * @returns Suspend pending or not.
1528 */
1529VMMR0_INT_DECL(bool) HMR0SuspendPending(void)
1530{
1531 return ASMAtomicReadBool(&g_HmR0.fSuspended);
1532}
1533
1534
1535/**
1536 * Invalidates a guest page from the host TLB.
1537 *
1538 * @param pVCpu The cross context virtual CPU structure.
1539 * @param GCVirt Page to invalidate.
1540 */
1541VMMR0_INT_DECL(int) HMR0InvalidatePage(PVMCPUCC pVCpu, RTGCPTR GCVirt)
1542{
1543 PVMCC pVM = pVCpu->CTX_SUFF(pVM);
1544 if (pVM->hm.s.vmx.fSupported)
1545 return VMXR0InvalidatePage(pVCpu, GCVirt);
1546 return SVMR0InvalidatePage(pVCpu, GCVirt);
1547}
1548
1549
1550/**
1551 * Returns the cpu structure for the current cpu.
1552 * Keep in mind that there is no guarantee it will stay the same (long jumps to ring 3!!!).
1553 *
1554 * @returns The cpu structure pointer.
1555 */
1556VMMR0_INT_DECL(PHMPHYSCPU) hmR0GetCurrentCpu(void)
1557{
1558 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
1559 RTCPUID const idCpu = RTMpCpuId();
1560 Assert(idCpu < RT_ELEMENTS(g_HmR0.aCpuInfo));
1561 return &g_HmR0.aCpuInfo[idCpu];
1562}
1563
1564
1565/**
1566 * Interface for importing state on demand (used by IEM).
1567 *
1568 * @returns VBox status code.
1569 * @param pVCpu The cross context CPU structure.
1570 * @param fWhat What to import, CPUMCTX_EXTRN_XXX.
1571 */
1572VMMR0_INT_DECL(int) HMR0ImportStateOnDemand(PVMCPUCC pVCpu, uint64_t fWhat)
1573{
1574 if (pVCpu->CTX_SUFF(pVM)->hm.s.vmx.fSupported)
1575 return VMXR0ImportStateOnDemand(pVCpu, fWhat);
1576 return SVMR0ImportStateOnDemand(pVCpu, fWhat);
1577}
1578
1579#ifdef VBOX_STRICT
1580
1581/**
1582 * Dumps a descriptor.
1583 *
1584 * @param pDesc Descriptor to dump.
1585 * @param Sel The selector.
1586 * @param pszSel The name of the selector.
1587 */
1588VMMR0_INT_DECL(void) hmR0DumpDescriptor(PCX86DESCHC pDesc, RTSEL Sel, const char *pszSel)
1589{
1590 /*
1591 * Make variable description string.
1592 */
1593 static struct
1594 {
1595 unsigned cch;
1596 const char *psz;
1597 } const s_aTypes[32] =
1598 {
1599# define STRENTRY(str) { sizeof(str) - 1, str }
1600
1601 /* system */
1602# if HC_ARCH_BITS == 64
1603 STRENTRY("Reserved0 "), /* 0x00 */
1604 STRENTRY("Reserved1 "), /* 0x01 */
1605 STRENTRY("LDT "), /* 0x02 */
1606 STRENTRY("Reserved3 "), /* 0x03 */
1607 STRENTRY("Reserved4 "), /* 0x04 */
1608 STRENTRY("Reserved5 "), /* 0x05 */
1609 STRENTRY("Reserved6 "), /* 0x06 */
1610 STRENTRY("Reserved7 "), /* 0x07 */
1611 STRENTRY("Reserved8 "), /* 0x08 */
1612 STRENTRY("TSS64Avail "), /* 0x09 */
1613 STRENTRY("ReservedA "), /* 0x0a */
1614 STRENTRY("TSS64Busy "), /* 0x0b */
1615 STRENTRY("Call64 "), /* 0x0c */
1616 STRENTRY("ReservedD "), /* 0x0d */
1617 STRENTRY("Int64 "), /* 0x0e */
1618 STRENTRY("Trap64 "), /* 0x0f */
1619# else
1620 STRENTRY("Reserved0 "), /* 0x00 */
1621 STRENTRY("TSS16Avail "), /* 0x01 */
1622 STRENTRY("LDT "), /* 0x02 */
1623 STRENTRY("TSS16Busy "), /* 0x03 */
1624 STRENTRY("Call16 "), /* 0x04 */
1625 STRENTRY("Task "), /* 0x05 */
1626 STRENTRY("Int16 "), /* 0x06 */
1627 STRENTRY("Trap16 "), /* 0x07 */
1628 STRENTRY("Reserved8 "), /* 0x08 */
1629 STRENTRY("TSS32Avail "), /* 0x09 */
1630 STRENTRY("ReservedA "), /* 0x0a */
1631 STRENTRY("TSS32Busy "), /* 0x0b */
1632 STRENTRY("Call32 "), /* 0x0c */
1633 STRENTRY("ReservedD "), /* 0x0d */
1634 STRENTRY("Int32 "), /* 0x0e */
1635 STRENTRY("Trap32 "), /* 0x0f */
1636# endif
1637 /* non system */
1638 STRENTRY("DataRO "), /* 0x10 */
1639 STRENTRY("DataRO Accessed "), /* 0x11 */
1640 STRENTRY("DataRW "), /* 0x12 */
1641 STRENTRY("DataRW Accessed "), /* 0x13 */
1642 STRENTRY("DataDownRO "), /* 0x14 */
1643 STRENTRY("DataDownRO Accessed "), /* 0x15 */
1644 STRENTRY("DataDownRW "), /* 0x16 */
1645 STRENTRY("DataDownRW Accessed "), /* 0x17 */
1646 STRENTRY("CodeEO "), /* 0x18 */
1647 STRENTRY("CodeEO Accessed "), /* 0x19 */
1648 STRENTRY("CodeER "), /* 0x1a */
1649 STRENTRY("CodeER Accessed "), /* 0x1b */
1650 STRENTRY("CodeConfEO "), /* 0x1c */
1651 STRENTRY("CodeConfEO Accessed "), /* 0x1d */
1652 STRENTRY("CodeConfER "), /* 0x1e */
1653 STRENTRY("CodeConfER Accessed ") /* 0x1f */
1654# undef SYSENTRY
1655 };
1656# define ADD_STR(psz, pszAdd) do { strcpy(psz, pszAdd); psz += strlen(pszAdd); } while (0)
1657 char szMsg[128];
1658 char *psz = &szMsg[0];
1659 unsigned i = pDesc->Gen.u1DescType << 4 | pDesc->Gen.u4Type;
1660 memcpy(psz, s_aTypes[i].psz, s_aTypes[i].cch);
1661 psz += s_aTypes[i].cch;
1662
1663 if (pDesc->Gen.u1Present)
1664 ADD_STR(psz, "Present ");
1665 else
1666 ADD_STR(psz, "Not-Present ");
1667# if HC_ARCH_BITS == 64
1668 if (pDesc->Gen.u1Long)
1669 ADD_STR(psz, "64-bit ");
1670 else
1671 ADD_STR(psz, "Comp ");
1672# else
1673 if (pDesc->Gen.u1Granularity)
1674 ADD_STR(psz, "Page ");
1675 if (pDesc->Gen.u1DefBig)
1676 ADD_STR(psz, "32-bit ");
1677 else
1678 ADD_STR(psz, "16-bit ");
1679# endif
1680# undef ADD_STR
1681 *psz = '\0';
1682
1683 /*
1684 * Limit and Base and format the output.
1685 */
1686#ifdef LOG_ENABLED
1687 uint32_t u32Limit = X86DESC_LIMIT_G(pDesc);
1688
1689# if HC_ARCH_BITS == 64
1690 uint64_t const u64Base = X86DESC64_BASE(pDesc);
1691 Log((" %s { %#04x - %#RX64 %#RX64 - base=%#RX64 limit=%#08x dpl=%d } %s\n", pszSel,
1692 Sel, pDesc->au64[0], pDesc->au64[1], u64Base, u32Limit, pDesc->Gen.u2Dpl, szMsg));
1693# else
1694 uint32_t const u32Base = X86DESC_BASE(pDesc);
1695 Log((" %s { %#04x - %#08x %#08x - base=%#08x limit=%#08x dpl=%d } %s\n", pszSel,
1696 Sel, pDesc->au32[0], pDesc->au32[1], u32Base, u32Limit, pDesc->Gen.u2Dpl, szMsg));
1697# endif
1698#else
1699 NOREF(Sel); NOREF(pszSel);
1700#endif
1701}
1702
1703
1704/**
1705 * Formats a full register dump.
1706 *
1707 * @param pVCpu The cross context virtual CPU structure.
1708 * @param fFlags The dumping flags (HM_DUMP_REG_FLAGS_XXX).
1709 */
1710VMMR0_INT_DECL(void) hmR0DumpRegs(PVMCPUCC pVCpu, uint32_t fFlags)
1711{
1712 /*
1713 * Format the flags.
1714 */
1715 static struct
1716 {
1717 const char *pszSet;
1718 const char *pszClear;
1719 uint32_t fFlag;
1720 } const s_aFlags[] =
1721 {
1722 { "vip", NULL, X86_EFL_VIP },
1723 { "vif", NULL, X86_EFL_VIF },
1724 { "ac", NULL, X86_EFL_AC },
1725 { "vm", NULL, X86_EFL_VM },
1726 { "rf", NULL, X86_EFL_RF },
1727 { "nt", NULL, X86_EFL_NT },
1728 { "ov", "nv", X86_EFL_OF },
1729 { "dn", "up", X86_EFL_DF },
1730 { "ei", "di", X86_EFL_IF },
1731 { "tf", NULL, X86_EFL_TF },
1732 { "nt", "pl", X86_EFL_SF },
1733 { "nz", "zr", X86_EFL_ZF },
1734 { "ac", "na", X86_EFL_AF },
1735 { "po", "pe", X86_EFL_PF },
1736 { "cy", "nc", X86_EFL_CF },
1737 };
1738 char szEFlags[80];
1739 char *psz = szEFlags;
1740 PCCPUMCTX pCtx = &pVCpu->cpum.GstCtx;
1741 uint32_t uEFlags = pCtx->eflags.u32;
1742 for (unsigned i = 0; i < RT_ELEMENTS(s_aFlags); i++)
1743 {
1744 const char *pszAdd = s_aFlags[i].fFlag & uEFlags ? s_aFlags[i].pszSet : s_aFlags[i].pszClear;
1745 if (pszAdd)
1746 {
1747 strcpy(psz, pszAdd);
1748 psz += strlen(pszAdd);
1749 *psz++ = ' ';
1750 }
1751 }
1752 psz[-1] = '\0';
1753
1754 if (fFlags & HM_DUMP_REG_FLAGS_GPRS)
1755 {
1756 /*
1757 * Format the registers.
1758 */
1759 if (CPUMIsGuestIn64BitCode(pVCpu))
1760 {
1761 Log(("rax=%016RX64 rbx=%016RX64 rcx=%016RX64 rdx=%016RX64\n"
1762 "rsi=%016RX64 rdi=%016RX64 r8 =%016RX64 r9 =%016RX64\n"
1763 "r10=%016RX64 r11=%016RX64 r12=%016RX64 r13=%016RX64\n"
1764 "r14=%016RX64 r15=%016RX64\n"
1765 "rip=%016RX64 rsp=%016RX64 rbp=%016RX64 iopl=%d %*s\n"
1766 "cs={%04x base=%016RX64 limit=%08x flags=%08x}\n"
1767 "ds={%04x base=%016RX64 limit=%08x flags=%08x}\n"
1768 "es={%04x base=%016RX64 limit=%08x flags=%08x}\n"
1769 "fs={%04x base=%016RX64 limit=%08x flags=%08x}\n"
1770 "gs={%04x base=%016RX64 limit=%08x flags=%08x}\n"
1771 "ss={%04x base=%016RX64 limit=%08x flags=%08x}\n"
1772 "cr0=%016RX64 cr2=%016RX64 cr3=%016RX64 cr4=%016RX64\n"
1773 "dr0=%016RX64 dr1=%016RX64 dr2=%016RX64 dr3=%016RX64\n"
1774 "dr4=%016RX64 dr5=%016RX64 dr6=%016RX64 dr7=%016RX64\n"
1775 "gdtr=%016RX64:%04x idtr=%016RX64:%04x eflags=%08x\n"
1776 "ldtr={%04x base=%08RX64 limit=%08x flags=%08x}\n"
1777 "tr ={%04x base=%08RX64 limit=%08x flags=%08x}\n"
1778 "SysEnter={cs=%04llx eip=%08llx esp=%08llx}\n"
1779 ,
1780 pCtx->rax, pCtx->rbx, pCtx->rcx, pCtx->rdx, pCtx->rsi, pCtx->rdi,
1781 pCtx->r8, pCtx->r9, pCtx->r10, pCtx->r11, pCtx->r12, pCtx->r13,
1782 pCtx->r14, pCtx->r15,
1783 pCtx->rip, pCtx->rsp, pCtx->rbp, X86_EFL_GET_IOPL(uEFlags), 31, szEFlags,
1784 pCtx->cs.Sel, pCtx->cs.u64Base, pCtx->cs.u32Limit, pCtx->cs.Attr.u,
1785 pCtx->ds.Sel, pCtx->ds.u64Base, pCtx->ds.u32Limit, pCtx->ds.Attr.u,
1786 pCtx->es.Sel, pCtx->es.u64Base, pCtx->es.u32Limit, pCtx->es.Attr.u,
1787 pCtx->fs.Sel, pCtx->fs.u64Base, pCtx->fs.u32Limit, pCtx->fs.Attr.u,
1788 pCtx->gs.Sel, pCtx->gs.u64Base, pCtx->gs.u32Limit, pCtx->gs.Attr.u,
1789 pCtx->ss.Sel, pCtx->ss.u64Base, pCtx->ss.u32Limit, pCtx->ss.Attr.u,
1790 pCtx->cr0, pCtx->cr2, pCtx->cr3, pCtx->cr4,
1791 pCtx->dr[0], pCtx->dr[1], pCtx->dr[2], pCtx->dr[3],
1792 pCtx->dr[4], pCtx->dr[5], pCtx->dr[6], pCtx->dr[7],
1793 pCtx->gdtr.pGdt, pCtx->gdtr.cbGdt, pCtx->idtr.pIdt, pCtx->idtr.cbIdt, uEFlags,
1794 pCtx->ldtr.Sel, pCtx->ldtr.u64Base, pCtx->ldtr.u32Limit, pCtx->ldtr.Attr.u,
1795 pCtx->tr.Sel, pCtx->tr.u64Base, pCtx->tr.u32Limit, pCtx->tr.Attr.u,
1796 pCtx->SysEnter.cs, pCtx->SysEnter.eip, pCtx->SysEnter.esp));
1797 }
1798 else
1799 Log(("eax=%08x ebx=%08x ecx=%08x edx=%08x esi=%08x edi=%08x\n"
1800 "eip=%08x esp=%08x ebp=%08x iopl=%d %*s\n"
1801 "cs={%04x base=%016RX64 limit=%08x flags=%08x} dr0=%08RX64 dr1=%08RX64\n"
1802 "ds={%04x base=%016RX64 limit=%08x flags=%08x} dr2=%08RX64 dr3=%08RX64\n"
1803 "es={%04x base=%016RX64 limit=%08x flags=%08x} dr4=%08RX64 dr5=%08RX64\n"
1804 "fs={%04x base=%016RX64 limit=%08x flags=%08x} dr6=%08RX64 dr7=%08RX64\n"
1805 "gs={%04x base=%016RX64 limit=%08x flags=%08x} cr0=%08RX64 cr2=%08RX64\n"
1806 "ss={%04x base=%016RX64 limit=%08x flags=%08x} cr3=%08RX64 cr4=%08RX64\n"
1807 "gdtr=%016RX64:%04x idtr=%016RX64:%04x eflags=%08x\n"
1808 "ldtr={%04x base=%08RX64 limit=%08x flags=%08x}\n"
1809 "tr ={%04x base=%08RX64 limit=%08x flags=%08x}\n"
1810 "SysEnter={cs=%04llx eip=%08llx esp=%08llx}\n"
1811 ,
1812 pCtx->eax, pCtx->ebx, pCtx->ecx, pCtx->edx, pCtx->esi, pCtx->edi,
1813 pCtx->eip, pCtx->esp, pCtx->ebp, X86_EFL_GET_IOPL(uEFlags), 31, szEFlags,
1814 pCtx->cs.Sel, pCtx->cs.u64Base, pCtx->cs.u32Limit, pCtx->cs.Attr.u, pCtx->dr[0], pCtx->dr[1],
1815 pCtx->ds.Sel, pCtx->ds.u64Base, pCtx->ds.u32Limit, pCtx->ds.Attr.u, pCtx->dr[2], pCtx->dr[3],
1816 pCtx->es.Sel, pCtx->es.u64Base, pCtx->es.u32Limit, pCtx->es.Attr.u, pCtx->dr[4], pCtx->dr[5],
1817 pCtx->fs.Sel, pCtx->fs.u64Base, pCtx->fs.u32Limit, pCtx->fs.Attr.u, pCtx->dr[6], pCtx->dr[7],
1818 pCtx->gs.Sel, pCtx->gs.u64Base, pCtx->gs.u32Limit, pCtx->gs.Attr.u, pCtx->cr0, pCtx->cr2,
1819 pCtx->ss.Sel, pCtx->ss.u64Base, pCtx->ss.u32Limit, pCtx->ss.Attr.u, pCtx->cr3, pCtx->cr4,
1820 pCtx->gdtr.pGdt, pCtx->gdtr.cbGdt, pCtx->idtr.pIdt, pCtx->idtr.cbIdt, uEFlags,
1821 pCtx->ldtr.Sel, pCtx->ldtr.u64Base, pCtx->ldtr.u32Limit, pCtx->ldtr.Attr.u,
1822 pCtx->tr.Sel, pCtx->tr.u64Base, pCtx->tr.u32Limit, pCtx->tr.Attr.u,
1823 pCtx->SysEnter.cs, pCtx->SysEnter.eip, pCtx->SysEnter.esp));
1824 }
1825
1826 if (fFlags & HM_DUMP_REG_FLAGS_FPU)
1827 {
1828 PCX86FXSTATE pFpuCtx = &pCtx->CTX_SUFF(pXState)->x87;
1829 Log(("FPU:\n"
1830 "FCW=%04x FSW=%04x FTW=%02x\n"
1831 "FOP=%04x FPUIP=%08x CS=%04x Rsrvd1=%04x\n"
1832 "FPUDP=%04x DS=%04x Rsvrd2=%04x MXCSR=%08x MXCSR_MASK=%08x\n"
1833 ,
1834 pFpuCtx->FCW, pFpuCtx->FSW, pFpuCtx->FTW,
1835 pFpuCtx->FOP, pFpuCtx->FPUIP, pFpuCtx->CS, pFpuCtx->Rsrvd1,
1836 pFpuCtx->FPUDP, pFpuCtx->DS, pFpuCtx->Rsrvd2,
1837 pFpuCtx->MXCSR, pFpuCtx->MXCSR_MASK));
1838 NOREF(pFpuCtx);
1839 }
1840
1841 if (fFlags & HM_DUMP_REG_FLAGS_MSRS)
1842 {
1843 Log(("MSR:\n"
1844 "EFER =%016RX64\n"
1845 "PAT =%016RX64\n"
1846 "STAR =%016RX64\n"
1847 "CSTAR =%016RX64\n"
1848 "LSTAR =%016RX64\n"
1849 "SFMASK =%016RX64\n"
1850 "KERNELGSBASE =%016RX64\n",
1851 pCtx->msrEFER,
1852 pCtx->msrPAT,
1853 pCtx->msrSTAR,
1854 pCtx->msrCSTAR,
1855 pCtx->msrLSTAR,
1856 pCtx->msrSFMASK,
1857 pCtx->msrKERNELGSBASE));
1858 }
1859}
1860
1861#endif /* VBOX_STRICT */
1862
Note: See TracBrowser for help on using the repository browser.

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