VirtualBox

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

Last change on this file since 80239 was 80191, checked in by vboxsync, 5 years ago

VMM/r3: Refactored VMCPU enumeration in preparation that aCpus will be replaced with a pointer array. Removed two raw-mode offset members from the CPUM and CPUMCPU sub-structures. bugref:9217 bugref:9517

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