VirtualBox

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

Last change on this file since 94884 was 93115, checked in by vboxsync, 3 years ago

scm --update-copyright-year

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