VirtualBox

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

Last change on this file since 92216 was 92200, checked in by vboxsync, 3 years ago

VMM/GVMM,VMM: Make it possible for known worker thread to enter critical sections in ring-0. Added a couple of helpers for safely signalling event semaphores. bugref:10093 bugref:6695

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id Revision
File size: 134.4 KB
Line 
1/* $Id: VMMR0.cpp 92200 2021-11-03 21:46:36Z vboxsync $ */
2/** @file
3 * VMM - 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_VMM
23#include <VBox/vmm/vmm.h>
24#include <VBox/sup.h>
25#include <VBox/vmm/iom.h>
26#include <VBox/vmm/trpm.h>
27#include <VBox/vmm/cpum.h>
28#include <VBox/vmm/pdmapi.h>
29#include <VBox/vmm/pgm.h>
30#ifdef VBOX_WITH_NEM_R0
31# include <VBox/vmm/nem.h>
32#endif
33#include <VBox/vmm/em.h>
34#include <VBox/vmm/stam.h>
35#include <VBox/vmm/tm.h>
36#include "VMMInternal.h"
37#include <VBox/vmm/vmcc.h>
38#include <VBox/vmm/gvm.h>
39#ifdef VBOX_WITH_PCI_PASSTHROUGH
40# include <VBox/vmm/pdmpci.h>
41#endif
42#include <VBox/vmm/apic.h>
43
44#include <VBox/vmm/gvmm.h>
45#include <VBox/vmm/gmm.h>
46#include <VBox/vmm/gim.h>
47#include <VBox/intnet.h>
48#include <VBox/vmm/hm.h>
49#include <VBox/param.h>
50#include <VBox/err.h>
51#include <VBox/version.h>
52#include <VBox/log.h>
53
54#include <iprt/asm-amd64-x86.h>
55#include <iprt/assert.h>
56#include <iprt/crc.h>
57#include <iprt/mem.h>
58#include <iprt/memobj.h>
59#include <iprt/mp.h>
60#include <iprt/once.h>
61#include <iprt/semaphore.h>
62#include <iprt/spinlock.h>
63#include <iprt/stdarg.h>
64#include <iprt/string.h>
65#include <iprt/thread.h>
66#include <iprt/timer.h>
67#include <iprt/time.h>
68
69#include "dtrace/VBoxVMM.h"
70
71
72#if defined(_MSC_VER) && defined(RT_ARCH_AMD64) /** @todo check this with with VC7! */
73# pragma intrinsic(_AddressOfReturnAddress)
74#endif
75
76#if defined(RT_OS_DARWIN) && ARCH_BITS == 32
77# error "32-bit darwin is no longer supported. Go back to 4.3 or earlier!"
78#endif
79
80
81/*********************************************************************************************************************************
82* Internal Functions *
83*********************************************************************************************************************************/
84RT_C_DECLS_BEGIN
85#if defined(RT_ARCH_X86) && (defined(RT_OS_SOLARIS) || defined(RT_OS_FREEBSD))
86extern uint64_t __udivdi3(uint64_t, uint64_t);
87extern uint64_t __umoddi3(uint64_t, uint64_t);
88#endif
89RT_C_DECLS_END
90static int vmmR0UpdateLoggers(PGVM pGVM, VMCPUID idCpu, PVMMR0UPDATELOGGERSREQ pReq, size_t idxLogger);
91static int vmmR0LogFlusher(PGVM pGVM);
92static int vmmR0LogWaitFlushed(PGVM pGVM, VMCPUID idCpu, size_t idxLogger);
93static int vmmR0InitLoggers(PGVM pGVM);
94static void vmmR0CleanupLoggers(PGVM pGVM);
95
96
97/*********************************************************************************************************************************
98* Global Variables *
99*********************************************************************************************************************************/
100/** Drag in necessary library bits.
101 * The runtime lives here (in VMMR0.r0) and VBoxDD*R0.r0 links against us. */
102struct CLANG11WEIRDNOTHROW { PFNRT pfn; } g_VMMR0Deps[] =
103{
104 { (PFNRT)RTCrc32 },
105 { (PFNRT)RTOnce },
106#if defined(RT_ARCH_X86) && (defined(RT_OS_SOLARIS) || defined(RT_OS_FREEBSD))
107 { (PFNRT)__udivdi3 },
108 { (PFNRT)__umoddi3 },
109#endif
110 { NULL }
111};
112
113#ifdef RT_OS_SOLARIS
114/* Dependency information for the native solaris loader. */
115extern "C" { char _depends_on[] = "vboxdrv"; }
116#endif
117
118
119/**
120 * Initialize the module.
121 * This is called when we're first loaded.
122 *
123 * @returns 0 on success.
124 * @returns VBox status on failure.
125 * @param hMod Image handle for use in APIs.
126 */
127DECLEXPORT(int) ModuleInit(void *hMod)
128{
129#ifdef VBOX_WITH_DTRACE_R0
130 /*
131 * The first thing to do is register the static tracepoints.
132 * (Deregistration is automatic.)
133 */
134 int rc2 = SUPR0TracerRegisterModule(hMod, &g_VTGObjHeader);
135 if (RT_FAILURE(rc2))
136 return rc2;
137#endif
138 LogFlow(("ModuleInit:\n"));
139
140#ifdef VBOX_WITH_64ON32_CMOS_DEBUG
141 /*
142 * Display the CMOS debug code.
143 */
144 ASMOutU8(0x72, 0x03);
145 uint8_t bDebugCode = ASMInU8(0x73);
146 LogRel(("CMOS Debug Code: %#x (%d)\n", bDebugCode, bDebugCode));
147 RTLogComPrintf("CMOS Debug Code: %#x (%d)\n", bDebugCode, bDebugCode);
148#endif
149
150 /*
151 * Initialize the VMM, GVMM, GMM, HM, PGM (Darwin) and INTNET.
152 */
153 int rc = vmmInitFormatTypes();
154 if (RT_SUCCESS(rc))
155 {
156 rc = GVMMR0Init();
157 if (RT_SUCCESS(rc))
158 {
159 rc = GMMR0Init();
160 if (RT_SUCCESS(rc))
161 {
162 rc = HMR0Init();
163 if (RT_SUCCESS(rc))
164 {
165 PDMR0Init(hMod);
166
167 rc = PGMRegisterStringFormatTypes();
168 if (RT_SUCCESS(rc))
169 {
170 rc = IntNetR0Init();
171 if (RT_SUCCESS(rc))
172 {
173#ifdef VBOX_WITH_PCI_PASSTHROUGH
174 rc = PciRawR0Init();
175#endif
176 if (RT_SUCCESS(rc))
177 {
178 rc = CPUMR0ModuleInit();
179 if (RT_SUCCESS(rc))
180 {
181#ifdef VBOX_WITH_TRIPLE_FAULT_HACK
182 rc = vmmR0TripleFaultHackInit();
183 if (RT_SUCCESS(rc))
184#endif
185 {
186#ifdef VBOX_WITH_NEM_R0
187 rc = NEMR0Init();
188 if (RT_SUCCESS(rc))
189#endif
190 {
191 LogFlow(("ModuleInit: returns success\n"));
192 return VINF_SUCCESS;
193 }
194 }
195
196 /*
197 * Bail out.
198 */
199#ifdef VBOX_WITH_TRIPLE_FAULT_HACK
200 vmmR0TripleFaultHackTerm();
201#endif
202 }
203 else
204 LogRel(("ModuleInit: CPUMR0ModuleInit -> %Rrc\n", rc));
205#ifdef VBOX_WITH_PCI_PASSTHROUGH
206 PciRawR0Term();
207#endif
208 }
209 else
210 LogRel(("ModuleInit: PciRawR0Init -> %Rrc\n", rc));
211 IntNetR0Term();
212 }
213 else
214 LogRel(("ModuleInit: IntNetR0Init -> %Rrc\n", rc));
215 PGMDeregisterStringFormatTypes();
216 }
217 else
218 LogRel(("ModuleInit: PGMRegisterStringFormatTypes -> %Rrc\n", rc));
219 HMR0Term();
220 }
221 else
222 LogRel(("ModuleInit: HMR0Init -> %Rrc\n", rc));
223 GMMR0Term();
224 }
225 else
226 LogRel(("ModuleInit: GMMR0Init -> %Rrc\n", rc));
227 GVMMR0Term();
228 }
229 else
230 LogRel(("ModuleInit: GVMMR0Init -> %Rrc\n", rc));
231 vmmTermFormatTypes();
232 }
233 else
234 LogRel(("ModuleInit: vmmInitFormatTypes -> %Rrc\n", rc));
235
236 LogFlow(("ModuleInit: failed %Rrc\n", rc));
237 return rc;
238}
239
240
241/**
242 * Terminate the module.
243 * This is called when we're finally unloaded.
244 *
245 * @param hMod Image handle for use in APIs.
246 */
247DECLEXPORT(void) ModuleTerm(void *hMod)
248{
249 NOREF(hMod);
250 LogFlow(("ModuleTerm:\n"));
251
252 /*
253 * Terminate the CPUM module (Local APIC cleanup).
254 */
255 CPUMR0ModuleTerm();
256
257 /*
258 * Terminate the internal network service.
259 */
260 IntNetR0Term();
261
262 /*
263 * PGM (Darwin), HM and PciRaw global cleanup.
264 */
265#ifdef VBOX_WITH_PCI_PASSTHROUGH
266 PciRawR0Term();
267#endif
268 PGMDeregisterStringFormatTypes();
269 HMR0Term();
270#ifdef VBOX_WITH_TRIPLE_FAULT_HACK
271 vmmR0TripleFaultHackTerm();
272#endif
273#ifdef VBOX_WITH_NEM_R0
274 NEMR0Term();
275#endif
276
277 /*
278 * Destroy the GMM and GVMM instances.
279 */
280 GMMR0Term();
281 GVMMR0Term();
282
283 vmmTermFormatTypes();
284
285 LogFlow(("ModuleTerm: returns\n"));
286}
287
288
289/**
290 * Initializes VMM specific members when the GVM structure is created,
291 * allocating loggers and stuff.
292 *
293 * The loggers are allocated here so that we can update their settings before
294 * doing VMMR0_DO_VMMR0_INIT and have correct logging at that time.
295 *
296 * @returns VBox status code.
297 * @param pGVM The global (ring-0) VM structure.
298 */
299VMMR0_INT_DECL(int) VMMR0InitPerVMData(PGVM pGVM)
300{
301 AssertCompile(sizeof(pGVM->vmmr0.s) <= sizeof(pGVM->vmmr0.padding));
302
303 /*
304 * Initialize all members first.
305 */
306 pGVM->vmmr0.s.fCalledInitVm = false;
307 pGVM->vmmr0.s.hMemObjLogger = NIL_RTR0MEMOBJ;
308 pGVM->vmmr0.s.hMapObjLogger = NIL_RTR0MEMOBJ;
309 pGVM->vmmr0.s.hMemObjReleaseLogger = NIL_RTR0MEMOBJ;
310 pGVM->vmmr0.s.hMapObjReleaseLogger = NIL_RTR0MEMOBJ;
311 pGVM->vmmr0.s.LogFlusher.hSpinlock = NIL_RTSPINLOCK;
312 pGVM->vmmr0.s.LogFlusher.hThread = NIL_RTNATIVETHREAD;
313 pGVM->vmmr0.s.LogFlusher.hEvent = NIL_RTSEMEVENT;
314 pGVM->vmmr0.s.LogFlusher.idxRingHead = 0;
315 pGVM->vmmr0.s.LogFlusher.idxRingTail = 0;
316 pGVM->vmmr0.s.LogFlusher.fThreadWaiting = false;
317
318 for (VMCPUID idCpu = 0; idCpu < pGVM->cCpus; idCpu++)
319 {
320 PGVMCPU pGVCpu = &pGVM->aCpus[idCpu];
321 Assert(pGVCpu->idHostCpu == NIL_RTCPUID);
322 Assert(pGVCpu->iHostCpuSet == UINT32_MAX);
323 pGVCpu->vmmr0.s.pPreemptState = NULL;
324 pGVCpu->vmmr0.s.hCtxHook = NIL_RTTHREADCTXHOOK;
325 for (size_t iLogger = 0; iLogger < RT_ELEMENTS(pGVCpu->vmmr0.s.u.aLoggers); iLogger++)
326 pGVCpu->vmmr0.s.u.aLoggers[iLogger].hEventFlushWait = NIL_RTSEMEVENT;
327 }
328
329 /*
330 * Create the loggers.
331 */
332 return vmmR0InitLoggers(pGVM);
333}
334
335
336/**
337 * Initiates the R0 driver for a particular VM instance.
338 *
339 * @returns VBox status code.
340 *
341 * @param pGVM The global (ring-0) VM structure.
342 * @param uSvnRev The SVN revision of the ring-3 part.
343 * @param uBuildType Build type indicator.
344 * @thread EMT(0)
345 */
346static int vmmR0InitVM(PGVM pGVM, uint32_t uSvnRev, uint32_t uBuildType)
347{
348 /*
349 * Match the SVN revisions and build type.
350 */
351 if (uSvnRev != VMMGetSvnRev())
352 {
353 LogRel(("VMMR0InitVM: Revision mismatch, r3=%d r0=%d\n", uSvnRev, VMMGetSvnRev()));
354 SUPR0Printf("VMMR0InitVM: Revision mismatch, r3=%d r0=%d\n", uSvnRev, VMMGetSvnRev());
355 return VERR_VMM_R0_VERSION_MISMATCH;
356 }
357 if (uBuildType != vmmGetBuildType())
358 {
359 LogRel(("VMMR0InitVM: Build type mismatch, r3=%#x r0=%#x\n", uBuildType, vmmGetBuildType()));
360 SUPR0Printf("VMMR0InitVM: Build type mismatch, r3=%#x r0=%#x\n", uBuildType, vmmGetBuildType());
361 return VERR_VMM_R0_VERSION_MISMATCH;
362 }
363
364 int rc = GVMMR0ValidateGVMandEMT(pGVM, 0 /*idCpu*/);
365 if (RT_FAILURE(rc))
366 return rc;
367
368 /* Don't allow this to be called more than once. */
369 if (!pGVM->vmmr0.s.fCalledInitVm)
370 pGVM->vmmr0.s.fCalledInitVm = true;
371 else
372 return VERR_ALREADY_INITIALIZED;
373
374#ifdef LOG_ENABLED
375
376 /*
377 * Register the EMT R0 logger instance for VCPU 0.
378 */
379 PVMCPUCC pVCpu = VMCC_GET_CPU_0(pGVM);
380 if (pVCpu->vmmr0.s.u.s.Logger.pLogger)
381 {
382# if 0 /* testing of the logger. */
383 LogCom(("vmmR0InitVM: before %p\n", RTLogDefaultInstance()));
384 LogCom(("vmmR0InitVM: pfnFlush=%p actual=%p\n", pR0Logger->Logger.pfnFlush, vmmR0LoggerFlush));
385 LogCom(("vmmR0InitVM: pfnLogger=%p actual=%p\n", pR0Logger->Logger.pfnLogger, vmmR0LoggerWrapper));
386 LogCom(("vmmR0InitVM: offScratch=%d fFlags=%#x fDestFlags=%#x\n", pR0Logger->Logger.offScratch, pR0Logger->Logger.fFlags, pR0Logger->Logger.fDestFlags));
387
388 RTLogSetDefaultInstanceThread(&pR0Logger->Logger, (uintptr_t)pGVM->pSession);
389 LogCom(("vmmR0InitVM: after %p reg\n", RTLogDefaultInstance()));
390 RTLogSetDefaultInstanceThread(NULL, pGVM->pSession);
391 LogCom(("vmmR0InitVM: after %p dereg\n", RTLogDefaultInstance()));
392
393 pR0Logger->Logger.pfnLogger("hello ring-0 logger\n");
394 LogCom(("vmmR0InitVM: returned successfully from direct logger call.\n"));
395 pR0Logger->Logger.pfnFlush(&pR0Logger->Logger);
396 LogCom(("vmmR0InitVM: returned successfully from direct flush call.\n"));
397
398 RTLogSetDefaultInstanceThread(&pR0Logger->Logger, (uintptr_t)pGVM->pSession);
399 LogCom(("vmmR0InitVM: after %p reg2\n", RTLogDefaultInstance()));
400 pR0Logger->Logger.pfnLogger("hello ring-0 logger\n");
401 LogCom(("vmmR0InitVM: returned successfully from direct logger call (2). offScratch=%d\n", pR0Logger->Logger.offScratch));
402 RTLogSetDefaultInstanceThread(NULL, pGVM->pSession);
403 LogCom(("vmmR0InitVM: after %p dereg2\n", RTLogDefaultInstance()));
404
405 RTLogLoggerEx(&pR0Logger->Logger, 0, ~0U, "hello ring-0 logger (RTLogLoggerEx)\n");
406 LogCom(("vmmR0InitVM: RTLogLoggerEx returned fine offScratch=%d\n", pR0Logger->Logger.offScratch));
407
408 RTLogSetDefaultInstanceThread(&pR0Logger->Logger, (uintptr_t)pGVM->pSession);
409 RTLogPrintf("hello ring-0 logger (RTLogPrintf)\n");
410 LogCom(("vmmR0InitVM: RTLogPrintf returned fine offScratch=%d\n", pR0Logger->Logger.offScratch));
411# endif
412# ifdef VBOX_WITH_R0_LOGGING
413 Log(("Switching to per-thread logging instance %p (key=%p)\n", pVCpu->vmmr0.s.u.s.Logger.pLogger, pGVM->pSession));
414 RTLogSetDefaultInstanceThread(pVCpu->vmmr0.s.u.s.Logger.pLogger, (uintptr_t)pGVM->pSession);
415 pVCpu->vmmr0.s.u.s.Logger.fRegistered = true;
416# endif
417 }
418#endif /* LOG_ENABLED */
419
420 /*
421 * Check if the host supports high resolution timers or not.
422 */
423 if ( pGVM->vmm.s.fUsePeriodicPreemptionTimers
424 && !RTTimerCanDoHighResolution())
425 pGVM->vmm.s.fUsePeriodicPreemptionTimers = false;
426
427 /*
428 * Initialize the per VM data for GVMM and GMM.
429 */
430 rc = GVMMR0InitVM(pGVM);
431 if (RT_SUCCESS(rc))
432 {
433 /*
434 * Init HM, CPUM and PGM (Darwin only).
435 */
436 rc = HMR0InitVM(pGVM);
437 if (RT_SUCCESS(rc))
438 {
439 rc = CPUMR0InitVM(pGVM);
440 if (RT_SUCCESS(rc))
441 {
442 rc = PGMR0InitVM(pGVM);
443 if (RT_SUCCESS(rc))
444 {
445 rc = EMR0InitVM(pGVM);
446 if (RT_SUCCESS(rc))
447 {
448#ifdef VBOX_WITH_PCI_PASSTHROUGH
449 rc = PciRawR0InitVM(pGVM);
450#endif
451 if (RT_SUCCESS(rc))
452 {
453 rc = GIMR0InitVM(pGVM);
454 if (RT_SUCCESS(rc))
455 {
456 GVMMR0DoneInitVM(pGVM);
457
458 /*
459 * Collect a bit of info for the VM release log.
460 */
461 pGVM->vmm.s.fIsPreemptPendingApiTrusty = RTThreadPreemptIsPendingTrusty();
462 pGVM->vmm.s.fIsPreemptPossible = RTThreadPreemptIsPossible();;
463 return rc;
464
465 /* bail out*/
466 //GIMR0TermVM(pGVM);
467 }
468#ifdef VBOX_WITH_PCI_PASSTHROUGH
469 PciRawR0TermVM(pGVM);
470#endif
471 }
472 }
473 }
474 }
475 HMR0TermVM(pGVM);
476 }
477 }
478
479 RTLogSetDefaultInstanceThread(NULL, (uintptr_t)pGVM->pSession);
480 return rc;
481}
482
483
484/**
485 * Does EMT specific VM initialization.
486 *
487 * @returns VBox status code.
488 * @param pGVM The ring-0 VM structure.
489 * @param idCpu The EMT that's calling.
490 */
491static int vmmR0InitVMEmt(PGVM pGVM, VMCPUID idCpu)
492{
493 /* Paranoia (caller checked these already). */
494 AssertReturn(idCpu < pGVM->cCpus, VERR_INVALID_CPU_ID);
495 AssertReturn(pGVM->aCpus[idCpu].hEMT == RTThreadNativeSelf(), VERR_INVALID_CPU_ID);
496
497#if defined(LOG_ENABLED) && defined(VBOX_WITH_R0_LOGGING)
498 /*
499 * Registration of ring 0 loggers.
500 */
501 PVMCPUCC pVCpu = &pGVM->aCpus[idCpu];
502 if ( pVCpu->vmmr0.s.u.s.Logger.pLogger
503 && !pVCpu->vmmr0.s.u.s.Logger.fRegistered)
504 {
505 RTLogSetDefaultInstanceThread(pVCpu->vmmr0.s.u.s.Logger.pLogger, (uintptr_t)pGVM->pSession);
506 pVCpu->vmmr0.s.u.s.Logger.fRegistered = true;
507 }
508#endif
509
510 return VINF_SUCCESS;
511}
512
513
514
515/**
516 * Terminates the R0 bits for a particular VM instance.
517 *
518 * This is normally called by ring-3 as part of the VM termination process, but
519 * may alternatively be called during the support driver session cleanup when
520 * the VM object is destroyed (see GVMM).
521 *
522 * @returns VBox status code.
523 *
524 * @param pGVM The global (ring-0) VM structure.
525 * @param idCpu Set to 0 if EMT(0) or NIL_VMCPUID if session cleanup
526 * thread.
527 * @thread EMT(0) or session clean up thread.
528 */
529VMMR0_INT_DECL(int) VMMR0TermVM(PGVM pGVM, VMCPUID idCpu)
530{
531 /*
532 * Check EMT(0) claim if we're called from userland.
533 */
534 if (idCpu != NIL_VMCPUID)
535 {
536 AssertReturn(idCpu == 0, VERR_INVALID_CPU_ID);
537 int rc = GVMMR0ValidateGVMandEMT(pGVM, idCpu);
538 if (RT_FAILURE(rc))
539 return rc;
540 }
541
542#ifdef VBOX_WITH_PCI_PASSTHROUGH
543 PciRawR0TermVM(pGVM);
544#endif
545
546 /*
547 * Tell GVMM what we're up to and check that we only do this once.
548 */
549 if (GVMMR0DoingTermVM(pGVM))
550 {
551 GIMR0TermVM(pGVM);
552
553 /** @todo I wish to call PGMR0PhysFlushHandyPages(pGVM, &pGVM->aCpus[idCpu])
554 * here to make sure we don't leak any shared pages if we crash... */
555 HMR0TermVM(pGVM);
556 }
557
558 /*
559 * Deregister the logger for this EMT.
560 */
561 RTLogSetDefaultInstanceThread(NULL, (uintptr_t)pGVM->pSession);
562
563 /*
564 * Start log flusher thread termination.
565 */
566 ASMAtomicWriteBool(&pGVM->vmmr0.s.LogFlusher.fThreadShutdown, true);
567 if (pGVM->vmmr0.s.LogFlusher.hEvent != NIL_RTSEMEVENT)
568 RTSemEventSignal(pGVM->vmmr0.s.LogFlusher.hEvent);
569
570 return VINF_SUCCESS;
571}
572
573
574/**
575 * This is called at the end of gvmmR0CleanupVM().
576 *
577 * @param pGVM The global (ring-0) VM structure.
578 */
579VMMR0_INT_DECL(void) VMMR0CleanupVM(PGVM pGVM)
580{
581 AssertCompile(NIL_RTTHREADCTXHOOK == (RTTHREADCTXHOOK)0); /* Depends on zero initialized memory working for NIL at the moment. */
582 for (VMCPUID idCpu = 0; idCpu < pGVM->cCpus; idCpu++)
583 {
584 PGVMCPU pGVCpu = &pGVM->aCpus[idCpu];
585
586 /** @todo Can we busy wait here for all thread-context hooks to be
587 * deregistered before releasing (destroying) it? Only until we find a
588 * solution for not deregistering hooks everytime we're leaving HMR0
589 * context. */
590 VMMR0ThreadCtxHookDestroyForEmt(pGVCpu);
591 }
592
593 vmmR0CleanupLoggers(pGVM);
594}
595
596
597/**
598 * An interrupt or unhalt force flag is set, deal with it.
599 *
600 * @returns VINF_SUCCESS (or VINF_EM_HALT).
601 * @param pVCpu The cross context virtual CPU structure.
602 * @param uMWait Result from EMMonitorWaitIsActive().
603 * @param enmInterruptibility Guest CPU interruptbility level.
604 */
605static int vmmR0DoHaltInterrupt(PVMCPUCC pVCpu, unsigned uMWait, CPUMINTERRUPTIBILITY enmInterruptibility)
606{
607 Assert(!TRPMHasTrap(pVCpu));
608 Assert( enmInterruptibility > CPUMINTERRUPTIBILITY_INVALID
609 && enmInterruptibility < CPUMINTERRUPTIBILITY_END);
610
611 /*
612 * Pending interrupts w/o any SMIs or NMIs? That the usual case.
613 */
614 if ( VMCPU_FF_IS_ANY_SET(pVCpu, VMCPU_FF_INTERRUPT_APIC | VMCPU_FF_INTERRUPT_PIC)
615 && !VMCPU_FF_IS_ANY_SET(pVCpu, VMCPU_FF_INTERRUPT_SMI | VMCPU_FF_INTERRUPT_NMI))
616 {
617 if (enmInterruptibility <= CPUMINTERRUPTIBILITY_UNRESTRAINED)
618 {
619 uint8_t u8Interrupt = 0;
620 int rc = PDMGetInterrupt(pVCpu, &u8Interrupt);
621 Log(("vmmR0DoHaltInterrupt: CPU%d u8Interrupt=%d (%#x) rc=%Rrc\n", pVCpu->idCpu, u8Interrupt, u8Interrupt, rc));
622 if (RT_SUCCESS(rc))
623 {
624 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_UNHALT);
625
626 rc = TRPMAssertTrap(pVCpu, u8Interrupt, TRPM_HARDWARE_INT);
627 AssertRCSuccess(rc);
628 STAM_REL_COUNTER_INC(&pVCpu->vmm.s.StatR0HaltExec);
629 return rc;
630 }
631 }
632 }
633 /*
634 * SMI is not implemented yet, at least not here.
635 */
636 else if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_INTERRUPT_SMI))
637 {
638 Log12(("vmmR0DoHaltInterrupt: CPU%d failed #3\n", pVCpu->idCpu));
639 STAM_REL_COUNTER_INC(&pVCpu->vmm.s.StatR0HaltToR3);
640 return VINF_EM_HALT;
641 }
642 /*
643 * NMI.
644 */
645 else if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_INTERRUPT_NMI))
646 {
647 if (enmInterruptibility < CPUMINTERRUPTIBILITY_NMI_INHIBIT)
648 {
649 /** @todo later. */
650 Log12(("vmmR0DoHaltInterrupt: CPU%d failed #2 (uMWait=%u enmInt=%d)\n", pVCpu->idCpu, uMWait, enmInterruptibility));
651 STAM_REL_COUNTER_INC(&pVCpu->vmm.s.StatR0HaltToR3);
652 return VINF_EM_HALT;
653 }
654 }
655 /*
656 * Nested-guest virtual interrupt.
657 */
658 else if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_INTERRUPT_NESTED_GUEST))
659 {
660 if (enmInterruptibility < CPUMINTERRUPTIBILITY_VIRT_INT_DISABLED)
661 {
662 /** @todo NSTVMX: NSTSVM: Remember, we might have to check and perform VM-exits
663 * here before injecting the virtual interrupt. See emR3ForcedActions
664 * for details. */
665 Log12(("vmmR0DoHaltInterrupt: CPU%d failed #1 (uMWait=%u enmInt=%d)\n", pVCpu->idCpu, uMWait, enmInterruptibility));
666 STAM_REL_COUNTER_INC(&pVCpu->vmm.s.StatR0HaltToR3);
667 return VINF_EM_HALT;
668 }
669 }
670
671 if (VMCPU_FF_TEST_AND_CLEAR(pVCpu, VMCPU_FF_UNHALT))
672 {
673 STAM_REL_COUNTER_INC(&pVCpu->vmm.s.StatR0HaltExec);
674 Log11(("vmmR0DoHaltInterrupt: CPU%d success VINF_SUCCESS (UNHALT)\n", pVCpu->idCpu));
675 return VINF_SUCCESS;
676 }
677 if (uMWait > 1)
678 {
679 STAM_REL_COUNTER_INC(&pVCpu->vmm.s.StatR0HaltExec);
680 Log11(("vmmR0DoHaltInterrupt: CPU%d success VINF_SUCCESS (uMWait=%u > 1)\n", pVCpu->idCpu, uMWait));
681 return VINF_SUCCESS;
682 }
683
684 Log12(("vmmR0DoHaltInterrupt: CPU%d failed #0 (uMWait=%u enmInt=%d)\n", pVCpu->idCpu, uMWait, enmInterruptibility));
685 STAM_REL_COUNTER_INC(&pVCpu->vmm.s.StatR0HaltToR3);
686 return VINF_EM_HALT;
687}
688
689
690/**
691 * This does one round of vmR3HaltGlobal1Halt().
692 *
693 * The rational here is that we'll reduce latency in interrupt situations if we
694 * don't go to ring-3 immediately on a VINF_EM_HALT (guest executed HLT or
695 * MWAIT), but do one round of blocking here instead and hope the interrupt is
696 * raised in the meanwhile.
697 *
698 * If we go to ring-3 we'll quit the inner HM/NEM loop in EM and end up in the
699 * outer loop, which will then call VMR3WaitHalted() and that in turn will do a
700 * ring-0 call (unless we're too close to a timer event). When the interrupt
701 * wakes us up, we'll return from ring-0 and EM will by instinct do a
702 * rescheduling (because of raw-mode) before it resumes the HM/NEM loop and gets
703 * back to VMMR0EntryFast().
704 *
705 * @returns VINF_SUCCESS or VINF_EM_HALT.
706 * @param pGVM The ring-0 VM structure.
707 * @param pGVCpu The ring-0 virtual CPU structure.
708 *
709 * @todo r=bird: All the blocking/waiting and EMT managment should move out of
710 * the VM module, probably to VMM. Then this would be more weird wrt
711 * parameters and statistics.
712 */
713static int vmmR0DoHalt(PGVM pGVM, PGVMCPU pGVCpu)
714{
715 /*
716 * Do spin stat historization.
717 */
718 if (++pGVCpu->vmm.s.cR0Halts & 0xff)
719 { /* likely */ }
720 else if (pGVCpu->vmm.s.cR0HaltsSucceeded > pGVCpu->vmm.s.cR0HaltsToRing3)
721 {
722 pGVCpu->vmm.s.cR0HaltsSucceeded = 2;
723 pGVCpu->vmm.s.cR0HaltsToRing3 = 0;
724 }
725 else
726 {
727 pGVCpu->vmm.s.cR0HaltsSucceeded = 0;
728 pGVCpu->vmm.s.cR0HaltsToRing3 = 2;
729 }
730
731 /*
732 * Flags that makes us go to ring-3.
733 */
734 uint32_t const fVmFFs = VM_FF_TM_VIRTUAL_SYNC | VM_FF_PDM_QUEUES | VM_FF_PDM_DMA
735 | VM_FF_DBGF | VM_FF_REQUEST | VM_FF_CHECK_VM_STATE
736 | VM_FF_RESET | VM_FF_EMT_RENDEZVOUS | VM_FF_PGM_NEED_HANDY_PAGES
737 | VM_FF_PGM_NO_MEMORY | VM_FF_DEBUG_SUSPEND;
738 uint64_t const fCpuFFs = VMCPU_FF_TIMER | VMCPU_FF_PDM_CRITSECT | VMCPU_FF_IEM
739 | VMCPU_FF_REQUEST | VMCPU_FF_DBGF | VMCPU_FF_HM_UPDATE_CR3
740 | VMCPU_FF_PGM_SYNC_CR3 | VMCPU_FF_PGM_SYNC_CR3_NON_GLOBAL
741 | VMCPU_FF_TO_R3 | VMCPU_FF_IOM;
742
743 /*
744 * Check preconditions.
745 */
746 unsigned const uMWait = EMMonitorWaitIsActive(pGVCpu);
747 CPUMINTERRUPTIBILITY const enmInterruptibility = CPUMGetGuestInterruptibility(pGVCpu);
748 if ( pGVCpu->vmm.s.fMayHaltInRing0
749 && !TRPMHasTrap(pGVCpu)
750 && ( enmInterruptibility == CPUMINTERRUPTIBILITY_UNRESTRAINED
751 || uMWait > 1))
752 {
753 if ( !VM_FF_IS_ANY_SET(pGVM, fVmFFs)
754 && !VMCPU_FF_IS_ANY_SET(pGVCpu, fCpuFFs))
755 {
756 /*
757 * Interrupts pending already?
758 */
759 if (VMCPU_FF_TEST_AND_CLEAR(pGVCpu, VMCPU_FF_UPDATE_APIC))
760 APICUpdatePendingInterrupts(pGVCpu);
761
762 /*
763 * Flags that wake up from the halted state.
764 */
765 uint64_t const fIntMask = VMCPU_FF_INTERRUPT_APIC | VMCPU_FF_INTERRUPT_PIC | VMCPU_FF_INTERRUPT_NESTED_GUEST
766 | VMCPU_FF_INTERRUPT_NMI | VMCPU_FF_INTERRUPT_SMI | VMCPU_FF_UNHALT;
767
768 if (VMCPU_FF_IS_ANY_SET(pGVCpu, fIntMask))
769 return vmmR0DoHaltInterrupt(pGVCpu, uMWait, enmInterruptibility);
770 ASMNopPause();
771
772 /*
773 * Check out how long till the next timer event.
774 */
775 uint64_t u64Delta;
776 uint64_t u64GipTime = TMTimerPollGIP(pGVM, pGVCpu, &u64Delta);
777
778 if ( !VM_FF_IS_ANY_SET(pGVM, fVmFFs)
779 && !VMCPU_FF_IS_ANY_SET(pGVCpu, fCpuFFs))
780 {
781 if (VMCPU_FF_TEST_AND_CLEAR(pGVCpu, VMCPU_FF_UPDATE_APIC))
782 APICUpdatePendingInterrupts(pGVCpu);
783
784 if (VMCPU_FF_IS_ANY_SET(pGVCpu, fIntMask))
785 return vmmR0DoHaltInterrupt(pGVCpu, uMWait, enmInterruptibility);
786
787 /*
788 * Wait if there is enough time to the next timer event.
789 */
790 if (u64Delta >= pGVCpu->vmm.s.cNsSpinBlockThreshold)
791 {
792 /* If there are few other CPU cores around, we will procrastinate a
793 little before going to sleep, hoping for some device raising an
794 interrupt or similar. Though, the best thing here would be to
795 dynamically adjust the spin count according to its usfulness or
796 something... */
797 if ( pGVCpu->vmm.s.cR0HaltsSucceeded > pGVCpu->vmm.s.cR0HaltsToRing3
798 && RTMpGetOnlineCount() >= 4)
799 {
800 /** @todo Figure out how we can skip this if it hasn't help recently...
801 * @bugref{9172#c12} */
802 uint32_t cSpinLoops = 42;
803 while (cSpinLoops-- > 0)
804 {
805 ASMNopPause();
806 if (VMCPU_FF_TEST_AND_CLEAR(pGVCpu, VMCPU_FF_UPDATE_APIC))
807 APICUpdatePendingInterrupts(pGVCpu);
808 ASMNopPause();
809 if (VM_FF_IS_ANY_SET(pGVM, fVmFFs))
810 {
811 STAM_REL_COUNTER_INC(&pGVCpu->vmm.s.StatR0HaltToR3FromSpin);
812 STAM_REL_COUNTER_INC(&pGVCpu->vmm.s.StatR0HaltToR3);
813 return VINF_EM_HALT;
814 }
815 ASMNopPause();
816 if (VMCPU_FF_IS_ANY_SET(pGVCpu, fCpuFFs))
817 {
818 STAM_REL_COUNTER_INC(&pGVCpu->vmm.s.StatR0HaltToR3FromSpin);
819 STAM_REL_COUNTER_INC(&pGVCpu->vmm.s.StatR0HaltToR3);
820 return VINF_EM_HALT;
821 }
822 ASMNopPause();
823 if (VMCPU_FF_IS_ANY_SET(pGVCpu, fIntMask))
824 {
825 STAM_REL_COUNTER_INC(&pGVCpu->vmm.s.StatR0HaltExecFromSpin);
826 return vmmR0DoHaltInterrupt(pGVCpu, uMWait, enmInterruptibility);
827 }
828 ASMNopPause();
829 }
830 }
831
832 /*
833 * We have to set the state to VMCPUSTATE_STARTED_HALTED here so ring-3
834 * knows when to notify us (cannot access VMINTUSERPERVMCPU::fWait from here).
835 * After changing the state we must recheck the force flags of course.
836 */
837 if (VMCPU_CMPXCHG_STATE(pGVCpu, VMCPUSTATE_STARTED_HALTED, VMCPUSTATE_STARTED))
838 {
839 if ( !VM_FF_IS_ANY_SET(pGVM, fVmFFs)
840 && !VMCPU_FF_IS_ANY_SET(pGVCpu, fCpuFFs))
841 {
842 if (VMCPU_FF_TEST_AND_CLEAR(pGVCpu, VMCPU_FF_UPDATE_APIC))
843 APICUpdatePendingInterrupts(pGVCpu);
844
845 if (VMCPU_FF_IS_ANY_SET(pGVCpu, fIntMask))
846 {
847 VMCPU_CMPXCHG_STATE(pGVCpu, VMCPUSTATE_STARTED, VMCPUSTATE_STARTED_HALTED);
848 return vmmR0DoHaltInterrupt(pGVCpu, uMWait, enmInterruptibility);
849 }
850
851 /* Okay, block! */
852 uint64_t const u64StartSchedHalt = RTTimeNanoTS();
853 int rc = GVMMR0SchedHalt(pGVM, pGVCpu, u64GipTime);
854 uint64_t const u64EndSchedHalt = RTTimeNanoTS();
855 uint64_t const cNsElapsedSchedHalt = u64EndSchedHalt - u64StartSchedHalt;
856 Log10(("vmmR0DoHalt: CPU%d: halted %llu ns\n", pGVCpu->idCpu, cNsElapsedSchedHalt));
857
858 VMCPU_CMPXCHG_STATE(pGVCpu, VMCPUSTATE_STARTED, VMCPUSTATE_STARTED_HALTED);
859 STAM_REL_PROFILE_ADD_PERIOD(&pGVCpu->vmm.s.StatR0HaltBlock, cNsElapsedSchedHalt);
860 if ( rc == VINF_SUCCESS
861 || rc == VERR_INTERRUPTED)
862 {
863 /* Keep some stats like ring-3 does. */
864 int64_t const cNsOverslept = u64EndSchedHalt - u64GipTime;
865 if (cNsOverslept > 50000)
866 STAM_REL_PROFILE_ADD_PERIOD(&pGVCpu->vmm.s.StatR0HaltBlockOverslept, cNsOverslept);
867 else if (cNsOverslept < -50000)
868 STAM_REL_PROFILE_ADD_PERIOD(&pGVCpu->vmm.s.StatR0HaltBlockInsomnia, cNsElapsedSchedHalt);
869 else
870 STAM_REL_PROFILE_ADD_PERIOD(&pGVCpu->vmm.s.StatR0HaltBlockOnTime, cNsElapsedSchedHalt);
871
872 /*
873 * Recheck whether we can resume execution or have to go to ring-3.
874 */
875 if ( !VM_FF_IS_ANY_SET(pGVM, fVmFFs)
876 && !VMCPU_FF_IS_ANY_SET(pGVCpu, fCpuFFs))
877 {
878 if (VMCPU_FF_TEST_AND_CLEAR(pGVCpu, VMCPU_FF_UPDATE_APIC))
879 APICUpdatePendingInterrupts(pGVCpu);
880 if (VMCPU_FF_IS_ANY_SET(pGVCpu, fIntMask))
881 {
882 STAM_REL_COUNTER_INC(&pGVCpu->vmm.s.StatR0HaltExecFromBlock);
883 return vmmR0DoHaltInterrupt(pGVCpu, uMWait, enmInterruptibility);
884 }
885 STAM_REL_COUNTER_INC(&pGVCpu->vmm.s.StatR0HaltToR3PostNoInt);
886 Log12(("vmmR0DoHalt: CPU%d post #2 - No pending interrupt\n", pGVCpu->idCpu));
887 }
888 else
889 {
890 STAM_REL_COUNTER_INC(&pGVCpu->vmm.s.StatR0HaltToR3PostPendingFF);
891 Log12(("vmmR0DoHalt: CPU%d post #1 - Pending FF\n", pGVCpu->idCpu));
892 }
893 }
894 else
895 {
896 STAM_REL_COUNTER_INC(&pGVCpu->vmm.s.StatR0HaltToR3Other);
897 Log12(("vmmR0DoHalt: CPU%d GVMMR0SchedHalt failed: %Rrc\n", pGVCpu->idCpu, rc));
898 }
899 }
900 else
901 {
902 VMCPU_CMPXCHG_STATE(pGVCpu, VMCPUSTATE_STARTED, VMCPUSTATE_STARTED_HALTED);
903 STAM_REL_COUNTER_INC(&pGVCpu->vmm.s.StatR0HaltToR3PendingFF);
904 Log12(("vmmR0DoHalt: CPU%d failed #5 - Pending FF\n", pGVCpu->idCpu));
905 }
906 }
907 else
908 {
909 STAM_REL_COUNTER_INC(&pGVCpu->vmm.s.StatR0HaltToR3Other);
910 Log12(("vmmR0DoHalt: CPU%d failed #4 - enmState=%d\n", pGVCpu->idCpu, VMCPU_GET_STATE(pGVCpu)));
911 }
912 }
913 else
914 {
915 STAM_REL_COUNTER_INC(&pGVCpu->vmm.s.StatR0HaltToR3SmallDelta);
916 Log12(("vmmR0DoHalt: CPU%d failed #3 - delta too small: %RU64\n", pGVCpu->idCpu, u64Delta));
917 }
918 }
919 else
920 {
921 STAM_REL_COUNTER_INC(&pGVCpu->vmm.s.StatR0HaltToR3PendingFF);
922 Log12(("vmmR0DoHalt: CPU%d failed #2 - Pending FF\n", pGVCpu->idCpu));
923 }
924 }
925 else
926 {
927 STAM_REL_COUNTER_INC(&pGVCpu->vmm.s.StatR0HaltToR3PendingFF);
928 Log12(("vmmR0DoHalt: CPU%d failed #1 - Pending FF\n", pGVCpu->idCpu));
929 }
930 }
931 else
932 {
933 STAM_REL_COUNTER_INC(&pGVCpu->vmm.s.StatR0HaltToR3Other);
934 Log12(("vmmR0DoHalt: CPU%d failed #0 - fMayHaltInRing0=%d TRPMHasTrap=%d enmInt=%d uMWait=%u\n",
935 pGVCpu->idCpu, pGVCpu->vmm.s.fMayHaltInRing0, TRPMHasTrap(pGVCpu), enmInterruptibility, uMWait));
936 }
937
938 STAM_REL_COUNTER_INC(&pGVCpu->vmm.s.StatR0HaltToR3);
939 return VINF_EM_HALT;
940}
941
942
943/**
944 * VMM ring-0 thread-context callback.
945 *
946 * This does common HM state updating and calls the HM-specific thread-context
947 * callback.
948 *
949 * This is used together with RTThreadCtxHookCreate() on platforms which
950 * supports it, and directly from VMMR0EmtPrepareForBlocking() and
951 * VMMR0EmtResumeAfterBlocking() on platforms which don't.
952 *
953 * @param enmEvent The thread-context event.
954 * @param pvUser Opaque pointer to the VMCPU.
955 *
956 * @thread EMT(pvUser)
957 */
958static DECLCALLBACK(void) vmmR0ThreadCtxCallback(RTTHREADCTXEVENT enmEvent, void *pvUser)
959{
960 PVMCPUCC pVCpu = (PVMCPUCC)pvUser;
961
962 switch (enmEvent)
963 {
964 case RTTHREADCTXEVENT_IN:
965 {
966 /*
967 * Linux may call us with preemption enabled (really!) but technically we
968 * cannot get preempted here, otherwise we end up in an infinite recursion
969 * scenario (i.e. preempted in resume hook -> preempt hook -> resume hook...
970 * ad infinitum). Let's just disable preemption for now...
971 */
972 /** @todo r=bird: I don't believe the above. The linux code is clearly enabling
973 * preemption after doing the callout (one or two functions up the
974 * call chain). */
975 /** @todo r=ramshankar: See @bugref{5313#c30}. */
976 RTTHREADPREEMPTSTATE ParanoidPreemptState = RTTHREADPREEMPTSTATE_INITIALIZER;
977 RTThreadPreemptDisable(&ParanoidPreemptState);
978
979 /* We need to update the VCPU <-> host CPU mapping. */
980 RTCPUID idHostCpu;
981 uint32_t iHostCpuSet = RTMpCurSetIndexAndId(&idHostCpu);
982 pVCpu->iHostCpuSet = iHostCpuSet;
983 ASMAtomicWriteU32(&pVCpu->idHostCpu, idHostCpu);
984
985 /* In the very unlikely event that the GIP delta for the CPU we're
986 rescheduled needs calculating, try force a return to ring-3.
987 We unfortunately cannot do the measurements right here. */
988 if (RT_LIKELY(!SUPIsTscDeltaAvailableForCpuSetIndex(iHostCpuSet)))
989 { /* likely */ }
990 else
991 VMCPU_FF_SET(pVCpu, VMCPU_FF_TO_R3);
992
993 /* Invoke the HM-specific thread-context callback. */
994 HMR0ThreadCtxCallback(enmEvent, pvUser);
995
996 /* Restore preemption. */
997 RTThreadPreemptRestore(&ParanoidPreemptState);
998 break;
999 }
1000
1001 case RTTHREADCTXEVENT_OUT:
1002 {
1003 /* Invoke the HM-specific thread-context callback. */
1004 HMR0ThreadCtxCallback(enmEvent, pvUser);
1005
1006 /*
1007 * Sigh. See VMMGetCpu() used by VMCPU_ASSERT_EMT(). We cannot let several VCPUs
1008 * have the same host CPU associated with it.
1009 */
1010 pVCpu->iHostCpuSet = UINT32_MAX;
1011 ASMAtomicWriteU32(&pVCpu->idHostCpu, NIL_RTCPUID);
1012 break;
1013 }
1014
1015 default:
1016 /* Invoke the HM-specific thread-context callback. */
1017 HMR0ThreadCtxCallback(enmEvent, pvUser);
1018 break;
1019 }
1020}
1021
1022
1023/**
1024 * Creates thread switching hook for the current EMT thread.
1025 *
1026 * This is called by GVMMR0CreateVM and GVMMR0RegisterVCpu. If the host
1027 * platform does not implement switcher hooks, no hooks will be create and the
1028 * member set to NIL_RTTHREADCTXHOOK.
1029 *
1030 * @returns VBox status code.
1031 * @param pVCpu The cross context virtual CPU structure.
1032 * @thread EMT(pVCpu)
1033 */
1034VMMR0_INT_DECL(int) VMMR0ThreadCtxHookCreateForEmt(PVMCPUCC pVCpu)
1035{
1036 VMCPU_ASSERT_EMT(pVCpu);
1037 Assert(pVCpu->vmmr0.s.hCtxHook == NIL_RTTHREADCTXHOOK);
1038
1039#if 1 /* To disable this stuff change to zero. */
1040 int rc = RTThreadCtxHookCreate(&pVCpu->vmmr0.s.hCtxHook, 0, vmmR0ThreadCtxCallback, pVCpu);
1041 if (RT_SUCCESS(rc))
1042 {
1043 pVCpu->pGVM->vmm.s.fIsUsingContextHooks = true;
1044 return rc;
1045 }
1046#else
1047 RT_NOREF(vmmR0ThreadCtxCallback);
1048 int rc = VERR_NOT_SUPPORTED;
1049#endif
1050
1051 pVCpu->vmmr0.s.hCtxHook = NIL_RTTHREADCTXHOOK;
1052 pVCpu->pGVM->vmm.s.fIsUsingContextHooks = false;
1053 if (rc == VERR_NOT_SUPPORTED)
1054 return VINF_SUCCESS;
1055
1056 LogRelMax(32, ("RTThreadCtxHookCreate failed! rc=%Rrc pVCpu=%p idCpu=%RU32\n", rc, pVCpu, pVCpu->idCpu));
1057 return VINF_SUCCESS; /* Just ignore it, we can live without context hooks. */
1058}
1059
1060
1061/**
1062 * Destroys the thread switching hook for the specified VCPU.
1063 *
1064 * @param pVCpu The cross context virtual CPU structure.
1065 * @remarks Can be called from any thread.
1066 */
1067VMMR0_INT_DECL(void) VMMR0ThreadCtxHookDestroyForEmt(PVMCPUCC pVCpu)
1068{
1069 int rc = RTThreadCtxHookDestroy(pVCpu->vmmr0.s.hCtxHook);
1070 AssertRC(rc);
1071 pVCpu->vmmr0.s.hCtxHook = NIL_RTTHREADCTXHOOK;
1072}
1073
1074
1075/**
1076 * Disables the thread switching hook for this VCPU (if we got one).
1077 *
1078 * @param pVCpu The cross context virtual CPU structure.
1079 * @thread EMT(pVCpu)
1080 *
1081 * @remarks This also clears GVMCPU::idHostCpu, so the mapping is invalid after
1082 * this call. This means you have to be careful with what you do!
1083 */
1084VMMR0_INT_DECL(void) VMMR0ThreadCtxHookDisable(PVMCPUCC pVCpu)
1085{
1086 /*
1087 * Clear the VCPU <-> host CPU mapping as we've left HM context.
1088 * @bugref{7726#c19} explains the need for this trick:
1089 *
1090 * VMXR0CallRing3Callback/SVMR0CallRing3Callback &
1091 * hmR0VmxLeaveSession/hmR0SvmLeaveSession disables context hooks during
1092 * longjmp & normal return to ring-3, which opens a window where we may be
1093 * rescheduled without changing GVMCPUID::idHostCpu and cause confusion if
1094 * the CPU starts executing a different EMT. Both functions first disables
1095 * preemption and then calls HMR0LeaveCpu which invalids idHostCpu, leaving
1096 * an opening for getting preempted.
1097 */
1098 /** @todo Make HM not need this API! Then we could leave the hooks enabled
1099 * all the time. */
1100
1101 /*
1102 * Disable the context hook, if we got one.
1103 */
1104 if (pVCpu->vmmr0.s.hCtxHook != NIL_RTTHREADCTXHOOK)
1105 {
1106 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
1107 ASMAtomicWriteU32(&pVCpu->idHostCpu, NIL_RTCPUID);
1108 int rc = RTThreadCtxHookDisable(pVCpu->vmmr0.s.hCtxHook);
1109 AssertRC(rc);
1110 }
1111}
1112
1113
1114/**
1115 * Internal version of VMMR0ThreadCtxHooksAreRegistered.
1116 *
1117 * @returns true if registered, false otherwise.
1118 * @param pVCpu The cross context virtual CPU structure.
1119 */
1120DECLINLINE(bool) vmmR0ThreadCtxHookIsEnabled(PVMCPUCC pVCpu)
1121{
1122 return RTThreadCtxHookIsEnabled(pVCpu->vmmr0.s.hCtxHook);
1123}
1124
1125
1126/**
1127 * Whether thread-context hooks are registered for this VCPU.
1128 *
1129 * @returns true if registered, false otherwise.
1130 * @param pVCpu The cross context virtual CPU structure.
1131 */
1132VMMR0_INT_DECL(bool) VMMR0ThreadCtxHookIsEnabled(PVMCPUCC pVCpu)
1133{
1134 return vmmR0ThreadCtxHookIsEnabled(pVCpu);
1135}
1136
1137
1138/**
1139 * Returns the ring-0 release logger instance.
1140 *
1141 * @returns Pointer to release logger, NULL if not configured.
1142 * @param pVCpu The cross context virtual CPU structure of the caller.
1143 * @thread EMT(pVCpu)
1144 */
1145VMMR0_INT_DECL(PRTLOGGER) VMMR0GetReleaseLogger(PVMCPUCC pVCpu)
1146{
1147 return pVCpu->vmmr0.s.u.s.RelLogger.pLogger;
1148}
1149
1150
1151#ifdef VBOX_WITH_STATISTICS
1152/**
1153 * Record return code statistics
1154 * @param pVM The cross context VM structure.
1155 * @param pVCpu The cross context virtual CPU structure.
1156 * @param rc The status code.
1157 */
1158static void vmmR0RecordRC(PVMCC pVM, PVMCPUCC pVCpu, int rc)
1159{
1160 /*
1161 * Collect statistics.
1162 */
1163 switch (rc)
1164 {
1165 case VINF_SUCCESS:
1166 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetNormal);
1167 break;
1168 case VINF_EM_RAW_INTERRUPT:
1169 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetInterrupt);
1170 break;
1171 case VINF_EM_RAW_INTERRUPT_HYPER:
1172 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetInterruptHyper);
1173 break;
1174 case VINF_EM_RAW_GUEST_TRAP:
1175 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetGuestTrap);
1176 break;
1177 case VINF_EM_RAW_RING_SWITCH:
1178 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetRingSwitch);
1179 break;
1180 case VINF_EM_RAW_RING_SWITCH_INT:
1181 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetRingSwitchInt);
1182 break;
1183 case VINF_EM_RAW_STALE_SELECTOR:
1184 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetStaleSelector);
1185 break;
1186 case VINF_EM_RAW_IRET_TRAP:
1187 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetIRETTrap);
1188 break;
1189 case VINF_IOM_R3_IOPORT_READ:
1190 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetIORead);
1191 break;
1192 case VINF_IOM_R3_IOPORT_WRITE:
1193 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetIOWrite);
1194 break;
1195 case VINF_IOM_R3_IOPORT_COMMIT_WRITE:
1196 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetIOCommitWrite);
1197 break;
1198 case VINF_IOM_R3_MMIO_READ:
1199 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetMMIORead);
1200 break;
1201 case VINF_IOM_R3_MMIO_WRITE:
1202 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetMMIOWrite);
1203 break;
1204 case VINF_IOM_R3_MMIO_COMMIT_WRITE:
1205 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetMMIOCommitWrite);
1206 break;
1207 case VINF_IOM_R3_MMIO_READ_WRITE:
1208 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetMMIOReadWrite);
1209 break;
1210 case VINF_PATM_HC_MMIO_PATCH_READ:
1211 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetMMIOPatchRead);
1212 break;
1213 case VINF_PATM_HC_MMIO_PATCH_WRITE:
1214 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetMMIOPatchWrite);
1215 break;
1216 case VINF_CPUM_R3_MSR_READ:
1217 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetMSRRead);
1218 break;
1219 case VINF_CPUM_R3_MSR_WRITE:
1220 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetMSRWrite);
1221 break;
1222 case VINF_EM_RAW_EMULATE_INSTR:
1223 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetEmulate);
1224 break;
1225 case VINF_PATCH_EMULATE_INSTR:
1226 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetPatchEmulate);
1227 break;
1228 case VINF_EM_RAW_EMULATE_INSTR_LDT_FAULT:
1229 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetLDTFault);
1230 break;
1231 case VINF_EM_RAW_EMULATE_INSTR_GDT_FAULT:
1232 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetGDTFault);
1233 break;
1234 case VINF_EM_RAW_EMULATE_INSTR_IDT_FAULT:
1235 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetIDTFault);
1236 break;
1237 case VINF_EM_RAW_EMULATE_INSTR_TSS_FAULT:
1238 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetTSSFault);
1239 break;
1240 case VINF_CSAM_PENDING_ACTION:
1241 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetCSAMTask);
1242 break;
1243 case VINF_PGM_SYNC_CR3:
1244 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetSyncCR3);
1245 break;
1246 case VINF_PATM_PATCH_INT3:
1247 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetPatchInt3);
1248 break;
1249 case VINF_PATM_PATCH_TRAP_PF:
1250 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetPatchPF);
1251 break;
1252 case VINF_PATM_PATCH_TRAP_GP:
1253 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetPatchGP);
1254 break;
1255 case VINF_PATM_PENDING_IRQ_AFTER_IRET:
1256 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetPatchIretIRQ);
1257 break;
1258 case VINF_EM_RESCHEDULE_REM:
1259 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetRescheduleREM);
1260 break;
1261 case VINF_EM_RAW_TO_R3:
1262 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetToR3Total);
1263 if (VM_FF_IS_SET(pVM, VM_FF_TM_VIRTUAL_SYNC))
1264 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetToR3TMVirt);
1265 else if (VM_FF_IS_SET(pVM, VM_FF_PGM_NEED_HANDY_PAGES))
1266 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetToR3HandyPages);
1267 else if (VM_FF_IS_SET(pVM, VM_FF_PDM_QUEUES))
1268 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetToR3PDMQueues);
1269 else if (VM_FF_IS_SET(pVM, VM_FF_EMT_RENDEZVOUS))
1270 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetToR3Rendezvous);
1271 else if (VM_FF_IS_SET(pVM, VM_FF_PDM_DMA))
1272 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetToR3DMA);
1273 else if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_TIMER))
1274 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetToR3Timer);
1275 else if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_PDM_CRITSECT))
1276 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetToR3CritSect);
1277 else if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_TO_R3))
1278 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetToR3FF);
1279 else if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_IEM))
1280 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetToR3Iem);
1281 else if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_IOM))
1282 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetToR3Iom);
1283 else
1284 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetToR3Unknown);
1285 break;
1286
1287 case VINF_EM_RAW_TIMER_PENDING:
1288 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetTimerPending);
1289 break;
1290 case VINF_EM_RAW_INTERRUPT_PENDING:
1291 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetInterruptPending);
1292 break;
1293 case VINF_VMM_CALL_HOST:
1294 switch (pVCpu->vmm.s.enmCallRing3Operation)
1295 {
1296 case VMMCALLRING3_PGM_ALLOCATE_HANDY_PAGES:
1297 STAM_COUNTER_INC(&pVM->vmm.s.StatRZCallPGMAllocHandy);
1298 break;
1299 case VMMCALLRING3_VM_R0_ASSERTION:
1300 default:
1301 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetCallRing3);
1302 break;
1303 }
1304 break;
1305 case VINF_PATM_DUPLICATE_FUNCTION:
1306 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetPATMDuplicateFn);
1307 break;
1308 case VINF_PGM_CHANGE_MODE:
1309 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetPGMChangeMode);
1310 break;
1311 case VINF_PGM_POOL_FLUSH_PENDING:
1312 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetPGMFlushPending);
1313 break;
1314 case VINF_EM_PENDING_REQUEST:
1315 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetPendingRequest);
1316 break;
1317 case VINF_EM_HM_PATCH_TPR_INSTR:
1318 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetPatchTPR);
1319 break;
1320 default:
1321 STAM_COUNTER_INC(&pVM->vmm.s.StatRZRetMisc);
1322 break;
1323 }
1324}
1325#endif /* VBOX_WITH_STATISTICS */
1326
1327
1328/**
1329 * The Ring 0 entry point, called by the fast-ioctl path.
1330 *
1331 * @param pGVM The global (ring-0) VM structure.
1332 * @param pVMIgnored The cross context VM structure. The return code is
1333 * stored in pVM->vmm.s.iLastGZRc.
1334 * @param idCpu The Virtual CPU ID of the calling EMT.
1335 * @param enmOperation Which operation to execute.
1336 * @remarks Assume called with interrupts _enabled_.
1337 */
1338VMMR0DECL(void) VMMR0EntryFast(PGVM pGVM, PVMCC pVMIgnored, VMCPUID idCpu, VMMR0OPERATION enmOperation)
1339{
1340 RT_NOREF(pVMIgnored);
1341
1342 /*
1343 * Validation.
1344 */
1345 if ( idCpu < pGVM->cCpus
1346 && pGVM->cCpus == pGVM->cCpusUnsafe)
1347 { /*likely*/ }
1348 else
1349 {
1350 SUPR0Printf("VMMR0EntryFast: Bad idCpu=%#x cCpus=%#x cCpusUnsafe=%#x\n", idCpu, pGVM->cCpus, pGVM->cCpusUnsafe);
1351 return;
1352 }
1353
1354 PGVMCPU pGVCpu = &pGVM->aCpus[idCpu];
1355 RTNATIVETHREAD const hNativeThread = RTThreadNativeSelf();
1356 if (RT_LIKELY( pGVCpu->hEMT == hNativeThread
1357 && pGVCpu->hNativeThreadR0 == hNativeThread))
1358 { /* likely */ }
1359 else
1360 {
1361 SUPR0Printf("VMMR0EntryFast: Bad thread idCpu=%#x hNativeSelf=%p pGVCpu->hEmt=%p pGVCpu->hNativeThreadR0=%p\n",
1362 idCpu, hNativeThread, pGVCpu->hEMT, pGVCpu->hNativeThreadR0);
1363 return;
1364 }
1365
1366 /*
1367 * Perform requested operation.
1368 */
1369 switch (enmOperation)
1370 {
1371 /*
1372 * Run guest code using the available hardware acceleration technology.
1373 */
1374 case VMMR0_DO_HM_RUN:
1375 {
1376 for (;;) /* hlt loop */
1377 {
1378 /*
1379 * Disable ring-3 calls & blocking till we've successfully entered HM.
1380 * Otherwise we sometimes end up blocking at the finall Log4 statement
1381 * in VMXR0Enter, while still in a somewhat inbetween state.
1382 */
1383 VMMRZCallRing3Disable(pGVCpu);
1384
1385 /*
1386 * Disable preemption.
1387 */
1388 Assert(!vmmR0ThreadCtxHookIsEnabled(pGVCpu));
1389 RTTHREADPREEMPTSTATE PreemptState = RTTHREADPREEMPTSTATE_INITIALIZER;
1390 RTThreadPreemptDisable(&PreemptState);
1391 pGVCpu->vmmr0.s.pPreemptState = &PreemptState;
1392
1393 /*
1394 * Get the host CPU identifiers, make sure they are valid and that
1395 * we've got a TSC delta for the CPU.
1396 */
1397 RTCPUID idHostCpu;
1398 uint32_t iHostCpuSet = RTMpCurSetIndexAndId(&idHostCpu);
1399 if (RT_LIKELY( iHostCpuSet < RTCPUSET_MAX_CPUS
1400 && SUPIsTscDeltaAvailableForCpuSetIndex(iHostCpuSet)))
1401 {
1402 pGVCpu->iHostCpuSet = iHostCpuSet;
1403 ASMAtomicWriteU32(&pGVCpu->idHostCpu, idHostCpu);
1404
1405 /*
1406 * Update the periodic preemption timer if it's active.
1407 */
1408 if (pGVM->vmm.s.fUsePeriodicPreemptionTimers)
1409 GVMMR0SchedUpdatePeriodicPreemptionTimer(pGVM, pGVCpu->idHostCpu, TMCalcHostTimerFrequency(pGVM, pGVCpu));
1410
1411#ifdef VMM_R0_TOUCH_FPU
1412 /*
1413 * Make sure we've got the FPU state loaded so and we don't need to clear
1414 * CR0.TS and get out of sync with the host kernel when loading the guest
1415 * FPU state. @ref sec_cpum_fpu (CPUM.cpp) and @bugref{4053}.
1416 */
1417 CPUMR0TouchHostFpu();
1418#endif
1419 int rc;
1420 bool fPreemptRestored = false;
1421 if (!HMR0SuspendPending())
1422 {
1423 /*
1424 * Enable the context switching hook.
1425 */
1426 if (pGVCpu->vmmr0.s.hCtxHook != NIL_RTTHREADCTXHOOK)
1427 {
1428 Assert(!RTThreadCtxHookIsEnabled(pGVCpu->vmmr0.s.hCtxHook));
1429 int rc2 = RTThreadCtxHookEnable(pGVCpu->vmmr0.s.hCtxHook); AssertRC(rc2);
1430 }
1431
1432 /*
1433 * Enter HM context.
1434 */
1435 rc = HMR0Enter(pGVCpu);
1436 if (RT_SUCCESS(rc))
1437 {
1438 VMCPU_SET_STATE(pGVCpu, VMCPUSTATE_STARTED_HM);
1439
1440 /*
1441 * When preemption hooks are in place, enable preemption now that
1442 * we're in HM context.
1443 */
1444 if (vmmR0ThreadCtxHookIsEnabled(pGVCpu))
1445 {
1446 fPreemptRestored = true;
1447 pGVCpu->vmmr0.s.pPreemptState = NULL;
1448 RTThreadPreemptRestore(&PreemptState);
1449 }
1450 VMMRZCallRing3Enable(pGVCpu);
1451
1452 /*
1453 * Setup the longjmp machinery and execute guest code (calls HMR0RunGuestCode).
1454 */
1455 rc = vmmR0CallRing3SetJmp(&pGVCpu->vmm.s.CallRing3JmpBufR0, HMR0RunGuestCode, pGVM, pGVCpu);
1456
1457 /*
1458 * Assert sanity on the way out. Using manual assertions code here as normal
1459 * assertions are going to panic the host since we're outside the setjmp/longjmp zone.
1460 */
1461 if (RT_UNLIKELY( VMCPU_GET_STATE(pGVCpu) != VMCPUSTATE_STARTED_HM
1462 && RT_SUCCESS_NP(rc)
1463 && rc != VINF_VMM_CALL_HOST ))
1464 {
1465 pGVM->vmm.s.szRing0AssertMsg1[0] = '\0';
1466 RTStrPrintf(pGVM->vmm.s.szRing0AssertMsg2, sizeof(pGVM->vmm.s.szRing0AssertMsg2),
1467 "Got VMCPU state %d expected %d.\n", VMCPU_GET_STATE(pGVCpu), VMCPUSTATE_STARTED_HM);
1468 rc = VERR_VMM_WRONG_HM_VMCPU_STATE;
1469 }
1470#if 0
1471 /** @todo Get rid of this. HM shouldn't disable the context hook. */
1472 else if (RT_UNLIKELY(vmmR0ThreadCtxHookIsEnabled(pGVCpu)))
1473 {
1474 pGVM->vmm.s.szRing0AssertMsg1[0] = '\0';
1475 RTStrPrintf(pGVM->vmm.s.szRing0AssertMsg2, sizeof(pGVM->vmm.s.szRing0AssertMsg2),
1476 "Thread-context hooks still enabled! VCPU=%p Id=%u rc=%d.\n", pGVCpu, pGVCpu->idCpu, rc);
1477 rc = VERR_VMM_CONTEXT_HOOK_STILL_ENABLED;
1478 }
1479#endif
1480
1481 VMMRZCallRing3Disable(pGVCpu); /* Lazy bird: Simpler just disabling it again... */
1482 VMCPU_SET_STATE(pGVCpu, VMCPUSTATE_STARTED);
1483 }
1484 STAM_COUNTER_INC(&pGVM->vmm.s.StatRunGC);
1485
1486 /*
1487 * Invalidate the host CPU identifiers before we disable the context
1488 * hook / restore preemption.
1489 */
1490 pGVCpu->iHostCpuSet = UINT32_MAX;
1491 ASMAtomicWriteU32(&pGVCpu->idHostCpu, NIL_RTCPUID);
1492
1493 /*
1494 * Disable context hooks. Due to unresolved cleanup issues, we
1495 * cannot leave the hooks enabled when we return to ring-3.
1496 *
1497 * Note! At the moment HM may also have disabled the hook
1498 * when we get here, but the IPRT API handles that.
1499 */
1500 if (pGVCpu->vmmr0.s.hCtxHook != NIL_RTTHREADCTXHOOK)
1501 RTThreadCtxHookDisable(pGVCpu->vmmr0.s.hCtxHook);
1502 }
1503 /*
1504 * The system is about to go into suspend mode; go back to ring 3.
1505 */
1506 else
1507 {
1508 pGVCpu->iHostCpuSet = UINT32_MAX;
1509 ASMAtomicWriteU32(&pGVCpu->idHostCpu, NIL_RTCPUID);
1510 rc = VINF_EM_RAW_INTERRUPT;
1511 }
1512
1513 /** @todo When HM stops messing with the context hook state, we'll disable
1514 * preemption again before the RTThreadCtxHookDisable call. */
1515 if (!fPreemptRestored)
1516 {
1517 pGVCpu->vmmr0.s.pPreemptState = NULL;
1518 RTThreadPreemptRestore(&PreemptState);
1519 }
1520
1521 pGVCpu->vmm.s.iLastGZRc = rc;
1522
1523 /* Fire dtrace probe and collect statistics. */
1524 VBOXVMM_R0_VMM_RETURN_TO_RING3_HM(pGVCpu, CPUMQueryGuestCtxPtr(pGVCpu), rc);
1525#ifdef VBOX_WITH_STATISTICS
1526 vmmR0RecordRC(pGVM, pGVCpu, rc);
1527#endif
1528 VMMRZCallRing3Enable(pGVCpu);
1529
1530 /*
1531 * If this is a halt.
1532 */
1533 if (rc != VINF_EM_HALT)
1534 { /* we're not in a hurry for a HLT, so prefer this path */ }
1535 else
1536 {
1537 pGVCpu->vmm.s.iLastGZRc = rc = vmmR0DoHalt(pGVM, pGVCpu);
1538 if (rc == VINF_SUCCESS)
1539 {
1540 pGVCpu->vmm.s.cR0HaltsSucceeded++;
1541 continue;
1542 }
1543 pGVCpu->vmm.s.cR0HaltsToRing3++;
1544 }
1545 }
1546 /*
1547 * Invalid CPU set index or TSC delta in need of measuring.
1548 */
1549 else
1550 {
1551 pGVCpu->vmmr0.s.pPreemptState = NULL;
1552 pGVCpu->iHostCpuSet = UINT32_MAX;
1553 ASMAtomicWriteU32(&pGVCpu->idHostCpu, NIL_RTCPUID);
1554 RTThreadPreemptRestore(&PreemptState);
1555
1556 VMMRZCallRing3Enable(pGVCpu);
1557
1558 if (iHostCpuSet < RTCPUSET_MAX_CPUS)
1559 {
1560 int rc = SUPR0TscDeltaMeasureBySetIndex(pGVM->pSession, iHostCpuSet, 0 /*fFlags*/,
1561 2 /*cMsWaitRetry*/, 5*RT_MS_1SEC /*cMsWaitThread*/,
1562 0 /*default cTries*/);
1563 if (RT_SUCCESS(rc) || rc == VERR_CPU_OFFLINE)
1564 pGVCpu->vmm.s.iLastGZRc = VINF_EM_RAW_TO_R3;
1565 else
1566 pGVCpu->vmm.s.iLastGZRc = rc;
1567 }
1568 else
1569 pGVCpu->vmm.s.iLastGZRc = VERR_INVALID_CPU_INDEX;
1570 }
1571 break;
1572 } /* halt loop. */
1573 break;
1574 }
1575
1576#ifdef VBOX_WITH_NEM_R0
1577# if defined(RT_ARCH_AMD64) && defined(RT_OS_WINDOWS)
1578 case VMMR0_DO_NEM_RUN:
1579 {
1580 /*
1581 * Setup the longjmp machinery and execute guest code (calls NEMR0RunGuestCode).
1582 */
1583# ifdef VBOXSTRICTRC_STRICT_ENABLED
1584 int rc = vmmR0CallRing3SetJmp2(&pGVCpu->vmm.s.CallRing3JmpBufR0, (PFNVMMR0SETJMP2)NEMR0RunGuestCode, pGVM, idCpu);
1585# else
1586 int rc = vmmR0CallRing3SetJmp2(&pGVCpu->vmm.s.CallRing3JmpBufR0, NEMR0RunGuestCode, pGVM, idCpu);
1587# endif
1588 STAM_COUNTER_INC(&pGVM->vmm.s.StatRunGC);
1589
1590 pGVCpu->vmm.s.iLastGZRc = rc;
1591
1592 /*
1593 * Fire dtrace probe and collect statistics.
1594 */
1595 VBOXVMM_R0_VMM_RETURN_TO_RING3_NEM(pGVCpu, CPUMQueryGuestCtxPtr(pGVCpu), rc);
1596# ifdef VBOX_WITH_STATISTICS
1597 vmmR0RecordRC(pGVM, pGVCpu, rc);
1598# endif
1599 break;
1600 }
1601# endif
1602#endif
1603
1604 /*
1605 * For profiling.
1606 */
1607 case VMMR0_DO_NOP:
1608 pGVCpu->vmm.s.iLastGZRc = VINF_SUCCESS;
1609 break;
1610
1611 /*
1612 * Shouldn't happen.
1613 */
1614 default:
1615 AssertMsgFailed(("%#x\n", enmOperation));
1616 pGVCpu->vmm.s.iLastGZRc = VERR_NOT_SUPPORTED;
1617 break;
1618 }
1619}
1620
1621
1622/**
1623 * Validates a session or VM session argument.
1624 *
1625 * @returns true / false accordingly.
1626 * @param pGVM The global (ring-0) VM structure.
1627 * @param pClaimedSession The session claim to validate.
1628 * @param pSession The session argument.
1629 */
1630DECLINLINE(bool) vmmR0IsValidSession(PGVM pGVM, PSUPDRVSESSION pClaimedSession, PSUPDRVSESSION pSession)
1631{
1632 /* This must be set! */
1633 if (!pSession)
1634 return false;
1635
1636 /* Only one out of the two. */
1637 if (pGVM && pClaimedSession)
1638 return false;
1639 if (pGVM)
1640 pClaimedSession = pGVM->pSession;
1641 return pClaimedSession == pSession;
1642}
1643
1644
1645/**
1646 * VMMR0EntryEx worker function, either called directly or when ever possible
1647 * called thru a longjmp so we can exit safely on failure.
1648 *
1649 * @returns VBox status code.
1650 * @param pGVM The global (ring-0) VM structure.
1651 * @param idCpu Virtual CPU ID argument. Must be NIL_VMCPUID if pVM
1652 * is NIL_RTR0PTR, and may be NIL_VMCPUID if it isn't
1653 * @param enmOperation Which operation to execute.
1654 * @param pReqHdr This points to a SUPVMMR0REQHDR packet. Optional.
1655 * The support driver validates this if it's present.
1656 * @param u64Arg Some simple constant argument.
1657 * @param pSession The session of the caller.
1658 *
1659 * @remarks Assume called with interrupts _enabled_.
1660 */
1661DECL_NO_INLINE(static, int) vmmR0EntryExWorker(PGVM pGVM, VMCPUID idCpu, VMMR0OPERATION enmOperation,
1662 PSUPVMMR0REQHDR pReqHdr, uint64_t u64Arg, PSUPDRVSESSION pSession)
1663{
1664 /*
1665 * Validate pGVM and idCpu for consistency and validity.
1666 */
1667 if (pGVM != NULL)
1668 {
1669 if (RT_LIKELY(((uintptr_t)pGVM & PAGE_OFFSET_MASK) == 0))
1670 { /* likely */ }
1671 else
1672 {
1673 SUPR0Printf("vmmR0EntryExWorker: Invalid pGVM=%p! (op=%d)\n", pGVM, enmOperation);
1674 return VERR_INVALID_POINTER;
1675 }
1676
1677 if (RT_LIKELY(idCpu == NIL_VMCPUID || idCpu < pGVM->cCpus))
1678 { /* likely */ }
1679 else
1680 {
1681 SUPR0Printf("vmmR0EntryExWorker: Invalid idCpu %#x (cCpus=%#x)\n", idCpu, pGVM->cCpus);
1682 return VERR_INVALID_PARAMETER;
1683 }
1684
1685 if (RT_LIKELY( pGVM->enmVMState >= VMSTATE_CREATING
1686 && pGVM->enmVMState <= VMSTATE_TERMINATED
1687 && pGVM->pSession == pSession
1688 && pGVM->pSelf == pGVM))
1689 { /* likely */ }
1690 else
1691 {
1692 SUPR0Printf("vmmR0EntryExWorker: Invalid pGVM=%p:{.enmVMState=%d, .cCpus=%#x, .pSession=%p(==%p), .pSelf=%p(==%p)}! (op=%d)\n",
1693 pGVM, pGVM->enmVMState, pGVM->cCpus, pGVM->pSession, pSession, pGVM->pSelf, pGVM, enmOperation);
1694 return VERR_INVALID_POINTER;
1695 }
1696 }
1697 else if (RT_LIKELY(idCpu == NIL_VMCPUID))
1698 { /* likely */ }
1699 else
1700 {
1701 SUPR0Printf("vmmR0EntryExWorker: Invalid idCpu=%u\n", idCpu);
1702 return VERR_INVALID_PARAMETER;
1703 }
1704
1705 /*
1706 * Process the request.
1707 */
1708 int rc;
1709 switch (enmOperation)
1710 {
1711 /*
1712 * GVM requests
1713 */
1714 case VMMR0_DO_GVMM_CREATE_VM:
1715 if (pGVM == NULL && u64Arg == 0 && idCpu == NIL_VMCPUID)
1716 rc = GVMMR0CreateVMReq((PGVMMCREATEVMREQ)pReqHdr, pSession);
1717 else
1718 rc = VERR_INVALID_PARAMETER;
1719 break;
1720
1721 case VMMR0_DO_GVMM_DESTROY_VM:
1722 if (pReqHdr == NULL && u64Arg == 0)
1723 rc = GVMMR0DestroyVM(pGVM);
1724 else
1725 rc = VERR_INVALID_PARAMETER;
1726 break;
1727
1728 case VMMR0_DO_GVMM_REGISTER_VMCPU:
1729 if (pGVM != NULL)
1730 rc = GVMMR0RegisterVCpu(pGVM, idCpu);
1731 else
1732 rc = VERR_INVALID_PARAMETER;
1733 break;
1734
1735 case VMMR0_DO_GVMM_DEREGISTER_VMCPU:
1736 if (pGVM != NULL)
1737 rc = GVMMR0DeregisterVCpu(pGVM, idCpu);
1738 else
1739 rc = VERR_INVALID_PARAMETER;
1740 break;
1741
1742 case VMMR0_DO_GVMM_REGISTER_WORKER_THREAD:
1743 if (pGVM != NULL && pReqHdr && pReqHdr->cbReq == sizeof(GVMMREGISTERWORKERTHREADREQ))
1744 rc = GVMMR0RegisterWorkerThread(pGVM, (GVMMWORKERTHREAD)(unsigned)u64Arg,
1745 ((PGVMMREGISTERWORKERTHREADREQ)(pReqHdr))->hNativeThreadR3);
1746 else
1747 rc = VERR_INVALID_PARAMETER;
1748 break;
1749
1750 case VMMR0_DO_GVMM_DEREGISTER_WORKER_THREAD:
1751 if (pGVM != NULL)
1752 rc = GVMMR0DeregisterWorkerThread(pGVM, (GVMMWORKERTHREAD)(unsigned)u64Arg);
1753 else
1754 rc = VERR_INVALID_PARAMETER;
1755 break;
1756
1757 case VMMR0_DO_GVMM_SCHED_HALT:
1758 if (pReqHdr)
1759 return VERR_INVALID_PARAMETER;
1760 rc = GVMMR0SchedHaltReq(pGVM, idCpu, u64Arg);
1761 break;
1762
1763 case VMMR0_DO_GVMM_SCHED_WAKE_UP:
1764 if (pReqHdr || u64Arg)
1765 return VERR_INVALID_PARAMETER;
1766 rc = GVMMR0SchedWakeUp(pGVM, idCpu);
1767 break;
1768
1769 case VMMR0_DO_GVMM_SCHED_POKE:
1770 if (pReqHdr || u64Arg)
1771 return VERR_INVALID_PARAMETER;
1772 rc = GVMMR0SchedPoke(pGVM, idCpu);
1773 break;
1774
1775 case VMMR0_DO_GVMM_SCHED_WAKE_UP_AND_POKE_CPUS:
1776 if (u64Arg)
1777 return VERR_INVALID_PARAMETER;
1778 rc = GVMMR0SchedWakeUpAndPokeCpusReq(pGVM, (PGVMMSCHEDWAKEUPANDPOKECPUSREQ)pReqHdr);
1779 break;
1780
1781 case VMMR0_DO_GVMM_SCHED_POLL:
1782 if (pReqHdr || u64Arg > 1)
1783 return VERR_INVALID_PARAMETER;
1784 rc = GVMMR0SchedPoll(pGVM, idCpu, !!u64Arg);
1785 break;
1786
1787 case VMMR0_DO_GVMM_QUERY_STATISTICS:
1788 if (u64Arg)
1789 return VERR_INVALID_PARAMETER;
1790 rc = GVMMR0QueryStatisticsReq(pGVM, (PGVMMQUERYSTATISTICSSREQ)pReqHdr, pSession);
1791 break;
1792
1793 case VMMR0_DO_GVMM_RESET_STATISTICS:
1794 if (u64Arg)
1795 return VERR_INVALID_PARAMETER;
1796 rc = GVMMR0ResetStatisticsReq(pGVM, (PGVMMRESETSTATISTICSSREQ)pReqHdr, pSession);
1797 break;
1798
1799 /*
1800 * Initialize the R0 part of a VM instance.
1801 */
1802 case VMMR0_DO_VMMR0_INIT:
1803 rc = vmmR0InitVM(pGVM, RT_LODWORD(u64Arg), RT_HIDWORD(u64Arg));
1804 break;
1805
1806 /*
1807 * Does EMT specific ring-0 init.
1808 */
1809 case VMMR0_DO_VMMR0_INIT_EMT:
1810 rc = vmmR0InitVMEmt(pGVM, idCpu);
1811 break;
1812
1813 /*
1814 * Terminate the R0 part of a VM instance.
1815 */
1816 case VMMR0_DO_VMMR0_TERM:
1817 rc = VMMR0TermVM(pGVM, 0 /*idCpu*/);
1818 break;
1819
1820 /*
1821 * Update release or debug logger instances.
1822 */
1823 case VMMR0_DO_VMMR0_UPDATE_LOGGERS:
1824 if (idCpu == NIL_VMCPUID)
1825 return VERR_INVALID_CPU_ID;
1826 if (u64Arg < VMMLOGGER_IDX_MAX && pReqHdr != NULL)
1827 rc = vmmR0UpdateLoggers(pGVM, idCpu /*idCpu*/, (PVMMR0UPDATELOGGERSREQ)pReqHdr, (size_t)u64Arg);
1828 else
1829 return VERR_INVALID_PARAMETER;
1830 break;
1831
1832 /*
1833 * Log flusher thread.
1834 */
1835 case VMMR0_DO_VMMR0_LOG_FLUSHER:
1836 if (idCpu != NIL_VMCPUID)
1837 return VERR_INVALID_CPU_ID;
1838 if (pReqHdr == NULL)
1839 rc = vmmR0LogFlusher(pGVM);
1840 else
1841 return VERR_INVALID_PARAMETER;
1842 break;
1843
1844 /*
1845 * Wait for the flush to finish with all the buffers for the given logger.
1846 */
1847 case VMMR0_DO_VMMR0_LOG_WAIT_FLUSHED:
1848 if (idCpu == NIL_VMCPUID)
1849 return VERR_INVALID_CPU_ID;
1850 if (u64Arg < VMMLOGGER_IDX_MAX && pReqHdr == NULL)
1851 rc = vmmR0LogWaitFlushed(pGVM, idCpu /*idCpu*/, (size_t)u64Arg);
1852 else
1853 return VERR_INVALID_PARAMETER;
1854 break;
1855
1856 /*
1857 * Attempt to enable hm mode and check the current setting.
1858 */
1859 case VMMR0_DO_HM_ENABLE:
1860 rc = HMR0EnableAllCpus(pGVM);
1861 break;
1862
1863 /*
1864 * Setup the hardware accelerated session.
1865 */
1866 case VMMR0_DO_HM_SETUP_VM:
1867 rc = HMR0SetupVM(pGVM);
1868 break;
1869
1870 /*
1871 * PGM wrappers.
1872 */
1873 case VMMR0_DO_PGM_ALLOCATE_HANDY_PAGES:
1874 if (idCpu == NIL_VMCPUID)
1875 return VERR_INVALID_CPU_ID;
1876 rc = PGMR0PhysAllocateHandyPages(pGVM, idCpu);
1877 break;
1878
1879 case VMMR0_DO_PGM_FLUSH_HANDY_PAGES:
1880 if (idCpu == NIL_VMCPUID)
1881 return VERR_INVALID_CPU_ID;
1882 rc = PGMR0PhysFlushHandyPages(pGVM, idCpu);
1883 break;
1884
1885 case VMMR0_DO_PGM_ALLOCATE_LARGE_HANDY_PAGE:
1886 if (idCpu == NIL_VMCPUID)
1887 return VERR_INVALID_CPU_ID;
1888 rc = PGMR0PhysAllocateLargeHandyPage(pGVM, idCpu);
1889 break;
1890
1891 case VMMR0_DO_PGM_PHYS_SETUP_IOMMU:
1892 if (idCpu != 0)
1893 return VERR_INVALID_CPU_ID;
1894 rc = PGMR0PhysSetupIoMmu(pGVM);
1895 break;
1896
1897 case VMMR0_DO_PGM_POOL_GROW:
1898 if (idCpu == NIL_VMCPUID)
1899 return VERR_INVALID_CPU_ID;
1900 rc = PGMR0PoolGrow(pGVM, idCpu);
1901 break;
1902
1903 /*
1904 * GMM wrappers.
1905 */
1906 case VMMR0_DO_GMM_INITIAL_RESERVATION:
1907 if (u64Arg)
1908 return VERR_INVALID_PARAMETER;
1909 rc = GMMR0InitialReservationReq(pGVM, idCpu, (PGMMINITIALRESERVATIONREQ)pReqHdr);
1910 break;
1911
1912 case VMMR0_DO_GMM_UPDATE_RESERVATION:
1913 if (u64Arg)
1914 return VERR_INVALID_PARAMETER;
1915 rc = GMMR0UpdateReservationReq(pGVM, idCpu, (PGMMUPDATERESERVATIONREQ)pReqHdr);
1916 break;
1917
1918 case VMMR0_DO_GMM_ALLOCATE_PAGES:
1919 if (u64Arg)
1920 return VERR_INVALID_PARAMETER;
1921 rc = GMMR0AllocatePagesReq(pGVM, idCpu, (PGMMALLOCATEPAGESREQ)pReqHdr);
1922 break;
1923
1924 case VMMR0_DO_GMM_FREE_PAGES:
1925 if (u64Arg)
1926 return VERR_INVALID_PARAMETER;
1927 rc = GMMR0FreePagesReq(pGVM, idCpu, (PGMMFREEPAGESREQ)pReqHdr);
1928 break;
1929
1930 case VMMR0_DO_GMM_FREE_LARGE_PAGE:
1931 if (u64Arg)
1932 return VERR_INVALID_PARAMETER;
1933 rc = GMMR0FreeLargePageReq(pGVM, idCpu, (PGMMFREELARGEPAGEREQ)pReqHdr);
1934 break;
1935
1936 case VMMR0_DO_GMM_QUERY_HYPERVISOR_MEM_STATS:
1937 if (u64Arg)
1938 return VERR_INVALID_PARAMETER;
1939 rc = GMMR0QueryHypervisorMemoryStatsReq((PGMMMEMSTATSREQ)pReqHdr);
1940 break;
1941
1942 case VMMR0_DO_GMM_QUERY_MEM_STATS:
1943 if (idCpu == NIL_VMCPUID)
1944 return VERR_INVALID_CPU_ID;
1945 if (u64Arg)
1946 return VERR_INVALID_PARAMETER;
1947 rc = GMMR0QueryMemoryStatsReq(pGVM, idCpu, (PGMMMEMSTATSREQ)pReqHdr);
1948 break;
1949
1950 case VMMR0_DO_GMM_BALLOONED_PAGES:
1951 if (u64Arg)
1952 return VERR_INVALID_PARAMETER;
1953 rc = GMMR0BalloonedPagesReq(pGVM, idCpu, (PGMMBALLOONEDPAGESREQ)pReqHdr);
1954 break;
1955
1956 case VMMR0_DO_GMM_MAP_UNMAP_CHUNK:
1957 if (u64Arg)
1958 return VERR_INVALID_PARAMETER;
1959 rc = GMMR0MapUnmapChunkReq(pGVM, (PGMMMAPUNMAPCHUNKREQ)pReqHdr);
1960 break;
1961
1962 case VMMR0_DO_GMM_SEED_CHUNK:
1963 if (pReqHdr)
1964 return VERR_INVALID_PARAMETER;
1965 rc = GMMR0SeedChunk(pGVM, idCpu, (RTR3PTR)u64Arg);
1966 break;
1967
1968 case VMMR0_DO_GMM_REGISTER_SHARED_MODULE:
1969 if (idCpu == NIL_VMCPUID)
1970 return VERR_INVALID_CPU_ID;
1971 if (u64Arg)
1972 return VERR_INVALID_PARAMETER;
1973 rc = GMMR0RegisterSharedModuleReq(pGVM, idCpu, (PGMMREGISTERSHAREDMODULEREQ)pReqHdr);
1974 break;
1975
1976 case VMMR0_DO_GMM_UNREGISTER_SHARED_MODULE:
1977 if (idCpu == NIL_VMCPUID)
1978 return VERR_INVALID_CPU_ID;
1979 if (u64Arg)
1980 return VERR_INVALID_PARAMETER;
1981 rc = GMMR0UnregisterSharedModuleReq(pGVM, idCpu, (PGMMUNREGISTERSHAREDMODULEREQ)pReqHdr);
1982 break;
1983
1984 case VMMR0_DO_GMM_RESET_SHARED_MODULES:
1985 if (idCpu == NIL_VMCPUID)
1986 return VERR_INVALID_CPU_ID;
1987 if ( u64Arg
1988 || pReqHdr)
1989 return VERR_INVALID_PARAMETER;
1990 rc = GMMR0ResetSharedModules(pGVM, idCpu);
1991 break;
1992
1993#ifdef VBOX_WITH_PAGE_SHARING
1994 case VMMR0_DO_GMM_CHECK_SHARED_MODULES:
1995 {
1996 if (idCpu == NIL_VMCPUID)
1997 return VERR_INVALID_CPU_ID;
1998 if ( u64Arg
1999 || pReqHdr)
2000 return VERR_INVALID_PARAMETER;
2001 rc = GMMR0CheckSharedModules(pGVM, idCpu);
2002 break;
2003 }
2004#endif
2005
2006#if defined(VBOX_STRICT) && HC_ARCH_BITS == 64
2007 case VMMR0_DO_GMM_FIND_DUPLICATE_PAGE:
2008 if (u64Arg)
2009 return VERR_INVALID_PARAMETER;
2010 rc = GMMR0FindDuplicatePageReq(pGVM, (PGMMFINDDUPLICATEPAGEREQ)pReqHdr);
2011 break;
2012#endif
2013
2014 case VMMR0_DO_GMM_QUERY_STATISTICS:
2015 if (u64Arg)
2016 return VERR_INVALID_PARAMETER;
2017 rc = GMMR0QueryStatisticsReq(pGVM, (PGMMQUERYSTATISTICSSREQ)pReqHdr);
2018 break;
2019
2020 case VMMR0_DO_GMM_RESET_STATISTICS:
2021 if (u64Arg)
2022 return VERR_INVALID_PARAMETER;
2023 rc = GMMR0ResetStatisticsReq(pGVM, (PGMMRESETSTATISTICSSREQ)pReqHdr);
2024 break;
2025
2026 /*
2027 * A quick GCFGM mock-up.
2028 */
2029 /** @todo GCFGM with proper access control, ring-3 management interface and all that. */
2030 case VMMR0_DO_GCFGM_SET_VALUE:
2031 case VMMR0_DO_GCFGM_QUERY_VALUE:
2032 {
2033 if (pGVM || !pReqHdr || u64Arg || idCpu != NIL_VMCPUID)
2034 return VERR_INVALID_PARAMETER;
2035 PGCFGMVALUEREQ pReq = (PGCFGMVALUEREQ)pReqHdr;
2036 if (pReq->Hdr.cbReq != sizeof(*pReq))
2037 return VERR_INVALID_PARAMETER;
2038 if (enmOperation == VMMR0_DO_GCFGM_SET_VALUE)
2039 {
2040 rc = GVMMR0SetConfig(pReq->pSession, &pReq->szName[0], pReq->u64Value);
2041 //if (rc == VERR_CFGM_VALUE_NOT_FOUND)
2042 // rc = GMMR0SetConfig(pReq->pSession, &pReq->szName[0], pReq->u64Value);
2043 }
2044 else
2045 {
2046 rc = GVMMR0QueryConfig(pReq->pSession, &pReq->szName[0], &pReq->u64Value);
2047 //if (rc == VERR_CFGM_VALUE_NOT_FOUND)
2048 // rc = GMMR0QueryConfig(pReq->pSession, &pReq->szName[0], &pReq->u64Value);
2049 }
2050 break;
2051 }
2052
2053 /*
2054 * PDM Wrappers.
2055 */
2056 case VMMR0_DO_PDM_DRIVER_CALL_REQ_HANDLER:
2057 {
2058 if (!pReqHdr || u64Arg || idCpu != NIL_VMCPUID)
2059 return VERR_INVALID_PARAMETER;
2060 rc = PDMR0DriverCallReqHandler(pGVM, (PPDMDRIVERCALLREQHANDLERREQ)pReqHdr);
2061 break;
2062 }
2063
2064 case VMMR0_DO_PDM_DEVICE_CREATE:
2065 {
2066 if (!pReqHdr || u64Arg || idCpu != 0)
2067 return VERR_INVALID_PARAMETER;
2068 rc = PDMR0DeviceCreateReqHandler(pGVM, (PPDMDEVICECREATEREQ)pReqHdr);
2069 break;
2070 }
2071
2072 case VMMR0_DO_PDM_DEVICE_GEN_CALL:
2073 {
2074 if (!pReqHdr || u64Arg)
2075 return VERR_INVALID_PARAMETER;
2076 rc = PDMR0DeviceGenCallReqHandler(pGVM, (PPDMDEVICEGENCALLREQ)pReqHdr, idCpu);
2077 break;
2078 }
2079
2080 /** @todo Remove the once all devices has been converted to new style! @bugref{9218} */
2081 case VMMR0_DO_PDM_DEVICE_COMPAT_SET_CRITSECT:
2082 {
2083 if (!pReqHdr || u64Arg || idCpu != 0)
2084 return VERR_INVALID_PARAMETER;
2085 rc = PDMR0DeviceCompatSetCritSectReqHandler(pGVM, (PPDMDEVICECOMPATSETCRITSECTREQ)pReqHdr);
2086 break;
2087 }
2088
2089 /*
2090 * Requests to the internal networking service.
2091 */
2092 case VMMR0_DO_INTNET_OPEN:
2093 {
2094 PINTNETOPENREQ pReq = (PINTNETOPENREQ)pReqHdr;
2095 if (u64Arg || !pReq || !vmmR0IsValidSession(pGVM, pReq->pSession, pSession) || idCpu != NIL_VMCPUID)
2096 return VERR_INVALID_PARAMETER;
2097 rc = IntNetR0OpenReq(pSession, pReq);
2098 break;
2099 }
2100
2101 case VMMR0_DO_INTNET_IF_CLOSE:
2102 if (u64Arg || !pReqHdr || !vmmR0IsValidSession(pGVM, ((PINTNETIFCLOSEREQ)pReqHdr)->pSession, pSession) || idCpu != NIL_VMCPUID)
2103 return VERR_INVALID_PARAMETER;
2104 rc = IntNetR0IfCloseReq(pSession, (PINTNETIFCLOSEREQ)pReqHdr);
2105 break;
2106
2107
2108 case VMMR0_DO_INTNET_IF_GET_BUFFER_PTRS:
2109 if (u64Arg || !pReqHdr || !vmmR0IsValidSession(pGVM, ((PINTNETIFGETBUFFERPTRSREQ)pReqHdr)->pSession, pSession) || idCpu != NIL_VMCPUID)
2110 return VERR_INVALID_PARAMETER;
2111 rc = IntNetR0IfGetBufferPtrsReq(pSession, (PINTNETIFGETBUFFERPTRSREQ)pReqHdr);
2112 break;
2113
2114 case VMMR0_DO_INTNET_IF_SET_PROMISCUOUS_MODE:
2115 if (u64Arg || !pReqHdr || !vmmR0IsValidSession(pGVM, ((PINTNETIFSETPROMISCUOUSMODEREQ)pReqHdr)->pSession, pSession) || idCpu != NIL_VMCPUID)
2116 return VERR_INVALID_PARAMETER;
2117 rc = IntNetR0IfSetPromiscuousModeReq(pSession, (PINTNETIFSETPROMISCUOUSMODEREQ)pReqHdr);
2118 break;
2119
2120 case VMMR0_DO_INTNET_IF_SET_MAC_ADDRESS:
2121 if (u64Arg || !pReqHdr || !vmmR0IsValidSession(pGVM, ((PINTNETIFSETMACADDRESSREQ)pReqHdr)->pSession, pSession) || idCpu != NIL_VMCPUID)
2122 return VERR_INVALID_PARAMETER;
2123 rc = IntNetR0IfSetMacAddressReq(pSession, (PINTNETIFSETMACADDRESSREQ)pReqHdr);
2124 break;
2125
2126 case VMMR0_DO_INTNET_IF_SET_ACTIVE:
2127 if (u64Arg || !pReqHdr || !vmmR0IsValidSession(pGVM, ((PINTNETIFSETACTIVEREQ)pReqHdr)->pSession, pSession) || idCpu != NIL_VMCPUID)
2128 return VERR_INVALID_PARAMETER;
2129 rc = IntNetR0IfSetActiveReq(pSession, (PINTNETIFSETACTIVEREQ)pReqHdr);
2130 break;
2131
2132 case VMMR0_DO_INTNET_IF_SEND:
2133 if (u64Arg || !pReqHdr || !vmmR0IsValidSession(pGVM, ((PINTNETIFSENDREQ)pReqHdr)->pSession, pSession) || idCpu != NIL_VMCPUID)
2134 return VERR_INVALID_PARAMETER;
2135 rc = IntNetR0IfSendReq(pSession, (PINTNETIFSENDREQ)pReqHdr);
2136 break;
2137
2138 case VMMR0_DO_INTNET_IF_WAIT:
2139 if (u64Arg || !pReqHdr || !vmmR0IsValidSession(pGVM, ((PINTNETIFWAITREQ)pReqHdr)->pSession, pSession) || idCpu != NIL_VMCPUID)
2140 return VERR_INVALID_PARAMETER;
2141 rc = IntNetR0IfWaitReq(pSession, (PINTNETIFWAITREQ)pReqHdr);
2142 break;
2143
2144 case VMMR0_DO_INTNET_IF_ABORT_WAIT:
2145 if (u64Arg || !pReqHdr || !vmmR0IsValidSession(pGVM, ((PINTNETIFWAITREQ)pReqHdr)->pSession, pSession) || idCpu != NIL_VMCPUID)
2146 return VERR_INVALID_PARAMETER;
2147 rc = IntNetR0IfAbortWaitReq(pSession, (PINTNETIFABORTWAITREQ)pReqHdr);
2148 break;
2149
2150#if 0 //def VBOX_WITH_PCI_PASSTHROUGH
2151 /*
2152 * Requests to host PCI driver service.
2153 */
2154 case VMMR0_DO_PCIRAW_REQ:
2155 if (u64Arg || !pReqHdr || !vmmR0IsValidSession(pGVM, ((PPCIRAWSENDREQ)pReqHdr)->pSession, pSession) || idCpu != NIL_VMCPUID)
2156 return VERR_INVALID_PARAMETER;
2157 rc = PciRawR0ProcessReq(pGVM, pSession, (PPCIRAWSENDREQ)pReqHdr);
2158 break;
2159#endif
2160
2161 /*
2162 * NEM requests.
2163 */
2164#ifdef VBOX_WITH_NEM_R0
2165# if defined(RT_ARCH_AMD64) && defined(RT_OS_WINDOWS)
2166 case VMMR0_DO_NEM_INIT_VM:
2167 if (u64Arg || pReqHdr || idCpu != 0)
2168 return VERR_INVALID_PARAMETER;
2169 rc = NEMR0InitVM(pGVM);
2170 break;
2171
2172 case VMMR0_DO_NEM_INIT_VM_PART_2:
2173 if (u64Arg || pReqHdr || idCpu != 0)
2174 return VERR_INVALID_PARAMETER;
2175 rc = NEMR0InitVMPart2(pGVM);
2176 break;
2177
2178 case VMMR0_DO_NEM_MAP_PAGES:
2179 if (u64Arg || pReqHdr || idCpu == NIL_VMCPUID)
2180 return VERR_INVALID_PARAMETER;
2181 rc = NEMR0MapPages(pGVM, idCpu);
2182 break;
2183
2184 case VMMR0_DO_NEM_UNMAP_PAGES:
2185 if (u64Arg || pReqHdr || idCpu == NIL_VMCPUID)
2186 return VERR_INVALID_PARAMETER;
2187 rc = NEMR0UnmapPages(pGVM, idCpu);
2188 break;
2189
2190 case VMMR0_DO_NEM_EXPORT_STATE:
2191 if (u64Arg || pReqHdr || idCpu == NIL_VMCPUID)
2192 return VERR_INVALID_PARAMETER;
2193 rc = NEMR0ExportState(pGVM, idCpu);
2194 break;
2195
2196 case VMMR0_DO_NEM_IMPORT_STATE:
2197 if (pReqHdr || idCpu == NIL_VMCPUID)
2198 return VERR_INVALID_PARAMETER;
2199 rc = NEMR0ImportState(pGVM, idCpu, u64Arg);
2200 break;
2201
2202 case VMMR0_DO_NEM_QUERY_CPU_TICK:
2203 if (u64Arg || pReqHdr || idCpu == NIL_VMCPUID)
2204 return VERR_INVALID_PARAMETER;
2205 rc = NEMR0QueryCpuTick(pGVM, idCpu);
2206 break;
2207
2208 case VMMR0_DO_NEM_RESUME_CPU_TICK_ON_ALL:
2209 if (pReqHdr || idCpu == NIL_VMCPUID)
2210 return VERR_INVALID_PARAMETER;
2211 rc = NEMR0ResumeCpuTickOnAll(pGVM, idCpu, u64Arg);
2212 break;
2213
2214 case VMMR0_DO_NEM_UPDATE_STATISTICS:
2215 if (u64Arg || pReqHdr)
2216 return VERR_INVALID_PARAMETER;
2217 rc = NEMR0UpdateStatistics(pGVM, idCpu);
2218 break;
2219
2220# if 1 && defined(DEBUG_bird)
2221 case VMMR0_DO_NEM_EXPERIMENT:
2222 if (pReqHdr)
2223 return VERR_INVALID_PARAMETER;
2224 rc = NEMR0DoExperiment(pGVM, idCpu, u64Arg);
2225 break;
2226# endif
2227# endif
2228#endif
2229
2230 /*
2231 * IOM requests.
2232 */
2233 case VMMR0_DO_IOM_GROW_IO_PORTS:
2234 {
2235 if (pReqHdr || idCpu != 0)
2236 return VERR_INVALID_PARAMETER;
2237 rc = IOMR0IoPortGrowRegistrationTables(pGVM, u64Arg);
2238 break;
2239 }
2240
2241 case VMMR0_DO_IOM_GROW_IO_PORT_STATS:
2242 {
2243 if (pReqHdr || idCpu != 0)
2244 return VERR_INVALID_PARAMETER;
2245 rc = IOMR0IoPortGrowStatisticsTable(pGVM, u64Arg);
2246 break;
2247 }
2248
2249 case VMMR0_DO_IOM_GROW_MMIO_REGS:
2250 {
2251 if (pReqHdr || idCpu != 0)
2252 return VERR_INVALID_PARAMETER;
2253 rc = IOMR0MmioGrowRegistrationTables(pGVM, u64Arg);
2254 break;
2255 }
2256
2257 case VMMR0_DO_IOM_GROW_MMIO_STATS:
2258 {
2259 if (pReqHdr || idCpu != 0)
2260 return VERR_INVALID_PARAMETER;
2261 rc = IOMR0MmioGrowStatisticsTable(pGVM, u64Arg);
2262 break;
2263 }
2264
2265 case VMMR0_DO_IOM_SYNC_STATS_INDICES:
2266 {
2267 if (pReqHdr || idCpu != 0)
2268 return VERR_INVALID_PARAMETER;
2269 rc = IOMR0IoPortSyncStatisticsIndices(pGVM);
2270 if (RT_SUCCESS(rc))
2271 rc = IOMR0MmioSyncStatisticsIndices(pGVM);
2272 break;
2273 }
2274
2275 /*
2276 * DBGF requests.
2277 */
2278#ifdef VBOX_WITH_DBGF_TRACING
2279 case VMMR0_DO_DBGF_TRACER_CREATE:
2280 {
2281 if (!pReqHdr || u64Arg || idCpu != 0)
2282 return VERR_INVALID_PARAMETER;
2283 rc = DBGFR0TracerCreateReqHandler(pGVM, (PDBGFTRACERCREATEREQ)pReqHdr);
2284 break;
2285 }
2286
2287 case VMMR0_DO_DBGF_TRACER_CALL_REQ_HANDLER:
2288 {
2289 if (!pReqHdr || u64Arg)
2290 return VERR_INVALID_PARAMETER;
2291# if 0 /** @todo */
2292 rc = DBGFR0TracerGenCallReqHandler(pGVM, (PDBGFTRACERGENCALLREQ)pReqHdr, idCpu);
2293# else
2294 rc = VERR_NOT_IMPLEMENTED;
2295# endif
2296 break;
2297 }
2298#endif
2299
2300 case VMMR0_DO_DBGF_BP_INIT:
2301 {
2302 if (!pReqHdr || u64Arg || idCpu != 0)
2303 return VERR_INVALID_PARAMETER;
2304 rc = DBGFR0BpInitReqHandler(pGVM, (PDBGFBPINITREQ)pReqHdr);
2305 break;
2306 }
2307
2308 case VMMR0_DO_DBGF_BP_CHUNK_ALLOC:
2309 {
2310 if (!pReqHdr || u64Arg || idCpu != 0)
2311 return VERR_INVALID_PARAMETER;
2312 rc = DBGFR0BpChunkAllocReqHandler(pGVM, (PDBGFBPCHUNKALLOCREQ)pReqHdr);
2313 break;
2314 }
2315
2316 case VMMR0_DO_DBGF_BP_L2_TBL_CHUNK_ALLOC:
2317 {
2318 if (!pReqHdr || u64Arg || idCpu != 0)
2319 return VERR_INVALID_PARAMETER;
2320 rc = DBGFR0BpL2TblChunkAllocReqHandler(pGVM, (PDBGFBPL2TBLCHUNKALLOCREQ)pReqHdr);
2321 break;
2322 }
2323
2324 case VMMR0_DO_DBGF_BP_OWNER_INIT:
2325 {
2326 if (!pReqHdr || u64Arg || idCpu != 0)
2327 return VERR_INVALID_PARAMETER;
2328 rc = DBGFR0BpOwnerInitReqHandler(pGVM, (PDBGFBPOWNERINITREQ)pReqHdr);
2329 break;
2330 }
2331
2332 case VMMR0_DO_DBGF_BP_PORTIO_INIT:
2333 {
2334 if (!pReqHdr || u64Arg || idCpu != 0)
2335 return VERR_INVALID_PARAMETER;
2336 rc = DBGFR0BpPortIoInitReqHandler(pGVM, (PDBGFBPINITREQ)pReqHdr);
2337 break;
2338 }
2339
2340
2341 /*
2342 * TM requests.
2343 */
2344 case VMMR0_DO_TM_GROW_TIMER_QUEUE:
2345 {
2346 if (pReqHdr || idCpu == NIL_VMCPUID)
2347 return VERR_INVALID_PARAMETER;
2348 rc = TMR0TimerQueueGrow(pGVM, RT_HI_U32(u64Arg), RT_LO_U32(u64Arg));
2349 break;
2350 }
2351
2352 /*
2353 * For profiling.
2354 */
2355 case VMMR0_DO_NOP:
2356 case VMMR0_DO_SLOW_NOP:
2357 return VINF_SUCCESS;
2358
2359 /*
2360 * For testing Ring-0 APIs invoked in this environment.
2361 */
2362 case VMMR0_DO_TESTS:
2363 /** @todo make new test */
2364 return VINF_SUCCESS;
2365
2366 default:
2367 /*
2368 * We're returning VERR_NOT_SUPPORT here so we've got something else
2369 * than -1 which the interrupt gate glue code might return.
2370 */
2371 Log(("operation %#x is not supported\n", enmOperation));
2372 return VERR_NOT_SUPPORTED;
2373 }
2374 return rc;
2375}
2376
2377#ifndef VMM_R0_SWITCH_STACK /* Not safe unless we disable preemption first. */
2378/**
2379 * This is just a longjmp wrapper function for VMMR0EntryEx calls.
2380 *
2381 * @returns VBox status code.
2382 * @param pvArgs The argument package
2383 */
2384static DECLCALLBACK(int) vmmR0EntryExWrapper(void *pvArgs)
2385{
2386 PGVMCPU pGVCpu = (PGVMCPU)pvArgs;
2387 return vmmR0EntryExWorker(pGVCpu->vmmr0.s.pGVM,
2388 pGVCpu->vmmr0.s.idCpu,
2389 pGVCpu->vmmr0.s.enmOperation,
2390 pGVCpu->vmmr0.s.pReq,
2391 pGVCpu->vmmr0.s.u64Arg,
2392 pGVCpu->vmmr0.s.pSession);
2393}
2394#endif
2395
2396
2397/**
2398 * The Ring 0 entry point, called by the support library (SUP).
2399 *
2400 * @returns VBox status code.
2401 * @param pGVM The global (ring-0) VM structure.
2402 * @param pVM The cross context VM structure.
2403 * @param idCpu Virtual CPU ID argument. Must be NIL_VMCPUID if pVM
2404 * is NIL_RTR0PTR, and may be NIL_VMCPUID if it isn't
2405 * @param enmOperation Which operation to execute.
2406 * @param pReq Pointer to the SUPVMMR0REQHDR packet. Optional.
2407 * @param u64Arg Some simple constant argument.
2408 * @param pSession The session of the caller.
2409 * @remarks Assume called with interrupts _enabled_.
2410 */
2411VMMR0DECL(int) VMMR0EntryEx(PGVM pGVM, PVMCC pVM, VMCPUID idCpu, VMMR0OPERATION enmOperation,
2412 PSUPVMMR0REQHDR pReq, uint64_t u64Arg, PSUPDRVSESSION pSession)
2413{
2414#ifndef VMM_R0_SWITCH_STACK /* Not safe unless we disable preemption first. */
2415 /*
2416 * Requests that should only happen on the EMT thread will be
2417 * wrapped in a setjmp so we can assert without causing trouble.
2418 */
2419 if ( pVM != NULL
2420 && pGVM != NULL
2421 && pVM == pGVM /** @todo drop pVM or pGVM */
2422 && idCpu < pGVM->cCpus
2423 && pGVM->pSession == pSession
2424 && pGVM->pSelf == pVM)
2425 {
2426 switch (enmOperation)
2427 {
2428 /* These might/will be called before VMMR3Init. */
2429 case VMMR0_DO_GMM_INITIAL_RESERVATION:
2430 case VMMR0_DO_GMM_UPDATE_RESERVATION:
2431 case VMMR0_DO_GMM_ALLOCATE_PAGES:
2432 case VMMR0_DO_GMM_FREE_PAGES:
2433 case VMMR0_DO_GMM_BALLOONED_PAGES:
2434 /* On the mac we might not have a valid jmp buf, so check these as well. */
2435 case VMMR0_DO_VMMR0_INIT:
2436 case VMMR0_DO_VMMR0_TERM:
2437
2438 case VMMR0_DO_PDM_DEVICE_CREATE:
2439 case VMMR0_DO_PDM_DEVICE_GEN_CALL:
2440 case VMMR0_DO_IOM_GROW_IO_PORTS:
2441 case VMMR0_DO_IOM_GROW_IO_PORT_STATS:
2442 case VMMR0_DO_DBGF_BP_INIT:
2443 case VMMR0_DO_DBGF_BP_CHUNK_ALLOC:
2444 case VMMR0_DO_DBGF_BP_L2_TBL_CHUNK_ALLOC:
2445 {
2446 PGVMCPU pGVCpu = &pGVM->aCpus[idCpu];
2447 RTNATIVETHREAD hNativeThread = RTThreadNativeSelf();
2448 if (RT_LIKELY( pGVCpu->hEMT == hNativeThread
2449 && pGVCpu->hNativeThreadR0 == hNativeThread))
2450 {
2451 if (!pGVCpu->vmm.s.CallRing3JmpBufR0.pvSavedStack)
2452 break;
2453
2454 pGVCpu->vmmr0.s.pGVM = pGVM;
2455 pGVCpu->vmmr0.s.idCpu = idCpu;
2456 pGVCpu->vmmr0.s.enmOperation = enmOperation;
2457 pGVCpu->vmmr0.s.pReq = pReq;
2458 pGVCpu->vmmr0.s.u64Arg = u64Arg;
2459 pGVCpu->vmmr0.s.pSession = pSession;
2460 return vmmR0CallRing3SetJmpEx(&pGVCpu->vmm.s.CallRing3JmpBufR0, vmmR0EntryExWrapper, pGVCpu,
2461 ((uintptr_t)u64Arg << 16) | (uintptr_t)enmOperation);
2462 }
2463 return VERR_VM_THREAD_NOT_EMT;
2464 }
2465
2466 default:
2467 case VMMR0_DO_PGM_POOL_GROW:
2468 break;
2469 }
2470 }
2471#else
2472 RT_NOREF(pVM);
2473#endif
2474 return vmmR0EntryExWorker(pGVM, idCpu, enmOperation, pReq, u64Arg, pSession);
2475}
2476
2477
2478/*********************************************************************************************************************************
2479* EMT Blocking *
2480*********************************************************************************************************************************/
2481
2482/**
2483 * Checks whether we've armed the ring-0 long jump machinery.
2484 *
2485 * @returns @c true / @c false
2486 * @param pVCpu The cross context virtual CPU structure.
2487 * @thread EMT
2488 * @sa VMMIsLongJumpArmed
2489 */
2490VMMR0_INT_DECL(bool) VMMR0IsLongJumpArmed(PVMCPUCC pVCpu)
2491{
2492#ifdef RT_ARCH_X86
2493 return pVCpu->vmm.s.CallRing3JmpBufR0.eip
2494 && !pVCpu->vmm.s.CallRing3JmpBufR0.fInRing3Call;
2495#else
2496 return pVCpu->vmm.s.CallRing3JmpBufR0.rip
2497 && !pVCpu->vmm.s.CallRing3JmpBufR0.fInRing3Call;
2498#endif
2499}
2500
2501
2502/**
2503 * Checks whether we've done a ring-3 long jump.
2504 *
2505 * @returns @c true / @c false
2506 * @param pVCpu The cross context virtual CPU structure.
2507 * @thread EMT
2508 */
2509VMMR0_INT_DECL(bool) VMMR0IsInRing3LongJump(PVMCPUCC pVCpu)
2510{
2511 return pVCpu->vmm.s.CallRing3JmpBufR0.fInRing3Call;
2512}
2513
2514
2515/**
2516 * Locking helper that deals with HM context and checks if the thread can block.
2517 *
2518 * @returns VINF_SUCCESS if we can block. Returns @a rcBusy or
2519 * VERR_VMM_CANNOT_BLOCK if not able to block.
2520 * @param pVCpu The cross context virtual CPU structure of the calling
2521 * thread.
2522 * @param rcBusy What to return in case of a blocking problem. Will IPE
2523 * if VINF_SUCCESS and we cannot block.
2524 * @param pszCaller The caller (for logging problems).
2525 * @param pvLock The lock address (for logging problems).
2526 * @param pCtx Where to return context info for the resume call.
2527 * @thread EMT(pVCpu)
2528 */
2529VMMR0_INT_DECL(int) VMMR0EmtPrepareToBlock(PVMCPUCC pVCpu, int rcBusy, const char *pszCaller, void *pvLock,
2530 PVMMR0EMTBLOCKCTX pCtx)
2531{
2532 const char *pszMsg;
2533
2534 /*
2535 * Check that we are allowed to block.
2536 */
2537 if (RT_LIKELY(VMMRZCallRing3IsEnabled(pVCpu)))
2538 {
2539 /*
2540 * Are we in HM context and w/o a context hook? If so work the context hook.
2541 */
2542 if (pVCpu->idHostCpu != NIL_RTCPUID)
2543 {
2544 Assert(pVCpu->iHostCpuSet != UINT32_MAX);
2545
2546 if (pVCpu->vmmr0.s.hCtxHook == NIL_RTTHREADCTXHOOK)
2547 {
2548 vmmR0ThreadCtxCallback(RTTHREADCTXEVENT_OUT, pVCpu);
2549 if (pVCpu->vmmr0.s.pPreemptState)
2550 RTThreadPreemptRestore(pVCpu->vmmr0.s.pPreemptState);
2551
2552 pCtx->uMagic = VMMR0EMTBLOCKCTX_MAGIC;
2553 pCtx->fWasInHmContext = true;
2554 return VINF_SUCCESS;
2555 }
2556 }
2557
2558 if (RT_LIKELY(!pVCpu->vmmr0.s.pPreemptState))
2559 {
2560 /*
2561 * Not in HM context or we've got hooks, so just check that preemption
2562 * is enabled.
2563 */
2564 if (RT_LIKELY(RTThreadPreemptIsEnabled(NIL_RTTHREAD)))
2565 {
2566 pCtx->uMagic = VMMR0EMTBLOCKCTX_MAGIC;
2567 pCtx->fWasInHmContext = false;
2568 return VINF_SUCCESS;
2569 }
2570 pszMsg = "Preemption is disabled!";
2571 }
2572 else
2573 pszMsg = "Preemption state w/o HM state!";
2574 }
2575 else
2576 pszMsg = "Ring-3 calls are disabled!";
2577
2578 static uint32_t volatile s_cWarnings = 0;
2579 if (++s_cWarnings < 50)
2580 SUPR0Printf("VMMR0EmtPrepareToBlock: %s pvLock=%p pszCaller=%s rcBusy=%p\n", pszMsg, pvLock, pszCaller, rcBusy);
2581 pCtx->uMagic = VMMR0EMTBLOCKCTX_MAGIC_DEAD;
2582 pCtx->fWasInHmContext = false;
2583 return rcBusy != VINF_SUCCESS ? rcBusy : VERR_VMM_CANNOT_BLOCK;
2584}
2585
2586
2587/**
2588 * Counterpart to VMMR0EmtPrepareToBlock.
2589 *
2590 * @param pVCpu The cross context virtual CPU structure of the calling
2591 * thread.
2592 * @param pCtx The context structure used with VMMR0EmtPrepareToBlock.
2593 * @thread EMT(pVCpu)
2594 */
2595VMMR0_INT_DECL(void) VMMR0EmtResumeAfterBlocking(PVMCPUCC pVCpu, PVMMR0EMTBLOCKCTX pCtx)
2596{
2597 AssertReturnVoid(pCtx->uMagic == VMMR0EMTBLOCKCTX_MAGIC);
2598 if (pCtx->fWasInHmContext)
2599 {
2600 if (pVCpu->vmmr0.s.pPreemptState)
2601 RTThreadPreemptDisable(pVCpu->vmmr0.s.pPreemptState);
2602
2603 pCtx->fWasInHmContext = false;
2604 vmmR0ThreadCtxCallback(RTTHREADCTXEVENT_IN, pVCpu);
2605 }
2606 pCtx->uMagic = VMMR0EMTBLOCKCTX_MAGIC_DEAD;
2607}
2608
2609
2610/**
2611 * Helper for waiting on an RTSEMEVENT, caller did VMMR0EmtPrepareToBlock.
2612 *
2613 * @returns
2614 * @retval VERR_THREAD_IS_TERMINATING
2615 * @retval VERR_TIMEOUT if we ended up waiting too long, either according to
2616 * @a cMsTimeout or to maximum wait values.
2617 *
2618 * @param pGVCpu The ring-0 virtual CPU structure.
2619 * @param fFlags VMMR0EMTWAIT_F_XXX.
2620 * @param hEvent The event to wait on.
2621 * @param cMsTimeout The timeout or RT_INDEFINITE_WAIT.
2622 */
2623VMMR0_INT_DECL(int) VMMR0EmtWaitEventInner(PGVMCPU pGVCpu, uint32_t fFlags, RTSEMEVENT hEvent, RTMSINTERVAL cMsTimeout)
2624{
2625 AssertReturn(pGVCpu->hEMT == RTThreadNativeSelf(), VERR_VM_THREAD_NOT_EMT);
2626
2627 /*
2628 * Note! Similar code is found in the PDM critical sections too.
2629 */
2630 uint64_t const nsStart = RTTimeNanoTS();
2631 uint64_t cNsMaxTotal = cMsTimeout == RT_INDEFINITE_WAIT
2632 ? RT_NS_5MIN : RT_MIN(RT_NS_5MIN, RT_NS_1MS_64 * cMsTimeout);
2633 uint32_t cMsMaxOne = RT_MS_5SEC;
2634 bool fNonInterruptible = false;
2635 for (;;)
2636 {
2637 /* Wait. */
2638 int rcWait = !fNonInterruptible
2639 ? RTSemEventWaitNoResume(hEvent, cMsMaxOne)
2640 : RTSemEventWait(hEvent, cMsMaxOne);
2641 if (RT_SUCCESS(rcWait))
2642 return rcWait;
2643
2644 if (rcWait == VERR_TIMEOUT || rcWait == VERR_INTERRUPTED)
2645 {
2646 uint64_t const cNsElapsed = RTTimeNanoTS() - nsStart;
2647
2648 /*
2649 * Check the thread termination status.
2650 */
2651 int const rcTerm = RTThreadQueryTerminationStatus(NIL_RTTHREAD);
2652 AssertMsg(rcTerm == VINF_SUCCESS || rcTerm == VERR_NOT_SUPPORTED || rcTerm == VINF_THREAD_IS_TERMINATING,
2653 ("rcTerm=%Rrc\n", rcTerm));
2654 if ( rcTerm == VERR_NOT_SUPPORTED
2655 && !fNonInterruptible
2656 && cNsMaxTotal > RT_NS_1MIN)
2657 cNsMaxTotal = RT_NS_1MIN;
2658
2659 /* We return immediately if it looks like the thread is terminating. */
2660 if (rcTerm == VINF_THREAD_IS_TERMINATING)
2661 return VERR_THREAD_IS_TERMINATING;
2662
2663 /* We may suppress VERR_INTERRUPTED if VMMR0EMTWAIT_F_TRY_SUPPRESS_INTERRUPTED was
2664 specified, otherwise we'll just return it. */
2665 if (rcWait == VERR_INTERRUPTED)
2666 {
2667 if (!(fFlags & VMMR0EMTWAIT_F_TRY_SUPPRESS_INTERRUPTED))
2668 return VERR_INTERRUPTED;
2669 if (!fNonInterruptible)
2670 {
2671 /* First time: Adjust down the wait parameters and make sure we get at least
2672 one non-interruptible wait before timing out. */
2673 fNonInterruptible = true;
2674 cMsMaxOne = 32;
2675 uint64_t const cNsLeft = cNsMaxTotal - cNsElapsed;
2676 if (cNsLeft > RT_NS_10SEC)
2677 cNsMaxTotal = cNsElapsed + RT_NS_10SEC;
2678 continue;
2679 }
2680 }
2681
2682 /* Check for timeout. */
2683 if (cNsElapsed > cNsMaxTotal)
2684 return VERR_TIMEOUT;
2685 }
2686 else
2687 return rcWait;
2688 }
2689 /* not reached */
2690}
2691
2692
2693/**
2694 * Helper for signalling an SUPSEMEVENT.
2695 *
2696 * This may temporarily leave the HM context if the host requires that for
2697 * signalling SUPSEMEVENT objects.
2698 *
2699 * @returns VBox status code (see VMMR0EmtPrepareToBlock)
2700 * @param pGVM The ring-0 VM structure.
2701 * @param pGVCpu The ring-0 virtual CPU structure.
2702 * @param hEvent The event to signal.
2703 */
2704VMMR0_INT_DECL(int) VMMR0EmtSignalSupEvent(PGVM pGVM, PGVMCPU pGVCpu, SUPSEMEVENT hEvent)
2705{
2706 AssertReturn(pGVCpu->hEMT == RTThreadNativeSelf(), VERR_VM_THREAD_NOT_EMT);
2707 if (RTSemEventIsSignalSafe())
2708 return SUPSemEventSignal(pGVM->pSession, hEvent);
2709
2710 VMMR0EMTBLOCKCTX Ctx;
2711 int rc = VMMR0EmtPrepareToBlock(pGVCpu, VINF_SUCCESS, __FUNCTION__, (void *)(uintptr_t)hEvent, &Ctx);
2712 if (RT_SUCCESS(rc))
2713 {
2714 rc = SUPSemEventSignal(pGVM->pSession, hEvent);
2715 VMMR0EmtResumeAfterBlocking(pGVCpu, &Ctx);
2716 }
2717 return rc;
2718}
2719
2720
2721/**
2722 * Helper for signalling an SUPSEMEVENT, variant supporting non-EMTs.
2723 *
2724 * This may temporarily leave the HM context if the host requires that for
2725 * signalling SUPSEMEVENT objects.
2726 *
2727 * @returns VBox status code (see VMMR0EmtPrepareToBlock)
2728 * @param pGVM The ring-0 VM structure.
2729 * @param hEvent The event to signal.
2730 */
2731VMMR0_INT_DECL(int) VMMR0EmtSignalSupEventByGVM(PGVM pGVM, SUPSEMEVENT hEvent)
2732{
2733 if (!RTSemEventIsSignalSafe())
2734 {
2735 PGVMCPU pGVCpu = GVMMR0GetGVCpuByGVMandEMT(pGVM, NIL_RTNATIVETHREAD);
2736 if (pGVCpu)
2737 {
2738 VMMR0EMTBLOCKCTX Ctx;
2739 int rc = VMMR0EmtPrepareToBlock(pGVCpu, VINF_SUCCESS, __FUNCTION__, (void *)(uintptr_t)hEvent, &Ctx);
2740 if (RT_SUCCESS(rc))
2741 {
2742 rc = SUPSemEventSignal(pGVM->pSession, hEvent);
2743 VMMR0EmtResumeAfterBlocking(pGVCpu, &Ctx);
2744 }
2745 return rc;
2746 }
2747 }
2748 return SUPSemEventSignal(pGVM->pSession, hEvent);
2749}
2750
2751
2752/*********************************************************************************************************************************
2753* Logging. *
2754*********************************************************************************************************************************/
2755
2756/**
2757 * VMMR0_DO_VMMR0_UPDATE_LOGGERS: Updates the EMT loggers for the VM.
2758 *
2759 * @returns VBox status code.
2760 * @param pGVM The global (ring-0) VM structure.
2761 * @param idCpu The ID of the calling EMT.
2762 * @param pReq The request data.
2763 * @param idxLogger Which logger set to update.
2764 * @thread EMT(idCpu)
2765 */
2766static int vmmR0UpdateLoggers(PGVM pGVM, VMCPUID idCpu, PVMMR0UPDATELOGGERSREQ pReq, size_t idxLogger)
2767{
2768 /*
2769 * Check sanity. First we require EMT to be calling us.
2770 */
2771 AssertReturn(idCpu < pGVM->cCpus, VERR_INVALID_CPU_ID);
2772 AssertReturn(pGVM->aCpus[idCpu].hEMT == RTThreadNativeSelf(), VERR_INVALID_CPU_ID);
2773
2774 AssertReturn(pReq->Hdr.cbReq >= RT_UOFFSETOF_DYN(VMMR0UPDATELOGGERSREQ, afGroups[0]), VERR_INVALID_PARAMETER);
2775 AssertReturn(pReq->cGroups < _8K, VERR_INVALID_PARAMETER);
2776 AssertReturn(pReq->Hdr.cbReq == RT_UOFFSETOF_DYN(VMMR0UPDATELOGGERSREQ, afGroups[pReq->cGroups]), VERR_INVALID_PARAMETER);
2777
2778 AssertReturn(idxLogger < VMMLOGGER_IDX_MAX, VERR_OUT_OF_RANGE);
2779
2780 /*
2781 * Adjust flags.
2782 */
2783 /* Always buffered: */
2784 pReq->fFlags |= RTLOGFLAGS_BUFFERED;
2785 /* These doesn't make sense at present: */
2786 pReq->fFlags &= ~(RTLOGFLAGS_FLUSH | RTLOGFLAGS_WRITE_THROUGH);
2787 /* We've traditionally skipped the group restrictions. */
2788 pReq->fFlags &= ~RTLOGFLAGS_RESTRICT_GROUPS;
2789
2790 /*
2791 * Do the updating.
2792 */
2793 int rc = VINF_SUCCESS;
2794 for (idCpu = 0; idCpu < pGVM->cCpus; idCpu++)
2795 {
2796 PGVMCPU pGVCpu = &pGVM->aCpus[idCpu];
2797 PRTLOGGER pLogger = pGVCpu->vmmr0.s.u.aLoggers[idxLogger].pLogger;
2798 if (pLogger)
2799 {
2800 RTLogSetR0ProgramStart(pLogger, pGVM->vmm.s.nsProgramStart);
2801 rc = RTLogBulkUpdate(pLogger, pReq->fFlags, pReq->uGroupCrc32, pReq->cGroups, pReq->afGroups);
2802 }
2803 }
2804
2805 return rc;
2806}
2807
2808
2809/**
2810 * VMMR0_DO_VMMR0_LOG_FLUSHER: Get the next log flushing job.
2811 *
2812 * The job info is copied into VMM::LogFlusherItem.
2813 *
2814 * @returns VBox status code.
2815 * @retval VERR_OBJECT_DESTROYED if we're shutting down.
2816 * @retval VERR_NOT_OWNER if the calling thread is not the flusher thread.
2817 * @param pGVM The global (ring-0) VM structure.
2818 * @thread The log flusher thread (first caller automatically becomes the log
2819 * flusher).
2820 */
2821static int vmmR0LogFlusher(PGVM pGVM)
2822{
2823 /*
2824 * Check that this really is the flusher thread.
2825 */
2826 RTNATIVETHREAD const hNativeSelf = RTThreadNativeSelf();
2827 AssertReturn(hNativeSelf != NIL_RTNATIVETHREAD, VERR_INTERNAL_ERROR_3);
2828 if (RT_LIKELY(pGVM->vmmr0.s.LogFlusher.hThread == hNativeSelf))
2829 { /* likely */ }
2830 else
2831 {
2832 /* The first caller becomes the flusher thread. */
2833 bool fOk;
2834 ASMAtomicCmpXchgHandle(&pGVM->vmmr0.s.LogFlusher.hThread, hNativeSelf, NIL_RTNATIVETHREAD, fOk);
2835 if (!fOk)
2836 return VERR_NOT_OWNER;
2837 pGVM->vmmr0.s.LogFlusher.fThreadRunning = true;
2838 }
2839
2840 /*
2841 * Acknowledge flush, waking up waiting EMT.
2842 */
2843 RTSpinlockAcquire(pGVM->vmmr0.s.LogFlusher.hSpinlock);
2844
2845 uint32_t idxTail = pGVM->vmmr0.s.LogFlusher.idxRingTail % RT_ELEMENTS(pGVM->vmmr0.s.LogFlusher.aRing);
2846 uint32_t idxHead = pGVM->vmmr0.s.LogFlusher.idxRingHead % RT_ELEMENTS(pGVM->vmmr0.s.LogFlusher.aRing);
2847 if ( idxTail != idxHead
2848 && pGVM->vmmr0.s.LogFlusher.aRing[idxHead].s.fProcessing)
2849 {
2850 /* Pop the head off the ring buffer. */
2851 uint32_t const idCpu = pGVM->vmmr0.s.LogFlusher.aRing[idxHead].s.idCpu;
2852 uint32_t const idxLogger = pGVM->vmmr0.s.LogFlusher.aRing[idxHead].s.idxLogger;
2853 uint32_t const idxBuffer = pGVM->vmmr0.s.LogFlusher.aRing[idxHead].s.idxBuffer;
2854
2855 pGVM->vmmr0.s.LogFlusher.aRing[idxHead].u32 = UINT32_MAX >> 1; /* invalidate the entry */
2856 pGVM->vmmr0.s.LogFlusher.idxRingHead = (idxHead + 1) % RT_ELEMENTS(pGVM->vmmr0.s.LogFlusher.aRing);
2857
2858 /* Validate content. */
2859 if ( idCpu < pGVM->cCpus
2860 && idxLogger < VMMLOGGER_IDX_MAX
2861 && idxBuffer < VMMLOGGER_BUFFER_COUNT)
2862 {
2863 PGVMCPU pGVCpu = &pGVM->aCpus[idCpu];
2864 PVMMR0PERVCPULOGGER pR0Log = &pGVCpu->vmmr0.s.u.aLoggers[idxLogger];
2865 PVMMR3CPULOGGER pShared = &pGVCpu->vmm.s.u.aLoggers[idxLogger];
2866
2867 /*
2868 * Accounting.
2869 */
2870 uint32_t cFlushing = pR0Log->cFlushing - 1;
2871 if (RT_LIKELY(cFlushing < VMMLOGGER_BUFFER_COUNT))
2872 { /*likely*/ }
2873 else
2874 cFlushing = 0;
2875 pR0Log->cFlushing = cFlushing;
2876 ASMAtomicWriteU32(&pShared->cFlushing, cFlushing);
2877
2878 /*
2879 * Wake up the EMT if it's waiting.
2880 */
2881 if (!pR0Log->fEmtWaiting)
2882 RTSpinlockRelease(pGVM->vmmr0.s.LogFlusher.hSpinlock);
2883 else
2884 {
2885 pR0Log->fEmtWaiting = false;
2886 RTSpinlockRelease(pGVM->vmmr0.s.LogFlusher.hSpinlock);
2887
2888 int rc = RTSemEventSignal(pR0Log->hEventFlushWait);
2889 if (RT_FAILURE(rc))
2890 LogRelMax(64, ("vmmR0LogFlusher: RTSemEventSignal failed ACKing entry #%u (%u/%u/%u): %Rrc!\n",
2891 idxHead, idCpu, idxLogger, idxBuffer, rc));
2892 }
2893 }
2894 else
2895 {
2896 RTSpinlockRelease(pGVM->vmmr0.s.LogFlusher.hSpinlock);
2897 LogRelMax(64, ("vmmR0LogFlusher: Bad ACK entry #%u: %u/%u/%u!\n", idxHead, idCpu, idxLogger, idxBuffer));
2898 }
2899
2900 RTSpinlockAcquire(pGVM->vmmr0.s.LogFlusher.hSpinlock);
2901 }
2902
2903 /*
2904 * The wait loop.
2905 */
2906 int rc;
2907 for (;;)
2908 {
2909 /*
2910 * Work pending?
2911 */
2912 idxTail = pGVM->vmmr0.s.LogFlusher.idxRingTail % RT_ELEMENTS(pGVM->vmmr0.s.LogFlusher.aRing);
2913 idxHead = pGVM->vmmr0.s.LogFlusher.idxRingHead % RT_ELEMENTS(pGVM->vmmr0.s.LogFlusher.aRing);
2914 if (idxTail != idxHead)
2915 {
2916 pGVM->vmmr0.s.LogFlusher.aRing[idxHead].s.fProcessing = true;
2917 pGVM->vmm.s.LogFlusherItem.u32 = pGVM->vmmr0.s.LogFlusher.aRing[idxHead].u32;
2918
2919 RTSpinlockRelease(pGVM->vmmr0.s.LogFlusher.hSpinlock);
2920 return VINF_SUCCESS;
2921 }
2922
2923 /*
2924 * Nothing to do, so, check for termination and go to sleep.
2925 */
2926 if (!pGVM->vmmr0.s.LogFlusher.fThreadShutdown)
2927 { /* likely */ }
2928 else
2929 {
2930 rc = VERR_OBJECT_DESTROYED;
2931 break;
2932 }
2933
2934 pGVM->vmmr0.s.LogFlusher.fThreadWaiting = true;
2935 RTSpinlockRelease(pGVM->vmmr0.s.LogFlusher.hSpinlock);
2936
2937 rc = RTSemEventWaitNoResume(pGVM->vmmr0.s.LogFlusher.hEvent, RT_MS_5MIN);
2938
2939 RTSpinlockAcquire(pGVM->vmmr0.s.LogFlusher.hSpinlock);
2940 pGVM->vmmr0.s.LogFlusher.fThreadWaiting = false;
2941
2942 if (RT_SUCCESS(rc) || rc == VERR_TIMEOUT)
2943 { /* likely */ }
2944 else if (rc == VERR_INTERRUPTED)
2945 {
2946 RTSpinlockRelease(pGVM->vmmr0.s.LogFlusher.hSpinlock);
2947 return rc;
2948 }
2949 else if (rc == VERR_SEM_DESTROYED || rc == VERR_INVALID_HANDLE)
2950 break;
2951 else
2952 {
2953 LogRel(("vmmR0LogFlusher: RTSemEventWaitNoResume returned unexpected status %Rrc\n", rc));
2954 break;
2955 }
2956 }
2957
2958 /*
2959 * Terminating - prevent further calls and indicate to the EMTs that we're no longer around.
2960 */
2961 pGVM->vmmr0.s.LogFlusher.hThread = ~pGVM->vmmr0.s.LogFlusher.hThread; /* (should be reasonably safe) */
2962 pGVM->vmmr0.s.LogFlusher.fThreadRunning = false;
2963
2964 RTSpinlockRelease(pGVM->vmmr0.s.LogFlusher.hSpinlock);
2965 return rc;
2966}
2967
2968
2969/**
2970 * VMMR0_DO_VMMR0_LOG_WAIT_FLUSHED: Waits for the flusher thread to finish all
2971 * buffers for logger @a idxLogger.
2972 *
2973 * @returns VBox status code.
2974 * @param pGVM The global (ring-0) VM structure.
2975 * @param idCpu The ID of the calling EMT.
2976 * @param idxLogger Which logger to wait on.
2977 * @thread EMT(idCpu)
2978 */
2979static int vmmR0LogWaitFlushed(PGVM pGVM, VMCPUID idCpu, size_t idxLogger)
2980{
2981 /*
2982 * Check sanity. First we require EMT to be calling us.
2983 */
2984 AssertReturn(idCpu < pGVM->cCpus, VERR_INVALID_CPU_ID);
2985 PGVMCPU pGVCpu = &pGVM->aCpus[idCpu];
2986 AssertReturn(pGVCpu->hEMT == RTThreadNativeSelf(), VERR_INVALID_CPU_ID);
2987 AssertReturn(idxLogger < VMMLOGGER_IDX_MAX, VERR_OUT_OF_RANGE);
2988 PVMMR0PERVCPULOGGER const pR0Log = &pGVCpu->vmmr0.s.u.aLoggers[idxLogger];
2989
2990 /*
2991 * Do the waiting.
2992 */
2993 int rc = VINF_SUCCESS;
2994 RTSpinlockAcquire(pGVM->vmmr0.s.LogFlusher.hSpinlock);
2995 uint32_t cFlushing = pR0Log->cFlushing;
2996 while (cFlushing > 0)
2997 {
2998 pR0Log->fEmtWaiting = true;
2999 RTSpinlockRelease(pGVM->vmmr0.s.LogFlusher.hSpinlock);
3000
3001 rc = RTSemEventWaitNoResume(pR0Log->hEventFlushWait, RT_MS_5MIN);
3002
3003 RTSpinlockAcquire(pGVM->vmmr0.s.LogFlusher.hSpinlock);
3004 pR0Log->fEmtWaiting = false;
3005 if (RT_SUCCESS(rc))
3006 {
3007 /* Read the new count, make sure it decreased before looping. That
3008 way we can guarentee that we will only wait more than 5 min * buffers. */
3009 uint32_t const cPrevFlushing = cFlushing;
3010 cFlushing = pR0Log->cFlushing;
3011 if (cFlushing < cPrevFlushing)
3012 continue;
3013 rc = VERR_INTERNAL_ERROR_3;
3014 }
3015 break;
3016 }
3017 RTSpinlockRelease(pGVM->vmmr0.s.LogFlusher.hSpinlock);
3018 return rc;
3019}
3020
3021
3022/**
3023 * Inner worker for vmmR0LoggerFlushCommon.
3024 */
3025#ifndef VMM_R0_SWITCH_STACK
3026static bool vmmR0LoggerFlushInner(PGVM pGVM, PGVMCPU pGVCpu, uint32_t idxLogger, size_t idxBuffer, uint32_t cbToFlush)
3027#else
3028DECLASM(bool) vmmR0LoggerFlushInner(PGVM pGVM, PGVMCPU pGVCpu, uint32_t idxLogger, size_t idxBuffer, uint32_t cbToFlush);
3029DECLASM(bool) StkBack_vmmR0LoggerFlushInner(PGVM pGVM, PGVMCPU pGVCpu, uint32_t idxLogger, size_t idxBuffer, uint32_t cbToFlush)
3030#endif
3031{
3032 PVMMR0PERVCPULOGGER const pR0Log = &pGVCpu->vmmr0.s.u.aLoggers[idxLogger];
3033 PVMMR3CPULOGGER const pShared = &pGVCpu->vmm.s.u.aLoggers[idxLogger];
3034
3035 /*
3036 * Figure out what we need to do and whether we can.
3037 */
3038 enum { kJustSignal, kPrepAndSignal, kPrepSignalAndWait } enmAction;
3039#if VMMLOGGER_BUFFER_COUNT >= 2
3040 if (pR0Log->cFlushing < VMMLOGGER_BUFFER_COUNT - 1)
3041 {
3042 if (RTSemEventIsSignalSafe())
3043 enmAction = kJustSignal;
3044 else if (VMMRZCallRing3IsEnabled(pGVCpu))
3045 enmAction = kPrepAndSignal;
3046 else
3047 {
3048 /** @todo This is a bit simplistic. We could introduce a FF to signal the
3049 * thread or similar. */
3050 STAM_REL_COUNTER_INC(&pShared->StatCannotBlock);
3051# if defined(RT_OS_LINUX)
3052 SUP_DPRINTF(("vmmR0LoggerFlush: Signalling not safe and EMT blocking disabled! (%u bytes)\n", cbToFlush));
3053# endif
3054 pShared->cbDropped += cbToFlush;
3055 return true;
3056 }
3057 }
3058 else
3059#endif
3060 if (VMMRZCallRing3IsEnabled(pGVCpu))
3061 enmAction = kPrepSignalAndWait;
3062 else
3063 {
3064 STAM_REL_COUNTER_INC(&pShared->StatCannotBlock);
3065# if defined(RT_OS_LINUX)
3066 SUP_DPRINTF(("vmmR0LoggerFlush: EMT blocking disabled! (%u bytes)\n", cbToFlush));
3067# endif
3068 pShared->cbDropped += cbToFlush;
3069 return true;
3070 }
3071
3072 /*
3073 * Prepare for blocking if necessary.
3074 */
3075 VMMR0EMTBLOCKCTX Ctx;
3076 if (enmAction != kJustSignal)
3077 {
3078 int rc = VMMR0EmtPrepareToBlock(pGVCpu, VINF_SUCCESS, "vmmR0LoggerFlushInner", pR0Log->hEventFlushWait, &Ctx);
3079 if (RT_SUCCESS(rc))
3080 { /* likely */ }
3081 else
3082 {
3083 STAM_REL_COUNTER_INC(&pShared->StatCannotBlock);
3084 SUP_DPRINTF(("vmmR0LoggerFlush: VMMR0EmtPrepareToBlock failed! rc=%d\n", rc));
3085 return false;
3086 }
3087 }
3088
3089 /*
3090 * Queue the flush job.
3091 */
3092 bool fFlushedBuffer;
3093 RTSpinlockAcquire(pGVM->vmmr0.s.LogFlusher.hSpinlock);
3094 if (pGVM->vmmr0.s.LogFlusher.fThreadRunning)
3095 {
3096 uint32_t const idxHead = pGVM->vmmr0.s.LogFlusher.idxRingHead % RT_ELEMENTS(pGVM->vmmr0.s.LogFlusher.aRing);
3097 uint32_t const idxTail = pGVM->vmmr0.s.LogFlusher.idxRingTail % RT_ELEMENTS(pGVM->vmmr0.s.LogFlusher.aRing);
3098 uint32_t const idxNewTail = (idxTail + 1) % RT_ELEMENTS(pGVM->vmmr0.s.LogFlusher.aRing);
3099 if (idxNewTail != idxHead)
3100 {
3101 /* Queue it. */
3102 pGVM->vmmr0.s.LogFlusher.aRing[idxTail].s.idCpu = pGVCpu->idCpu;
3103 pGVM->vmmr0.s.LogFlusher.aRing[idxTail].s.idxLogger = idxLogger;
3104 pGVM->vmmr0.s.LogFlusher.aRing[idxTail].s.idxBuffer = (uint32_t)idxBuffer;
3105 pGVM->vmmr0.s.LogFlusher.aRing[idxTail].s.fProcessing = 0;
3106 pGVM->vmmr0.s.LogFlusher.idxRingTail = idxNewTail;
3107
3108 /* Update the number of buffers currently being flushed. */
3109 uint32_t cFlushing = pR0Log->cFlushing;
3110 cFlushing = RT_MIN(cFlushing + 1, VMMLOGGER_BUFFER_COUNT);
3111 pShared->cFlushing = pR0Log->cFlushing = cFlushing;
3112
3113 /* We must wait if all buffers are currently being flushed. */
3114 bool const fEmtWaiting = cFlushing >= VMMLOGGER_BUFFER_COUNT && enmAction != kJustSignal /* paranoia */;
3115 pR0Log->fEmtWaiting = fEmtWaiting;
3116
3117 /* Stats. */
3118 STAM_REL_COUNTER_INC(&pShared->StatFlushes);
3119 STAM_REL_COUNTER_INC(&pGVM->vmm.s.StatLogFlusherFlushes);
3120
3121 /* Signal the worker thread. */
3122 if (pGVM->vmmr0.s.LogFlusher.fThreadWaiting)
3123 {
3124 RTSpinlockRelease(pGVM->vmmr0.s.LogFlusher.hSpinlock);
3125 RTSemEventSignal(pGVM->vmmr0.s.LogFlusher.hEvent);
3126 }
3127 else
3128 {
3129 STAM_REL_COUNTER_INC(&pGVM->vmm.s.StatLogFlusherNoWakeUp);
3130 RTSpinlockRelease(pGVM->vmmr0.s.LogFlusher.hSpinlock);
3131 }
3132
3133 /*
3134 * Wait for a buffer to finish flushing.
3135 *
3136 * Note! Lazy bird is ignoring the status code here. The result is
3137 * that we might end up with an extra even signalling and the
3138 * next time we need to wait we won't and end up with some log
3139 * corruption. However, it's too much hazzle right now for
3140 * a scenario which would most likely end the process rather
3141 * than causing log corruption.
3142 */
3143 if (fEmtWaiting)
3144 {
3145 STAM_REL_PROFILE_START(&pShared->StatWait, a);
3146 VMMR0EmtWaitEventInner(pGVCpu, VMMR0EMTWAIT_F_TRY_SUPPRESS_INTERRUPTED,
3147 pR0Log->hEventFlushWait, RT_INDEFINITE_WAIT);
3148 STAM_REL_PROFILE_STOP(&pShared->StatWait, a);
3149 }
3150
3151 /*
3152 * We always switch buffer if we have more than one.
3153 */
3154#if VMMLOGGER_BUFFER_COUNT == 1
3155 fFlushedBuffer = true;
3156#else
3157 AssertCompile(VMMLOGGER_BUFFER_COUNT >= 1);
3158 pShared->idxBuf = (idxBuffer + 1) % VMMLOGGER_BUFFER_COUNT;
3159 fFlushedBuffer = false;
3160#endif
3161 }
3162 else
3163 {
3164 RTSpinlockRelease(pGVM->vmmr0.s.LogFlusher.hSpinlock);
3165 SUP_DPRINTF(("vmmR0LoggerFlush: ring buffer is full!\n"));
3166 fFlushedBuffer = true;
3167 }
3168 }
3169 else
3170 {
3171 RTSpinlockRelease(pGVM->vmmr0.s.LogFlusher.hSpinlock);
3172 SUP_DPRINTF(("vmmR0LoggerFlush: flusher not active - dropping %u bytes\n", cbToFlush));
3173 fFlushedBuffer = true;
3174 }
3175
3176 /*
3177 * Restore the HM context.
3178 */
3179 if (enmAction != kJustSignal)
3180 VMMR0EmtResumeAfterBlocking(pGVCpu, &Ctx);
3181
3182 return fFlushedBuffer;
3183}
3184
3185
3186/**
3187 * Common worker for vmmR0LogFlush and vmmR0LogRelFlush.
3188 */
3189static bool vmmR0LoggerFlushCommon(PRTLOGGER pLogger, PRTLOGBUFFERDESC pBufDesc, uint32_t idxLogger)
3190{
3191 /*
3192 * Convert the pLogger into a GVMCPU handle and 'call' back to Ring-3.
3193 * (This is a bit paranoid code.)
3194 */
3195 if (RT_VALID_PTR(pLogger))
3196 {
3197 if ( pLogger->u32Magic == RTLOGGER_MAGIC
3198 && (pLogger->u32UserValue1 & VMMR0_LOGGER_FLAGS_MAGIC_MASK) == VMMR0_LOGGER_FLAGS_MAGIC_VALUE
3199 && pLogger->u64UserValue2 == pLogger->u64UserValue3)
3200 {
3201 PGVMCPU const pGVCpu = (PGVMCPU)(uintptr_t)pLogger->u64UserValue2;
3202 if ( RT_VALID_PTR(pGVCpu)
3203 && ((uintptr_t)pGVCpu & PAGE_OFFSET_MASK) == 0)
3204 {
3205 RTNATIVETHREAD const hNativeSelf = RTThreadNativeSelf();
3206 PGVM const pGVM = pGVCpu->pGVM;
3207 if ( hNativeSelf == pGVCpu->hEMT
3208 && RT_VALID_PTR(pGVM))
3209 {
3210 PVMMR0PERVCPULOGGER const pR0Log = &pGVCpu->vmmr0.s.u.aLoggers[idxLogger];
3211 size_t const idxBuffer = pBufDesc - &pR0Log->aBufDescs[0];
3212 if (idxBuffer < VMMLOGGER_BUFFER_COUNT)
3213 {
3214 /*
3215 * Make sure we don't recurse forever here should something in the
3216 * following code trigger logging or an assertion. Do the rest in
3217 * an inner work to avoid hitting the right margin too hard.
3218 */
3219 if (!pR0Log->fFlushing)
3220 {
3221 pR0Log->fFlushing = true;
3222 bool fFlushed = vmmR0LoggerFlushInner(pGVM, pGVCpu, idxLogger, idxBuffer, pBufDesc->offBuf);
3223 pR0Log->fFlushing = false;
3224 return fFlushed;
3225 }
3226
3227 SUP_DPRINTF(("vmmR0LoggerFlush: Recursive flushing!\n"));
3228 }
3229 else
3230 SUP_DPRINTF(("vmmR0LoggerFlush: pLogger=%p pGVCpu=%p: idxBuffer=%#zx\n", pLogger, pGVCpu, idxBuffer));
3231 }
3232 else
3233 SUP_DPRINTF(("vmmR0LoggerFlush: pLogger=%p pGVCpu=%p hEMT=%p hNativeSelf=%p!\n",
3234 pLogger, pGVCpu, pGVCpu->hEMT, hNativeSelf));
3235 }
3236 else
3237 SUP_DPRINTF(("vmmR0LoggerFlush: pLogger=%p pGVCpu=%p!\n", pLogger, pGVCpu));
3238 }
3239 else
3240 SUP_DPRINTF(("vmmR0LoggerFlush: pLogger=%p u32Magic=%#x u32UserValue1=%#x u64UserValue2=%#RX64 u64UserValue3=%#RX64!\n",
3241 pLogger, pLogger->u32Magic, pLogger->u32UserValue1, pLogger->u64UserValue2, pLogger->u64UserValue3));
3242 }
3243 else
3244 SUP_DPRINTF(("vmmR0LoggerFlush: pLogger=%p!\n", pLogger));
3245 return true;
3246}
3247
3248
3249/**
3250 * @callback_method_impl{FNRTLOGFLUSH, Release logger buffer flush callback.}
3251 */
3252static DECLCALLBACK(bool) vmmR0LogRelFlush(PRTLOGGER pLogger, PRTLOGBUFFERDESC pBufDesc)
3253{
3254 return vmmR0LoggerFlushCommon(pLogger, pBufDesc, VMMLOGGER_IDX_RELEASE);
3255}
3256
3257
3258/**
3259 * @callback_method_impl{FNRTLOGFLUSH, Logger (debug) buffer flush callback.}
3260 */
3261static DECLCALLBACK(bool) vmmR0LogFlush(PRTLOGGER pLogger, PRTLOGBUFFERDESC pBufDesc)
3262{
3263#ifdef LOG_ENABLED
3264 return vmmR0LoggerFlushCommon(pLogger, pBufDesc, VMMLOGGER_IDX_REGULAR);
3265#else
3266 RT_NOREF(pLogger, pBufDesc);
3267 return true;
3268#endif
3269}
3270
3271
3272/*
3273 * Override RTLogDefaultInstanceEx so we can do logging from EMTs in ring-0.
3274 */
3275DECLEXPORT(PRTLOGGER) RTLogDefaultInstanceEx(uint32_t fFlagsAndGroup)
3276{
3277#ifdef LOG_ENABLED
3278 PGVMCPU pGVCpu = GVMMR0GetGVCpuByEMT(NIL_RTNATIVETHREAD);
3279 if (pGVCpu)
3280 {
3281 PRTLOGGER pLogger = pGVCpu->vmmr0.s.u.s.Logger.pLogger;
3282 if (RT_VALID_PTR(pLogger))
3283 {
3284 if ( pLogger->u64UserValue2 == (uintptr_t)pGVCpu
3285 && pLogger->u64UserValue3 == (uintptr_t)pGVCpu)
3286 {
3287 if (!pGVCpu->vmmr0.s.u.s.Logger.fFlushing)
3288 {
3289 if (!(pGVCpu->vmmr0.s.fLogFlushingDisabled))
3290 return RTLogCheckGroupFlags(pLogger, fFlagsAndGroup);
3291 return NULL;
3292 }
3293
3294 /*
3295 * When we're flushing we _must_ return NULL here to suppress any
3296 * attempts at using the logger while in vmmR0LoggerFlushCommon.
3297 * The VMMR0EmtPrepareToBlock code may trigger logging in HM,
3298 * which will reset the buffer content before we even get to queue
3299 * the flush request. (Only an issue when VBOX_WITH_R0_LOGGING
3300 * is enabled.)
3301 */
3302 return NULL;
3303 }
3304 }
3305 }
3306#endif
3307 return SUPR0DefaultLogInstanceEx(fFlagsAndGroup);
3308}
3309
3310
3311/*
3312 * Override RTLogRelGetDefaultInstanceEx so we can do LogRel to VBox.log from EMTs in ring-0.
3313 */
3314DECLEXPORT(PRTLOGGER) RTLogRelGetDefaultInstanceEx(uint32_t fFlagsAndGroup)
3315{
3316 PGVMCPU pGVCpu = GVMMR0GetGVCpuByEMT(NIL_RTNATIVETHREAD);
3317 if (pGVCpu)
3318 {
3319 PRTLOGGER pLogger = pGVCpu->vmmr0.s.u.s.RelLogger.pLogger;
3320 if (RT_VALID_PTR(pLogger))
3321 {
3322 if ( pLogger->u64UserValue2 == (uintptr_t)pGVCpu
3323 && pLogger->u64UserValue3 == (uintptr_t)pGVCpu)
3324 {
3325 if (!pGVCpu->vmmr0.s.u.s.RelLogger.fFlushing)
3326 {
3327 if (!(pGVCpu->vmmr0.s.fLogFlushingDisabled))
3328 return RTLogCheckGroupFlags(pLogger, fFlagsAndGroup);
3329 return NULL;
3330 }
3331 }
3332 }
3333 }
3334 return SUPR0GetDefaultLogRelInstanceEx(fFlagsAndGroup);
3335}
3336
3337
3338/**
3339 * Helper for vmmR0InitLoggerSet
3340 */
3341static int vmmR0InitLoggerOne(PGVMCPU pGVCpu, bool fRelease, PVMMR0PERVCPULOGGER pR0Log, PVMMR3CPULOGGER pShared,
3342 uint32_t cbBuf, char *pchBuf, RTR3PTR pchBufR3)
3343{
3344 /*
3345 * Create and configure the logger.
3346 */
3347 for (size_t i = 0; i < VMMLOGGER_BUFFER_COUNT; i++)
3348 {
3349 pR0Log->aBufDescs[i].u32Magic = RTLOGBUFFERDESC_MAGIC;
3350 pR0Log->aBufDescs[i].uReserved = 0;
3351 pR0Log->aBufDescs[i].cbBuf = cbBuf;
3352 pR0Log->aBufDescs[i].offBuf = 0;
3353 pR0Log->aBufDescs[i].pchBuf = pchBuf + i * cbBuf;
3354 pR0Log->aBufDescs[i].pAux = &pShared->aBufs[i].AuxDesc;
3355
3356 pShared->aBufs[i].AuxDesc.fFlushedIndicator = false;
3357 pShared->aBufs[i].AuxDesc.afPadding[0] = 0;
3358 pShared->aBufs[i].AuxDesc.afPadding[1] = 0;
3359 pShared->aBufs[i].AuxDesc.afPadding[2] = 0;
3360 pShared->aBufs[i].AuxDesc.offBuf = 0;
3361 pShared->aBufs[i].pchBufR3 = pchBufR3 + i * cbBuf;
3362 }
3363 pShared->cbBuf = cbBuf;
3364
3365 static const char * const s_apszGroups[] = VBOX_LOGGROUP_NAMES;
3366 int rc = RTLogCreateEx(&pR0Log->pLogger, fRelease ? "VBOX_RELEASE_LOG" : "VBOX_LOG", RTLOG_F_NO_LOCKING | RTLOGFLAGS_BUFFERED,
3367 "all", RT_ELEMENTS(s_apszGroups), s_apszGroups, UINT32_MAX,
3368 VMMLOGGER_BUFFER_COUNT, pR0Log->aBufDescs, RTLOGDEST_DUMMY,
3369 NULL /*pfnPhase*/, 0 /*cHistory*/, 0 /*cbHistoryFileMax*/, 0 /*cSecsHistoryTimeSlot*/,
3370 NULL /*pErrInfo*/, NULL /*pszFilenameFmt*/);
3371 if (RT_SUCCESS(rc))
3372 {
3373 PRTLOGGER pLogger = pR0Log->pLogger;
3374 pLogger->u32UserValue1 = VMMR0_LOGGER_FLAGS_MAGIC_VALUE;
3375 pLogger->u64UserValue2 = (uintptr_t)pGVCpu;
3376 pLogger->u64UserValue3 = (uintptr_t)pGVCpu;
3377
3378 rc = RTLogSetFlushCallback(pLogger, fRelease ? vmmR0LogRelFlush : vmmR0LogFlush);
3379 if (RT_SUCCESS(rc))
3380 {
3381 RTLogSetR0ThreadNameF(pLogger, "EMT-%u-R0", pGVCpu->idCpu);
3382
3383 /*
3384 * Create the event sem the EMT waits on while flushing is happening.
3385 */
3386 rc = RTSemEventCreate(&pR0Log->hEventFlushWait);
3387 if (RT_SUCCESS(rc))
3388 return VINF_SUCCESS;
3389 pR0Log->hEventFlushWait = NIL_RTSEMEVENT;
3390 }
3391 RTLogDestroy(pLogger);
3392 }
3393 pR0Log->pLogger = NULL;
3394 return rc;
3395}
3396
3397
3398/**
3399 * Worker for VMMR0CleanupVM and vmmR0InitLoggerSet that destroys one logger.
3400 */
3401static void vmmR0TermLoggerOne(PVMMR0PERVCPULOGGER pR0Log, PVMMR3CPULOGGER pShared)
3402{
3403 RTLogDestroy(pR0Log->pLogger);
3404 pR0Log->pLogger = NULL;
3405
3406 for (size_t i = 0; i < VMMLOGGER_BUFFER_COUNT; i++)
3407 pShared->aBufs[i].pchBufR3 = NIL_RTR3PTR;
3408
3409 RTSemEventDestroy(pR0Log->hEventFlushWait);
3410 pR0Log->hEventFlushWait = NIL_RTSEMEVENT;
3411}
3412
3413
3414/**
3415 * Initializes one type of loggers for each EMT.
3416 */
3417static int vmmR0InitLoggerSet(PGVM pGVM, uint8_t idxLogger, uint32_t cbBuf, PRTR0MEMOBJ phMemObj, PRTR0MEMOBJ phMapObj)
3418{
3419 /* Allocate buffers first. */
3420 int rc = RTR0MemObjAllocPage(phMemObj, cbBuf * pGVM->cCpus * VMMLOGGER_BUFFER_COUNT, false /*fExecutable*/);
3421 if (RT_SUCCESS(rc))
3422 {
3423 rc = RTR0MemObjMapUser(phMapObj, *phMemObj, (RTR3PTR)-1, 0 /*uAlignment*/, RTMEM_PROT_READ, NIL_RTR0PROCESS);
3424 if (RT_SUCCESS(rc))
3425 {
3426 char * const pchBuf = (char *)RTR0MemObjAddress(*phMemObj);
3427 AssertPtrReturn(pchBuf, VERR_INTERNAL_ERROR_2);
3428
3429 RTR3PTR const pchBufR3 = RTR0MemObjAddressR3(*phMapObj);
3430 AssertReturn(pchBufR3 != NIL_RTR3PTR, VERR_INTERNAL_ERROR_3);
3431
3432 /* Initialize the per-CPU loggers. */
3433 for (uint32_t i = 0; i < pGVM->cCpus; i++)
3434 {
3435 PGVMCPU pGVCpu = &pGVM->aCpus[i];
3436 PVMMR0PERVCPULOGGER pR0Log = &pGVCpu->vmmr0.s.u.aLoggers[idxLogger];
3437 PVMMR3CPULOGGER pShared = &pGVCpu->vmm.s.u.aLoggers[idxLogger];
3438 rc = vmmR0InitLoggerOne(pGVCpu, idxLogger == VMMLOGGER_IDX_RELEASE, pR0Log, pShared, cbBuf,
3439 pchBuf + i * cbBuf * VMMLOGGER_BUFFER_COUNT,
3440 pchBufR3 + i * cbBuf * VMMLOGGER_BUFFER_COUNT);
3441 if (RT_FAILURE(rc))
3442 {
3443 vmmR0TermLoggerOne(pR0Log, pShared);
3444 while (i-- > 0)
3445 {
3446 pGVCpu = &pGVM->aCpus[i];
3447 vmmR0TermLoggerOne(&pGVCpu->vmmr0.s.u.aLoggers[idxLogger], &pGVCpu->vmm.s.u.aLoggers[idxLogger]);
3448 }
3449 break;
3450 }
3451 }
3452 if (RT_SUCCESS(rc))
3453 return VINF_SUCCESS;
3454
3455 /* Bail out. */
3456 RTR0MemObjFree(*phMapObj, false /*fFreeMappings*/);
3457 *phMapObj = NIL_RTR0MEMOBJ;
3458 }
3459 RTR0MemObjFree(*phMemObj, true /*fFreeMappings*/);
3460 *phMemObj = NIL_RTR0MEMOBJ;
3461 }
3462 return rc;
3463}
3464
3465
3466/**
3467 * Worker for VMMR0InitPerVMData that initializes all the logging related stuff.
3468 *
3469 * @returns VBox status code.
3470 * @param pGVM The global (ring-0) VM structure.
3471 */
3472static int vmmR0InitLoggers(PGVM pGVM)
3473{
3474 /*
3475 * Invalidate the ring buffer (not really necessary).
3476 */
3477 for (size_t idx = 0; idx < RT_ELEMENTS(pGVM->vmmr0.s.LogFlusher.aRing); idx++)
3478 pGVM->vmmr0.s.LogFlusher.aRing[idx].u32 = UINT32_MAX >> 1; /* (all bits except fProcessing set) */
3479
3480 /*
3481 * Create the spinlock and flusher event semaphore.
3482 */
3483 int rc = RTSpinlockCreate(&pGVM->vmmr0.s.LogFlusher.hSpinlock, RTSPINLOCK_FLAGS_INTERRUPT_SAFE, "VM-Log-Flusher");
3484 if (RT_SUCCESS(rc))
3485 {
3486 rc = RTSemEventCreate(&pGVM->vmmr0.s.LogFlusher.hEvent);
3487 if (RT_SUCCESS(rc))
3488 {
3489 /*
3490 * Create the ring-0 release loggers.
3491 */
3492 rc = vmmR0InitLoggerSet(pGVM, VMMLOGGER_IDX_RELEASE, _4K,
3493 &pGVM->vmmr0.s.hMemObjReleaseLogger, &pGVM->vmmr0.s.hMapObjReleaseLogger);
3494#ifdef LOG_ENABLED
3495 if (RT_SUCCESS(rc))
3496 {
3497 /*
3498 * Create debug loggers.
3499 */
3500 rc = vmmR0InitLoggerSet(pGVM, VMMLOGGER_IDX_REGULAR, _64K,
3501 &pGVM->vmmr0.s.hMemObjLogger, &pGVM->vmmr0.s.hMapObjLogger);
3502 }
3503#endif
3504 }
3505 }
3506 return rc;
3507}
3508
3509
3510/**
3511 * Worker for VMMR0InitPerVMData that initializes all the logging related stuff.
3512 *
3513 * @param pGVM The global (ring-0) VM structure.
3514 */
3515static void vmmR0CleanupLoggers(PGVM pGVM)
3516{
3517 for (VMCPUID idCpu = 0; idCpu < pGVM->cCpus; idCpu++)
3518 {
3519 PGVMCPU pGVCpu = &pGVM->aCpus[idCpu];
3520 for (size_t iLogger = 0; iLogger < RT_ELEMENTS(pGVCpu->vmmr0.s.u.aLoggers); iLogger++)
3521 vmmR0TermLoggerOne(&pGVCpu->vmmr0.s.u.aLoggers[iLogger], &pGVCpu->vmm.s.u.aLoggers[iLogger]);
3522 }
3523
3524 /*
3525 * Free logger buffer memory.
3526 */
3527 RTR0MemObjFree(pGVM->vmmr0.s.hMapObjReleaseLogger, false /*fFreeMappings*/);
3528 pGVM->vmmr0.s.hMapObjReleaseLogger = NIL_RTR0MEMOBJ;
3529 RTR0MemObjFree(pGVM->vmmr0.s.hMemObjReleaseLogger, true /*fFreeMappings*/);
3530 pGVM->vmmr0.s.hMemObjReleaseLogger = NIL_RTR0MEMOBJ;
3531
3532 RTR0MemObjFree(pGVM->vmmr0.s.hMapObjLogger, false /*fFreeMappings*/);
3533 pGVM->vmmr0.s.hMapObjLogger = NIL_RTR0MEMOBJ;
3534 RTR0MemObjFree(pGVM->vmmr0.s.hMemObjLogger, true /*fFreeMappings*/);
3535 pGVM->vmmr0.s.hMemObjLogger = NIL_RTR0MEMOBJ;
3536
3537 /*
3538 * Free log flusher related stuff.
3539 */
3540 RTSpinlockDestroy(pGVM->vmmr0.s.LogFlusher.hSpinlock);
3541 pGVM->vmmr0.s.LogFlusher.hSpinlock = NIL_RTSPINLOCK;
3542 RTSemEventDestroy(pGVM->vmmr0.s.LogFlusher.hEvent);
3543 pGVM->vmmr0.s.LogFlusher.hEvent = NIL_RTSEMEVENT;
3544}
3545
3546
3547/*********************************************************************************************************************************
3548* Assertions *
3549*********************************************************************************************************************************/
3550
3551/*
3552 * Jump back to ring-3 if we're the EMT and the longjmp is armed.
3553 *
3554 * @returns true if the breakpoint should be hit, false if it should be ignored.
3555 */
3556DECLEXPORT(bool) RTCALL RTAssertShouldPanic(void)
3557{
3558#if 0
3559 return true;
3560#else
3561 PVMCC pVM = GVMMR0GetVMByEMT(NIL_RTNATIVETHREAD);
3562 if (pVM)
3563 {
3564 PVMCPUCC pVCpu = VMMGetCpu(pVM);
3565
3566 if (pVCpu)
3567 {
3568# ifdef RT_ARCH_X86
3569 if ( pVCpu->vmm.s.CallRing3JmpBufR0.eip
3570 && !pVCpu->vmm.s.CallRing3JmpBufR0.fInRing3Call)
3571# else
3572 if ( pVCpu->vmm.s.CallRing3JmpBufR0.rip
3573 && !pVCpu->vmm.s.CallRing3JmpBufR0.fInRing3Call)
3574# endif
3575 {
3576 int rc = VMMRZCallRing3(pVM, pVCpu, VMMCALLRING3_VM_R0_ASSERTION, 0);
3577 return RT_FAILURE_NP(rc);
3578 }
3579 }
3580 }
3581# ifdef RT_OS_LINUX
3582 return true;
3583# else
3584 return false;
3585# endif
3586#endif
3587}
3588
3589
3590/*
3591 * Override this so we can push it up to ring-3.
3592 */
3593DECLEXPORT(void) RTCALL RTAssertMsg1Weak(const char *pszExpr, unsigned uLine, const char *pszFile, const char *pszFunction)
3594{
3595 /*
3596 * To host kernel log/whatever.
3597 */
3598 SUPR0Printf("!!R0-Assertion Failed!!\n"
3599 "Expression: %s\n"
3600 "Location : %s(%d) %s\n",
3601 pszExpr, pszFile, uLine, pszFunction);
3602
3603 /*
3604 * To the log.
3605 */
3606 LogAlways(("\n!!R0-Assertion Failed!!\n"
3607 "Expression: %s\n"
3608 "Location : %s(%d) %s\n",
3609 pszExpr, pszFile, uLine, pszFunction));
3610
3611 /*
3612 * To the global VMM buffer.
3613 */
3614 PVMCC pVM = GVMMR0GetVMByEMT(NIL_RTNATIVETHREAD);
3615 if (pVM)
3616 RTStrPrintf(pVM->vmm.s.szRing0AssertMsg1, sizeof(pVM->vmm.s.szRing0AssertMsg1),
3617 "\n!!R0-Assertion Failed!!\n"
3618 "Expression: %.*s\n"
3619 "Location : %s(%d) %s\n",
3620 sizeof(pVM->vmm.s.szRing0AssertMsg1) / 4 * 3, pszExpr,
3621 pszFile, uLine, pszFunction);
3622
3623 /*
3624 * Continue the normal way.
3625 */
3626 RTAssertMsg1(pszExpr, uLine, pszFile, pszFunction);
3627}
3628
3629
3630/**
3631 * Callback for RTLogFormatV which writes to the ring-3 log port.
3632 * See PFNLOGOUTPUT() for details.
3633 */
3634static DECLCALLBACK(size_t) rtLogOutput(void *pv, const char *pachChars, size_t cbChars)
3635{
3636 for (size_t i = 0; i < cbChars; i++)
3637 {
3638 LogAlways(("%c", pachChars[i])); NOREF(pachChars);
3639 }
3640
3641 NOREF(pv);
3642 return cbChars;
3643}
3644
3645
3646/*
3647 * Override this so we can push it up to ring-3.
3648 */
3649DECLEXPORT(void) RTCALL RTAssertMsg2WeakV(const char *pszFormat, va_list va)
3650{
3651 va_list vaCopy;
3652
3653 /*
3654 * Push the message to the loggers.
3655 */
3656 PRTLOGGER pLog = RTLogRelGetDefaultInstance();
3657 if (pLog)
3658 {
3659 va_copy(vaCopy, va);
3660 RTLogFormatV(rtLogOutput, pLog, pszFormat, vaCopy);
3661 va_end(vaCopy);
3662 }
3663 pLog = RTLogGetDefaultInstance(); /* Don't initialize it here... */
3664 if (pLog)
3665 {
3666 va_copy(vaCopy, va);
3667 RTLogFormatV(rtLogOutput, pLog, pszFormat, vaCopy);
3668 va_end(vaCopy);
3669 }
3670
3671 /*
3672 * Push it to the global VMM buffer.
3673 */
3674 PVMCC pVM = GVMMR0GetVMByEMT(NIL_RTNATIVETHREAD);
3675 if (pVM)
3676 {
3677 va_copy(vaCopy, va);
3678 RTStrPrintfV(pVM->vmm.s.szRing0AssertMsg2, sizeof(pVM->vmm.s.szRing0AssertMsg2), pszFormat, vaCopy);
3679 va_end(vaCopy);
3680 }
3681
3682 /*
3683 * Continue the normal way.
3684 */
3685 RTAssertMsg2V(pszFormat, va);
3686}
3687
Note: See TracBrowser for help on using the repository browser.

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