VirtualBox

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

Last change on this file since 73494 was 71129, checked in by vboxsync, 7 years ago

VMM/NEM/win: Reimplemented virtual process API, optimizing the cancel case and prepping for doing this from ring-0. bugref:9044

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