VirtualBox

source: vbox/trunk/src/VBox/VMM/VMMR3/VMEmt.cpp

Last change on this file was 107466, checked in by vboxsync, 7 days ago

VMM/VMEmt.cpp: Compile logging only code only if LOG_ENABLED is defined, bugref:3409

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id Revision
File size: 52.9 KB
Line 
1/* $Id: VMEmt.cpp 107466 2025-01-07 12:39:48Z vboxsync $ */
2/** @file
3 * VM - Virtual Machine, The Emulation Thread.
4 */
5
6/*
7 * Copyright (C) 2006-2024 Oracle and/or its affiliates.
8 *
9 * This file is part of VirtualBox base platform packages, as
10 * available from https://www.virtualbox.org.
11 *
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation, in version 3 of the
15 * License.
16 *
17 * This program is distributed in the hope that it will be useful, but
18 * WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * General Public License for more details.
21 *
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, see <https://www.gnu.org/licenses>.
24 *
25 * SPDX-License-Identifier: GPL-3.0-only
26 */
27
28
29/*********************************************************************************************************************************
30* Header Files *
31*********************************************************************************************************************************/
32#define LOG_GROUP LOG_GROUP_VM
33#include <VBox/vmm/tm.h>
34#include <VBox/vmm/dbgf.h>
35#include <VBox/vmm/em.h>
36#include <VBox/vmm/gvmm.h>
37#include <VBox/vmm/nem.h>
38#include <VBox/vmm/pdmapi.h>
39#include <VBox/vmm/tm.h>
40#include "VMInternal.h"
41#include <VBox/vmm/vmcc.h>
42
43#include <VBox/err.h>
44#include <VBox/log.h>
45#include <iprt/assert.h>
46#include <iprt/asm.h>
47#include <iprt/asm-math.h>
48#include <iprt/semaphore.h>
49#include <iprt/string.h>
50#include <iprt/thread.h>
51#include <iprt/time.h>
52
53
54/*********************************************************************************************************************************
55* Internal Functions *
56*********************************************************************************************************************************/
57int vmR3EmulationThreadWithId(RTTHREAD hThreadSelf, PUVMCPU pUVCpu, VMCPUID idCpu);
58
59
60/**
61 * The emulation thread main function.
62 *
63 * @returns Thread exit code.
64 * @param hThreadSelf The handle to the executing thread.
65 * @param pvArgs Pointer to the user mode per-VCpu structure (UVMPCU).
66 */
67DECLCALLBACK(int) vmR3EmulationThread(RTTHREAD hThreadSelf, void *pvArgs)
68{
69 PUVMCPU pUVCpu = (PUVMCPU)pvArgs;
70 return vmR3EmulationThreadWithId(hThreadSelf, pUVCpu, pUVCpu->idCpu);
71}
72
73
74/**
75 * The emulation thread main function, with Virtual CPU ID for debugging.
76 *
77 * @returns Thread exit code.
78 * @param hThreadSelf The handle to the executing thread.
79 * @param pUVCpu Pointer to the user mode per-VCpu structure.
80 * @param idCpu The virtual CPU ID, for backtrace purposes.
81 */
82int vmR3EmulationThreadWithId(RTTHREAD hThreadSelf, PUVMCPU pUVCpu, VMCPUID idCpu)
83{
84 PUVM pUVM = pUVCpu->pUVM;
85 int rc;
86 RT_NOREF_PV(hThreadSelf);
87
88 AssertReleaseMsg(RT_VALID_PTR(pUVM) && pUVM->u32Magic == UVM_MAGIC,
89 ("Invalid arguments to the emulation thread!\n"));
90
91 rc = RTTlsSet(pUVM->vm.s.idxTLS, pUVCpu);
92 AssertReleaseMsgRCReturn(rc, ("RTTlsSet %x failed with %Rrc\n", pUVM->vm.s.idxTLS, rc), rc);
93
94 if ( pUVM->pVmm2UserMethods
95 && pUVM->pVmm2UserMethods->pfnNotifyEmtInit)
96 pUVM->pVmm2UserMethods->pfnNotifyEmtInit(pUVM->pVmm2UserMethods, pUVM, pUVCpu);
97
98 /*
99 * The request loop.
100 */
101 rc = VINF_SUCCESS;
102 Log(("vmR3EmulationThread: Emulation thread starting the days work... Thread=%#x pUVM=%p\n", hThreadSelf, pUVM));
103#ifdef LOG_ENABLED
104 VMSTATE enmBefore = VMSTATE_CREATED; /* (only used for logging atm.) */
105#endif
106 ASMAtomicIncU32(&pUVM->vm.s.cActiveEmts);
107 for (;;)
108 {
109 /*
110 * During early init there is no pVM and/or pVCpu, so make a special path
111 * for that to keep things clearly separate.
112 */
113 PVM pVM = pUVM->pVM;
114 PVMCPU pVCpu = pUVCpu->pVCpu;
115 if (!pVCpu || !pVM)
116 {
117 /*
118 * Check for termination first.
119 */
120 if (pUVM->vm.s.fTerminateEMT)
121 {
122 rc = VINF_EM_TERMINATE;
123 break;
124 }
125
126 /*
127 * Only the first VCPU may initialize the VM during early init
128 * and must therefore service all VMCPUID_ANY requests.
129 * See also VMR3Create
130 */
131 if ( (pUVM->vm.s.pNormalReqs || pUVM->vm.s.pPriorityReqs)
132 && pUVCpu->idCpu == 0)
133 {
134 /*
135 * Service execute in any EMT request.
136 */
137 rc = VMR3ReqProcessU(pUVM, VMCPUID_ANY, false /*fPriorityOnly*/);
138 Log(("vmR3EmulationThread: Req rc=%Rrc, VM state %s -> %s\n", rc, VMR3GetStateName(enmBefore), pUVM->pVM ? VMR3GetStateName(pUVM->pVM->enmVMState) : "CREATING"));
139 }
140 else if (pUVCpu->vm.s.pNormalReqs || pUVCpu->vm.s.pPriorityReqs)
141 {
142 /*
143 * Service execute in specific EMT request.
144 */
145 rc = VMR3ReqProcessU(pUVM, pUVCpu->idCpu, false /*fPriorityOnly*/);
146 Log(("vmR3EmulationThread: Req (cpu=%u) rc=%Rrc, VM state %s -> %s\n", pUVCpu->idCpu, rc, VMR3GetStateName(enmBefore), pUVM->pVM ? VMR3GetStateName(pUVM->pVM->enmVMState) : "CREATING"));
147 }
148 else
149 {
150 /*
151 * Nothing important is pending, so wait for something.
152 */
153 rc = VMR3WaitU(pUVCpu);
154 if (RT_FAILURE(rc))
155 {
156 AssertLogRelMsgFailed(("VMR3WaitU failed with %Rrc\n", rc));
157 break;
158 }
159 }
160 }
161 else
162 {
163 /*
164 * Pending requests which needs servicing?
165 *
166 * We check for state changes in addition to status codes when
167 * servicing requests. (Look after the ifs.)
168 */
169#ifdef LOG_ENABLED
170 enmBefore = pVM->enmVMState;
171#endif
172 if (pUVM->vm.s.fTerminateEMT)
173 {
174 rc = VINF_EM_TERMINATE;
175 break;
176 }
177
178 if (VM_FF_IS_SET(pVM, VM_FF_EMT_RENDEZVOUS))
179 {
180 rc = VMMR3EmtRendezvousFF(pVM, pVM->apCpusR3[idCpu]);
181 Log(("vmR3EmulationThread: Rendezvous rc=%Rrc, VM state %s -> %s\n", rc, VMR3GetStateName(enmBefore), VMR3GetStateName(pVM->enmVMState)));
182 }
183 else if (pUVM->vm.s.pNormalReqs || pUVM->vm.s.pPriorityReqs)
184 {
185 /*
186 * Service execute in any EMT request.
187 */
188 rc = VMR3ReqProcessU(pUVM, VMCPUID_ANY, false /*fPriorityOnly*/);
189 Log(("vmR3EmulationThread: Req rc=%Rrc, VM state %s -> %s\n", rc, VMR3GetStateName(enmBefore), VMR3GetStateName(pVM->enmVMState)));
190 }
191 else if (pUVCpu->vm.s.pNormalReqs || pUVCpu->vm.s.pPriorityReqs)
192 {
193 /*
194 * Service execute in specific EMT request.
195 */
196 rc = VMR3ReqProcessU(pUVM, pUVCpu->idCpu, false /*fPriorityOnly*/);
197 Log(("vmR3EmulationThread: Req (cpu=%u) rc=%Rrc, VM state %s -> %s\n", pUVCpu->idCpu, rc, VMR3GetStateName(enmBefore), VMR3GetStateName(pVM->enmVMState)));
198 }
199 else if ( VM_FF_IS_SET(pVM, VM_FF_DBGF)
200 || VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_DBGF))
201 {
202 /*
203 * Service the debugger request.
204 */
205 rc = DBGFR3VMMForcedAction(pVM, pVCpu);
206 Log(("vmR3EmulationThread: Dbg rc=%Rrc, VM state %s -> %s\n", rc, VMR3GetStateName(enmBefore), VMR3GetStateName(pVM->enmVMState)));
207 }
208 else if (VM_FF_TEST_AND_CLEAR(pVM, VM_FF_RESET))
209 {
210 /*
211 * Service a delayed reset request.
212 */
213 rc = VBOXSTRICTRC_VAL(VMR3ResetFF(pVM));
214 VM_FF_CLEAR(pVM, VM_FF_RESET);
215 Log(("vmR3EmulationThread: Reset rc=%Rrc, VM state %s -> %s\n", rc, VMR3GetStateName(enmBefore), VMR3GetStateName(pVM->enmVMState)));
216 }
217 else
218 {
219 /*
220 * Nothing important is pending, so wait for something.
221 */
222 rc = VMR3WaitU(pUVCpu);
223 if (RT_FAILURE(rc))
224 {
225 AssertLogRelMsgFailed(("VMR3WaitU failed with %Rrc\n", rc));
226 break;
227 }
228 }
229
230 /*
231 * Check for termination requests, these have extremely high priority.
232 */
233 if ( rc == VINF_EM_TERMINATE
234 || pUVM->vm.s.fTerminateEMT)
235 break;
236 }
237
238 /*
239 * Some requests (both VMR3Req* and the DBGF) can potentially resume
240 * or start the VM, in that case we'll get a change in VM status
241 * indicating that we're now running.
242 */
243 if (RT_SUCCESS(rc))
244 {
245 pVM = pUVM->pVM;
246 if (pVM)
247 {
248 pVCpu = pVM->apCpusR3[idCpu];
249 if ( pVM->enmVMState == VMSTATE_RUNNING
250 && VMCPUSTATE_IS_STARTED(VMCPU_GET_STATE(pVCpu)))
251 {
252 rc = EMR3ExecuteVM(pVM, pVCpu);
253 Log(("vmR3EmulationThread: EMR3ExecuteVM() -> rc=%Rrc, enmVMState=%d\n", rc, pVM->enmVMState));
254 }
255 }
256 }
257
258 } /* forever */
259
260
261 /*
262 * Decrement the active EMT count if we haven't done it yet in vmR3Destroy.
263 */
264 if (!pUVCpu->vm.s.fBeenThruVmDestroy)
265 ASMAtomicDecU32(&pUVM->vm.s.cActiveEmts);
266
267
268 /*
269 * Cleanup and exit.
270 * EMT0 does the VM destruction after all other EMTs have deregistered and terminated.
271 */
272 Log(("vmR3EmulationThread: Terminating emulation thread! Thread=%#x pUVM=%p rc=%Rrc enmBefore=%d enmVMState=%d\n",
273 hThreadSelf, pUVM, rc, enmBefore, pUVM->pVM ? pUVM->pVM->enmVMState : VMSTATE_TERMINATED));
274 PVM pVM;
275 if ( idCpu == 0
276 && (pVM = pUVM->pVM) != NULL)
277 {
278 /* Wait for any other EMTs to terminate before we destroy the VM (see vmR3DestroyVM). */
279 for (VMCPUID iCpu = 1; iCpu < pUVM->cCpus; iCpu++)
280 {
281 RTTHREAD hThread;
282 ASMAtomicXchgHandle(&pUVM->aCpus[iCpu].vm.s.ThreadEMT, NIL_RTTHREAD, &hThread);
283 if (hThread != NIL_RTTHREAD)
284 {
285 int rc2 = RTThreadWait(hThread, 5 * RT_MS_1SEC, NULL);
286 AssertLogRelMsgRC(rc2, ("iCpu=%u rc=%Rrc\n", iCpu, rc2));
287 if (RT_FAILURE(rc2))
288 pUVM->aCpus[iCpu].vm.s.ThreadEMT = hThread;
289 }
290 }
291
292 /* Switch to the terminated state, clearing the VM pointer and finally destroy the VM. */
293 vmR3SetTerminated(pVM);
294
295 pUVM->pVM = NULL;
296 for (VMCPUID iCpu = 0; iCpu < pUVM->cCpus; iCpu++)
297 {
298 pUVM->aCpus[iCpu].pVM = NULL;
299 pUVM->aCpus[iCpu].pVCpu = NULL;
300 }
301
302 int rc2 = GVMMR3DestroyVM(pUVM, pVM);
303 AssertLogRelRC(rc2);
304 }
305 /* Deregister the EMT with VMMR0. */
306 else if ( idCpu != 0
307 && (pVM = pUVM->pVM) != NULL)
308 {
309 int rc2 = GVMMR3DeregisterVCpu(pVM, idCpu);
310 AssertLogRelRC(rc2);
311 }
312
313 if ( pUVM->pVmm2UserMethods
314 && pUVM->pVmm2UserMethods->pfnNotifyEmtTerm)
315 pUVM->pVmm2UserMethods->pfnNotifyEmtTerm(pUVM->pVmm2UserMethods, pUVM, pUVCpu);
316
317 pUVCpu->vm.s.NativeThreadEMT = NIL_RTNATIVETHREAD;
318 Log(("vmR3EmulationThread: EMT is terminated.\n"));
319 return rc;
320}
321
322
323/**
324 * Gets the name of a halt method.
325 *
326 * @returns Pointer to a read only string.
327 * @param enmMethod The method.
328 */
329static const char *vmR3GetHaltMethodName(VMHALTMETHOD enmMethod)
330{
331 switch (enmMethod)
332 {
333 case VMHALTMETHOD_BOOTSTRAP: return "bootstrap";
334 case VMHALTMETHOD_DEFAULT: return "default";
335 case VMHALTMETHOD_OLD: return "old";
336 case VMHALTMETHOD_1: return "method1";
337 //case VMHALTMETHOD_2: return "method2";
338 case VMHALTMETHOD_GLOBAL_1: return "global1";
339 default: return "unknown";
340 }
341}
342
343
344/**
345 * Signal a fatal wait error.
346 *
347 * @returns Fatal error code to be propagated up the call stack.
348 * @param pUVCpu The user mode per CPU structure of the calling
349 * EMT.
350 * @param pszFmt The error format with a single %Rrc in it.
351 * @param rcFmt The status code to format.
352 */
353static int vmR3FatalWaitError(PUVMCPU pUVCpu, const char *pszFmt, int rcFmt)
354{
355 /** @todo This is wrong ... raise a fatal error / guru meditation
356 * instead. */
357 AssertLogRelMsgFailed((pszFmt, rcFmt));
358 ASMAtomicUoWriteBool(&pUVCpu->pUVM->vm.s.fTerminateEMT, true);
359 if (pUVCpu->pVM)
360 VM_FF_SET(pUVCpu->pVM, VM_FF_CHECK_VM_STATE);
361 return VERR_VM_FATAL_WAIT_ERROR;
362}
363
364
365/**
366 * The old halt loop.
367 */
368static DECLCALLBACK(int) vmR3HaltOldDoHalt(PUVMCPU pUVCpu, const uint64_t fMask, uint64_t /* u64Now*/)
369{
370 /*
371 * Halt loop.
372 */
373 PVM pVM = pUVCpu->pVM;
374 PVMCPU pVCpu = pUVCpu->pVCpu;
375
376 int rc = VINF_SUCCESS;
377 ASMAtomicWriteBool(&pUVCpu->vm.s.fWait, true);
378 //unsigned cLoops = 0;
379 for (;;)
380 {
381 /*
382 * Work the timers and check if we can exit.
383 * The poll call gives us the ticks left to the next event in
384 * addition to perhaps set an FF.
385 */
386 uint64_t const u64StartTimers = RTTimeNanoTS();
387 TMR3TimerQueuesDo(pVM);
388 uint64_t const cNsElapsedTimers = RTTimeNanoTS() - u64StartTimers;
389 STAM_REL_PROFILE_ADD_PERIOD(&pUVCpu->vm.s.StatHaltTimers, cNsElapsedTimers);
390 if ( VM_FF_IS_ANY_SET(pVM, VM_FF_EXTERNAL_HALTED_MASK)
391 || VMCPU_FF_IS_ANY_SET(pVCpu, fMask))
392 break;
393 uint64_t u64NanoTS;
394 TMTimerPollGIP(pVM, pVCpu, &u64NanoTS);
395 if ( VM_FF_IS_ANY_SET(pVM, VM_FF_EXTERNAL_HALTED_MASK)
396 || VMCPU_FF_IS_ANY_SET(pVCpu, fMask))
397 break;
398
399 /*
400 * Wait for a while. Someone will wake us up or interrupt the call if
401 * anything needs our attention.
402 */
403 if (u64NanoTS < 50000)
404 {
405 //RTLogPrintf("u64NanoTS=%RI64 cLoops=%d spin\n", u64NanoTS, cLoops++);
406 /* spin */;
407 }
408 else
409 {
410 VMMR3YieldStop(pVM);
411 //uint64_t u64Start = RTTimeNanoTS();
412 if (u64NanoTS < 870000) /* this is a bit speculative... works fine on linux. */
413 {
414 //RTLogPrintf("u64NanoTS=%RI64 cLoops=%d yield", u64NanoTS, cLoops++);
415 uint64_t const u64StartSchedYield = RTTimeNanoTS();
416 RTThreadYield(); /* this is the best we can do here */
417 uint64_t const cNsElapsedSchedYield = RTTimeNanoTS() - u64StartSchedYield;
418 STAM_REL_PROFILE_ADD_PERIOD(&pUVCpu->vm.s.StatHaltYield, cNsElapsedSchedYield);
419 }
420 else if (u64NanoTS < 2000000)
421 {
422 //RTLogPrintf("u64NanoTS=%RI64 cLoops=%d sleep 1ms", u64NanoTS, cLoops++);
423 uint64_t const u64StartSchedHalt = RTTimeNanoTS();
424 rc = RTSemEventWait(pUVCpu->vm.s.EventSemWait, 1);
425 uint64_t const cNsElapsedSchedHalt = RTTimeNanoTS() - u64StartSchedHalt;
426 STAM_REL_PROFILE_ADD_PERIOD(&pUVCpu->vm.s.StatHaltBlock, cNsElapsedSchedHalt);
427 }
428 else
429 {
430 //RTLogPrintf("u64NanoTS=%RI64 cLoops=%d sleep %dms", u64NanoTS, cLoops++, (uint32_t)RT_MIN((u64NanoTS - 500000) / 1000000, 15));
431 uint64_t const u64StartSchedHalt = RTTimeNanoTS();
432 rc = RTSemEventWait(pUVCpu->vm.s.EventSemWait, RT_MIN((u64NanoTS - 1000000) / 1000000, 15));
433 uint64_t const cNsElapsedSchedHalt = RTTimeNanoTS() - u64StartSchedHalt;
434 STAM_REL_PROFILE_ADD_PERIOD(&pUVCpu->vm.s.StatHaltBlock, cNsElapsedSchedHalt);
435 }
436 //uint64_t u64Slept = RTTimeNanoTS() - u64Start;
437 //RTLogPrintf(" -> rc=%Rrc in %RU64 ns / %RI64 ns delta\n", rc, u64Slept, u64NanoTS - u64Slept);
438 }
439 if (rc == VERR_TIMEOUT)
440 rc = VINF_SUCCESS;
441 else if (RT_FAILURE(rc))
442 {
443 rc = vmR3FatalWaitError(pUVCpu, "RTSemEventWait->%Rrc\n", rc);
444 break;
445 }
446 }
447
448 ASMAtomicUoWriteBool(&pUVCpu->vm.s.fWait, false);
449 return rc;
450}
451
452
453/**
454 * Initialize the configuration of halt method 1 & 2.
455 *
456 * @return VBox status code. Failure on invalid CFGM data.
457 * @param pUVM The user mode VM structure.
458 */
459static int vmR3HaltMethod12ReadConfigU(PUVM pUVM)
460{
461 /*
462 * The defaults.
463 */
464#if 1 /* DEBUGGING STUFF - REMOVE LATER */
465 pUVM->vm.s.Halt.Method12.u32LagBlockIntervalDivisorCfg = 4;
466 pUVM->vm.s.Halt.Method12.u32MinBlockIntervalCfg = 2*1000000;
467 pUVM->vm.s.Halt.Method12.u32MaxBlockIntervalCfg = 75*1000000;
468 pUVM->vm.s.Halt.Method12.u32StartSpinningCfg = 30*1000000;
469 pUVM->vm.s.Halt.Method12.u32StopSpinningCfg = 20*1000000;
470#else
471 pUVM->vm.s.Halt.Method12.u32LagBlockIntervalDivisorCfg = 4;
472 pUVM->vm.s.Halt.Method12.u32MinBlockIntervalCfg = 5*1000000;
473 pUVM->vm.s.Halt.Method12.u32MaxBlockIntervalCfg = 200*1000000;
474 pUVM->vm.s.Halt.Method12.u32StartSpinningCfg = 20*1000000;
475 pUVM->vm.s.Halt.Method12.u32StopSpinningCfg = 2*1000000;
476#endif
477
478 /*
479 * Query overrides.
480 *
481 * I don't have time to bother with niceties such as invalid value checks
482 * here right now. sorry.
483 */
484 PCFGMNODE pCfg = CFGMR3GetChild(CFGMR3GetRoot(pUVM->pVM), "/VMM/HaltedMethod1");
485 if (pCfg)
486 {
487 uint32_t u32;
488 if (RT_SUCCESS(CFGMR3QueryU32(pCfg, "LagBlockIntervalDivisor", &u32)))
489 pUVM->vm.s.Halt.Method12.u32LagBlockIntervalDivisorCfg = u32;
490 if (RT_SUCCESS(CFGMR3QueryU32(pCfg, "MinBlockInterval", &u32)))
491 pUVM->vm.s.Halt.Method12.u32MinBlockIntervalCfg = u32;
492 if (RT_SUCCESS(CFGMR3QueryU32(pCfg, "MaxBlockInterval", &u32)))
493 pUVM->vm.s.Halt.Method12.u32MaxBlockIntervalCfg = u32;
494 if (RT_SUCCESS(CFGMR3QueryU32(pCfg, "StartSpinning", &u32)))
495 pUVM->vm.s.Halt.Method12.u32StartSpinningCfg = u32;
496 if (RT_SUCCESS(CFGMR3QueryU32(pCfg, "StopSpinning", &u32)))
497 pUVM->vm.s.Halt.Method12.u32StopSpinningCfg = u32;
498 LogRel(("VMEmt: HaltedMethod1 config: %d/%d/%d/%d/%d\n",
499 pUVM->vm.s.Halt.Method12.u32LagBlockIntervalDivisorCfg,
500 pUVM->vm.s.Halt.Method12.u32MinBlockIntervalCfg,
501 pUVM->vm.s.Halt.Method12.u32MaxBlockIntervalCfg,
502 pUVM->vm.s.Halt.Method12.u32StartSpinningCfg,
503 pUVM->vm.s.Halt.Method12.u32StopSpinningCfg));
504 }
505
506 return VINF_SUCCESS;
507}
508
509
510/**
511 * Initialize halt method 1.
512 *
513 * @return VBox status code.
514 * @param pUVM Pointer to the user mode VM structure.
515 */
516static DECLCALLBACK(int) vmR3HaltMethod1Init(PUVM pUVM)
517{
518 return vmR3HaltMethod12ReadConfigU(pUVM);
519}
520
521
522/**
523 * Method 1 - Block whenever possible, and when lagging behind
524 * switch to spinning for 10-30ms with occasional blocking until
525 * the lag has been eliminated.
526 */
527static DECLCALLBACK(int) vmR3HaltMethod1Halt(PUVMCPU pUVCpu, const uint64_t fMask, uint64_t u64Now)
528{
529 PUVM pUVM = pUVCpu->pUVM;
530 PVMCPU pVCpu = pUVCpu->pVCpu;
531 PVM pVM = pUVCpu->pVM;
532
533 /*
534 * To simplify things, we decide up-front whether we should switch to spinning or
535 * not. This makes some ASSUMPTIONS about the cause of the spinning (PIT/RTC/PCNet)
536 * and that it will generate interrupts or other events that will cause us to exit
537 * the halt loop.
538 */
539 bool fBlockOnce = false;
540 bool fSpinning = false;
541 uint32_t u32CatchUpPct = TMVirtualSyncGetCatchUpPct(pVM);
542 if (u32CatchUpPct /* non-zero if catching up */)
543 {
544 if (pUVCpu->vm.s.Halt.Method12.u64StartSpinTS)
545 {
546 fSpinning = TMVirtualSyncGetLag(pVM) >= pUVM->vm.s.Halt.Method12.u32StopSpinningCfg;
547 if (fSpinning)
548 {
549 uint64_t u64Lag = TMVirtualSyncGetLag(pVM);
550 fBlockOnce = u64Now - pUVCpu->vm.s.Halt.Method12.u64LastBlockTS
551 > RT_MAX(pUVM->vm.s.Halt.Method12.u32MinBlockIntervalCfg,
552 RT_MIN(u64Lag / pUVM->vm.s.Halt.Method12.u32LagBlockIntervalDivisorCfg,
553 pUVM->vm.s.Halt.Method12.u32MaxBlockIntervalCfg));
554 }
555 else
556 {
557 //RTLogRelPrintf("Stopped spinning (%u ms)\n", (u64Now - pUVCpu->vm.s.Halt.Method12.u64StartSpinTS) / 1000000);
558 pUVCpu->vm.s.Halt.Method12.u64StartSpinTS = 0;
559 }
560 }
561 else
562 {
563 fSpinning = TMVirtualSyncGetLag(pVM) >= pUVM->vm.s.Halt.Method12.u32StartSpinningCfg;
564 if (fSpinning)
565 pUVCpu->vm.s.Halt.Method12.u64StartSpinTS = u64Now;
566 }
567 }
568 else if (pUVCpu->vm.s.Halt.Method12.u64StartSpinTS)
569 {
570 //RTLogRelPrintf("Stopped spinning (%u ms)\n", (u64Now - pUVCpu->vm.s.Halt.Method12.u64StartSpinTS) / 1000000);
571 pUVCpu->vm.s.Halt.Method12.u64StartSpinTS = 0;
572 }
573
574#ifdef VBOX_VMM_TARGET_ARMV8
575 uint64_t cNsVTimerActivate = TMCpuGetVTimerActivationNano(pVCpu);
576 const bool fVTimerActive = cNsVTimerActivate != UINT64_MAX;
577#endif
578
579 /*
580 * Halt loop.
581 */
582 int rc = VINF_SUCCESS;
583 ASMAtomicWriteBool(&pUVCpu->vm.s.fWait, true);
584 unsigned cLoops = 0;
585 for (;; cLoops++)
586 {
587 /*
588 * Work the timers and check if we can exit.
589 */
590 uint64_t const u64StartTimers = RTTimeNanoTS();
591 TMR3TimerQueuesDo(pVM);
592 uint64_t const cNsElapsedTimers = RTTimeNanoTS() - u64StartTimers;
593 STAM_REL_PROFILE_ADD_PERIOD(&pUVCpu->vm.s.StatHaltTimers, cNsElapsedTimers);
594 if ( VM_FF_IS_ANY_SET(pVM, VM_FF_EXTERNAL_HALTED_MASK)
595 || VMCPU_FF_IS_ANY_SET(pVCpu, fMask)
596#ifdef VBOX_VMM_TARGET_ARMV8
597 || cNsElapsedTimers >= cNsVTimerActivate
598#endif
599 )
600 {
601#ifdef VBOX_VMM_TARGET_ARMV8
602 cNsVTimerActivate = 0;
603#endif
604 break;
605 }
606
607#ifdef VBOX_VMM_TARGET_ARMV8
608 cNsVTimerActivate -= cNsElapsedTimers;
609#endif
610
611 /*
612 * Estimate time left to the next event.
613 */
614 uint64_t u64NanoTS;
615 TMTimerPollGIP(pVM, pVCpu, &u64NanoTS);
616 if ( VM_FF_IS_ANY_SET(pVM, VM_FF_EXTERNAL_HALTED_MASK)
617 || VMCPU_FF_IS_ANY_SET(pVCpu, fMask))
618 break;
619
620#ifdef VBOX_VMM_TARGET_ARMV8
621 u64NanoTS = RT_MIN(cNsVTimerActivate, u64NanoTS);
622#endif
623
624 /*
625 * Block if we're not spinning and the interval isn't all that small.
626 */
627 if ( ( !fSpinning
628 || fBlockOnce)
629#if 1 /* DEBUGGING STUFF - REMOVE LATER */
630 && u64NanoTS >= 100000) /* 0.100 ms */
631#else
632 && u64NanoTS >= 250000) /* 0.250 ms */
633#endif
634 {
635 const uint64_t Start = pUVCpu->vm.s.Halt.Method12.u64LastBlockTS = RTTimeNanoTS();
636 VMMR3YieldStop(pVM);
637
638 uint32_t cMilliSecs = RT_MIN(u64NanoTS / RT_NS_1MS, 15);
639 if (cMilliSecs <= pUVCpu->vm.s.Halt.Method12.cNSBlockedTooLongAvg / RT_NS_1MS)
640 cMilliSecs = 1;
641 else
642 cMilliSecs -= pUVCpu->vm.s.Halt.Method12.cNSBlockedTooLongAvg / RT_NS_1MS;
643
644 //RTLogRelPrintf("u64NanoTS=%RI64 cLoops=%3d sleep %02dms (%7RU64) ", u64NanoTS, cLoops, cMilliSecs, u64NanoTS);
645 uint64_t const u64StartSchedHalt = RTTimeNanoTS();
646 rc = RTSemEventWait(pUVCpu->vm.s.EventSemWait, cMilliSecs);
647 uint64_t const cNsElapsedSchedHalt = RTTimeNanoTS() - u64StartSchedHalt;
648 STAM_REL_PROFILE_ADD_PERIOD(&pUVCpu->vm.s.StatHaltBlock, cNsElapsedSchedHalt);
649
650 if (rc == VERR_TIMEOUT)
651 rc = VINF_SUCCESS;
652 else if (RT_FAILURE(rc))
653 {
654 rc = vmR3FatalWaitError(pUVCpu, "RTSemEventWait->%Rrc\n", rc);
655 break;
656 }
657
658 /*
659 * Calc the statistics.
660 * Update averages every 16th time, and flush parts of the history every 64th time.
661 */
662 const uint64_t Elapsed = RTTimeNanoTS() - Start;
663 pUVCpu->vm.s.Halt.Method12.cNSBlocked += Elapsed;
664 if (Elapsed > u64NanoTS)
665 pUVCpu->vm.s.Halt.Method12.cNSBlockedTooLong += Elapsed - u64NanoTS;
666 pUVCpu->vm.s.Halt.Method12.cBlocks++;
667 if (!(pUVCpu->vm.s.Halt.Method12.cBlocks & 0xf))
668 {
669 pUVCpu->vm.s.Halt.Method12.cNSBlockedTooLongAvg = pUVCpu->vm.s.Halt.Method12.cNSBlockedTooLong / pUVCpu->vm.s.Halt.Method12.cBlocks;
670 if (!(pUVCpu->vm.s.Halt.Method12.cBlocks & 0x3f))
671 {
672 pUVCpu->vm.s.Halt.Method12.cNSBlockedTooLong = pUVCpu->vm.s.Halt.Method12.cNSBlockedTooLongAvg * 0x40;
673 pUVCpu->vm.s.Halt.Method12.cBlocks = 0x40;
674 }
675 }
676 //RTLogRelPrintf(" -> %7RU64 ns / %7RI64 ns delta%s\n", Elapsed, Elapsed - u64NanoTS, fBlockOnce ? " (block once)" : "");
677
678 /*
679 * Clear the block once flag if we actually blocked.
680 */
681 if ( fBlockOnce
682 && Elapsed > 100000 /* 0.1 ms */)
683 fBlockOnce = false;
684
685#ifdef VBOX_VMM_TARGET_ARMV8
686 cNsVTimerActivate -= RT_MIN(cNsVTimerActivate, Elapsed);
687 /* Did the vTimer expire? */
688 if (!cNsVTimerActivate)
689 break;
690#endif
691 }
692 }
693 //if (fSpinning) RTLogRelPrintf("spun for %RU64 ns %u loops; lag=%RU64 pct=%d\n", RTTimeNanoTS() - u64Now, cLoops, TMVirtualSyncGetLag(pVM), u32CatchUpPct);
694
695#ifdef VBOX_VMM_TARGET_ARMV8
696 if (fVTimerActive)
697 {
698 if (!cNsVTimerActivate)
699 VMCPU_FF_SET(pVCpu, VMCPU_FF_VTIMER_ACTIVATED);
700
701 TMCpuSetVTimerNextActivation(pVCpu, cNsVTimerActivate);
702 }
703#endif
704 ASMAtomicUoWriteBool(&pUVCpu->vm.s.fWait, false);
705 return rc;
706}
707
708
709/**
710 * Initialize the global 1 halt method.
711 *
712 * @return VBox status code.
713 * @param pUVM Pointer to the user mode VM structure.
714 */
715static DECLCALLBACK(int) vmR3HaltGlobal1Init(PUVM pUVM)
716{
717 /*
718 * The defaults.
719 */
720 uint32_t cNsResolution = SUPSemEventMultiGetResolution(pUVM->vm.s.pSession);
721 if (cNsResolution > 5*RT_NS_100US)
722 pUVM->vm.s.Halt.Global1.cNsSpinBlockThresholdCfg = 50000;
723 else if (cNsResolution > RT_NS_100US)
724 pUVM->vm.s.Halt.Global1.cNsSpinBlockThresholdCfg = cNsResolution / 4;
725 else
726 pUVM->vm.s.Halt.Global1.cNsSpinBlockThresholdCfg = 2000;
727
728 /*
729 * Query overrides.
730 *
731 * I don't have time to bother with niceties such as invalid value checks
732 * here right now. sorry.
733 */
734 PCFGMNODE pCfg = CFGMR3GetChild(CFGMR3GetRoot(pUVM->pVM), "/VMM/HaltedGlobal1");
735 if (pCfg)
736 {
737 uint32_t u32;
738 if (RT_SUCCESS(CFGMR3QueryU32(pCfg, "SpinBlockThreshold", &u32)))
739 pUVM->vm.s.Halt.Global1.cNsSpinBlockThresholdCfg = u32;
740 }
741 LogRel(("VMEmt: HaltedGlobal1 config: cNsSpinBlockThresholdCfg=%u\n",
742 pUVM->vm.s.Halt.Global1.cNsSpinBlockThresholdCfg));
743 return VINF_SUCCESS;
744}
745
746
747/**
748 * The global 1 halt method - Block in GMM (ring-0) and let it
749 * try take care of the global scheduling of EMT threads.
750 */
751static DECLCALLBACK(int) vmR3HaltGlobal1Halt(PUVMCPU pUVCpu, const uint64_t fMask, uint64_t u64Now)
752{
753 PUVM pUVM = pUVCpu->pUVM;
754 PVMCPU pVCpu = pUVCpu->pVCpu;
755 PVM pVM = pUVCpu->pVM;
756 Assert(VMMGetCpu(pVM) == pVCpu);
757 NOREF(u64Now);
758
759 /*
760 * Halt loop.
761 */
762 //uint64_t u64NowLog, u64Start;
763 //u64Start = u64NowLog = RTTimeNanoTS();
764 int rc = VINF_SUCCESS;
765 ASMAtomicWriteBool(&pUVCpu->vm.s.fWait, true);
766 unsigned cLoops = 0;
767 for (;; cLoops++)
768 {
769 /*
770 * Work the timers and check if we can exit.
771 */
772 uint64_t const u64StartTimers = RTTimeNanoTS();
773 TMR3TimerQueuesDo(pVM);
774 uint64_t const cNsElapsedTimers = RTTimeNanoTS() - u64StartTimers;
775 STAM_REL_PROFILE_ADD_PERIOD(&pUVCpu->vm.s.StatHaltTimers, cNsElapsedTimers);
776 if ( VM_FF_IS_ANY_SET(pVM, VM_FF_EXTERNAL_HALTED_MASK)
777 || VMCPU_FF_IS_ANY_SET(pVCpu, fMask))
778 break;
779
780 /*
781 * Estimate time left to the next event.
782 */
783 //u64NowLog = RTTimeNanoTS();
784 uint64_t u64Delta;
785 uint64_t u64GipTime = TMTimerPollGIP(pVM, pVCpu, &u64Delta);
786 if ( VM_FF_IS_ANY_SET(pVM, VM_FF_EXTERNAL_HALTED_MASK)
787 || VMCPU_FF_IS_ANY_SET(pVCpu, fMask))
788 break;
789
790 /*
791 * Block if we're not spinning and the interval isn't all that small.
792 */
793 if (u64Delta >= pUVM->vm.s.Halt.Global1.cNsSpinBlockThresholdCfg)
794 {
795 VMMR3YieldStop(pVM);
796 if ( VM_FF_IS_ANY_SET(pVM, VM_FF_EXTERNAL_HALTED_MASK)
797 || VMCPU_FF_IS_ANY_SET(pVCpu, fMask))
798 break;
799
800 //RTLogPrintf("loop=%-3d u64GipTime=%'llu / %'llu now=%'llu / %'llu\n", cLoops, u64GipTime, u64Delta, u64NowLog, u64GipTime - u64NowLog);
801 uint64_t const u64StartSchedHalt = RTTimeNanoTS();
802 rc = SUPR3CallVMMR0Ex(VMCC_GET_VMR0_FOR_CALL(pVM), pVCpu->idCpu, VMMR0_DO_GVMM_SCHED_HALT, u64GipTime, NULL);
803 uint64_t const u64EndSchedHalt = RTTimeNanoTS();
804 uint64_t const cNsElapsedSchedHalt = u64EndSchedHalt - u64StartSchedHalt;
805 STAM_REL_PROFILE_ADD_PERIOD(&pUVCpu->vm.s.StatHaltBlock, cNsElapsedSchedHalt);
806
807 if (rc == VERR_INTERRUPTED)
808 rc = VINF_SUCCESS;
809 else if (RT_FAILURE(rc))
810 {
811 rc = vmR3FatalWaitError(pUVCpu, "vmR3HaltGlobal1Halt: VMMR0_DO_GVMM_SCHED_HALT->%Rrc\n", rc);
812 break;
813 }
814 else
815 {
816 int64_t const cNsOverslept = u64EndSchedHalt - u64GipTime;
817 if (cNsOverslept > 50000)
818 STAM_REL_PROFILE_ADD_PERIOD(&pUVCpu->vm.s.StatHaltBlockOverslept, cNsOverslept);
819 else if (cNsOverslept < -50000)
820 STAM_REL_PROFILE_ADD_PERIOD(&pUVCpu->vm.s.StatHaltBlockInsomnia, cNsElapsedSchedHalt);
821 else
822 STAM_REL_PROFILE_ADD_PERIOD(&pUVCpu->vm.s.StatHaltBlockOnTime, cNsElapsedSchedHalt);
823 }
824 }
825 /*
826 * When spinning call upon the GVMM and do some wakups once
827 * in a while, it's not like we're actually busy or anything.
828 */
829 else if (!(cLoops & 0x1fff))
830 {
831 uint64_t const u64StartSchedYield = RTTimeNanoTS();
832 rc = SUPR3CallVMMR0Ex(VMCC_GET_VMR0_FOR_CALL(pVM), pVCpu->idCpu, VMMR0_DO_GVMM_SCHED_POLL, false /* don't yield */, NULL);
833 uint64_t const cNsElapsedSchedYield = RTTimeNanoTS() - u64StartSchedYield;
834 STAM_REL_PROFILE_ADD_PERIOD(&pUVCpu->vm.s.StatHaltYield, cNsElapsedSchedYield);
835 }
836 }
837 //RTLogPrintf("*** %u loops %'llu; lag=%RU64\n", cLoops, u64NowLog - u64Start, TMVirtualSyncGetLag(pVM));
838
839 ASMAtomicUoWriteBool(&pUVCpu->vm.s.fWait, false);
840 return rc;
841}
842
843
844/**
845 * The global 1 halt method - VMR3Wait() worker.
846 *
847 * @returns VBox status code.
848 * @param pUVCpu Pointer to the user mode VMCPU structure.
849 */
850static DECLCALLBACK(int) vmR3HaltGlobal1Wait(PUVMCPU pUVCpu)
851{
852 ASMAtomicWriteBool(&pUVCpu->vm.s.fWait, true);
853
854 PVM pVM = pUVCpu->pUVM->pVM;
855 PVMCPU pVCpu = VMMGetCpu(pVM);
856 Assert(pVCpu->idCpu == pUVCpu->idCpu);
857
858 int rc = VINF_SUCCESS;
859 for (;;)
860 {
861 /*
862 * Check Relevant FFs.
863 */
864 if ( VM_FF_IS_ANY_SET(pVM, VM_FF_EXTERNAL_SUSPENDED_MASK)
865 || VMCPU_FF_IS_ANY_SET(pVCpu, VMCPU_FF_EXTERNAL_SUSPENDED_MASK))
866 break;
867
868 /*
869 * Wait for a while. Someone will wake us up or interrupt the call if
870 * anything needs our attention.
871 */
872 rc = SUPR3CallVMMR0Ex(VMCC_GET_VMR0_FOR_CALL(pVM), pVCpu->idCpu, VMMR0_DO_GVMM_SCHED_HALT, RTTimeNanoTS() + 1000000000 /* +1s */, NULL);
873 if (rc == VERR_INTERRUPTED)
874 rc = VINF_SUCCESS;
875 else if (RT_FAILURE(rc))
876 {
877 rc = vmR3FatalWaitError(pUVCpu, "vmR3HaltGlobal1Wait: VMMR0_DO_GVMM_SCHED_HALT->%Rrc\n", rc);
878 break;
879 }
880 }
881
882 ASMAtomicUoWriteBool(&pUVCpu->vm.s.fWait, false);
883 return rc;
884}
885
886
887/**
888 * The global 1 halt method - VMR3NotifyFF() worker.
889 *
890 * @param pUVCpu Pointer to the user mode VMCPU structure.
891 * @param fFlags Notification flags, VMNOTIFYFF_FLAGS_*.
892 */
893static DECLCALLBACK(void) vmR3HaltGlobal1NotifyCpuFF(PUVMCPU pUVCpu, uint32_t fFlags)
894{
895 /*
896 * With ring-0 halting, the fWait flag isn't set, so we have to check the
897 * CPU state to figure out whether to do a wakeup call.
898 */
899 PVMCPU pVCpu = pUVCpu->pVCpu;
900 if (pVCpu)
901 {
902 VMCPUSTATE enmState = VMCPU_GET_STATE(pVCpu);
903 if (enmState == VMCPUSTATE_STARTED_HALTED || pUVCpu->vm.s.fWait)
904 {
905 int rc = SUPR3CallVMMR0Ex(VMCC_GET_VMR0_FOR_CALL(pUVCpu->pVM), pUVCpu->idCpu, VMMR0_DO_GVMM_SCHED_WAKE_UP, 0, NULL);
906 AssertRC(rc);
907
908 }
909 else if ( (fFlags & VMNOTIFYFF_FLAGS_POKE)
910 || !(fFlags & VMNOTIFYFF_FLAGS_DONE_REM))
911 {
912 if (enmState == VMCPUSTATE_STARTED_EXEC)
913 {
914 if (fFlags & VMNOTIFYFF_FLAGS_POKE)
915 {
916 int rc = SUPR3CallVMMR0Ex(VMCC_GET_VMR0_FOR_CALL(pUVCpu->pVM), pUVCpu->idCpu, VMMR0_DO_GVMM_SCHED_POKE, 0, NULL);
917 AssertRC(rc);
918 }
919 }
920 else if ( enmState == VMCPUSTATE_STARTED_EXEC_NEM
921 || enmState == VMCPUSTATE_STARTED_EXEC_NEM_WAIT)
922 NEMR3NotifyFF(pUVCpu->pVM, pVCpu, fFlags);
923 }
924 }
925 /* This probably makes little sense: */
926 else if (pUVCpu->vm.s.fWait)
927 {
928 int rc = SUPR3CallVMMR0Ex(VMCC_GET_VMR0_FOR_CALL(pUVCpu->pVM), pUVCpu->idCpu, VMMR0_DO_GVMM_SCHED_WAKE_UP, 0, NULL);
929 AssertRC(rc);
930 }
931}
932
933
934/**
935 * Bootstrap VMR3Wait() worker.
936 *
937 * @returns VBox status code.
938 * @param pUVCpu Pointer to the user mode VMCPU structure.
939 */
940static DECLCALLBACK(int) vmR3BootstrapWait(PUVMCPU pUVCpu)
941{
942 PUVM pUVM = pUVCpu->pUVM;
943
944 ASMAtomicWriteBool(&pUVCpu->vm.s.fWait, true);
945
946 int rc = VINF_SUCCESS;
947 for (;;)
948 {
949 /*
950 * Check Relevant FFs.
951 */
952 if (pUVM->vm.s.pNormalReqs || pUVM->vm.s.pPriorityReqs) /* global requests pending? */
953 break;
954 if (pUVCpu->vm.s.pNormalReqs || pUVCpu->vm.s.pPriorityReqs) /* local requests pending? */
955 break;
956
957 if ( pUVCpu->pVM
958 && ( VM_FF_IS_ANY_SET(pUVCpu->pVM, VM_FF_EXTERNAL_SUSPENDED_MASK)
959 || VMCPU_FF_IS_ANY_SET(VMMGetCpu(pUVCpu->pVM), VMCPU_FF_EXTERNAL_SUSPENDED_MASK)
960 )
961 )
962 break;
963 if (pUVM->vm.s.fTerminateEMT)
964 break;
965
966 /*
967 * Wait for a while. Someone will wake us up or interrupt the call if
968 * anything needs our attention.
969 */
970 rc = RTSemEventWait(pUVCpu->vm.s.EventSemWait, 1000);
971 if (rc == VERR_TIMEOUT)
972 rc = VINF_SUCCESS;
973 else if (RT_FAILURE(rc))
974 {
975 rc = vmR3FatalWaitError(pUVCpu, "RTSemEventWait->%Rrc\n", rc);
976 break;
977 }
978 }
979
980 ASMAtomicUoWriteBool(&pUVCpu->vm.s.fWait, false);
981 return rc;
982}
983
984
985/**
986 * Bootstrap VMR3NotifyFF() worker.
987 *
988 * @param pUVCpu Pointer to the user mode VMCPU structure.
989 * @param fFlags Notification flags, VMNOTIFYFF_FLAGS_*.
990 */
991static DECLCALLBACK(void) vmR3BootstrapNotifyCpuFF(PUVMCPU pUVCpu, uint32_t fFlags)
992{
993 if (pUVCpu->vm.s.fWait)
994 {
995 int rc = RTSemEventSignal(pUVCpu->vm.s.EventSemWait);
996 AssertRC(rc);
997 }
998 NOREF(fFlags);
999}
1000
1001
1002/**
1003 * Default VMR3Wait() worker.
1004 *
1005 * @returns VBox status code.
1006 * @param pUVCpu Pointer to the user mode VMCPU structure.
1007 */
1008static DECLCALLBACK(int) vmR3DefaultWait(PUVMCPU pUVCpu)
1009{
1010 ASMAtomicWriteBool(&pUVCpu->vm.s.fWait, true);
1011
1012 PVM pVM = pUVCpu->pVM;
1013 PVMCPU pVCpu = pUVCpu->pVCpu;
1014 int rc = VINF_SUCCESS;
1015 for (;;)
1016 {
1017 /*
1018 * Check Relevant FFs.
1019 */
1020 if ( VM_FF_IS_ANY_SET(pVM, VM_FF_EXTERNAL_SUSPENDED_MASK)
1021 || VMCPU_FF_IS_ANY_SET(pVCpu, VMCPU_FF_EXTERNAL_SUSPENDED_MASK))
1022 break;
1023
1024 /*
1025 * Wait for a while. Someone will wake us up or interrupt the call if
1026 * anything needs our attention.
1027 */
1028 rc = RTSemEventWait(pUVCpu->vm.s.EventSemWait, 1000);
1029 if (rc == VERR_TIMEOUT)
1030 rc = VINF_SUCCESS;
1031 else if (RT_FAILURE(rc))
1032 {
1033 rc = vmR3FatalWaitError(pUVCpu, "RTSemEventWait->%Rrc", rc);
1034 break;
1035 }
1036 }
1037
1038 ASMAtomicUoWriteBool(&pUVCpu->vm.s.fWait, false);
1039 return rc;
1040}
1041
1042
1043/**
1044 * Default VMR3NotifyFF() worker.
1045 *
1046 * @param pUVCpu Pointer to the user mode VMCPU structure.
1047 * @param fFlags Notification flags, VMNOTIFYFF_FLAGS_*.
1048 */
1049static DECLCALLBACK(void) vmR3DefaultNotifyCpuFF(PUVMCPU pUVCpu, uint32_t fFlags)
1050{
1051 if (pUVCpu->vm.s.fWait)
1052 {
1053 int rc = RTSemEventSignal(pUVCpu->vm.s.EventSemWait);
1054 AssertRC(rc);
1055 }
1056 else
1057 {
1058 PVMCPU pVCpu = pUVCpu->pVCpu;
1059 if (pVCpu)
1060 {
1061 VMCPUSTATE enmState = pVCpu->enmState;
1062 if ( enmState == VMCPUSTATE_STARTED_EXEC_NEM
1063 || enmState == VMCPUSTATE_STARTED_EXEC_NEM_WAIT)
1064 NEMR3NotifyFF(pUVCpu->pVM, pVCpu, fFlags);
1065 }
1066 }
1067}
1068
1069
1070/**
1071 * Array with halt method descriptors.
1072 * VMINT::iHaltMethod contains an index into this array.
1073 */
1074static const struct VMHALTMETHODDESC
1075{
1076 /** The halt method ID. */
1077 VMHALTMETHOD enmHaltMethod;
1078 /** Set if the method support halting directly in ring-0. */
1079 bool fMayHaltInRing0;
1080 /** The init function for loading config and initialize variables. */
1081 DECLR3CALLBACKMEMBER(int, pfnInit,(PUVM pUVM));
1082 /** The term function. */
1083 DECLR3CALLBACKMEMBER(void, pfnTerm,(PUVM pUVM));
1084 /** The VMR3WaitHaltedU function. */
1085 DECLR3CALLBACKMEMBER(int, pfnHalt,(PUVMCPU pUVCpu, const uint64_t fMask, uint64_t u64Now));
1086 /** The VMR3WaitU function. */
1087 DECLR3CALLBACKMEMBER(int, pfnWait,(PUVMCPU pUVCpu));
1088 /** The VMR3NotifyCpuFFU function. */
1089 DECLR3CALLBACKMEMBER(void, pfnNotifyCpuFF,(PUVMCPU pUVCpu, uint32_t fFlags));
1090 /** The VMR3NotifyGlobalFFU function. */
1091 DECLR3CALLBACKMEMBER(void, pfnNotifyGlobalFF,(PUVM pUVM, uint32_t fFlags));
1092} g_aHaltMethods[] =
1093{
1094 { VMHALTMETHOD_BOOTSTRAP, false, NULL, NULL, NULL, vmR3BootstrapWait, vmR3BootstrapNotifyCpuFF, NULL },
1095 { VMHALTMETHOD_OLD, false, NULL, NULL, vmR3HaltOldDoHalt, vmR3DefaultWait, vmR3DefaultNotifyCpuFF, NULL },
1096 { VMHALTMETHOD_1, false, vmR3HaltMethod1Init, NULL, vmR3HaltMethod1Halt, vmR3DefaultWait, vmR3DefaultNotifyCpuFF, NULL },
1097 { VMHALTMETHOD_GLOBAL_1, true, vmR3HaltGlobal1Init, NULL, vmR3HaltGlobal1Halt, vmR3HaltGlobal1Wait, vmR3HaltGlobal1NotifyCpuFF, NULL },
1098};
1099
1100
1101/**
1102 * Notify the emulation thread (EMT) about pending Forced Action (FF).
1103 *
1104 * This function is called by thread other than EMT to make
1105 * sure EMT wakes up and promptly service an FF request.
1106 *
1107 * @param pUVM Pointer to the user mode VM structure.
1108 * @param fFlags Notification flags, VMNOTIFYFF_FLAGS_*.
1109 * @internal
1110 */
1111VMMR3_INT_DECL(void) VMR3NotifyGlobalFFU(PUVM pUVM, uint32_t fFlags)
1112{
1113 LogFlow(("VMR3NotifyGlobalFFU:\n"));
1114 uint32_t iHaltMethod = pUVM->vm.s.iHaltMethod;
1115
1116 if (g_aHaltMethods[iHaltMethod].pfnNotifyGlobalFF) /** @todo make mandatory. */
1117 g_aHaltMethods[iHaltMethod].pfnNotifyGlobalFF(pUVM, fFlags);
1118 else
1119 for (VMCPUID iCpu = 0; iCpu < pUVM->cCpus; iCpu++)
1120 g_aHaltMethods[iHaltMethod].pfnNotifyCpuFF(&pUVM->aCpus[iCpu], fFlags);
1121}
1122
1123
1124/**
1125 * Notify the emulation thread (EMT) about pending Forced Action (FF).
1126 *
1127 * This function is called by thread other than EMT to make
1128 * sure EMT wakes up and promptly service an FF request.
1129 *
1130 * @param pUVCpu Pointer to the user mode per CPU VM structure.
1131 * @param fFlags Notification flags, VMNOTIFYFF_FLAGS_*.
1132 * @internal
1133 */
1134VMMR3_INT_DECL(void) VMR3NotifyCpuFFU(PUVMCPU pUVCpu, uint32_t fFlags)
1135{
1136 PUVM pUVM = pUVCpu->pUVM;
1137
1138 LogFlow(("VMR3NotifyCpuFFU:\n"));
1139 g_aHaltMethods[pUVM->vm.s.iHaltMethod].pfnNotifyCpuFF(pUVCpu, fFlags);
1140}
1141
1142
1143/**
1144 * Halted VM Wait.
1145 * Any external event will unblock the thread.
1146 *
1147 * @returns VINF_SUCCESS unless a fatal error occurred. In the latter
1148 * case an appropriate status code is returned.
1149 * @param pVM The cross context VM structure.
1150 * @param pVCpu The cross context virtual CPU structure.
1151 * @param fFlags Combination of VMWAITHALTED_F_XXX.
1152 * @thread The emulation thread.
1153 * @remarks Made visible for implementing vmsvga sync register.
1154 * @internal
1155 */
1156VMMR3_INT_DECL(int) VMR3WaitHalted(PVM pVM, PVMCPU pVCpu, uint32_t fFlags)
1157{
1158 LogFlow(("VMR3WaitHalted: fFlags=%#x\n", fFlags));
1159
1160 /*
1161 * Check Relevant FFs.
1162 */
1163#ifdef VBOX_VMM_TARGET_ARMV8
1164 const uint64_t fMaskIrqs = ((fFlags & VMWAITHALTED_F_IGNORE_IRQS) ? VMCPU_FF_INTERRUPT_IRQ : 0)
1165 | ((fFlags & VMWAITHALTED_F_IGNORE_FIQS) ? VMCPU_FF_INTERRUPT_FIQ : 0);
1166 const uint64_t fMask = VMCPU_FF_EXTERNAL_HALTED_MASK & ~fMaskIrqs;
1167#else
1168 const uint64_t fMask = !(fFlags & VMWAITHALTED_F_IGNORE_IRQS)
1169 ? VMCPU_FF_EXTERNAL_HALTED_MASK
1170 : VMCPU_FF_EXTERNAL_HALTED_MASK & ~(VMCPU_FF_UPDATE_APIC | VMCPU_FF_INTERRUPT_APIC | VMCPU_FF_INTERRUPT_PIC);
1171#endif
1172
1173 if ( VM_FF_IS_ANY_SET(pVM, VM_FF_EXTERNAL_HALTED_MASK)
1174 || VMCPU_FF_IS_ANY_SET(pVCpu, fMask))
1175 {
1176 LogFlow(("VMR3WaitHalted: returns VINF_SUCCESS (FF %#x FFCPU %#RX64)\n", pVM->fGlobalForcedActions, (uint64_t)pVCpu->fLocalForcedActions));
1177 return VINF_SUCCESS;
1178 }
1179
1180 /*
1181 * The yielder is suspended while we're halting, while TM might have clock(s) running
1182 * only at certain times and need to be notified..
1183 */
1184 if (pVCpu->idCpu == 0)
1185 VMMR3YieldSuspend(pVM);
1186 TMNotifyStartOfHalt(pVCpu);
1187
1188 /*
1189 * Record halt averages for the last second.
1190 */
1191 PUVMCPU pUVCpu = pVCpu->pUVCpu;
1192 uint64_t u64Now = RTTimeNanoTS();
1193 int64_t off = u64Now - pUVCpu->vm.s.u64HaltsStartTS;
1194 if (off > 1000000000)
1195 {
1196 if (off > _4G || !pUVCpu->vm.s.cHalts)
1197 {
1198 pUVCpu->vm.s.HaltInterval = 1000000000 /* 1 sec */;
1199 pUVCpu->vm.s.HaltFrequency = 1;
1200 }
1201 else
1202 {
1203 pUVCpu->vm.s.HaltInterval = (uint32_t)off / pUVCpu->vm.s.cHalts;
1204 pUVCpu->vm.s.HaltFrequency = ASMMultU64ByU32DivByU32(pUVCpu->vm.s.cHalts, 1000000000, (uint32_t)off);
1205 }
1206 pUVCpu->vm.s.u64HaltsStartTS = u64Now;
1207 pUVCpu->vm.s.cHalts = 0;
1208 }
1209 pUVCpu->vm.s.cHalts++;
1210
1211 /*
1212 * Do the halt.
1213 */
1214 VMCPU_ASSERT_STATE_2(pVCpu, VMCPUSTATE_STARTED, VMCPUSTATE_STARTED_EXEC_NEM);
1215 VMCPUSTATE enmStateOld = VMCPU_GET_STATE(pVCpu);
1216 VMCPU_SET_STATE(pVCpu, VMCPUSTATE_STARTED_HALTED);
1217 PUVM pUVM = pUVCpu->pUVM;
1218 int rc = g_aHaltMethods[pUVM->vm.s.iHaltMethod].pfnHalt(pUVCpu, fMask, u64Now);
1219 VMCPU_SET_STATE(pVCpu, enmStateOld);
1220
1221 /*
1222 * Notify TM and resume the yielder
1223 */
1224 TMNotifyEndOfHalt(pVCpu);
1225 if (pVCpu->idCpu == 0)
1226 VMMR3YieldResume(pVM);
1227
1228 LogFlow(("VMR3WaitHalted: returns %Rrc (FF %#x)\n", rc, pVM->fGlobalForcedActions));
1229 return rc;
1230}
1231
1232
1233/**
1234 * Suspended VM Wait.
1235 * Only a handful of forced actions will cause the function to
1236 * return to the caller.
1237 *
1238 * @returns VINF_SUCCESS unless a fatal error occurred. In the latter
1239 * case an appropriate status code is returned.
1240 * @param pUVCpu Pointer to the user mode VMCPU structure.
1241 * @thread The emulation thread.
1242 * @internal
1243 */
1244VMMR3_INT_DECL(int) VMR3WaitU(PUVMCPU pUVCpu)
1245{
1246 LogFlow(("VMR3WaitU:\n"));
1247
1248 /*
1249 * Check Relevant FFs.
1250 */
1251 PVM pVM = pUVCpu->pVM;
1252 PVMCPU pVCpu = pUVCpu->pVCpu;
1253
1254 if ( pVM
1255 && ( VM_FF_IS_ANY_SET(pVM, VM_FF_EXTERNAL_SUSPENDED_MASK)
1256 || VMCPU_FF_IS_ANY_SET(pVCpu, VMCPU_FF_EXTERNAL_SUSPENDED_MASK)
1257 )
1258 )
1259 {
1260 LogFlow(("VMR3Wait: returns VINF_SUCCESS (FF %#x)\n", pVM->fGlobalForcedActions));
1261 return VINF_SUCCESS;
1262 }
1263
1264 /*
1265 * Do waiting according to the halt method (so VMR3NotifyFF
1266 * doesn't have to special case anything).
1267 */
1268 PUVM pUVM = pUVCpu->pUVM;
1269 int rc = g_aHaltMethods[pUVM->vm.s.iHaltMethod].pfnWait(pUVCpu);
1270 LogFlow(("VMR3WaitU: returns %Rrc (FF %#x)\n", rc, pUVM->pVM ? pUVM->pVM->fGlobalForcedActions : 0));
1271 return rc;
1272}
1273
1274
1275/**
1276 * Interface that PDMR3Suspend, PDMR3PowerOff and PDMR3Reset uses when they wait
1277 * for the handling of asynchronous notifications to complete.
1278 *
1279 * @returns VINF_SUCCESS unless a fatal error occurred. In the latter
1280 * case an appropriate status code is returned.
1281 * @param pUVCpu Pointer to the user mode VMCPU structure.
1282 * @thread The emulation thread.
1283 */
1284VMMR3_INT_DECL(int) VMR3AsyncPdmNotificationWaitU(PUVMCPU pUVCpu)
1285{
1286 LogFlow(("VMR3AsyncPdmNotificationWaitU:\n"));
1287 return VMR3WaitU(pUVCpu);
1288}
1289
1290
1291/**
1292 * Interface that PDM the helper asynchronous notification completed methods
1293 * uses for EMT0 when it is waiting inside VMR3AsyncPdmNotificationWaitU().
1294 *
1295 * @param pUVM Pointer to the user mode VM structure.
1296 */
1297VMMR3_INT_DECL(void) VMR3AsyncPdmNotificationWakeupU(PUVM pUVM)
1298{
1299 LogFlow(("VMR3AsyncPdmNotificationWakeupU:\n"));
1300 VM_FF_SET(pUVM->pVM, VM_FF_REQUEST); /* this will have to do for now. */
1301 g_aHaltMethods[pUVM->vm.s.iHaltMethod].pfnNotifyCpuFF(&pUVM->aCpus[0], 0 /*fFlags*/);
1302}
1303
1304
1305/**
1306 * Rendezvous callback that will be called once.
1307 *
1308 * @returns VBox strict status code.
1309 * @param pVM The cross context VM structure.
1310 * @param pVCpu The cross context virtual CPU structure of the calling EMT.
1311 * @param pvUser The new g_aHaltMethods index.
1312 */
1313static DECLCALLBACK(VBOXSTRICTRC) vmR3SetHaltMethodCallback(PVM pVM, PVMCPU pVCpu, void *pvUser)
1314{
1315 PUVM pUVM = pVM->pUVM;
1316 int rc = VINF_SUCCESS;
1317 uintptr_t i = (uintptr_t)pvUser;
1318 Assert(i < RT_ELEMENTS(g_aHaltMethods));
1319
1320 /*
1321 * Main job is done once on EMT0 (it goes thru here first).
1322 */
1323 if (pVCpu->idCpu == 0)
1324 {
1325 /*
1326 * Terminate the old one.
1327 */
1328 if ( pUVM->vm.s.enmHaltMethod != VMHALTMETHOD_INVALID
1329 && g_aHaltMethods[pUVM->vm.s.iHaltMethod].pfnTerm)
1330 {
1331 g_aHaltMethods[pUVM->vm.s.iHaltMethod].pfnTerm(pUVM);
1332 pUVM->vm.s.enmHaltMethod = VMHALTMETHOD_INVALID;
1333 }
1334
1335 /* Assert that the failure fallback is where we expect. */
1336 Assert(g_aHaltMethods[0].enmHaltMethod == VMHALTMETHOD_BOOTSTRAP);
1337 Assert(!g_aHaltMethods[0].pfnTerm && !g_aHaltMethods[0].pfnInit);
1338
1339 /*
1340 * Init the new one.
1341 */
1342 memset(&pUVM->vm.s.Halt, 0, sizeof(pUVM->vm.s.Halt));
1343 if (g_aHaltMethods[i].pfnInit)
1344 {
1345 rc = g_aHaltMethods[i].pfnInit(pUVM);
1346 if (RT_FAILURE(rc))
1347 {
1348 /* Fall back on the bootstrap method. This requires no
1349 init/term (see assertion above), and will always work. */
1350 AssertLogRelRC(rc);
1351 i = 0;
1352 }
1353 }
1354
1355 /*
1356 * Commit it.
1357 */
1358 pUVM->vm.s.enmHaltMethod = g_aHaltMethods[i].enmHaltMethod;
1359 ASMAtomicWriteU32(&pUVM->vm.s.iHaltMethod, i);
1360 }
1361 else
1362 i = pUVM->vm.s.iHaltMethod;
1363
1364 /*
1365 * All EMTs must update their ring-0 halt configuration.
1366 */
1367 VMMR3SetMayHaltInRing0(pVCpu, g_aHaltMethods[i].fMayHaltInRing0,
1368 g_aHaltMethods[i].enmHaltMethod == VMHALTMETHOD_GLOBAL_1
1369 ? pUVM->vm.s.Halt.Global1.cNsSpinBlockThresholdCfg : 0);
1370
1371 return rc;
1372}
1373
1374
1375/**
1376 * Changes the halt method.
1377 *
1378 * @returns VBox status code.
1379 * @param pUVM Pointer to the user mode VM structure.
1380 * @param enmHaltMethod The new halt method.
1381 * @thread EMT.
1382 */
1383int vmR3SetHaltMethodU(PUVM pUVM, VMHALTMETHOD enmHaltMethod)
1384{
1385 PVM pVM = pUVM->pVM; Assert(pVM);
1386 VM_ASSERT_EMT(pVM);
1387 AssertReturn(enmHaltMethod > VMHALTMETHOD_INVALID && enmHaltMethod < VMHALTMETHOD_END, VERR_INVALID_PARAMETER);
1388
1389 /*
1390 * Resolve default (can be overridden in the configuration).
1391 */
1392 if (enmHaltMethod == VMHALTMETHOD_DEFAULT)
1393 {
1394 uint32_t u32;
1395 int rc = CFGMR3QueryU32(CFGMR3GetChild(CFGMR3GetRoot(pVM), "VM"), "HaltMethod", &u32);
1396 if (RT_SUCCESS(rc))
1397 {
1398 enmHaltMethod = (VMHALTMETHOD)u32;
1399 if (enmHaltMethod <= VMHALTMETHOD_INVALID || enmHaltMethod >= VMHALTMETHOD_END)
1400 return VMSetError(pVM, VERR_INVALID_PARAMETER, RT_SRC_POS, N_("Invalid VM/HaltMethod value %d"), enmHaltMethod);
1401 }
1402 else if (rc == VERR_CFGM_VALUE_NOT_FOUND || rc == VERR_CFGM_CHILD_NOT_FOUND)
1403 return VMSetError(pVM, rc, RT_SRC_POS, N_("Failed to Query VM/HaltMethod as uint32_t"));
1404 else
1405 enmHaltMethod = VMHALTMETHOD_GLOBAL_1;
1406 //enmHaltMethod = VMHALTMETHOD_1;
1407 //enmHaltMethod = VMHALTMETHOD_OLD;
1408 }
1409
1410 /*
1411 * The global halt method doesn't work in driverless mode, so fall back on
1412 * method #1 instead.
1413 */
1414 if (!SUPR3IsDriverless() || enmHaltMethod != VMHALTMETHOD_GLOBAL_1)
1415 LogRel(("VMEmt: Halt method %s (%d)\n", vmR3GetHaltMethodName(enmHaltMethod), enmHaltMethod));
1416 else
1417 {
1418 LogRel(("VMEmt: Halt method %s (%d) not available in driverless mode, using %s (%d) instead\n",
1419 vmR3GetHaltMethodName(enmHaltMethod), enmHaltMethod, vmR3GetHaltMethodName(VMHALTMETHOD_1), VMHALTMETHOD_1));
1420 enmHaltMethod = VMHALTMETHOD_1;
1421 }
1422
1423
1424 /*
1425 * Find the descriptor.
1426 */
1427 unsigned i = 0;
1428 while ( i < RT_ELEMENTS(g_aHaltMethods)
1429 && g_aHaltMethods[i].enmHaltMethod != enmHaltMethod)
1430 i++;
1431 AssertReturn(i < RT_ELEMENTS(g_aHaltMethods), VERR_INVALID_PARAMETER);
1432
1433 /*
1434 * This needs to be done while the other EMTs are not sleeping or otherwise messing around.
1435 */
1436 return VMMR3EmtRendezvous(pVM, VMMEMTRENDEZVOUS_FLAGS_TYPE_ASCENDING, vmR3SetHaltMethodCallback, (void *)(uintptr_t)i);
1437}
1438
1439
1440/**
1441 * Special interface for implementing a HLT-like port on a device.
1442 *
1443 * This can be called directly from device code, provide the device is trusted
1444 * to access the VMM directly. Since we may not have an accurate register set
1445 * and the caller certainly shouldn't (device code does not access CPU
1446 * registers), this function will return when interrupts are pending regardless
1447 * of the actual EFLAGS.IF state.
1448 *
1449 * @returns VBox error status (never informational statuses).
1450 * @param pVM The cross context VM structure.
1451 * @param idCpu The id of the calling EMT.
1452 */
1453VMMR3DECL(int) VMR3WaitForDeviceReady(PVM pVM, VMCPUID idCpu)
1454{
1455 /*
1456 * Validate caller and resolve the CPU ID.
1457 */
1458 VM_ASSERT_VALID_EXT_RETURN(pVM, VERR_INVALID_VM_HANDLE);
1459 AssertReturn(idCpu < pVM->cCpus, VERR_INVALID_CPU_ID);
1460 PVMCPU pVCpu = pVM->apCpusR3[idCpu];
1461 VMCPU_ASSERT_EMT_RETURN(pVCpu, VERR_VM_THREAD_NOT_EMT);
1462
1463 /*
1464 * Tag along with the HLT mechanics for now.
1465 */
1466 int rc = VMR3WaitHalted(pVM, pVCpu, false /*fIgnoreInterrupts*/);
1467 if (RT_SUCCESS(rc))
1468 return VINF_SUCCESS;
1469 return rc;
1470}
1471
1472
1473/**
1474 * Wakes up a CPU that has called VMR3WaitForDeviceReady.
1475 *
1476 * @returns VBox error status (never informational statuses).
1477 * @param pVM The cross context VM structure.
1478 * @param idCpu The id of the calling EMT.
1479 */
1480VMMR3DECL(int) VMR3NotifyCpuDeviceReady(PVM pVM, VMCPUID idCpu)
1481{
1482 /*
1483 * Validate caller and resolve the CPU ID.
1484 */
1485 VM_ASSERT_VALID_EXT_RETURN(pVM, VERR_INVALID_VM_HANDLE);
1486 AssertReturn(idCpu < pVM->cCpus, VERR_INVALID_CPU_ID);
1487 PVMCPU pVCpu = pVM->apCpusR3[idCpu];
1488
1489 /*
1490 * Pretend it was an FF that got set since we've got logic for that already.
1491 */
1492 VMR3NotifyCpuFFU(pVCpu->pUVCpu, VMNOTIFYFF_FLAGS_DONE_REM);
1493 return VINF_SUCCESS;
1494}
1495
1496
1497/**
1498 * Returns the number of active EMTs.
1499 *
1500 * This is used by the rendezvous code during VM destruction to avoid waiting
1501 * for EMTs that aren't around any more.
1502 *
1503 * @returns Number of active EMTs. 0 if invalid parameter.
1504 * @param pUVM The user mode VM structure.
1505 */
1506VMMR3_INT_DECL(uint32_t) VMR3GetActiveEmts(PUVM pUVM)
1507{
1508 UVM_ASSERT_VALID_EXT_RETURN(pUVM, 0);
1509 return pUVM->vm.s.cActiveEmts;
1510}
1511
Note: See TracBrowser for help on using the repository browser.

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