VirtualBox

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

Last change on this file since 56287 was 56287, checked in by vboxsync, 9 years ago

VMM: Updated (C) year.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id Revision
File size: 72.6 KB
Line 
1/* $Id: VMMR0.cpp 56287 2015-06-09 11:15:22Z vboxsync $ */
2/** @file
3 * VMM - Host Context Ring 0.
4 */
5
6/*
7 * Copyright (C) 2006-2015 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* Header Files *
20*******************************************************************************/
21#define LOG_GROUP LOG_GROUP_VMM
22#include <VBox/vmm/vmm.h>
23#include <VBox/sup.h>
24#include <VBox/vmm/trpm.h>
25#include <VBox/vmm/cpum.h>
26#include <VBox/vmm/pdmapi.h>
27#include <VBox/vmm/pgm.h>
28#include <VBox/vmm/stam.h>
29#include <VBox/vmm/tm.h>
30#include "VMMInternal.h"
31#include <VBox/vmm/vm.h>
32#ifdef VBOX_WITH_PCI_PASSTHROUGH
33# include <VBox/vmm/pdmpci.h>
34#endif
35
36#include <VBox/vmm/gvmm.h>
37#include <VBox/vmm/gmm.h>
38#include <VBox/vmm/gim.h>
39#include <VBox/intnet.h>
40#include <VBox/vmm/hm.h>
41#include <VBox/param.h>
42#include <VBox/err.h>
43#include <VBox/version.h>
44#include <VBox/log.h>
45
46#include <iprt/asm-amd64-x86.h>
47#include <iprt/assert.h>
48#include <iprt/crc.h>
49#include <iprt/mp.h>
50#include <iprt/once.h>
51#include <iprt/stdarg.h>
52#include <iprt/string.h>
53#include <iprt/thread.h>
54#include <iprt/timer.h>
55
56#include "dtrace/VBoxVMM.h"
57
58
59#if defined(_MSC_VER) && defined(RT_ARCH_AMD64) /** @todo check this with with VC7! */
60# pragma intrinsic(_AddressOfReturnAddress)
61#endif
62
63
64/*******************************************************************************
65* Internal Functions *
66*******************************************************************************/
67RT_C_DECLS_BEGIN
68#if defined(RT_ARCH_X86) && (defined(RT_OS_SOLARIS) || defined(RT_OS_FREEBSD))
69extern uint64_t __udivdi3(uint64_t, uint64_t);
70extern uint64_t __umoddi3(uint64_t, uint64_t);
71#endif
72RT_C_DECLS_END
73
74
75/*******************************************************************************
76* Global Variables *
77*******************************************************************************/
78/** Drag in necessary library bits.
79 * The runtime lives here (in VMMR0.r0) and VBoxDD*R0.r0 links against us. */
80PFNRT g_VMMR0Deps[] =
81{
82 (PFNRT)RTCrc32,
83 (PFNRT)RTOnce,
84#if defined(RT_ARCH_X86) && (defined(RT_OS_SOLARIS) || defined(RT_OS_FREEBSD))
85 (PFNRT)__udivdi3,
86 (PFNRT)__umoddi3,
87#endif
88 NULL
89};
90
91#ifdef RT_OS_SOLARIS
92/* Dependency information for the native solaris loader. */
93extern "C" { char _depends_on[] = "vboxdrv"; }
94#endif
95
96
97
98/**
99 * Initialize the module.
100 * This is called when we're first loaded.
101 *
102 * @returns 0 on success.
103 * @returns VBox status on failure.
104 * @param hMod Image handle for use in APIs.
105 */
106DECLEXPORT(int) ModuleInit(void *hMod)
107{
108#ifdef VBOX_WITH_DTRACE_R0
109 /*
110 * The first thing to do is register the static tracepoints.
111 * (Deregistration is automatic.)
112 */
113 int rc2 = SUPR0TracerRegisterModule(hMod, &g_VTGObjHeader);
114 if (RT_FAILURE(rc2))
115 return rc2;
116#endif
117 LogFlow(("ModuleInit:\n"));
118
119#ifdef VBOX_WITH_64ON32_CMOS_DEBUG
120 /*
121 * Display the CMOS debug code.
122 */
123 ASMOutU8(0x72, 0x03);
124 uint8_t bDebugCode = ASMInU8(0x73);
125 LogRel(("CMOS Debug Code: %#x (%d)\n", bDebugCode, bDebugCode));
126 RTLogComPrintf("CMOS Debug Code: %#x (%d)\n", bDebugCode, bDebugCode);
127#endif
128
129 /*
130 * Initialize the VMM, GVMM, GMM, HM, PGM (Darwin) and INTNET.
131 */
132 int rc = vmmInitFormatTypes();
133 if (RT_SUCCESS(rc))
134 {
135 rc = GVMMR0Init();
136 if (RT_SUCCESS(rc))
137 {
138 rc = GMMR0Init();
139 if (RT_SUCCESS(rc))
140 {
141 rc = HMR0Init();
142 if (RT_SUCCESS(rc))
143 {
144 rc = PGMRegisterStringFormatTypes();
145 if (RT_SUCCESS(rc))
146 {
147#ifdef VBOX_WITH_2X_4GB_ADDR_SPACE
148 rc = PGMR0DynMapInit();
149#endif
150 if (RT_SUCCESS(rc))
151 {
152 rc = IntNetR0Init();
153 if (RT_SUCCESS(rc))
154 {
155#ifdef VBOX_WITH_PCI_PASSTHROUGH
156 rc = PciRawR0Init();
157#endif
158 if (RT_SUCCESS(rc))
159 {
160 rc = CPUMR0ModuleInit();
161 if (RT_SUCCESS(rc))
162 {
163#ifdef VBOX_WITH_TRIPLE_FAULT_HACK
164 rc = vmmR0TripleFaultHackInit();
165 if (RT_SUCCESS(rc))
166#endif
167 {
168 LogFlow(("ModuleInit: returns success.\n"));
169 return VINF_SUCCESS;
170 }
171
172 /*
173 * Bail out.
174 */
175#ifdef VBOX_WITH_TRIPLE_FAULT_HACK
176 vmmR0TripleFaultHackTerm();
177#endif
178 }
179 else
180 LogRel(("ModuleInit: CPUMR0ModuleInit -> %Rrc\n", rc));
181#ifdef VBOX_WITH_PCI_PASSTHROUGH
182 PciRawR0Term();
183#endif
184 }
185 else
186 LogRel(("ModuleInit: PciRawR0Init -> %Rrc\n", rc));
187 IntNetR0Term();
188 }
189 else
190 LogRel(("ModuleInit: IntNetR0Init -> %Rrc\n", rc));
191#ifdef VBOX_WITH_2X_4GB_ADDR_SPACE
192 PGMR0DynMapTerm();
193#endif
194 }
195 else
196 LogRel(("ModuleInit: PGMR0DynMapInit -> %Rrc\n", rc));
197 PGMDeregisterStringFormatTypes();
198 }
199 else
200 LogRel(("ModuleInit: PGMRegisterStringFormatTypes -> %Rrc\n", rc));
201 HMR0Term();
202 }
203 else
204 LogRel(("ModuleInit: HMR0Init -> %Rrc\n", rc));
205 GMMR0Term();
206 }
207 else
208 LogRel(("ModuleInit: GMMR0Init -> %Rrc\n", rc));
209 GVMMR0Term();
210 }
211 else
212 LogRel(("ModuleInit: GVMMR0Init -> %Rrc\n", rc));
213 vmmTermFormatTypes();
214 }
215 else
216 LogRel(("ModuleInit: vmmInitFormatTypes -> %Rrc\n", rc));
217
218 LogFlow(("ModuleInit: failed %Rrc\n", rc));
219 return rc;
220}
221
222
223/**
224 * Terminate the module.
225 * This is called when we're finally unloaded.
226 *
227 * @param hMod Image handle for use in APIs.
228 */
229DECLEXPORT(void) ModuleTerm(void *hMod)
230{
231 NOREF(hMod);
232 LogFlow(("ModuleTerm:\n"));
233
234 /*
235 * Terminate the CPUM module (Local APIC cleanup).
236 */
237 CPUMR0ModuleTerm();
238
239 /*
240 * Terminate the internal network service.
241 */
242 IntNetR0Term();
243
244 /*
245 * PGM (Darwin), HM and PciRaw global cleanup.
246 */
247#ifdef VBOX_WITH_2X_4GB_ADDR_SPACE
248 PGMR0DynMapTerm();
249#endif
250#ifdef VBOX_WITH_PCI_PASSTHROUGH
251 PciRawR0Term();
252#endif
253 PGMDeregisterStringFormatTypes();
254 HMR0Term();
255#ifdef VBOX_WITH_TRIPLE_FAULT_HACK
256 vmmR0TripleFaultHackTerm();
257#endif
258
259 /*
260 * Destroy the GMM and GVMM instances.
261 */
262 GMMR0Term();
263 GVMMR0Term();
264
265 vmmTermFormatTypes();
266
267 LogFlow(("ModuleTerm: returns\n"));
268}
269
270
271/**
272 * Initiates the R0 driver for a particular VM instance.
273 *
274 * @returns VBox status code.
275 *
276 * @param pVM Pointer to the VM.
277 * @param uSvnRev The SVN revision of the ring-3 part.
278 * @param uBuildType Build type indicator.
279 * @thread EMT.
280 */
281static int vmmR0InitVM(PVM pVM, uint32_t uSvnRev, uint32_t uBuildType)
282{
283 /*
284 * Match the SVN revisions and build type.
285 */
286 if (uSvnRev != VMMGetSvnRev())
287 {
288 LogRel(("VMMR0InitVM: Revision mismatch, r3=%d r0=%d\n", uSvnRev, VMMGetSvnRev()));
289 SUPR0Printf("VMMR0InitVM: Revision mismatch, r3=%d r0=%d\n", uSvnRev, VMMGetSvnRev());
290 return VERR_VMM_R0_VERSION_MISMATCH;
291 }
292 if (uBuildType != vmmGetBuildType())
293 {
294 LogRel(("VMMR0InitVM: Build type mismatch, r3=%#x r0=%#x\n", uBuildType, vmmGetBuildType()));
295 SUPR0Printf("VMMR0InitVM: Build type mismatch, r3=%#x r0=%#x\n", uBuildType, vmmGetBuildType());
296 return VERR_VMM_R0_VERSION_MISMATCH;
297 }
298 if ( !VALID_PTR(pVM)
299 || pVM->pVMR0 != pVM)
300 return VERR_INVALID_PARAMETER;
301
302
303#ifdef LOG_ENABLED
304 /*
305 * Register the EMT R0 logger instance for VCPU 0.
306 */
307 PVMCPU pVCpu = &pVM->aCpus[0];
308
309 PVMMR0LOGGER pR0Logger = pVCpu->vmm.s.pR0LoggerR0;
310 if (pR0Logger)
311 {
312# if 0 /* testing of the logger. */
313 LogCom(("vmmR0InitVM: before %p\n", RTLogDefaultInstance()));
314 LogCom(("vmmR0InitVM: pfnFlush=%p actual=%p\n", pR0Logger->Logger.pfnFlush, vmmR0LoggerFlush));
315 LogCom(("vmmR0InitVM: pfnLogger=%p actual=%p\n", pR0Logger->Logger.pfnLogger, vmmR0LoggerWrapper));
316 LogCom(("vmmR0InitVM: offScratch=%d fFlags=%#x fDestFlags=%#x\n", pR0Logger->Logger.offScratch, pR0Logger->Logger.fFlags, pR0Logger->Logger.fDestFlags));
317
318 RTLogSetDefaultInstanceThread(&pR0Logger->Logger, (uintptr_t)pVM->pSession);
319 LogCom(("vmmR0InitVM: after %p reg\n", RTLogDefaultInstance()));
320 RTLogSetDefaultInstanceThread(NULL, pVM->pSession);
321 LogCom(("vmmR0InitVM: after %p dereg\n", RTLogDefaultInstance()));
322
323 pR0Logger->Logger.pfnLogger("hello ring-0 logger\n");
324 LogCom(("vmmR0InitVM: returned successfully from direct logger call.\n"));
325 pR0Logger->Logger.pfnFlush(&pR0Logger->Logger);
326 LogCom(("vmmR0InitVM: returned successfully from direct flush call.\n"));
327
328 RTLogSetDefaultInstanceThread(&pR0Logger->Logger, (uintptr_t)pVM->pSession);
329 LogCom(("vmmR0InitVM: after %p reg2\n", RTLogDefaultInstance()));
330 pR0Logger->Logger.pfnLogger("hello ring-0 logger\n");
331 LogCom(("vmmR0InitVM: returned successfully from direct logger call (2). offScratch=%d\n", pR0Logger->Logger.offScratch));
332 RTLogSetDefaultInstanceThread(NULL, pVM->pSession);
333 LogCom(("vmmR0InitVM: after %p dereg2\n", RTLogDefaultInstance()));
334
335 RTLogLoggerEx(&pR0Logger->Logger, 0, ~0U, "hello ring-0 logger (RTLogLoggerEx)\n");
336 LogCom(("vmmR0InitVM: RTLogLoggerEx returned fine offScratch=%d\n", pR0Logger->Logger.offScratch));
337
338 RTLogSetDefaultInstanceThread(&pR0Logger->Logger, (uintptr_t)pVM->pSession);
339 RTLogPrintf("hello ring-0 logger (RTLogPrintf)\n");
340 LogCom(("vmmR0InitVM: RTLogPrintf returned fine offScratch=%d\n", pR0Logger->Logger.offScratch));
341# endif
342 Log(("Switching to per-thread logging instance %p (key=%p)\n", &pR0Logger->Logger, pVM->pSession));
343 RTLogSetDefaultInstanceThread(&pR0Logger->Logger, (uintptr_t)pVM->pSession);
344 pR0Logger->fRegistered = true;
345 }
346#endif /* LOG_ENABLED */
347
348 /*
349 * Check if the host supports high resolution timers or not.
350 */
351 if ( pVM->vmm.s.fUsePeriodicPreemptionTimers
352 && !RTTimerCanDoHighResolution())
353 pVM->vmm.s.fUsePeriodicPreemptionTimers = false;
354
355 /*
356 * Initialize the per VM data for GVMM and GMM.
357 */
358 int rc = GVMMR0InitVM(pVM);
359// if (RT_SUCCESS(rc))
360// rc = GMMR0InitPerVMData(pVM);
361 if (RT_SUCCESS(rc))
362 {
363 /*
364 * Init HM, CPUM and PGM (Darwin only).
365 */
366 rc = HMR0InitVM(pVM);
367 if (RT_SUCCESS(rc))
368 {
369 rc = CPUMR0InitVM(pVM);
370 if (RT_SUCCESS(rc))
371 {
372#ifdef VBOX_WITH_2X_4GB_ADDR_SPACE
373 rc = PGMR0DynMapInitVM(pVM);
374#endif
375 if (RT_SUCCESS(rc))
376 {
377#ifdef VBOX_WITH_PCI_PASSTHROUGH
378 rc = PciRawR0InitVM(pVM);
379#endif
380 if (RT_SUCCESS(rc))
381 {
382 rc = GIMR0InitVM(pVM);
383 if (RT_SUCCESS(rc))
384 {
385 GVMMR0DoneInitVM(pVM);
386 return rc;
387 }
388
389 /* bail out*/
390#ifdef VBOX_WITH_PCI_PASSTHROUGH
391 PciRawR0TermVM(pVM);
392#endif
393 }
394 }
395 }
396 HMR0TermVM(pVM);
397 }
398 }
399
400
401 RTLogSetDefaultInstanceThread(NULL, (uintptr_t)pVM->pSession);
402 return rc;
403}
404
405
406/**
407 * Terminates the R0 bits for a particular VM instance.
408 *
409 * This is normally called by ring-3 as part of the VM termination process, but
410 * may alternatively be called during the support driver session cleanup when
411 * the VM object is destroyed (see GVMM).
412 *
413 * @returns VBox status code.
414 *
415 * @param pVM Pointer to the VM.
416 * @param pGVM Pointer to the global VM structure. Optional.
417 * @thread EMT or session clean up thread.
418 */
419VMMR0_INT_DECL(int) VMMR0TermVM(PVM pVM, PGVM pGVM)
420{
421#ifdef VBOX_WITH_PCI_PASSTHROUGH
422 PciRawR0TermVM(pVM);
423#endif
424
425 /*
426 * Tell GVMM what we're up to and check that we only do this once.
427 */
428 if (GVMMR0DoingTermVM(pVM, pGVM))
429 {
430 GIMR0TermVM(pVM);
431
432 /** @todo I wish to call PGMR0PhysFlushHandyPages(pVM, &pVM->aCpus[idCpu])
433 * here to make sure we don't leak any shared pages if we crash... */
434#ifdef VBOX_WITH_2X_4GB_ADDR_SPACE
435 PGMR0DynMapTermVM(pVM);
436#endif
437 HMR0TermVM(pVM);
438 }
439
440 /*
441 * Deregister the logger.
442 */
443 RTLogSetDefaultInstanceThread(NULL, (uintptr_t)pVM->pSession);
444 return VINF_SUCCESS;
445}
446
447
448/**
449 * VMM ring-0 thread-context callback.
450 *
451 * This does common HM state updating and calls the HM-specific thread-context
452 * callback.
453 *
454 * @param enmEvent The thread-context event.
455 * @param pvUser Opaque pointer to the VMCPU.
456 *
457 * @thread EMT(pvUser)
458 */
459static DECLCALLBACK(void) vmmR0ThreadCtxCallback(RTTHREADCTXEVENT enmEvent, void *pvUser)
460{
461 PVMCPU pVCpu = (PVMCPU)pvUser;
462
463 switch (enmEvent)
464 {
465 case RTTHREADCTXEVENT_IN:
466 {
467 /*
468 * Linux may call us with preemption enabled (really!) but technically we
469 * cannot get preempted here, otherwise we end up in an infinite recursion
470 * scenario (i.e. preempted in resume hook -> preempt hook -> resume hook...
471 * ad infinitum). Let's just disable preemption for now...
472 */
473 /** @todo r=bird: I don't believe the above. The linux code is clearly enabling
474 * preemption after doing the callout (one or two functions up the
475 * call chain). */
476 RTTHREADPREEMPTSTATE ParanoidPreemptState = RTTHREADPREEMPTSTATE_INITIALIZER;
477 RTThreadPreemptDisable(&ParanoidPreemptState);
478
479 /* We need to update the VCPU <-> host CPU mapping. */
480 RTCPUID idHostCpu;
481 uint32_t iHostCpuSet = RTMpCurSetIndexAndId(&idHostCpu);
482 pVCpu->iHostCpuSet = iHostCpuSet;
483 ASMAtomicWriteU32(&pVCpu->idHostCpu, idHostCpu);
484
485 /* In the very unlikely event that the GIP delta for the CPU we're
486 rescheduled needs calculating, try force a return to ring-3.
487 We unfortunately cannot do the measurements right here. */
488 if (RT_UNLIKELY(SUPIsTscDeltaAvailableForCpuSetIndex(iHostCpuSet)))
489 VMCPU_FF_SET(pVCpu, VMCPU_FF_TO_R3);
490
491 /* Invoke the HM-specific thread-context callback. */
492 HMR0ThreadCtxCallback(enmEvent, pvUser);
493
494 /* Restore preemption. */
495 RTThreadPreemptRestore(&ParanoidPreemptState);
496 break;
497 }
498
499 case RTTHREADCTXEVENT_OUT:
500 {
501 /* Invoke the HM-specific thread-context callback. */
502 HMR0ThreadCtxCallback(enmEvent, pvUser);
503
504 /*
505 * Sigh. See VMMGetCpu() used by VMCPU_ASSERT_EMT(). We cannot let several VCPUs
506 * have the same host CPU associated with it.
507 */
508 pVCpu->iHostCpuSet = UINT32_MAX;
509 ASMAtomicWriteU32(&pVCpu->idHostCpu, NIL_RTCPUID);
510 break;
511 }
512
513 default:
514 /* Invoke the HM-specific thread-context callback. */
515 HMR0ThreadCtxCallback(enmEvent, pvUser);
516 break;
517 }
518}
519
520
521/**
522 * Creates thread switching hook for the current EMT thread.
523 *
524 * This is called by GVMMR0CreateVM and GVMMR0RegisterVCpu. If the host
525 * platform does not implement switcher hooks, no hooks will be create and the
526 * member set to NIL_RTTHREADCTXHOOK.
527 *
528 * @returns VBox status code.
529 * @param pVCpu Pointer to the cross context CPU structure.
530 * @thread EMT(pVCpu)
531 */
532VMMR0_INT_DECL(int) VMMR0ThreadCtxHookCreateForEmt(PVMCPU pVCpu)
533{
534 VMCPU_ASSERT_EMT(pVCpu);
535 Assert(pVCpu->vmm.s.hCtxHook == NIL_RTTHREADCTXHOOK);
536
537 int rc = RTThreadCtxHookCreate(&pVCpu->vmm.s.hCtxHook, 0, vmmR0ThreadCtxCallback, pVCpu);
538 if (RT_SUCCESS(rc))
539 return rc;
540
541 pVCpu->vmm.s.hCtxHook = NIL_RTTHREADCTXHOOK;
542 if (rc == VERR_NOT_SUPPORTED)
543 return VINF_SUCCESS;
544
545 LogRelMax(32, ("RTThreadCtxHookCreate failed! rc=%Rrc pVCpu=%p idCpu=%RU32\n", rc, pVCpu, pVCpu->idCpu));
546 return VINF_SUCCESS; /* Just ignore it, we can live without context hooks. */
547}
548
549
550/**
551 * Destroys the thread switching hook for the specified VCPU.
552 *
553 * @param pVCpu Pointer to the cross context CPU structure.
554 * @remarks Can be called from any thread.
555 */
556VMMR0_INT_DECL(void) VMMR0ThreadCtxHookDestroyForEmt(PVMCPU pVCpu)
557{
558 int rc = RTThreadCtxHookDestroy(pVCpu->vmm.s.hCtxHook);
559 AssertRC(rc);
560}
561
562
563/**
564 * Disables the thread switching hook for this VCPU (if we got one).
565 *
566 * @param pVCpu Pointer to the cross context CPU structure.
567 * @thread EMT(pVCpu)
568 *
569 * @remarks This also clears VMCPU::idHostCpu, so the mapping is invalid after
570 * this call. This means you have to be careful with what you do!
571 */
572VMMR0_INT_DECL(void) VMMR0ThreadCtxHookDisable(PVMCPU pVCpu)
573{
574 /*
575 * Clear the VCPU <-> host CPU mapping as we've left HM context.
576 * @bugref{7726} comment #19 explains the need for this trick:
577 *
578 * hmR0VmxCallRing3Callback/hmR0SvmCallRing3Callback &
579 * hmR0VmxLeaveSession/hmR0SvmLeaveSession disables context hooks during
580 * longjmp & normal return to ring-3, which opens a window where we may be
581 * rescheduled without changing VMCPUID::idHostCpu and cause confusion if
582 * the CPU starts executing a different EMT. Both functions first disables
583 * preemption and then calls HMR0LeaveCpu which invalids idHostCpu, leaving
584 * an opening for getting preempted.
585 */
586 /** @todo Make HM not need this API! Then we could leave the hooks enabled
587 * all the time. */
588 /** @todo move this into the context hook disabling if(). */
589 ASMAtomicWriteU32(&pVCpu->idHostCpu, NIL_RTCPUID);
590
591 /*
592 * Disable the context hook, if we got one.
593 */
594 if (pVCpu->vmm.s.hCtxHook != NIL_RTTHREADCTXHOOK)
595 {
596 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
597 int rc = RTThreadCtxHookDisable(pVCpu->vmm.s.hCtxHook);
598 AssertRC(rc);
599 }
600}
601
602
603/**
604 * Internal version of VMMR0ThreadCtxHooksAreRegistered.
605 *
606 * @returns true if registered, false otherwise.
607 * @param pVCpu Pointer to the VMCPU.
608 */
609DECLINLINE(bool) vmmR0ThreadCtxHookIsEnabled(PVMCPU pVCpu)
610{
611 return RTThreadCtxHookIsEnabled(pVCpu->vmm.s.hCtxHook);
612}
613
614
615/**
616 * Whether thread-context hooks are registered for this VCPU.
617 *
618 * @returns true if registered, false otherwise.
619 * @param pVCpu Pointer to the VMCPU.
620 */
621VMMR0_INT_DECL(bool) VMMR0ThreadCtxHookIsEnabled(PVMCPU pVCpu)
622{
623 return vmmR0ThreadCtxHookIsEnabled(pVCpu);
624}
625
626
627#ifdef VBOX_WITH_STATISTICS
628/**
629 * Record return code statistics
630 * @param pVM Pointer to the VM.
631 * @param pVCpu Pointer to the VMCPU.
632 * @param rc The status code.
633 */
634static void vmmR0RecordRC(PVM pVM, PVMCPU pVCpu, int rc)
635{
636 /*
637 * Collect statistics.
638 */
639 switch (rc)
640 {
641 case VINF_SUCCESS:
642 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetNormal);
643 break;
644 case VINF_EM_RAW_INTERRUPT:
645 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetInterrupt);
646 break;
647 case VINF_EM_RAW_INTERRUPT_HYPER:
648 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetInterruptHyper);
649 break;
650 case VINF_EM_RAW_GUEST_TRAP:
651 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetGuestTrap);
652 break;
653 case VINF_EM_RAW_RING_SWITCH:
654 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetRingSwitch);
655 break;
656 case VINF_EM_RAW_RING_SWITCH_INT:
657 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetRingSwitchInt);
658 break;
659 case VINF_EM_RAW_STALE_SELECTOR:
660 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetStaleSelector);
661 break;
662 case VINF_EM_RAW_IRET_TRAP:
663 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetIRETTrap);
664 break;
665 case VINF_IOM_R3_IOPORT_READ:
666 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetIORead);
667 break;
668 case VINF_IOM_R3_IOPORT_WRITE:
669 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetIOWrite);
670 break;
671 case VINF_IOM_R3_MMIO_READ:
672 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetMMIORead);
673 break;
674 case VINF_IOM_R3_MMIO_WRITE:
675 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetMMIOWrite);
676 break;
677 case VINF_IOM_R3_MMIO_READ_WRITE:
678 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetMMIOReadWrite);
679 break;
680 case VINF_PATM_HC_MMIO_PATCH_READ:
681 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetMMIOPatchRead);
682 break;
683 case VINF_PATM_HC_MMIO_PATCH_WRITE:
684 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetMMIOPatchWrite);
685 break;
686 case VINF_CPUM_R3_MSR_READ:
687 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetMSRRead);
688 break;
689 case VINF_CPUM_R3_MSR_WRITE:
690 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetMSRWrite);
691 break;
692 case VINF_EM_RAW_EMULATE_INSTR:
693 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetEmulate);
694 break;
695 case VINF_EM_RAW_EMULATE_IO_BLOCK:
696 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetIOBlockEmulate);
697 break;
698 case VINF_PATCH_EMULATE_INSTR:
699 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetPatchEmulate);
700 break;
701 case VINF_EM_RAW_EMULATE_INSTR_LDT_FAULT:
702 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetLDTFault);
703 break;
704 case VINF_EM_RAW_EMULATE_INSTR_GDT_FAULT:
705 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetGDTFault);
706 break;
707 case VINF_EM_RAW_EMULATE_INSTR_IDT_FAULT:
708 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetIDTFault);
709 break;
710 case VINF_EM_RAW_EMULATE_INSTR_TSS_FAULT:
711 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetTSSFault);
712 break;
713 case VINF_CSAM_PENDING_ACTION:
714 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetCSAMTask);
715 break;
716 case VINF_PGM_SYNC_CR3:
717 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetSyncCR3);
718 break;
719 case VINF_PATM_PATCH_INT3:
720 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetPatchInt3);
721 break;
722 case VINF_PATM_PATCH_TRAP_PF:
723 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetPatchPF);
724 break;
725 case VINF_PATM_PATCH_TRAP_GP:
726 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetPatchGP);
727 break;
728 case VINF_PATM_PENDING_IRQ_AFTER_IRET:
729 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetPatchIretIRQ);
730 break;
731 case VINF_EM_RESCHEDULE_REM:
732 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetRescheduleREM);
733 break;
734 case VINF_EM_RAW_TO_R3:
735 if (VM_FF_IS_PENDING(pVM, VM_FF_TM_VIRTUAL_SYNC))
736 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetToR3TMVirt);
737 else if (VM_FF_IS_PENDING(pVM, VM_FF_PGM_NEED_HANDY_PAGES))
738 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetToR3HandyPages);
739 else if (VM_FF_IS_PENDING(pVM, VM_FF_PDM_QUEUES))
740 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetToR3PDMQueues);
741 else if (VM_FF_IS_PENDING(pVM, VM_FF_EMT_RENDEZVOUS))
742 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetToR3Rendezvous);
743 else if (VM_FF_IS_PENDING(pVM, VM_FF_PDM_DMA))
744 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetToR3DMA);
745 else if (VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_TIMER))
746 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetToR3Timer);
747 else if (VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_PDM_CRITSECT))
748 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetToR3CritSect);
749 else if (VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_TO_R3))
750 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetToR3);
751 else
752 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetToR3Unknown);
753 break;
754
755 case VINF_EM_RAW_TIMER_PENDING:
756 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetTimerPending);
757 break;
758 case VINF_EM_RAW_INTERRUPT_PENDING:
759 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetInterruptPending);
760 break;
761 case VINF_VMM_CALL_HOST:
762 switch (pVCpu->vmm.s.enmCallRing3Operation)
763 {
764 case VMMCALLRING3_PDM_CRIT_SECT_ENTER:
765 STAM_COUNTER_INC(&pVM->vmm.s.StatRZCallPDMCritSectEnter);
766 break;
767 case VMMCALLRING3_PDM_LOCK:
768 STAM_COUNTER_INC(&pVM->vmm.s.StatRZCallPDMLock);
769 break;
770 case VMMCALLRING3_PGM_POOL_GROW:
771 STAM_COUNTER_INC(&pVM->vmm.s.StatRZCallPGMPoolGrow);
772 break;
773 case VMMCALLRING3_PGM_LOCK:
774 STAM_COUNTER_INC(&pVM->vmm.s.StatRZCallPGMLock);
775 break;
776 case VMMCALLRING3_PGM_MAP_CHUNK:
777 STAM_COUNTER_INC(&pVM->vmm.s.StatRZCallPGMMapChunk);
778 break;
779 case VMMCALLRING3_PGM_ALLOCATE_HANDY_PAGES:
780 STAM_COUNTER_INC(&pVM->vmm.s.StatRZCallPGMAllocHandy);
781 break;
782 case VMMCALLRING3_REM_REPLAY_HANDLER_NOTIFICATIONS:
783 STAM_COUNTER_INC(&pVM->vmm.s.StatRZCallRemReplay);
784 break;
785 case VMMCALLRING3_VMM_LOGGER_FLUSH:
786 STAM_COUNTER_INC(&pVM->vmm.s.StatRZCallLogFlush);
787 break;
788 case VMMCALLRING3_VM_SET_ERROR:
789 STAM_COUNTER_INC(&pVM->vmm.s.StatRZCallVMSetError);
790 break;
791 case VMMCALLRING3_VM_SET_RUNTIME_ERROR:
792 STAM_COUNTER_INC(&pVM->vmm.s.StatRZCallVMSetRuntimeError);
793 break;
794 case VMMCALLRING3_VM_R0_ASSERTION:
795 default:
796 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetCallRing3);
797 break;
798 }
799 break;
800 case VINF_PATM_DUPLICATE_FUNCTION:
801 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetPATMDuplicateFn);
802 break;
803 case VINF_PGM_CHANGE_MODE:
804 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetPGMChangeMode);
805 break;
806 case VINF_PGM_POOL_FLUSH_PENDING:
807 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetPGMFlushPending);
808 break;
809 case VINF_EM_PENDING_REQUEST:
810 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetPendingRequest);
811 break;
812 case VINF_EM_HM_PATCH_TPR_INSTR:
813 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetPatchTPR);
814 break;
815 default:
816 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetMisc);
817 break;
818 }
819}
820#endif /* VBOX_WITH_STATISTICS */
821
822
823/**
824 * Unused ring-0 entry point that used to be called from the interrupt gate.
825 *
826 * Will be removed one of the next times we do a major SUPDrv version bump.
827 *
828 * @returns VBox status code.
829 * @param pVM Pointer to the VM.
830 * @param enmOperation Which operation to execute.
831 * @param pvArg Argument to the operation.
832 * @remarks Assume called with interrupts disabled.
833 */
834VMMR0DECL(int) VMMR0EntryInt(PVM pVM, VMMR0OPERATION enmOperation, void *pvArg)
835{
836 /*
837 * We're returning VERR_NOT_SUPPORT here so we've got something else
838 * than -1 which the interrupt gate glue code might return.
839 */
840 Log(("operation %#x is not supported\n", enmOperation));
841 NOREF(enmOperation); NOREF(pvArg); NOREF(pVM);
842 return VERR_NOT_SUPPORTED;
843}
844
845
846/**
847 * The Ring 0 entry point, called by the fast-ioctl path.
848 *
849 * @param pVM Pointer to the VM.
850 * The return code is stored in pVM->vmm.s.iLastGZRc.
851 * @param idCpu The Virtual CPU ID of the calling EMT.
852 * @param enmOperation Which operation to execute.
853 * @remarks Assume called with interrupts _enabled_.
854 */
855VMMR0DECL(void) VMMR0EntryFast(PVM pVM, VMCPUID idCpu, VMMR0OPERATION enmOperation)
856{
857 /*
858 * Validation.
859 */
860 if (RT_UNLIKELY(idCpu >= pVM->cCpus))
861 return;
862 PVMCPU pVCpu = &pVM->aCpus[idCpu];
863 if (RT_UNLIKELY(pVCpu->hNativeThreadR0 != RTThreadNativeSelf()))
864 return;
865
866 /*
867 * Perform requested operation.
868 */
869 switch (enmOperation)
870 {
871 /*
872 * Switch to GC and run guest raw mode code.
873 * Disable interrupts before doing the world switch.
874 */
875 case VMMR0_DO_RAW_RUN:
876 {
877#ifndef VBOX_WITH_2X_4GB_ADDR_SPACE_IN_R0
878 /* Some safety precautions first. */
879 if (RT_UNLIKELY(!PGMGetHyperCR3(pVCpu)))
880 {
881 pVCpu->vmm.s.iLastGZRc = VERR_PGM_NO_CR3_SHADOW_ROOT;
882 break;
883 }
884#endif
885
886 /*
887 * Disable preemption.
888 */
889 RTTHREADPREEMPTSTATE PreemptState = RTTHREADPREEMPTSTATE_INITIALIZER;
890 RTThreadPreemptDisable(&PreemptState);
891
892 /*
893 * Get the host CPU identifiers, make sure they are valid and that
894 * we've got a TSC delta for the CPU.
895 */
896 RTCPUID idHostCpu;
897 uint32_t iHostCpuSet = RTMpCurSetIndexAndId(&idHostCpu);
898 if (RT_LIKELY( iHostCpuSet < RTCPUSET_MAX_CPUS
899 && SUPIsTscDeltaAvailableForCpuSetIndex(iHostCpuSet)))
900 {
901 /*
902 * Commit the CPU identifiers and update the periodict preemption timer if it's active.
903 */
904#ifdef VBOX_WITH_VMMR0_DISABLE_LAPIC_NMI
905 CPUMR0SetLApic(pVCpu, iHostCpuSet);
906#endif
907 pVCpu->iHostCpuSet = iHostCpuSet;
908 ASMAtomicWriteU32(&pVCpu->idHostCpu, idHostCpu);
909
910 if (pVM->vmm.s.fUsePeriodicPreemptionTimers)
911 GVMMR0SchedUpdatePeriodicPreemptionTimer(pVM, pVCpu->idHostCpu, TMCalcHostTimerFrequency(pVM, pVCpu));
912
913 /*
914 * We might need to disable VT-x if the active switcher turns off paging.
915 */
916 bool fVTxDisabled;
917 int rc = HMR0EnterSwitcher(pVM, pVM->vmm.s.enmSwitcher, &fVTxDisabled);
918 if (RT_SUCCESS(rc))
919 {
920 /*
921 * Disable interrupts and run raw-mode code. The loop is for efficiently
922 * dispatching tracepoints that fired in raw-mode context.
923 */
924 RTCCUINTREG uFlags = ASMIntDisableFlags();
925
926 for (;;)
927 {
928 VMCPU_SET_STATE(pVCpu, VMCPUSTATE_STARTED_EXEC);
929 TMNotifyStartOfExecution(pVCpu);
930
931 rc = pVM->vmm.s.pfnR0ToRawMode(pVM);
932 pVCpu->vmm.s.iLastGZRc = rc;
933
934 TMNotifyEndOfExecution(pVCpu);
935 VMCPU_SET_STATE(pVCpu, VMCPUSTATE_STARTED);
936
937 if (rc != VINF_VMM_CALL_TRACER)
938 break;
939 SUPR0TracerUmodProbeFire(pVM->pSession, &pVCpu->vmm.s.TracerCtx);
940 }
941
942 /*
943 * Re-enable VT-x before we dispatch any pending host interrupts and
944 * re-enables interrupts.
945 */
946 HMR0LeaveSwitcher(pVM, fVTxDisabled);
947
948 if ( rc == VINF_EM_RAW_INTERRUPT
949 || rc == VINF_EM_RAW_INTERRUPT_HYPER)
950 TRPMR0DispatchHostInterrupt(pVM);
951
952 ASMSetFlags(uFlags);
953
954 /* Fire dtrace probe and collect statistics. */
955 VBOXVMM_R0_VMM_RETURN_TO_RING3_RC(pVCpu, CPUMQueryGuestCtxPtr(pVCpu), rc);
956#ifdef VBOX_WITH_STATISTICS
957 STAM_COUNTER_INC(&pVM->vmm.s.StatRunRC);
958 vmmR0RecordRC(pVM, pVCpu, rc);
959#endif
960 }
961 else
962 pVCpu->vmm.s.iLastGZRc = rc;
963
964 /*
965 * Invalidate the host CPU identifiers as we restore preemption.
966 */
967 pVCpu->iHostCpuSet = UINT32_MAX;
968 ASMAtomicWriteU32(&pVCpu->idHostCpu, NIL_RTCPUID);
969
970 RTThreadPreemptRestore(&PreemptState);
971 }
972 /*
973 * Invalid CPU set index or TSC delta in need of measuring.
974 */
975 else
976 {
977 RTThreadPreemptRestore(&PreemptState);
978 if (iHostCpuSet < RTCPUSET_MAX_CPUS)
979 {
980 int rc = SUPR0TscDeltaMeasureBySetIndex(pVM->pSession, iHostCpuSet, 0 /*fFlags*/,
981 2 /*cMsWaitRetry*/, 5*RT_MS_1SEC /*cMsWaitThread*/,
982 0 /*default cTries*/);
983 if (RT_SUCCESS(rc) || rc == VERR_CPU_OFFLINE)
984 pVCpu->vmm.s.iLastGZRc = VINF_EM_RAW_TO_R3;
985 else
986 pVCpu->vmm.s.iLastGZRc = rc;
987 }
988 else
989 pVCpu->vmm.s.iLastGZRc = VERR_INVALID_CPU_INDEX;
990 }
991 break;
992 }
993
994 /*
995 * Run guest code using the available hardware acceleration technology.
996 */
997 case VMMR0_DO_HM_RUN:
998 {
999 /*
1000 * Disable preemption.
1001 */
1002 Assert(!vmmR0ThreadCtxHookIsEnabled(pVCpu));
1003 RTTHREADPREEMPTSTATE PreemptState = RTTHREADPREEMPTSTATE_INITIALIZER;
1004 RTThreadPreemptDisable(&PreemptState);
1005
1006 /*
1007 * Get the host CPU identifiers, make sure they are valid and that
1008 * we've got a TSC delta for the CPU.
1009 */
1010 RTCPUID idHostCpu;
1011 uint32_t iHostCpuSet = RTMpCurSetIndexAndId(&idHostCpu);
1012 if (RT_LIKELY( iHostCpuSet < RTCPUSET_MAX_CPUS
1013 && SUPIsTscDeltaAvailableForCpuSetIndex(iHostCpuSet)))
1014 {
1015 pVCpu->iHostCpuSet = iHostCpuSet;
1016 ASMAtomicWriteU32(&pVCpu->idHostCpu, idHostCpu);
1017
1018 /*
1019 * Update the periodic preemption timer if it's active.
1020 */
1021 if (pVM->vmm.s.fUsePeriodicPreemptionTimers)
1022 GVMMR0SchedUpdatePeriodicPreemptionTimer(pVM, pVCpu->idHostCpu, TMCalcHostTimerFrequency(pVM, pVCpu));
1023
1024#ifdef LOG_ENABLED
1025 /*
1026 * Ugly: Lazy registration of ring 0 loggers.
1027 */
1028 if (pVCpu->idCpu > 0)
1029 {
1030 PVMMR0LOGGER pR0Logger = pVCpu->vmm.s.pR0LoggerR0;
1031 if ( pR0Logger
1032 && RT_UNLIKELY(!pR0Logger->fRegistered))
1033 {
1034 RTLogSetDefaultInstanceThread(&pR0Logger->Logger, (uintptr_t)pVM->pSession);
1035 pR0Logger->fRegistered = true;
1036 }
1037 }
1038#endif
1039
1040 int rc;
1041 bool fPreemptRestored = false;
1042 if (!HMR0SuspendPending())
1043 {
1044 /*
1045 * Enable the context switching hook.
1046 */
1047 if (pVCpu->vmm.s.hCtxHook != NIL_RTTHREADCTXHOOK)
1048 {
1049 Assert(!RTThreadCtxHookIsEnabled(pVCpu->vmm.s.hCtxHook));
1050 int rc2 = RTThreadCtxHookEnable(pVCpu->vmm.s.hCtxHook); AssertRC(rc2);
1051 }
1052
1053 /*
1054 * Enter HM context.
1055 */
1056 rc = HMR0Enter(pVM, pVCpu);
1057 if (RT_SUCCESS(rc))
1058 {
1059 VMCPU_SET_STATE(pVCpu, VMCPUSTATE_STARTED_HM);
1060
1061 /*
1062 * When preemption hooks are in place, enable preemption now that
1063 * we're in HM context.
1064 */
1065 if (vmmR0ThreadCtxHookIsEnabled(pVCpu))
1066 {
1067 fPreemptRestored = true;
1068 RTThreadPreemptRestore(&PreemptState);
1069 }
1070
1071 /*
1072 * Setup the longjmp machinery and execute guest code (calls HMR0RunGuestCode).
1073 */
1074 rc = vmmR0CallRing3SetJmp(&pVCpu->vmm.s.CallRing3JmpBufR0, HMR0RunGuestCode, pVM, pVCpu);
1075
1076 /*
1077 * Assert sanity on the way out. Using manual assertions code here as normal
1078 * assertions are going to panic the host since we're outside the setjmp/longjmp zone.
1079 */
1080 if (RT_UNLIKELY( VMCPU_GET_STATE(pVCpu) != VMCPUSTATE_STARTED_HM
1081 && RT_SUCCESS_NP(rc) && rc != VINF_VMM_CALL_HOST ))
1082 {
1083 pVM->vmm.s.szRing0AssertMsg1[0] = '\0';
1084 RTStrPrintf(pVM->vmm.s.szRing0AssertMsg2, sizeof(pVM->vmm.s.szRing0AssertMsg2),
1085 "Got VMCPU state %d expected %d.\n", VMCPU_GET_STATE(pVCpu), VMCPUSTATE_STARTED_HM);
1086 rc = VERR_VMM_WRONG_HM_VMCPU_STATE;
1087 }
1088 /** @todo Get rid of this. HM shouldn't disable the context hook. */
1089 else if (RT_UNLIKELY(vmmR0ThreadCtxHookIsEnabled(pVCpu)))
1090 {
1091 pVM->vmm.s.szRing0AssertMsg1[0] = '\0';
1092 RTStrPrintf(pVM->vmm.s.szRing0AssertMsg2, sizeof(pVM->vmm.s.szRing0AssertMsg2),
1093 "Thread-context hooks still enabled! VCPU=%p Id=%u rc=%d.\n", pVCpu, pVCpu->idCpu, rc);
1094 rc = VERR_INVALID_STATE;
1095 }
1096
1097 VMCPU_SET_STATE(pVCpu, VMCPUSTATE_STARTED);
1098 }
1099 STAM_COUNTER_INC(&pVM->vmm.s.StatRunRC);
1100
1101 /*
1102 * Invalidate the host CPU identifiers before we disable the context
1103 * hook / restore preemption.
1104 */
1105 pVCpu->iHostCpuSet = UINT32_MAX;
1106 ASMAtomicWriteU32(&pVCpu->idHostCpu, NIL_RTCPUID);
1107
1108 /*
1109 * Disable context hooks. Due to unresolved cleanup issues, we
1110 * cannot leave the hooks enabled when we return to ring-3.
1111 *
1112 * Note! At the moment HM may also have disabled the hook
1113 * when we get here, but the IPRT API handles that.
1114 */
1115 if (pVCpu->vmm.s.hCtxHook != NIL_RTTHREADCTXHOOK)
1116 {
1117 ASMAtomicWriteU32(&pVCpu->idHostCpu, NIL_RTCPUID);
1118 RTThreadCtxHookDisable(pVCpu->vmm.s.hCtxHook);
1119 }
1120 }
1121 /*
1122 * The system is about to go into suspend mode; go back to ring 3.
1123 */
1124 else
1125 {
1126 rc = VINF_EM_RAW_INTERRUPT;
1127 pVCpu->iHostCpuSet = UINT32_MAX;
1128 ASMAtomicWriteU32(&pVCpu->idHostCpu, NIL_RTCPUID);
1129 }
1130
1131 /** @todo When HM stops messing with the context hook state, we'll disable
1132 * preemption again before the RTThreadCtxHookDisable call. */
1133 if (!fPreemptRestored)
1134 RTThreadPreemptRestore(&PreemptState);
1135
1136 pVCpu->vmm.s.iLastGZRc = rc;
1137
1138 /* Fire dtrace probe and collect statistics. */
1139 VBOXVMM_R0_VMM_RETURN_TO_RING3_HM(pVCpu, CPUMQueryGuestCtxPtr(pVCpu), rc);
1140#ifdef VBOX_WITH_STATISTICS
1141 vmmR0RecordRC(pVM, pVCpu, rc);
1142#endif
1143 }
1144 /*
1145 * Invalid CPU set index or TSC delta in need of measuring.
1146 */
1147 else
1148 {
1149 pVCpu->iHostCpuSet = UINT32_MAX;
1150 ASMAtomicWriteU32(&pVCpu->idHostCpu, NIL_RTCPUID);
1151 RTThreadPreemptRestore(&PreemptState);
1152 if (iHostCpuSet < RTCPUSET_MAX_CPUS)
1153 {
1154 int rc = SUPR0TscDeltaMeasureBySetIndex(pVM->pSession, iHostCpuSet, 0 /*fFlags*/,
1155 2 /*cMsWaitRetry*/, 5*RT_MS_1SEC /*cMsWaitThread*/,
1156 0 /*default cTries*/);
1157 if (RT_SUCCESS(rc) || rc == VERR_CPU_OFFLINE)
1158 pVCpu->vmm.s.iLastGZRc = VINF_EM_RAW_TO_R3;
1159 else
1160 pVCpu->vmm.s.iLastGZRc = rc;
1161 }
1162 else
1163 pVCpu->vmm.s.iLastGZRc = VERR_INVALID_CPU_INDEX;
1164 }
1165 break;
1166 }
1167
1168 /*
1169 * For profiling.
1170 */
1171 case VMMR0_DO_NOP:
1172 pVCpu->vmm.s.iLastGZRc = VINF_SUCCESS;
1173 break;
1174
1175 /*
1176 * Impossible.
1177 */
1178 default:
1179 AssertMsgFailed(("%#x\n", enmOperation));
1180 pVCpu->vmm.s.iLastGZRc = VERR_NOT_SUPPORTED;
1181 break;
1182 }
1183}
1184
1185
1186/**
1187 * Validates a session or VM session argument.
1188 *
1189 * @returns true / false accordingly.
1190 * @param pVM Pointer to the VM.
1191 * @param pSession The session argument.
1192 */
1193DECLINLINE(bool) vmmR0IsValidSession(PVM pVM, PSUPDRVSESSION pClaimedSession, PSUPDRVSESSION pSession)
1194{
1195 /* This must be set! */
1196 if (!pSession)
1197 return false;
1198
1199 /* Only one out of the two. */
1200 if (pVM && pClaimedSession)
1201 return false;
1202 if (pVM)
1203 pClaimedSession = pVM->pSession;
1204 return pClaimedSession == pSession;
1205}
1206
1207
1208/**
1209 * VMMR0EntryEx worker function, either called directly or when ever possible
1210 * called thru a longjmp so we can exit safely on failure.
1211 *
1212 * @returns VBox status code.
1213 * @param pVM Pointer to the VM.
1214 * @param idCpu Virtual CPU ID argument. Must be NIL_VMCPUID if pVM
1215 * is NIL_RTR0PTR, and may be NIL_VMCPUID if it isn't
1216 * @param enmOperation Which operation to execute.
1217 * @param pReqHdr This points to a SUPVMMR0REQHDR packet. Optional.
1218 * The support driver validates this if it's present.
1219 * @param u64Arg Some simple constant argument.
1220 * @param pSession The session of the caller.
1221 * @remarks Assume called with interrupts _enabled_.
1222 */
1223static int vmmR0EntryExWorker(PVM pVM, VMCPUID idCpu, VMMR0OPERATION enmOperation, PSUPVMMR0REQHDR pReqHdr, uint64_t u64Arg, PSUPDRVSESSION pSession)
1224{
1225 /*
1226 * Common VM pointer validation.
1227 */
1228 if (pVM)
1229 {
1230 if (RT_UNLIKELY( !VALID_PTR(pVM)
1231 || ((uintptr_t)pVM & PAGE_OFFSET_MASK)))
1232 {
1233 SUPR0Printf("vmmR0EntryExWorker: Invalid pVM=%p! (op=%d)\n", pVM, enmOperation);
1234 return VERR_INVALID_POINTER;
1235 }
1236 if (RT_UNLIKELY( pVM->enmVMState < VMSTATE_CREATING
1237 || pVM->enmVMState > VMSTATE_TERMINATED
1238 || pVM->pVMR0 != pVM))
1239 {
1240 SUPR0Printf("vmmR0EntryExWorker: Invalid pVM=%p:{enmVMState=%d, .pVMR0=%p}! (op=%d)\n",
1241 pVM, pVM->enmVMState, pVM->pVMR0, enmOperation);
1242 return VERR_INVALID_POINTER;
1243 }
1244
1245 if (RT_UNLIKELY(idCpu >= pVM->cCpus && idCpu != NIL_VMCPUID))
1246 {
1247 SUPR0Printf("vmmR0EntryExWorker: Invalid idCpu (%u vs cCpus=%u)\n", idCpu, pVM->cCpus);
1248 return VERR_INVALID_PARAMETER;
1249 }
1250 }
1251 else if (RT_UNLIKELY(idCpu != NIL_VMCPUID))
1252 {
1253 SUPR0Printf("vmmR0EntryExWorker: Invalid idCpu=%u\n", idCpu);
1254 return VERR_INVALID_PARAMETER;
1255 }
1256
1257
1258 switch (enmOperation)
1259 {
1260 /*
1261 * GVM requests
1262 */
1263 case VMMR0_DO_GVMM_CREATE_VM:
1264 if (pVM || u64Arg || idCpu != NIL_VMCPUID)
1265 return VERR_INVALID_PARAMETER;
1266 return GVMMR0CreateVMReq((PGVMMCREATEVMREQ)pReqHdr);
1267
1268 case VMMR0_DO_GVMM_DESTROY_VM:
1269 if (pReqHdr || u64Arg)
1270 return VERR_INVALID_PARAMETER;
1271 return GVMMR0DestroyVM(pVM);
1272
1273 case VMMR0_DO_GVMM_REGISTER_VMCPU:
1274 {
1275 if (!pVM)
1276 return VERR_INVALID_PARAMETER;
1277 return GVMMR0RegisterVCpu(pVM, idCpu);
1278 }
1279
1280 case VMMR0_DO_GVMM_SCHED_HALT:
1281 if (pReqHdr)
1282 return VERR_INVALID_PARAMETER;
1283 return GVMMR0SchedHalt(pVM, idCpu, u64Arg);
1284
1285 case VMMR0_DO_GVMM_SCHED_WAKE_UP:
1286 if (pReqHdr || u64Arg)
1287 return VERR_INVALID_PARAMETER;
1288 return GVMMR0SchedWakeUp(pVM, idCpu);
1289
1290 case VMMR0_DO_GVMM_SCHED_POKE:
1291 if (pReqHdr || u64Arg)
1292 return VERR_INVALID_PARAMETER;
1293 return GVMMR0SchedPoke(pVM, idCpu);
1294
1295 case VMMR0_DO_GVMM_SCHED_WAKE_UP_AND_POKE_CPUS:
1296 if (u64Arg)
1297 return VERR_INVALID_PARAMETER;
1298 return GVMMR0SchedWakeUpAndPokeCpusReq(pVM, (PGVMMSCHEDWAKEUPANDPOKECPUSREQ)pReqHdr);
1299
1300 case VMMR0_DO_GVMM_SCHED_POLL:
1301 if (pReqHdr || u64Arg > 1)
1302 return VERR_INVALID_PARAMETER;
1303 return GVMMR0SchedPoll(pVM, idCpu, !!u64Arg);
1304
1305 case VMMR0_DO_GVMM_QUERY_STATISTICS:
1306 if (u64Arg)
1307 return VERR_INVALID_PARAMETER;
1308 return GVMMR0QueryStatisticsReq(pVM, (PGVMMQUERYSTATISTICSSREQ)pReqHdr);
1309
1310 case VMMR0_DO_GVMM_RESET_STATISTICS:
1311 if (u64Arg)
1312 return VERR_INVALID_PARAMETER;
1313 return GVMMR0ResetStatisticsReq(pVM, (PGVMMRESETSTATISTICSSREQ)pReqHdr);
1314
1315 /*
1316 * Initialize the R0 part of a VM instance.
1317 */
1318 case VMMR0_DO_VMMR0_INIT:
1319 return vmmR0InitVM(pVM, RT_LODWORD(u64Arg), RT_HIDWORD(u64Arg));
1320
1321 /*
1322 * Terminate the R0 part of a VM instance.
1323 */
1324 case VMMR0_DO_VMMR0_TERM:
1325 return VMMR0TermVM(pVM, NULL);
1326
1327 /*
1328 * Attempt to enable hm mode and check the current setting.
1329 */
1330 case VMMR0_DO_HM_ENABLE:
1331 return HMR0EnableAllCpus(pVM);
1332
1333 /*
1334 * Setup the hardware accelerated session.
1335 */
1336 case VMMR0_DO_HM_SETUP_VM:
1337 return HMR0SetupVM(pVM);
1338
1339 /*
1340 * Switch to RC to execute Hypervisor function.
1341 */
1342 case VMMR0_DO_CALL_HYPERVISOR:
1343 {
1344 /*
1345 * Validate input / context.
1346 */
1347 if (RT_UNLIKELY(idCpu != 0))
1348 return VERR_INVALID_CPU_ID;
1349 if (RT_UNLIKELY(pVM->cCpus != 1))
1350 return VERR_INVALID_PARAMETER;
1351 PVMCPU pVCpu = &pVM->aCpus[idCpu];
1352#ifndef VBOX_WITH_2X_4GB_ADDR_SPACE_IN_R0
1353 if (RT_UNLIKELY(!PGMGetHyperCR3(pVCpu)))
1354 return VERR_PGM_NO_CR3_SHADOW_ROOT;
1355#endif
1356
1357 /*
1358 * Disable interrupts.
1359 */
1360 RTCCUINTREG fFlags = ASMIntDisableFlags();
1361
1362 /*
1363 * Get the host CPU identifiers, make sure they are valid and that
1364 * we've got a TSC delta for the CPU.
1365 */
1366 RTCPUID idHostCpu;
1367 uint32_t iHostCpuSet = RTMpCurSetIndexAndId(&idHostCpu);
1368 if (RT_UNLIKELY(iHostCpuSet >= RTCPUSET_MAX_CPUS))
1369 {
1370 ASMSetFlags(fFlags);
1371 return VERR_INVALID_CPU_INDEX;
1372 }
1373 if (RT_UNLIKELY(!SUPIsTscDeltaAvailableForCpuSetIndex(iHostCpuSet)))
1374 {
1375 ASMSetFlags(fFlags);
1376 int rc = SUPR0TscDeltaMeasureBySetIndex(pVM->pSession, iHostCpuSet, 0 /*fFlags*/,
1377 2 /*cMsWaitRetry*/, 5*RT_MS_1SEC /*cMsWaitThread*/,
1378 0 /*default cTries*/);
1379 if (RT_FAILURE(rc) && rc != VERR_CPU_OFFLINE)
1380 return rc;
1381 }
1382
1383 /*
1384 * Commit the CPU identifiers.
1385 */
1386#ifdef VBOX_WITH_VMMR0_DISABLE_LAPIC_NMI
1387 CPUMR0SetLApic(pVCpu, iHostCpuSet);
1388#endif
1389 pVCpu->iHostCpuSet = iHostCpuSet;
1390 ASMAtomicWriteU32(&pVCpu->idHostCpu, idHostCpu);
1391
1392 /*
1393 * We might need to disable VT-x if the active switcher turns off paging.
1394 */
1395 bool fVTxDisabled;
1396 int rc = HMR0EnterSwitcher(pVM, pVM->vmm.s.enmSwitcher, &fVTxDisabled);
1397 if (RT_SUCCESS(rc))
1398 {
1399 /*
1400 * Go through the wormhole...
1401 */
1402 rc = pVM->vmm.s.pfnR0ToRawMode(pVM);
1403
1404 /*
1405 * Re-enable VT-x before we dispatch any pending host interrupts.
1406 */
1407 HMR0LeaveSwitcher(pVM, fVTxDisabled);
1408
1409 if ( rc == VINF_EM_RAW_INTERRUPT
1410 || rc == VINF_EM_RAW_INTERRUPT_HYPER)
1411 TRPMR0DispatchHostInterrupt(pVM);
1412 }
1413
1414 /*
1415 * Invalidate the host CPU identifiers as we restore interrupts.
1416 */
1417 pVCpu->iHostCpuSet = UINT32_MAX;
1418 ASMAtomicWriteU32(&pVCpu->idHostCpu, NIL_RTCPUID);
1419 ASMSetFlags(fFlags);
1420 return rc;
1421 }
1422
1423 /*
1424 * PGM wrappers.
1425 */
1426 case VMMR0_DO_PGM_ALLOCATE_HANDY_PAGES:
1427 if (idCpu == NIL_VMCPUID)
1428 return VERR_INVALID_CPU_ID;
1429 return PGMR0PhysAllocateHandyPages(pVM, &pVM->aCpus[idCpu]);
1430
1431 case VMMR0_DO_PGM_FLUSH_HANDY_PAGES:
1432 if (idCpu == NIL_VMCPUID)
1433 return VERR_INVALID_CPU_ID;
1434 return PGMR0PhysFlushHandyPages(pVM, &pVM->aCpus[idCpu]);
1435
1436 case VMMR0_DO_PGM_ALLOCATE_LARGE_HANDY_PAGE:
1437 if (idCpu == NIL_VMCPUID)
1438 return VERR_INVALID_CPU_ID;
1439 return PGMR0PhysAllocateLargeHandyPage(pVM, &pVM->aCpus[idCpu]);
1440
1441 case VMMR0_DO_PGM_PHYS_SETUP_IOMMU:
1442 if (idCpu != 0)
1443 return VERR_INVALID_CPU_ID;
1444 return PGMR0PhysSetupIommu(pVM);
1445
1446 /*
1447 * GMM wrappers.
1448 */
1449 case VMMR0_DO_GMM_INITIAL_RESERVATION:
1450 if (u64Arg)
1451 return VERR_INVALID_PARAMETER;
1452 return GMMR0InitialReservationReq(pVM, idCpu, (PGMMINITIALRESERVATIONREQ)pReqHdr);
1453
1454 case VMMR0_DO_GMM_UPDATE_RESERVATION:
1455 if (u64Arg)
1456 return VERR_INVALID_PARAMETER;
1457 return GMMR0UpdateReservationReq(pVM, idCpu, (PGMMUPDATERESERVATIONREQ)pReqHdr);
1458
1459 case VMMR0_DO_GMM_ALLOCATE_PAGES:
1460 if (u64Arg)
1461 return VERR_INVALID_PARAMETER;
1462 return GMMR0AllocatePagesReq(pVM, idCpu, (PGMMALLOCATEPAGESREQ)pReqHdr);
1463
1464 case VMMR0_DO_GMM_FREE_PAGES:
1465 if (u64Arg)
1466 return VERR_INVALID_PARAMETER;
1467 return GMMR0FreePagesReq(pVM, idCpu, (PGMMFREEPAGESREQ)pReqHdr);
1468
1469 case VMMR0_DO_GMM_FREE_LARGE_PAGE:
1470 if (u64Arg)
1471 return VERR_INVALID_PARAMETER;
1472 return GMMR0FreeLargePageReq(pVM, idCpu, (PGMMFREELARGEPAGEREQ)pReqHdr);
1473
1474 case VMMR0_DO_GMM_QUERY_HYPERVISOR_MEM_STATS:
1475 if (u64Arg)
1476 return VERR_INVALID_PARAMETER;
1477 return GMMR0QueryHypervisorMemoryStatsReq(pVM, (PGMMMEMSTATSREQ)pReqHdr);
1478
1479 case VMMR0_DO_GMM_QUERY_MEM_STATS:
1480 if (idCpu == NIL_VMCPUID)
1481 return VERR_INVALID_CPU_ID;
1482 if (u64Arg)
1483 return VERR_INVALID_PARAMETER;
1484 return GMMR0QueryMemoryStatsReq(pVM, idCpu, (PGMMMEMSTATSREQ)pReqHdr);
1485
1486 case VMMR0_DO_GMM_BALLOONED_PAGES:
1487 if (u64Arg)
1488 return VERR_INVALID_PARAMETER;
1489 return GMMR0BalloonedPagesReq(pVM, idCpu, (PGMMBALLOONEDPAGESREQ)pReqHdr);
1490
1491 case VMMR0_DO_GMM_MAP_UNMAP_CHUNK:
1492 if (u64Arg)
1493 return VERR_INVALID_PARAMETER;
1494 return GMMR0MapUnmapChunkReq(pVM, (PGMMMAPUNMAPCHUNKREQ)pReqHdr);
1495
1496 case VMMR0_DO_GMM_SEED_CHUNK:
1497 if (pReqHdr)
1498 return VERR_INVALID_PARAMETER;
1499 return GMMR0SeedChunk(pVM, idCpu, (RTR3PTR)u64Arg);
1500
1501 case VMMR0_DO_GMM_REGISTER_SHARED_MODULE:
1502 if (idCpu == NIL_VMCPUID)
1503 return VERR_INVALID_CPU_ID;
1504 if (u64Arg)
1505 return VERR_INVALID_PARAMETER;
1506 return GMMR0RegisterSharedModuleReq(pVM, idCpu, (PGMMREGISTERSHAREDMODULEREQ)pReqHdr);
1507
1508 case VMMR0_DO_GMM_UNREGISTER_SHARED_MODULE:
1509 if (idCpu == NIL_VMCPUID)
1510 return VERR_INVALID_CPU_ID;
1511 if (u64Arg)
1512 return VERR_INVALID_PARAMETER;
1513 return GMMR0UnregisterSharedModuleReq(pVM, idCpu, (PGMMUNREGISTERSHAREDMODULEREQ)pReqHdr);
1514
1515 case VMMR0_DO_GMM_RESET_SHARED_MODULES:
1516 if (idCpu == NIL_VMCPUID)
1517 return VERR_INVALID_CPU_ID;
1518 if ( u64Arg
1519 || pReqHdr)
1520 return VERR_INVALID_PARAMETER;
1521 return GMMR0ResetSharedModules(pVM, idCpu);
1522
1523#ifdef VBOX_WITH_PAGE_SHARING
1524 case VMMR0_DO_GMM_CHECK_SHARED_MODULES:
1525 {
1526 if (idCpu == NIL_VMCPUID)
1527 return VERR_INVALID_CPU_ID;
1528 if ( u64Arg
1529 || pReqHdr)
1530 return VERR_INVALID_PARAMETER;
1531
1532 PVMCPU pVCpu = &pVM->aCpus[idCpu];
1533 Assert(pVCpu->hNativeThreadR0 == RTThreadNativeSelf());
1534
1535# ifdef DEBUG_sandervl
1536 /* Make sure that log flushes can jump back to ring-3; annoying to get an incomplete log (this is risky though as the code doesn't take this into account). */
1537 /* Todo: this can have bad side effects for unexpected jumps back to r3. */
1538 int rc = GMMR0CheckSharedModulesStart(pVM);
1539 if (rc == VINF_SUCCESS)
1540 {
1541 rc = vmmR0CallRing3SetJmp(&pVCpu->vmm.s.CallRing3JmpBufR0, GMMR0CheckSharedModules, pVM, pVCpu); /* this may resume code. */
1542 Assert( rc == VINF_SUCCESS
1543 || (rc == VINF_VMM_CALL_HOST && pVCpu->vmm.s.enmCallRing3Operation == VMMCALLRING3_VMM_LOGGER_FLUSH));
1544 GMMR0CheckSharedModulesEnd(pVM);
1545 }
1546# else
1547 int rc = GMMR0CheckSharedModules(pVM, pVCpu);
1548# endif
1549 return rc;
1550 }
1551#endif
1552
1553#if defined(VBOX_STRICT) && HC_ARCH_BITS == 64
1554 case VMMR0_DO_GMM_FIND_DUPLICATE_PAGE:
1555 if (u64Arg)
1556 return VERR_INVALID_PARAMETER;
1557 return GMMR0FindDuplicatePageReq(pVM, (PGMMFINDDUPLICATEPAGEREQ)pReqHdr);
1558#endif
1559
1560 case VMMR0_DO_GMM_QUERY_STATISTICS:
1561 if (u64Arg)
1562 return VERR_INVALID_PARAMETER;
1563 return GMMR0QueryStatisticsReq(pVM, (PGMMQUERYSTATISTICSSREQ)pReqHdr);
1564
1565 case VMMR0_DO_GMM_RESET_STATISTICS:
1566 if (u64Arg)
1567 return VERR_INVALID_PARAMETER;
1568 return GMMR0ResetStatisticsReq(pVM, (PGMMRESETSTATISTICSSREQ)pReqHdr);
1569
1570 /*
1571 * A quick GCFGM mock-up.
1572 */
1573 /** @todo GCFGM with proper access control, ring-3 management interface and all that. */
1574 case VMMR0_DO_GCFGM_SET_VALUE:
1575 case VMMR0_DO_GCFGM_QUERY_VALUE:
1576 {
1577 if (pVM || !pReqHdr || u64Arg || idCpu != NIL_VMCPUID)
1578 return VERR_INVALID_PARAMETER;
1579 PGCFGMVALUEREQ pReq = (PGCFGMVALUEREQ)pReqHdr;
1580 if (pReq->Hdr.cbReq != sizeof(*pReq))
1581 return VERR_INVALID_PARAMETER;
1582 int rc;
1583 if (enmOperation == VMMR0_DO_GCFGM_SET_VALUE)
1584 {
1585 rc = GVMMR0SetConfig(pReq->pSession, &pReq->szName[0], pReq->u64Value);
1586 //if (rc == VERR_CFGM_VALUE_NOT_FOUND)
1587 // rc = GMMR0SetConfig(pReq->pSession, &pReq->szName[0], pReq->u64Value);
1588 }
1589 else
1590 {
1591 rc = GVMMR0QueryConfig(pReq->pSession, &pReq->szName[0], &pReq->u64Value);
1592 //if (rc == VERR_CFGM_VALUE_NOT_FOUND)
1593 // rc = GMMR0QueryConfig(pReq->pSession, &pReq->szName[0], &pReq->u64Value);
1594 }
1595 return rc;
1596 }
1597
1598 /*
1599 * PDM Wrappers.
1600 */
1601 case VMMR0_DO_PDM_DRIVER_CALL_REQ_HANDLER:
1602 {
1603 if (!pVM || !pReqHdr || u64Arg || idCpu != NIL_VMCPUID)
1604 return VERR_INVALID_PARAMETER;
1605 return PDMR0DriverCallReqHandler(pVM, (PPDMDRIVERCALLREQHANDLERREQ)pReqHdr);
1606 }
1607
1608 case VMMR0_DO_PDM_DEVICE_CALL_REQ_HANDLER:
1609 {
1610 if (!pVM || !pReqHdr || u64Arg || idCpu != NIL_VMCPUID)
1611 return VERR_INVALID_PARAMETER;
1612 return PDMR0DeviceCallReqHandler(pVM, (PPDMDEVICECALLREQHANDLERREQ)pReqHdr);
1613 }
1614
1615 /*
1616 * Requests to the internal networking service.
1617 */
1618 case VMMR0_DO_INTNET_OPEN:
1619 {
1620 PINTNETOPENREQ pReq = (PINTNETOPENREQ)pReqHdr;
1621 if (u64Arg || !pReq || !vmmR0IsValidSession(pVM, pReq->pSession, pSession) || idCpu != NIL_VMCPUID)
1622 return VERR_INVALID_PARAMETER;
1623 return IntNetR0OpenReq(pSession, pReq);
1624 }
1625
1626 case VMMR0_DO_INTNET_IF_CLOSE:
1627 if (u64Arg || !pReqHdr || !vmmR0IsValidSession(pVM, ((PINTNETIFCLOSEREQ)pReqHdr)->pSession, pSession) || idCpu != NIL_VMCPUID)
1628 return VERR_INVALID_PARAMETER;
1629 return IntNetR0IfCloseReq(pSession, (PINTNETIFCLOSEREQ)pReqHdr);
1630
1631 case VMMR0_DO_INTNET_IF_GET_BUFFER_PTRS:
1632 if (u64Arg || !pReqHdr || !vmmR0IsValidSession(pVM, ((PINTNETIFGETBUFFERPTRSREQ)pReqHdr)->pSession, pSession) || idCpu != NIL_VMCPUID)
1633 return VERR_INVALID_PARAMETER;
1634 return IntNetR0IfGetBufferPtrsReq(pSession, (PINTNETIFGETBUFFERPTRSREQ)pReqHdr);
1635
1636 case VMMR0_DO_INTNET_IF_SET_PROMISCUOUS_MODE:
1637 if (u64Arg || !pReqHdr || !vmmR0IsValidSession(pVM, ((PINTNETIFSETPROMISCUOUSMODEREQ)pReqHdr)->pSession, pSession) || idCpu != NIL_VMCPUID)
1638 return VERR_INVALID_PARAMETER;
1639 return IntNetR0IfSetPromiscuousModeReq(pSession, (PINTNETIFSETPROMISCUOUSMODEREQ)pReqHdr);
1640
1641 case VMMR0_DO_INTNET_IF_SET_MAC_ADDRESS:
1642 if (u64Arg || !pReqHdr || !vmmR0IsValidSession(pVM, ((PINTNETIFSETMACADDRESSREQ)pReqHdr)->pSession, pSession) || idCpu != NIL_VMCPUID)
1643 return VERR_INVALID_PARAMETER;
1644 return IntNetR0IfSetMacAddressReq(pSession, (PINTNETIFSETMACADDRESSREQ)pReqHdr);
1645
1646 case VMMR0_DO_INTNET_IF_SET_ACTIVE:
1647 if (u64Arg || !pReqHdr || !vmmR0IsValidSession(pVM, ((PINTNETIFSETACTIVEREQ)pReqHdr)->pSession, pSession) || idCpu != NIL_VMCPUID)
1648 return VERR_INVALID_PARAMETER;
1649 return IntNetR0IfSetActiveReq(pSession, (PINTNETIFSETACTIVEREQ)pReqHdr);
1650
1651 case VMMR0_DO_INTNET_IF_SEND:
1652 if (u64Arg || !pReqHdr || !vmmR0IsValidSession(pVM, ((PINTNETIFSENDREQ)pReqHdr)->pSession, pSession) || idCpu != NIL_VMCPUID)
1653 return VERR_INVALID_PARAMETER;
1654 return IntNetR0IfSendReq(pSession, (PINTNETIFSENDREQ)pReqHdr);
1655
1656 case VMMR0_DO_INTNET_IF_WAIT:
1657 if (u64Arg || !pReqHdr || !vmmR0IsValidSession(pVM, ((PINTNETIFWAITREQ)pReqHdr)->pSession, pSession) || idCpu != NIL_VMCPUID)
1658 return VERR_INVALID_PARAMETER;
1659 return IntNetR0IfWaitReq(pSession, (PINTNETIFWAITREQ)pReqHdr);
1660
1661 case VMMR0_DO_INTNET_IF_ABORT_WAIT:
1662 if (u64Arg || !pReqHdr || !vmmR0IsValidSession(pVM, ((PINTNETIFWAITREQ)pReqHdr)->pSession, pSession) || idCpu != NIL_VMCPUID)
1663 return VERR_INVALID_PARAMETER;
1664 return IntNetR0IfAbortWaitReq(pSession, (PINTNETIFABORTWAITREQ)pReqHdr);
1665
1666#ifdef VBOX_WITH_PCI_PASSTHROUGH
1667 /*
1668 * Requests to host PCI driver service.
1669 */
1670 case VMMR0_DO_PCIRAW_REQ:
1671 if (u64Arg || !pReqHdr || !vmmR0IsValidSession(pVM, ((PPCIRAWSENDREQ)pReqHdr)->pSession, pSession) || idCpu != NIL_VMCPUID)
1672 return VERR_INVALID_PARAMETER;
1673 return PciRawR0ProcessReq(pSession, pVM, (PPCIRAWSENDREQ)pReqHdr);
1674#endif
1675 /*
1676 * For profiling.
1677 */
1678 case VMMR0_DO_NOP:
1679 case VMMR0_DO_SLOW_NOP:
1680 return VINF_SUCCESS;
1681
1682 /*
1683 * For testing Ring-0 APIs invoked in this environment.
1684 */
1685 case VMMR0_DO_TESTS:
1686 /** @todo make new test */
1687 return VINF_SUCCESS;
1688
1689
1690#if HC_ARCH_BITS == 32 && defined(VBOX_WITH_64_BITS_GUESTS) && !defined(VBOX_WITH_HYBRID_32BIT_KERNEL)
1691 case VMMR0_DO_TEST_SWITCHER3264:
1692 if (idCpu == NIL_VMCPUID)
1693 return VERR_INVALID_CPU_ID;
1694 return HMR0TestSwitcher3264(pVM);
1695#endif
1696 default:
1697 /*
1698 * We're returning VERR_NOT_SUPPORT here so we've got something else
1699 * than -1 which the interrupt gate glue code might return.
1700 */
1701 Log(("operation %#x is not supported\n", enmOperation));
1702 return VERR_NOT_SUPPORTED;
1703 }
1704}
1705
1706
1707/**
1708 * Argument for vmmR0EntryExWrapper containing the arguments for VMMR0EntryEx.
1709 */
1710typedef struct VMMR0ENTRYEXARGS
1711{
1712 PVM pVM;
1713 VMCPUID idCpu;
1714 VMMR0OPERATION enmOperation;
1715 PSUPVMMR0REQHDR pReq;
1716 uint64_t u64Arg;
1717 PSUPDRVSESSION pSession;
1718} VMMR0ENTRYEXARGS;
1719/** Pointer to a vmmR0EntryExWrapper argument package. */
1720typedef VMMR0ENTRYEXARGS *PVMMR0ENTRYEXARGS;
1721
1722/**
1723 * This is just a longjmp wrapper function for VMMR0EntryEx calls.
1724 *
1725 * @returns VBox status code.
1726 * @param pvArgs The argument package
1727 */
1728static DECLCALLBACK(int) vmmR0EntryExWrapper(void *pvArgs)
1729{
1730 return vmmR0EntryExWorker(((PVMMR0ENTRYEXARGS)pvArgs)->pVM,
1731 ((PVMMR0ENTRYEXARGS)pvArgs)->idCpu,
1732 ((PVMMR0ENTRYEXARGS)pvArgs)->enmOperation,
1733 ((PVMMR0ENTRYEXARGS)pvArgs)->pReq,
1734 ((PVMMR0ENTRYEXARGS)pvArgs)->u64Arg,
1735 ((PVMMR0ENTRYEXARGS)pvArgs)->pSession);
1736}
1737
1738
1739/**
1740 * The Ring 0 entry point, called by the support library (SUP).
1741 *
1742 * @returns VBox status code.
1743 * @param pVM Pointer to the VM.
1744 * @param idCpu Virtual CPU ID argument. Must be NIL_VMCPUID if pVM
1745 * is NIL_RTR0PTR, and may be NIL_VMCPUID if it isn't
1746 * @param enmOperation Which operation to execute.
1747 * @param pReq Pointer to the SUPVMMR0REQHDR packet. Optional.
1748 * @param u64Arg Some simple constant argument.
1749 * @param pSession The session of the caller.
1750 * @remarks Assume called with interrupts _enabled_.
1751 */
1752VMMR0DECL(int) VMMR0EntryEx(PVM pVM, VMCPUID idCpu, VMMR0OPERATION enmOperation, PSUPVMMR0REQHDR pReq, uint64_t u64Arg, PSUPDRVSESSION pSession)
1753{
1754 /*
1755 * Requests that should only happen on the EMT thread will be
1756 * wrapped in a setjmp so we can assert without causing trouble.
1757 */
1758 if ( VALID_PTR(pVM)
1759 && pVM->pVMR0
1760 && idCpu < pVM->cCpus)
1761 {
1762 switch (enmOperation)
1763 {
1764 /* These might/will be called before VMMR3Init. */
1765 case VMMR0_DO_GMM_INITIAL_RESERVATION:
1766 case VMMR0_DO_GMM_UPDATE_RESERVATION:
1767 case VMMR0_DO_GMM_ALLOCATE_PAGES:
1768 case VMMR0_DO_GMM_FREE_PAGES:
1769 case VMMR0_DO_GMM_BALLOONED_PAGES:
1770 /* On the mac we might not have a valid jmp buf, so check these as well. */
1771 case VMMR0_DO_VMMR0_INIT:
1772 case VMMR0_DO_VMMR0_TERM:
1773 {
1774 PVMCPU pVCpu = &pVM->aCpus[idCpu];
1775
1776 if (!pVCpu->vmm.s.CallRing3JmpBufR0.pvSavedStack)
1777 break;
1778
1779 /** @todo validate this EMT claim... GVM knows. */
1780 VMMR0ENTRYEXARGS Args;
1781 Args.pVM = pVM;
1782 Args.idCpu = idCpu;
1783 Args.enmOperation = enmOperation;
1784 Args.pReq = pReq;
1785 Args.u64Arg = u64Arg;
1786 Args.pSession = pSession;
1787 return vmmR0CallRing3SetJmpEx(&pVCpu->vmm.s.CallRing3JmpBufR0, vmmR0EntryExWrapper, &Args);
1788 }
1789
1790 default:
1791 break;
1792 }
1793 }
1794 return vmmR0EntryExWorker(pVM, idCpu, enmOperation, pReq, u64Arg, pSession);
1795}
1796
1797
1798/**
1799 * Checks whether we've armed the ring-0 long jump machinery.
1800 *
1801 * @returns @c true / @c false
1802 * @param pVCpu Pointer to the VMCPU.
1803 * @thread EMT
1804 * @sa VMMIsLongJumpArmed
1805 */
1806VMMR0_INT_DECL(bool) VMMR0IsLongJumpArmed(PVMCPU pVCpu)
1807{
1808#ifdef RT_ARCH_X86
1809 return pVCpu->vmm.s.CallRing3JmpBufR0.eip
1810 && !pVCpu->vmm.s.CallRing3JmpBufR0.fInRing3Call;
1811#else
1812 return pVCpu->vmm.s.CallRing3JmpBufR0.rip
1813 && !pVCpu->vmm.s.CallRing3JmpBufR0.fInRing3Call;
1814#endif
1815}
1816
1817
1818/**
1819 * Checks whether we've done a ring-3 long jump.
1820 *
1821 * @returns @c true / @c false
1822 * @param pVCpu Pointer to the VMCPU.
1823 * @thread EMT
1824 */
1825VMMR0_INT_DECL(bool) VMMR0IsInRing3LongJump(PVMCPU pVCpu)
1826{
1827 return pVCpu->vmm.s.CallRing3JmpBufR0.fInRing3Call;
1828}
1829
1830
1831/**
1832 * Internal R0 logger worker: Flush logger.
1833 *
1834 * @param pLogger The logger instance to flush.
1835 * @remark This function must be exported!
1836 */
1837VMMR0DECL(void) vmmR0LoggerFlush(PRTLOGGER pLogger)
1838{
1839#ifdef LOG_ENABLED
1840 /*
1841 * Convert the pLogger into a VM handle and 'call' back to Ring-3.
1842 * (This is a bit paranoid code.)
1843 */
1844 PVMMR0LOGGER pR0Logger = (PVMMR0LOGGER)((uintptr_t)pLogger - RT_OFFSETOF(VMMR0LOGGER, Logger));
1845 if ( !VALID_PTR(pR0Logger)
1846 || !VALID_PTR(pR0Logger + 1)
1847 || pLogger->u32Magic != RTLOGGER_MAGIC)
1848 {
1849# ifdef DEBUG
1850 SUPR0Printf("vmmR0LoggerFlush: pLogger=%p!\n", pLogger);
1851# endif
1852 return;
1853 }
1854 if (pR0Logger->fFlushingDisabled)
1855 return; /* quietly */
1856
1857 PVM pVM = pR0Logger->pVM;
1858 if ( !VALID_PTR(pVM)
1859 || pVM->pVMR0 != pVM)
1860 {
1861# ifdef DEBUG
1862 SUPR0Printf("vmmR0LoggerFlush: pVM=%p! pVMR0=%p! pLogger=%p\n", pVM, pVM->pVMR0, pLogger);
1863# endif
1864 return;
1865 }
1866
1867 PVMCPU pVCpu = VMMGetCpu(pVM);
1868 if (pVCpu)
1869 {
1870 /*
1871 * Check that the jump buffer is armed.
1872 */
1873# ifdef RT_ARCH_X86
1874 if ( !pVCpu->vmm.s.CallRing3JmpBufR0.eip
1875 || pVCpu->vmm.s.CallRing3JmpBufR0.fInRing3Call)
1876# else
1877 if ( !pVCpu->vmm.s.CallRing3JmpBufR0.rip
1878 || pVCpu->vmm.s.CallRing3JmpBufR0.fInRing3Call)
1879# endif
1880 {
1881# ifdef DEBUG
1882 SUPR0Printf("vmmR0LoggerFlush: Jump buffer isn't armed!\n");
1883# endif
1884 return;
1885 }
1886 VMMRZCallRing3(pVM, pVCpu, VMMCALLRING3_VMM_LOGGER_FLUSH, 0);
1887 }
1888# ifdef DEBUG
1889 else
1890 SUPR0Printf("vmmR0LoggerFlush: invalid VCPU context!\n");
1891# endif
1892#endif
1893}
1894
1895/**
1896 * Internal R0 logger worker: Custom prefix.
1897 *
1898 * @returns Number of chars written.
1899 *
1900 * @param pLogger The logger instance.
1901 * @param pchBuf The output buffer.
1902 * @param cchBuf The size of the buffer.
1903 * @param pvUser User argument (ignored).
1904 */
1905VMMR0DECL(size_t) vmmR0LoggerPrefix(PRTLOGGER pLogger, char *pchBuf, size_t cchBuf, void *pvUser)
1906{
1907 NOREF(pvUser);
1908#ifdef LOG_ENABLED
1909 PVMMR0LOGGER pR0Logger = (PVMMR0LOGGER)((uintptr_t)pLogger - RT_OFFSETOF(VMMR0LOGGER, Logger));
1910 if ( !VALID_PTR(pR0Logger)
1911 || !VALID_PTR(pR0Logger + 1)
1912 || pLogger->u32Magic != RTLOGGER_MAGIC
1913 || cchBuf < 2)
1914 return 0;
1915
1916 static const char s_szHex[17] = "0123456789abcdef";
1917 VMCPUID const idCpu = pR0Logger->idCpu;
1918 pchBuf[1] = s_szHex[ idCpu & 15];
1919 pchBuf[0] = s_szHex[(idCpu >> 4) & 15];
1920
1921 return 2;
1922#else
1923 return 0;
1924#endif
1925}
1926
1927#ifdef LOG_ENABLED
1928
1929/**
1930 * Disables flushing of the ring-0 debug log.
1931 *
1932 * @param pVCpu Pointer to the VMCPU.
1933 */
1934VMMR0_INT_DECL(void) VMMR0LogFlushDisable(PVMCPU pVCpu)
1935{
1936 if (pVCpu->vmm.s.pR0LoggerR0)
1937 pVCpu->vmm.s.pR0LoggerR0->fFlushingDisabled = true;
1938}
1939
1940
1941/**
1942 * Enables flushing of the ring-0 debug log.
1943 *
1944 * @param pVCpu Pointer to the VMCPU.
1945 */
1946VMMR0_INT_DECL(void) VMMR0LogFlushEnable(PVMCPU pVCpu)
1947{
1948 if (pVCpu->vmm.s.pR0LoggerR0)
1949 pVCpu->vmm.s.pR0LoggerR0->fFlushingDisabled = false;
1950}
1951
1952
1953/**
1954 * Checks if log flushing is disabled or not.
1955 *
1956 * @param pVCpu Pointer to the VMCPU.
1957 */
1958VMMR0_INT_DECL(bool) VMMR0IsLogFlushDisabled(PVMCPU pVCpu)
1959{
1960 if (pVCpu->vmm.s.pR0LoggerR0)
1961 return pVCpu->vmm.s.pR0LoggerR0->fFlushingDisabled;
1962 return true;
1963}
1964#endif /* LOG_ENABLED */
1965
1966/**
1967 * Jump back to ring-3 if we're the EMT and the longjmp is armed.
1968 *
1969 * @returns true if the breakpoint should be hit, false if it should be ignored.
1970 */
1971DECLEXPORT(bool) RTCALL RTAssertShouldPanic(void)
1972{
1973#if 0
1974 return true;
1975#else
1976 PVM pVM = GVMMR0GetVMByEMT(NIL_RTNATIVETHREAD);
1977 if (pVM)
1978 {
1979 PVMCPU pVCpu = VMMGetCpu(pVM);
1980
1981 if (pVCpu)
1982 {
1983#ifdef RT_ARCH_X86
1984 if ( pVCpu->vmm.s.CallRing3JmpBufR0.eip
1985 && !pVCpu->vmm.s.CallRing3JmpBufR0.fInRing3Call)
1986#else
1987 if ( pVCpu->vmm.s.CallRing3JmpBufR0.rip
1988 && !pVCpu->vmm.s.CallRing3JmpBufR0.fInRing3Call)
1989#endif
1990 {
1991 int rc = VMMRZCallRing3(pVM, pVCpu, VMMCALLRING3_VM_R0_ASSERTION, 0);
1992 return RT_FAILURE_NP(rc);
1993 }
1994 }
1995 }
1996#ifdef RT_OS_LINUX
1997 return true;
1998#else
1999 return false;
2000#endif
2001#endif
2002}
2003
2004
2005/**
2006 * Override this so we can push it up to ring-3.
2007 *
2008 * @param pszExpr Expression. Can be NULL.
2009 * @param uLine Location line number.
2010 * @param pszFile Location file name.
2011 * @param pszFunction Location function name.
2012 */
2013DECLEXPORT(void) RTCALL RTAssertMsg1Weak(const char *pszExpr, unsigned uLine, const char *pszFile, const char *pszFunction)
2014{
2015 /*
2016 * To the log.
2017 */
2018 LogAlways(("\n!!R0-Assertion Failed!!\n"
2019 "Expression: %s\n"
2020 "Location : %s(%d) %s\n",
2021 pszExpr, pszFile, uLine, pszFunction));
2022
2023 /*
2024 * To the global VMM buffer.
2025 */
2026 PVM pVM = GVMMR0GetVMByEMT(NIL_RTNATIVETHREAD);
2027 if (pVM)
2028 RTStrPrintf(pVM->vmm.s.szRing0AssertMsg1, sizeof(pVM->vmm.s.szRing0AssertMsg1),
2029 "\n!!R0-Assertion Failed!!\n"
2030 "Expression: %s\n"
2031 "Location : %s(%d) %s\n",
2032 pszExpr, pszFile, uLine, pszFunction);
2033
2034 /*
2035 * Continue the normal way.
2036 */
2037 RTAssertMsg1(pszExpr, uLine, pszFile, pszFunction);
2038}
2039
2040
2041/**
2042 * Callback for RTLogFormatV which writes to the ring-3 log port.
2043 * See PFNLOGOUTPUT() for details.
2044 */
2045static DECLCALLBACK(size_t) rtLogOutput(void *pv, const char *pachChars, size_t cbChars)
2046{
2047 for (size_t i = 0; i < cbChars; i++)
2048 LogAlways(("%c", pachChars[i]));
2049
2050 NOREF(pv);
2051 return cbChars;
2052}
2053
2054
2055/**
2056 * Override this so we can push it up to ring-3.
2057 *
2058 * @param pszFormat The format string.
2059 * @param va Arguments.
2060 */
2061DECLEXPORT(void) RTCALL RTAssertMsg2WeakV(const char *pszFormat, va_list va)
2062{
2063 va_list vaCopy;
2064
2065 /*
2066 * Push the message to the loggers.
2067 */
2068 PRTLOGGER pLog = RTLogGetDefaultInstance(); /* Don't initialize it here... */
2069 if (pLog)
2070 {
2071 va_copy(vaCopy, va);
2072 RTLogFormatV(rtLogOutput, pLog, pszFormat, vaCopy);
2073 va_end(vaCopy);
2074 }
2075 pLog = RTLogRelGetDefaultInstance();
2076 if (pLog)
2077 {
2078 va_copy(vaCopy, va);
2079 RTLogFormatV(rtLogOutput, pLog, pszFormat, vaCopy);
2080 va_end(vaCopy);
2081 }
2082
2083 /*
2084 * Push it to the global VMM buffer.
2085 */
2086 PVM pVM = GVMMR0GetVMByEMT(NIL_RTNATIVETHREAD);
2087 if (pVM)
2088 {
2089 va_copy(vaCopy, va);
2090 RTStrPrintfV(pVM->vmm.s.szRing0AssertMsg2, sizeof(pVM->vmm.s.szRing0AssertMsg2), pszFormat, vaCopy);
2091 va_end(vaCopy);
2092 }
2093
2094 /*
2095 * Continue the normal way.
2096 */
2097 RTAssertMsg2V(pszFormat, va);
2098}
2099
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