VirtualBox

source: vbox/trunk/src/VBox/VMM/VM.cpp@ 19420

Last change on this file since 19420 was 19416, checked in by vboxsync, 15 years ago

Wrong return code in vmR3PowerOff for VCPUs

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 107.0 KB
Line 
1/* $Id: VM.cpp 19416 2009-05-06 09:09:51Z vboxsync $ */
2/** @file
3 * VM - Virtual Machine
4 */
5
6/*
7 * Copyright (C) 2006-2007 Sun Microsystems, Inc.
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 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
18 * Clara, CA 95054 USA or visit http://www.sun.com if you need
19 * additional information or have any questions.
20 */
21
22/** @page pg_vm VM API
23 *
24 * This is the encapsulating bit. It provides the APIs that Main and VBoxBFE
25 * use to create a VMM instance for running a guest in. It also provides
26 * facilities for queuing request for execution in EMT (serialization purposes
27 * mostly) and for reporting error back to the VMM user (Main/VBoxBFE).
28 *
29 *
30 * @section sec_vm_design Design Critique / Things To Do
31 *
32 * In hindsight this component is a big design mistake, all this stuff really
33 * belongs in the VMM component. It just seemed like a kind of ok idea at a
34 * time when the VMM bit was a bit vague. 'VM' also happend to be the name of
35 * the per-VM instance structure (see vm.h), so it kind of made sense. However
36 * as it turned out, VMM(.cpp) is almost empty all it provides in ring-3 is some
37 * minor functionally and some "routing" services.
38 *
39 * Fixing this is just a matter of some more or less straight forward
40 * refactoring, the question is just when someone will get to it.
41 *
42 */
43
44/*******************************************************************************
45* Header Files *
46*******************************************************************************/
47#define LOG_GROUP LOG_GROUP_VM
48#include <VBox/cfgm.h>
49#include <VBox/vmm.h>
50#include <VBox/gvmm.h>
51#include <VBox/mm.h>
52#include <VBox/cpum.h>
53#include <VBox/selm.h>
54#include <VBox/trpm.h>
55#include <VBox/dbgf.h>
56#include <VBox/pgm.h>
57#include <VBox/pdmapi.h>
58#include <VBox/pdmcritsect.h>
59#include <VBox/em.h>
60#include <VBox/rem.h>
61#include <VBox/tm.h>
62#include <VBox/stam.h>
63#include <VBox/patm.h>
64#ifdef VBOX_WITH_VMI
65# include <VBox/parav.h>
66#endif
67#include <VBox/csam.h>
68#include <VBox/iom.h>
69#include <VBox/ssm.h>
70#include <VBox/hwaccm.h>
71#include "VMInternal.h"
72#include <VBox/vm.h>
73#include <VBox/uvm.h>
74
75#include <VBox/sup.h>
76#include <VBox/dbg.h>
77#include <VBox/err.h>
78#include <VBox/param.h>
79#include <VBox/log.h>
80#include <iprt/assert.h>
81#include <iprt/alloc.h>
82#include <iprt/asm.h>
83#include <iprt/env.h>
84#include <iprt/string.h>
85#include <iprt/time.h>
86#include <iprt/semaphore.h>
87#include <iprt/thread.h>
88
89
90/*******************************************************************************
91* Structures and Typedefs *
92*******************************************************************************/
93/**
94 * VM destruction callback registration record.
95 */
96typedef struct VMATDTOR
97{
98 /** Pointer to the next record in the list. */
99 struct VMATDTOR *pNext;
100 /** Pointer to the callback function. */
101 PFNVMATDTOR pfnAtDtor;
102 /** The user argument. */
103 void *pvUser;
104} VMATDTOR;
105/** Pointer to a VM destruction callback registration record. */
106typedef VMATDTOR *PVMATDTOR;
107
108
109/*******************************************************************************
110* Global Variables *
111*******************************************************************************/
112/** Pointer to the list of VMs. */
113static PUVM g_pUVMsHead = NULL;
114
115/** Pointer to the list of at VM destruction callbacks. */
116static PVMATDTOR g_pVMAtDtorHead = NULL;
117/** Lock the g_pVMAtDtorHead list. */
118#define VM_ATDTOR_LOCK() do { } while (0)
119/** Unlock the g_pVMAtDtorHead list. */
120#define VM_ATDTOR_UNLOCK() do { } while (0)
121
122
123/*******************************************************************************
124* Internal Functions *
125*******************************************************************************/
126static int vmR3CreateUVM(uint32_t cCPUs, PUVM *ppUVM);
127static int vmR3CreateU(PUVM pUVM, uint32_t cCPUs, PFNCFGMCONSTRUCTOR pfnCFGMConstructor, void *pvUserCFGM);
128static int vmR3InitRing3(PVM pVM, PUVM pUVM);
129static int vmR3InitVMCpu(PVM pVM);
130static int vmR3InitRing0(PVM pVM);
131static int vmR3InitGC(PVM pVM);
132static int vmR3InitDoCompleted(PVM pVM, VMINITCOMPLETED enmWhat);
133static DECLCALLBACK(int) vmR3PowerOn(PVM pVM);
134static DECLCALLBACK(int) vmR3Suspend(PVM pVM);
135static DECLCALLBACK(int) vmR3Resume(PVM pVM);
136static DECLCALLBACK(int) vmR3Save(PVM pVM, const char *pszFilename, PFNVMPROGRESS pfnProgress, void *pvUser);
137static DECLCALLBACK(int) vmR3Load(PVM pVM, const char *pszFilename, PFNVMPROGRESS pfnProgress, void *pvUser);
138static DECLCALLBACK(int) vmR3PowerOff(PVM pVM);
139static void vmR3DestroyUVM(PUVM pUVM, uint32_t cMilliesEMTWait);
140static void vmR3AtDtor(PVM pVM);
141static int vmR3AtResetU(PUVM pUVM);
142static DECLCALLBACK(int) vmR3Reset(PVM pVM);
143static DECLCALLBACK(int) vmR3AtStateRegisterU(PUVM pUVM, PFNVMATSTATE pfnAtState, void *pvUser);
144static DECLCALLBACK(int) vmR3AtStateDeregisterU(PUVM pUVM, PFNVMATSTATE pfnAtState, void *pvUser);
145static DECLCALLBACK(int) vmR3AtErrorRegisterU(PUVM pUVM, PFNVMATERROR pfnAtError, void *pvUser);
146static DECLCALLBACK(int) vmR3AtErrorDeregisterU(PUVM pUVM, PFNVMATERROR pfnAtError, void *pvUser);
147static int vmR3SetErrorU(PUVM pUVM, int rc, RT_SRC_POS_DECL, const char *pszFormat, ...);
148static DECLCALLBACK(int) vmR3AtRuntimeErrorRegisterU(PUVM pUVM, PFNVMATRUNTIMEERROR pfnAtRuntimeError, void *pvUser);
149static DECLCALLBACK(int) vmR3AtRuntimeErrorDeregisterU(PUVM pUVM, PFNVMATRUNTIMEERROR pfnAtRuntimeError, void *pvUser);
150
151
152/**
153 * Do global VMM init.
154 *
155 * @returns VBox status code.
156 */
157VMMR3DECL(int) VMR3GlobalInit(void)
158{
159 /*
160 * Only once.
161 */
162 static bool volatile s_fDone = false;
163 if (s_fDone)
164 return VINF_SUCCESS;
165
166 /*
167 * We're done.
168 */
169 s_fDone = true;
170 return VINF_SUCCESS;
171}
172
173
174
175/**
176 * Creates a virtual machine by calling the supplied configuration constructor.
177 *
178 * On successful returned the VM is powered, i.e. VMR3PowerOn() should be
179 * called to start the execution.
180 *
181 * @returns 0 on success.
182 * @returns VBox error code on failure.
183 * @param cCPUs Number of virtual CPUs for the new VM.
184 * @param pfnVMAtError Pointer to callback function for setting VM
185 * errors. This was added as an implicit call to
186 * VMR3AtErrorRegister() since there is no way the
187 * caller can get to the VM handle early enough to
188 * do this on its own.
189 * This is called in the context of an EMT.
190 * @param pvUserVM The user argument passed to pfnVMAtError.
191 * @param pfnCFGMConstructor Pointer to callback function for constructing the VM configuration tree.
192 * This is called in the context of an EMT0.
193 * @param pvUserCFGM The user argument passed to pfnCFGMConstructor.
194 * @param ppVM Where to store the 'handle' of the created VM.
195 */
196VMMR3DECL(int) VMR3Create(uint32_t cCPUs, PFNVMATERROR pfnVMAtError, void *pvUserVM, PFNCFGMCONSTRUCTOR pfnCFGMConstructor, void *pvUserCFGM, PVM *ppVM)
197{
198 LogFlow(("VMR3Create: cCPUs=%RU32 pfnVMAtError=%p pvUserVM=%p pfnCFGMConstructor=%p pvUserCFGM=%p ppVM=%p\n", cCPUs, pfnVMAtError, pvUserVM, pfnCFGMConstructor, pvUserCFGM, ppVM));
199
200 /*
201 * Because of the current hackiness of the applications
202 * we'll have to initialize global stuff from here.
203 * Later the applications will take care of this in a proper way.
204 */
205 static bool fGlobalInitDone = false;
206 if (!fGlobalInitDone)
207 {
208 int rc = VMR3GlobalInit();
209 if (RT_FAILURE(rc))
210 return rc;
211 fGlobalInitDone = true;
212 }
213
214 /*
215 * Validate input.
216 */
217 AssertLogRelMsgReturn(cCPUs > 0 && cCPUs <= VMM_MAX_CPU_COUNT, ("%RU32\n", cCPUs), VERR_INVALID_PARAMETER);
218
219 /*
220 * Create the UVM so we can register the at-error callback
221 * and consoliate a bit of cleanup code.
222 */
223 PUVM pUVM;
224 int rc = vmR3CreateUVM(cCPUs, &pUVM);
225 if (RT_FAILURE(rc))
226 return rc;
227 if (pfnVMAtError)
228 rc = VMR3AtErrorRegisterU(pUVM, pfnVMAtError, pvUserVM);
229 if (RT_SUCCESS(rc))
230 {
231 /*
232 * Initialize the support library creating the session for this VM.
233 */
234 rc = SUPR3Init(&pUVM->vm.s.pSession);
235 if (RT_SUCCESS(rc))
236 {
237 /*
238 * Call vmR3CreateU in the EMT thread and wait for it to finish.
239 *
240 * Note! VMCPUID_ANY is used here because VMR3ReqQueueU would have trouble
241 * submitting a request to a specific VCPU without a pVM. So, to make
242 * sure init is running on EMT(0), vmR3EmulationThreadWithId makes sure
243 * that only EMT(0) is servicing VMCPUID_ANY requests when pVM is NULL.
244 */
245 PVMREQ pReq;
246 rc = VMR3ReqCallU(pUVM, VMCPUID_ANY, &pReq, RT_INDEFINITE_WAIT, 0, (PFNRT)vmR3CreateU, 4,
247 pUVM, cCPUs, pfnCFGMConstructor, pvUserCFGM);
248 if (RT_SUCCESS(rc))
249 {
250 rc = pReq->iStatus;
251 VMR3ReqFree(pReq);
252 if (RT_SUCCESS(rc))
253 {
254 /*
255 * Success!
256 */
257 *ppVM = pUVM->pVM;
258 LogFlow(("VMR3Create: returns VINF_SUCCESS *ppVM=%p\n", *ppVM));
259 return VINF_SUCCESS;
260 }
261 }
262 else
263 AssertMsgFailed(("VMR3ReqCall failed rc=%Rrc\n", rc));
264
265 /*
266 * An error occurred during VM creation. Set the error message directly
267 * using the initial callback, as the callback list doesn't exist yet.
268 */
269 const char *pszError = NULL;
270 switch (rc)
271 {
272 case VERR_VMX_IN_VMX_ROOT_MODE:
273#ifdef RT_OS_LINUX
274 pszError = N_("VirtualBox can't operate in VMX root mode. "
275 "Please disable the KVM kernel extension, recompile your kernel and reboot");
276#else
277 pszError = N_("VirtualBox can't operate in VMX root mode. Please close all other virtualization programs.");
278#endif
279 break;
280
281 case VERR_VERSION_MISMATCH:
282 pszError = N_("VMMR0 driver version mismatch. Please terminate all VMs, make sure that "
283 "VBoxNetDHCP is not running and try again. If you still get this error, "
284 "re-install VirtualBox");
285 break;
286
287 default:
288 pszError = N_("Unknown error creating VM");
289 break;
290 }
291 vmR3SetErrorU(pUVM, rc, RT_SRC_POS, pszError, rc);
292 }
293 else
294 {
295 /*
296 * An error occurred at support library initialization time (before the
297 * VM could be created). Set the error message directly using the
298 * initial callback, as the callback list doesn't exist yet.
299 */
300 const char *pszError;
301 switch (rc)
302 {
303 case VERR_VM_DRIVER_LOAD_ERROR:
304#ifdef RT_OS_LINUX
305 pszError = N_("VirtualBox kernel driver not loaded. The vboxdrv kernel module "
306 "was either not loaded or /dev/vboxdrv is not set up properly. "
307 "Re-setup the kernel module by executing "
308 "'/etc/init.d/vboxdrv setup' as root");
309#else
310 pszError = N_("VirtualBox kernel driver not loaded");
311#endif
312 break;
313 case VERR_VM_DRIVER_OPEN_ERROR:
314 pszError = N_("VirtualBox kernel driver cannot be opened");
315 break;
316 case VERR_VM_DRIVER_NOT_ACCESSIBLE:
317#ifdef VBOX_WITH_HARDENING
318 /* This should only happen if the executable wasn't hardened - bad code/build. */
319 pszError = N_("VirtualBox kernel driver not accessible, permission problem. "
320 "Re-install VirtualBox. If you are building it yourself, you "
321 "should make sure it installed correctly and that the setuid "
322 "bit is set on the executables calling VMR3Create.");
323#else
324 /* This should only happen when mixing builds or with the usual /dev/vboxdrv access issues. */
325# if defined(RT_OS_DARWIN)
326 pszError = N_("VirtualBox KEXT is not accessible, permission problem. "
327 "If you have built VirtualBox yourself, make sure that you do not "
328 "have the vboxdrv KEXT from a different build or installation loaded.");
329# elif defined(RT_OS_LINUX)
330 pszError = N_("VirtualBox kernel driver is not accessible, permission problem. "
331 "If you have built VirtualBox yourself, make sure that you do "
332 "not have the vboxdrv kernel module from a different build or "
333 "installation loaded. Also, make sure the vboxdrv udev rule gives "
334 "you the permission you need to access the device.");
335# elif defined(RT_OS_WINDOWS)
336 pszError = N_("VirtualBox kernel driver is not accessible, permission problem.");
337# else /* solaris, freebsd, ++. */
338 pszError = N_("VirtualBox kernel module is not accessible, permission problem. "
339 "If you have built VirtualBox yourself, make sure that you do "
340 "not have the vboxdrv kernel module from a different install loaded.");
341# endif
342#endif
343 break;
344 case VERR_INVALID_HANDLE: /** @todo track down and fix this error. */
345 case VERR_VM_DRIVER_NOT_INSTALLED:
346#ifdef RT_OS_LINUX
347 pszError = N_("VirtualBox kernel driver not installed. The vboxdrv kernel module "
348 "was either not loaded or /dev/vboxdrv was not created for some "
349 "reason. Re-setup the kernel module by executing "
350 "'/etc/init.d/vboxdrv setup' as root");
351#else
352 pszError = N_("VirtualBox kernel driver not installed");
353#endif
354 break;
355 case VERR_NO_MEMORY:
356 pszError = N_("VirtualBox support library out of memory");
357 break;
358 case VERR_VERSION_MISMATCH:
359 case VERR_VM_DRIVER_VERSION_MISMATCH:
360 pszError = N_("The VirtualBox support driver which is running is from a different "
361 "version of VirtualBox. You can correct this by stopping all "
362 "running instances of VirtualBox and reinstalling the software.");
363 break;
364 default:
365 pszError = N_("Unknown error initializing kernel driver");
366 AssertMsgFailed(("Add error message for rc=%d (%Rrc)\n", rc, rc));
367 }
368 vmR3SetErrorU(pUVM, rc, RT_SRC_POS, pszError, rc);
369 }
370 }
371
372 /* cleanup */
373 vmR3DestroyUVM(pUVM, 2000);
374 LogFlow(("VMR3Create: returns %Rrc\n", rc));
375 return rc;
376}
377
378
379/**
380 * Creates the UVM.
381 *
382 * This will not initialize the support library even if vmR3DestroyUVM
383 * will terminate that.
384 *
385 * @returns VBox status code.
386 * @param cCpus Number of virtual CPUs
387 * @param ppUVM Where to store the UVM pointer.
388 */
389static int vmR3CreateUVM(uint32_t cCpus, PUVM *ppUVM)
390{
391 uint32_t i;
392
393 /*
394 * Create and initialize the UVM.
395 */
396 PUVM pUVM = (PUVM)RTMemAllocZ(RT_OFFSETOF(UVM, aCpus[cCpus]));
397 AssertReturn(pUVM, VERR_NO_MEMORY);
398 pUVM->u32Magic = UVM_MAGIC;
399 pUVM->cCpus = cCpus;
400
401 AssertCompile(sizeof(pUVM->vm.s) <= sizeof(pUVM->vm.padding));
402
403 pUVM->vm.s.ppAtResetNext = &pUVM->vm.s.pAtReset;
404 pUVM->vm.s.ppAtStateNext = &pUVM->vm.s.pAtState;
405 pUVM->vm.s.ppAtErrorNext = &pUVM->vm.s.pAtError;
406 pUVM->vm.s.ppAtRuntimeErrorNext = &pUVM->vm.s.pAtRuntimeError;
407
408 pUVM->vm.s.enmHaltMethod = VMHALTMETHOD_BOOTSTRAP;
409
410 /* Initialize the VMCPU array in the UVM. */
411 for (i = 0; i < cCpus; i++)
412 {
413 pUVM->aCpus[i].pUVM = pUVM;
414 pUVM->aCpus[i].idCpu = i;
415 }
416
417 /* Allocate a TLS entry to store the VMINTUSERPERVMCPU pointer. */
418 int rc = RTTlsAllocEx(&pUVM->vm.s.idxTLS, NULL);
419 AssertRC(rc);
420 if (RT_SUCCESS(rc))
421 {
422 /* Allocate a halt method event semaphore for each VCPU. */
423 for (i = 0; i < cCpus; i++)
424 {
425 rc = RTSemEventCreate(&pUVM->aCpus[i].vm.s.EventSemWait);
426 if (RT_FAILURE(rc))
427 break;
428 }
429
430 if (RT_SUCCESS(rc))
431 {
432 /*
433 * Init fundamental (sub-)components - STAM, MMR3Heap and PDMLdr.
434 */
435 rc = STAMR3InitUVM(pUVM);
436 if (RT_SUCCESS(rc))
437 {
438 rc = MMR3InitUVM(pUVM);
439 if (RT_SUCCESS(rc))
440 {
441 rc = PDMR3InitUVM(pUVM);
442 if (RT_SUCCESS(rc))
443 {
444 /*
445 * Start the emulation threads for all VMCPUs.
446 */
447 for (i = 0; i < cCpus; i++)
448 {
449 rc = RTThreadCreate(&pUVM->aCpus[i].vm.s.ThreadEMT, vmR3EmulationThread, &pUVM->aCpus[i], _1M,
450 RTTHREADTYPE_EMULATION, RTTHREADFLAGS_WAITABLE, "EMT");
451 if (RT_FAILURE(rc))
452 break;
453
454 pUVM->aCpus[i].vm.s.NativeThreadEMT = RTThreadGetNative(pUVM->aCpus[i].vm.s.ThreadEMT);
455 }
456
457 if (RT_SUCCESS(rc))
458 {
459 *ppUVM = pUVM;
460 return VINF_SUCCESS;
461 }
462
463 /* bail out. */
464 while (i-- > 0)
465 {
466 /** @todo rainy day: terminate the EMTs. */
467 }
468 PDMR3TermUVM(pUVM);
469 }
470 MMR3TermUVM(pUVM);
471 }
472 STAMR3TermUVM(pUVM);
473 }
474 for (i = 0; i < cCpus; i++)
475 {
476 RTSemEventDestroy(pUVM->aCpus[i].vm.s.EventSemWait);
477 pUVM->aCpus[i].vm.s.EventSemWait = NIL_RTSEMEVENT;
478 }
479 }
480 RTTlsFree(pUVM->vm.s.idxTLS);
481 }
482 RTMemFree(pUVM);
483 return rc;
484}
485
486
487/**
488 * Creates and initializes the VM.
489 *
490 * @thread EMT
491 */
492static int vmR3CreateU(PUVM pUVM, uint32_t cCpus, PFNCFGMCONSTRUCTOR pfnCFGMConstructor, void *pvUserCFGM)
493{
494 int rc = VINF_SUCCESS;
495
496 /*
497 * Load the VMMR0.r0 module so that we can call GVMMR0CreateVM.
498 */
499 rc = PDMR3LdrLoadVMMR0U(pUVM);
500 if (RT_FAILURE(rc))
501 {
502 /** @todo we need a cleaner solution for this (VERR_VMX_IN_VMX_ROOT_MODE).
503 * bird: what about moving the message down here? Main picks the first message, right? */
504 if (rc == VERR_VMX_IN_VMX_ROOT_MODE)
505 return rc; /* proper error message set later on */
506 return vmR3SetErrorU(pUVM, rc, RT_SRC_POS, N_("Failed to load VMMR0.r0"));
507 }
508
509 /*
510 * Request GVMM to create a new VM for us.
511 */
512 GVMMCREATEVMREQ CreateVMReq;
513 CreateVMReq.Hdr.u32Magic = SUPVMMR0REQHDR_MAGIC;
514 CreateVMReq.Hdr.cbReq = sizeof(CreateVMReq);
515 CreateVMReq.pSession = pUVM->vm.s.pSession;
516 CreateVMReq.pVMR0 = NIL_RTR0PTR;
517 CreateVMReq.pVMR3 = NULL;
518 CreateVMReq.cCpus = cCpus;
519 rc = SUPCallVMMR0Ex(NIL_RTR0PTR, 0 /* VCPU 0 */, VMMR0_DO_GVMM_CREATE_VM, 0, &CreateVMReq.Hdr);
520 if (RT_SUCCESS(rc))
521 {
522 PVM pVM = pUVM->pVM = CreateVMReq.pVMR3;
523 AssertRelease(VALID_PTR(pVM));
524 AssertRelease(pVM->pVMR0 == CreateVMReq.pVMR0);
525 AssertRelease(pVM->pSession == pUVM->vm.s.pSession);
526 AssertRelease(pVM->cCPUs == cCpus);
527 AssertRelease(pVM->offVMCPU == RT_UOFFSETOF(VM, aCpus));
528
529 Log(("VMR3Create: Created pUVM=%p pVM=%p pVMR0=%p hSelf=%#x cCPUs=%RU32\n",
530 pUVM, pVM, pVM->pVMR0, pVM->hSelf, pVM->cCPUs));
531
532 /*
533 * Initialize the VM structure and our internal data (VMINT).
534 */
535 pVM->pUVM = pUVM;
536
537 for (uint32_t i = 0; i < pVM->cCPUs; i++)
538 {
539 pVM->aCpus[i].pUVCpu = &pUVM->aCpus[i];
540 pVM->aCpus[i].idCpu = i;
541 pVM->aCpus[i].hNativeThread = pUVM->aCpus[i].vm.s.NativeThreadEMT;
542 Assert(pVM->aCpus[i].hNativeThread != NIL_RTNATIVETHREAD);
543
544 pUVM->aCpus[i].pVCpu = &pVM->aCpus[i];
545 pUVM->aCpus[i].pVM = pVM;
546 }
547
548
549 /*
550 * Init the configuration.
551 */
552 rc = CFGMR3Init(pVM, pfnCFGMConstructor, pvUserCFGM);
553 if (RT_SUCCESS(rc))
554 {
555 rc = CFGMR3QueryBoolDef(CFGMR3GetRoot(pVM), "HwVirtExtForced", &pVM->fHwVirtExtForced, false);
556 if (RT_SUCCESS(rc) && pVM->fHwVirtExtForced)
557 pVM->fHWACCMEnabled = true;
558
559 /*
560 * If executing in fake suplib mode disable RR3 and RR0 in the config.
561 */
562 const char *psz = RTEnvGet("VBOX_SUPLIB_FAKE");
563 if (psz && !strcmp(psz, "fake"))
564 {
565 CFGMR3RemoveValue(CFGMR3GetRoot(pVM), "RawR3Enabled");
566 CFGMR3InsertInteger(CFGMR3GetRoot(pVM), "RawR3Enabled", 0);
567 CFGMR3RemoveValue(CFGMR3GetRoot(pVM), "RawR0Enabled");
568 CFGMR3InsertInteger(CFGMR3GetRoot(pVM), "RawR0Enabled", 0);
569 }
570
571 /*
572 * Make sure the CPU count in the config data matches.
573 */
574 if (RT_SUCCESS(rc))
575 {
576 uint32_t cCPUsCfg;
577 rc = CFGMR3QueryU32Def(CFGMR3GetRoot(pVM), "NumCPUs", &cCPUsCfg, 1);
578 AssertLogRelMsgRC(rc, ("Configuration error: Querying \"NumCPUs\" as integer failed, rc=%Rrc\n", rc));
579 if (RT_SUCCESS(rc) && cCPUsCfg != cCpus)
580 {
581 AssertLogRelMsgFailed(("Configuration error: \"NumCPUs\"=%RU32 and VMR3CreateVM::cCPUs=%RU32 does not match!\n",
582 cCPUsCfg, cCpus));
583 rc = VERR_INVALID_PARAMETER;
584 }
585 }
586 if (RT_SUCCESS(rc))
587 {
588 /*
589 * Init the ring-3 components and ring-3 per cpu data, finishing it off
590 * by a relocation round (intermediate context finalization will do this).
591 */
592 rc = vmR3InitRing3(pVM, pUVM);
593 if (RT_SUCCESS(rc))
594 {
595 rc = vmR3InitVMCpu(pVM);
596 if (RT_SUCCESS(rc))
597 rc = PGMR3FinalizeMappings(pVM);
598 if (RT_SUCCESS(rc))
599 {
600
601 LogFlow(("Ring-3 init succeeded\n"));
602
603 /*
604 * Init the Ring-0 components.
605 */
606 rc = vmR3InitRing0(pVM);
607 if (RT_SUCCESS(rc))
608 {
609 /* Relocate again, because some switcher fixups depends on R0 init results. */
610 VMR3Relocate(pVM, 0);
611
612#ifdef VBOX_WITH_DEBUGGER
613 /*
614 * Init the tcp debugger console if we're building
615 * with debugger support.
616 */
617 void *pvUser = NULL;
618 rc = DBGCTcpCreate(pVM, &pvUser);
619 if ( RT_SUCCESS(rc)
620 || rc == VERR_NET_ADDRESS_IN_USE)
621 {
622 pUVM->vm.s.pvDBGC = pvUser;
623#endif
624 /*
625 * Init the Guest Context components.
626 */
627 rc = vmR3InitGC(pVM);
628 if (RT_SUCCESS(rc))
629 {
630 /*
631 * Now we can safely set the VM halt method to default.
632 */
633 rc = vmR3SetHaltMethodU(pUVM, VMHALTMETHOD_DEFAULT);
634 if (RT_SUCCESS(rc))
635 {
636 /*
637 * Set the state and link into the global list.
638 */
639 vmR3SetState(pVM, VMSTATE_CREATED);
640 pUVM->pNext = g_pUVMsHead;
641 g_pUVMsHead = pUVM;
642 return VINF_SUCCESS;
643 }
644 }
645#ifdef VBOX_WITH_DEBUGGER
646 DBGCTcpTerminate(pVM, pUVM->vm.s.pvDBGC);
647 pUVM->vm.s.pvDBGC = NULL;
648 }
649#endif
650 //..
651 }
652 }
653 vmR3Destroy(pVM);
654 }
655 }
656 //..
657
658 /* Clean CFGM. */
659 int rc2 = CFGMR3Term(pVM);
660 AssertRC(rc2);
661 }
662
663 /* Tell GVMM that it can destroy the VM now. */
664 int rc2 = SUPCallVMMR0Ex(CreateVMReq.pVMR0, 0 /* VCPU 0 */, VMMR0_DO_GVMM_DESTROY_VM, 0, NULL);
665 AssertRC(rc2);
666 pUVM->pVM = NULL;
667 }
668 else
669 vmR3SetErrorU(pUVM, rc, RT_SRC_POS, N_("VM creation failed (GVMM)"));
670
671 LogFlow(("vmR3Create: returns %Rrc\n", rc));
672 return rc;
673}
674
675/**
676 * Register the calling EMT with GVM.
677 *
678 * @returns VBox status code.
679 * @param pVM The VM handle.
680 * @param idCpu The Virtual CPU ID.
681 */
682static DECLCALLBACK(int) vmR3RegisterEMT(PVM pVM, VMCPUID idCpu)
683{
684 Assert(VMMGetCpuId(pVM) == idCpu);
685 int rc = SUPCallVMMR0Ex(pVM->pVMR0, idCpu, VMMR0_DO_GVMM_REGISTER_VMCPU, 0, NULL);
686 if (RT_FAILURE(rc))
687 LogRel(("idCpu=%u rc=%Rrc\n", idCpu, rc));
688 return rc;
689}
690
691
692/**
693 * Initializes all R3 components of the VM
694 */
695static int vmR3InitRing3(PVM pVM, PUVM pUVM)
696{
697 int rc;
698
699 /*
700 * Register the other EMTs with GVM.
701 */
702 for (VMCPUID idCpu = 1; idCpu < pVM->cCPUs; idCpu++)
703 {
704 PVMREQ pReq;
705 rc = VMR3ReqCallU(pUVM, idCpu, &pReq, RT_INDEFINITE_WAIT, 0 /*fFlags*/,
706 (PFNRT)vmR3RegisterEMT, 2, pVM, idCpu);
707 if (RT_SUCCESS(rc))
708 rc = pReq->iStatus;
709 VMR3ReqFree(pReq);
710 if (RT_FAILURE(rc))
711 return rc;
712 }
713
714 /*
715 * Init all R3 components, the order here might be important.
716 */
717 rc = MMR3Init(pVM);
718 if (RT_SUCCESS(rc))
719 {
720 STAM_REG(pVM, &pVM->StatTotalInGC, STAMTYPE_PROFILE_ADV, "/PROF/VM/InGC", STAMUNIT_TICKS_PER_CALL, "Profiling the total time spent in GC.");
721 STAM_REG(pVM, &pVM->StatSwitcherToGC, STAMTYPE_PROFILE_ADV, "/PROF/VM/SwitchToGC", STAMUNIT_TICKS_PER_CALL, "Profiling switching to GC.");
722 STAM_REG(pVM, &pVM->StatSwitcherToHC, STAMTYPE_PROFILE_ADV, "/PROF/VM/SwitchToHC", STAMUNIT_TICKS_PER_CALL, "Profiling switching to HC.");
723 STAM_REG(pVM, &pVM->StatSwitcherSaveRegs, STAMTYPE_PROFILE_ADV, "/VM/Switcher/ToGC/SaveRegs", STAMUNIT_TICKS_PER_CALL,"Profiling switching to GC.");
724 STAM_REG(pVM, &pVM->StatSwitcherSysEnter, STAMTYPE_PROFILE_ADV, "/VM/Switcher/ToGC/SysEnter", STAMUNIT_TICKS_PER_CALL,"Profiling switching to GC.");
725 STAM_REG(pVM, &pVM->StatSwitcherDebug, STAMTYPE_PROFILE_ADV, "/VM/Switcher/ToGC/Debug", STAMUNIT_TICKS_PER_CALL,"Profiling switching to GC.");
726 STAM_REG(pVM, &pVM->StatSwitcherCR0, STAMTYPE_PROFILE_ADV, "/VM/Switcher/ToGC/CR0", STAMUNIT_TICKS_PER_CALL, "Profiling switching to GC.");
727 STAM_REG(pVM, &pVM->StatSwitcherCR4, STAMTYPE_PROFILE_ADV, "/VM/Switcher/ToGC/CR4", STAMUNIT_TICKS_PER_CALL, "Profiling switching to GC.");
728 STAM_REG(pVM, &pVM->StatSwitcherLgdt, STAMTYPE_PROFILE_ADV, "/VM/Switcher/ToGC/Lgdt", STAMUNIT_TICKS_PER_CALL, "Profiling switching to GC.");
729 STAM_REG(pVM, &pVM->StatSwitcherLidt, STAMTYPE_PROFILE_ADV, "/VM/Switcher/ToGC/Lidt", STAMUNIT_TICKS_PER_CALL, "Profiling switching to GC.");
730 STAM_REG(pVM, &pVM->StatSwitcherLldt, STAMTYPE_PROFILE_ADV, "/VM/Switcher/ToGC/Lldt", STAMUNIT_TICKS_PER_CALL, "Profiling switching to GC.");
731 STAM_REG(pVM, &pVM->StatSwitcherTSS, STAMTYPE_PROFILE_ADV, "/VM/Switcher/ToGC/TSS", STAMUNIT_TICKS_PER_CALL, "Profiling switching to GC.");
732 STAM_REG(pVM, &pVM->StatSwitcherJmpCR3, STAMTYPE_PROFILE_ADV, "/VM/Switcher/ToGC/JmpCR3", STAMUNIT_TICKS_PER_CALL,"Profiling switching to GC.");
733 STAM_REG(pVM, &pVM->StatSwitcherRstrRegs, STAMTYPE_PROFILE_ADV, "/VM/Switcher/ToGC/RstrRegs", STAMUNIT_TICKS_PER_CALL,"Profiling switching to GC.");
734
735 for (unsigned iCpu=0;iCpu<pVM->cCPUs;iCpu++)
736 {
737 rc = STAMR3RegisterF(pVM, &pUVM->aCpus[iCpu].vm.s.StatHaltYield, STAMTYPE_PROFILE, STAMVISIBILITY_ALWAYS, STAMUNIT_TICKS_PER_CALL, "Profiling halted state yielding.", "/PROF/VM/CPU%d/Halt/Yield", iCpu);
738 AssertRC(rc);
739 rc = STAMR3RegisterF(pVM, &pUVM->aCpus[iCpu].vm.s.StatHaltBlock, STAMTYPE_PROFILE, STAMVISIBILITY_ALWAYS, STAMUNIT_TICKS_PER_CALL, "Profiling halted state blocking.", "/PROF/VM/CPU%d/Halt/Block", iCpu);
740 AssertRC(rc);
741 rc = STAMR3RegisterF(pVM, &pUVM->aCpus[iCpu].vm.s.StatHaltTimers, STAMTYPE_PROFILE, STAMVISIBILITY_ALWAYS, STAMUNIT_TICKS_PER_CALL, "Profiling halted state timer tasks.", "/PROF/VM/CPU%d/Halt/Timers", iCpu);
742 AssertRC(rc);
743 }
744
745 STAM_REG(pVM, &pUVM->vm.s.StatReqAllocNew, STAMTYPE_COUNTER, "/VM/Req/AllocNew", STAMUNIT_OCCURENCES, "Number of VMR3ReqAlloc returning a new packet.");
746 STAM_REG(pVM, &pUVM->vm.s.StatReqAllocRaces, STAMTYPE_COUNTER, "/VM/Req/AllocRaces", STAMUNIT_OCCURENCES, "Number of VMR3ReqAlloc causing races.");
747 STAM_REG(pVM, &pUVM->vm.s.StatReqAllocRecycled, STAMTYPE_COUNTER, "/VM/Req/AllocRecycled", STAMUNIT_OCCURENCES, "Number of VMR3ReqAlloc returning a recycled packet.");
748 STAM_REG(pVM, &pUVM->vm.s.StatReqFree, STAMTYPE_COUNTER, "/VM/Req/Free", STAMUNIT_OCCURENCES, "Number of VMR3ReqFree calls.");
749 STAM_REG(pVM, &pUVM->vm.s.StatReqFreeOverflow, STAMTYPE_COUNTER, "/VM/Req/FreeOverflow", STAMUNIT_OCCURENCES, "Number of times the request was actually freed.");
750
751 rc = CPUMR3Init(pVM);
752 if (RT_SUCCESS(rc))
753 {
754 rc = HWACCMR3Init(pVM);
755 if (RT_SUCCESS(rc))
756 {
757 rc = PGMR3Init(pVM);
758 if (RT_SUCCESS(rc))
759 {
760 rc = REMR3Init(pVM);
761 if (RT_SUCCESS(rc))
762 {
763 rc = MMR3InitPaging(pVM);
764 if (RT_SUCCESS(rc))
765 rc = TMR3Init(pVM);
766 if (RT_SUCCESS(rc))
767 {
768 rc = VMMR3Init(pVM);
769 if (RT_SUCCESS(rc))
770 {
771 rc = SELMR3Init(pVM);
772 if (RT_SUCCESS(rc))
773 {
774 rc = TRPMR3Init(pVM);
775 if (RT_SUCCESS(rc))
776 {
777 rc = CSAMR3Init(pVM);
778 if (RT_SUCCESS(rc))
779 {
780 rc = PATMR3Init(pVM);
781 if (RT_SUCCESS(rc))
782 {
783#ifdef VBOX_WITH_VMI
784 rc = PARAVR3Init(pVM);
785 if (RT_SUCCESS(rc))
786 {
787#endif
788 rc = IOMR3Init(pVM);
789 if (RT_SUCCESS(rc))
790 {
791 rc = EMR3Init(pVM);
792 if (RT_SUCCESS(rc))
793 {
794 rc = DBGFR3Init(pVM);
795 if (RT_SUCCESS(rc))
796 {
797 rc = PDMR3Init(pVM);
798 if (RT_SUCCESS(rc))
799 {
800 rc = PGMR3InitDynMap(pVM);
801 if (RT_SUCCESS(rc))
802 rc = MMR3HyperInitFinalize(pVM);
803 if (RT_SUCCESS(rc))
804 rc = PATMR3InitFinalize(pVM);
805 if (RT_SUCCESS(rc))
806 rc = PGMR3InitFinalize(pVM);
807 if (RT_SUCCESS(rc))
808 rc = SELMR3InitFinalize(pVM);
809 if (RT_SUCCESS(rc))
810 rc = TMR3InitFinalize(pVM);
811 if (RT_SUCCESS(rc))
812 rc = VMMR3InitFinalize(pVM);
813 if (RT_SUCCESS(rc))
814 rc = REMR3InitFinalize(pVM);
815 if (RT_SUCCESS(rc))
816 rc = vmR3InitDoCompleted(pVM, VMINITCOMPLETED_RING3);
817 if (RT_SUCCESS(rc))
818 {
819 LogFlow(("vmR3InitRing3: returns %Rrc\n", VINF_SUCCESS));
820 return VINF_SUCCESS;
821 }
822 int rc2 = PDMR3Term(pVM);
823 AssertRC(rc2);
824 }
825 int rc2 = DBGFR3Term(pVM);
826 AssertRC(rc2);
827 }
828 int rc2 = EMR3Term(pVM);
829 AssertRC(rc2);
830 }
831 int rc2 = IOMR3Term(pVM);
832 AssertRC(rc2);
833 }
834#ifdef VBOX_WITH_VMI
835 int rc2 = PARAVR3Term(pVM);
836 AssertRC(rc2);
837 }
838#endif
839 int rc2 = PATMR3Term(pVM);
840 AssertRC(rc2);
841 }
842 int rc2 = CSAMR3Term(pVM);
843 AssertRC(rc2);
844 }
845 int rc2 = TRPMR3Term(pVM);
846 AssertRC(rc2);
847 }
848 int rc2 = SELMR3Term(pVM);
849 AssertRC(rc2);
850 }
851 int rc2 = VMMR3Term(pVM);
852 AssertRC(rc2);
853 }
854 int rc2 = TMR3Term(pVM);
855 AssertRC(rc2);
856 }
857 int rc2 = REMR3Term(pVM);
858 AssertRC(rc2);
859 }
860 int rc2 = PGMR3Term(pVM);
861 AssertRC(rc2);
862 }
863 int rc2 = HWACCMR3Term(pVM);
864 AssertRC(rc2);
865 }
866 //int rc2 = CPUMR3Term(pVM);
867 //AssertRC(rc2);
868 }
869 /* MMR3Term is not called here because it'll kill the heap. */
870 }
871
872 LogFlow(("vmR3InitRing3: returns %Rrc\n", rc));
873 return rc;
874}
875
876
877/**
878 * Initializes all VM CPU components of the VM
879 */
880static int vmR3InitVMCpu(PVM pVM)
881{
882 int rc = VINF_SUCCESS;
883 int rc2;
884
885 rc = CPUMR3InitCPU(pVM);
886 if (RT_SUCCESS(rc))
887 {
888 rc = HWACCMR3InitCPU(pVM);
889 if (RT_SUCCESS(rc))
890 {
891 rc = PGMR3InitCPU(pVM);
892 if (RT_SUCCESS(rc))
893 {
894 rc = TMR3InitCPU(pVM);
895 if (RT_SUCCESS(rc))
896 {
897 rc = VMMR3InitCPU(pVM);
898 if (RT_SUCCESS(rc))
899 {
900 rc = EMR3InitCPU(pVM);
901 if (RT_SUCCESS(rc))
902 {
903 LogFlow(("vmR3InitVMCpu: returns %Rrc\n", VINF_SUCCESS));
904 return VINF_SUCCESS;
905 }
906
907 rc2 = VMMR3TermCPU(pVM);
908 AssertRC(rc2);
909 }
910 rc2 = TMR3TermCPU(pVM);
911 AssertRC(rc2);
912 }
913 rc2 = PGMR3TermCPU(pVM);
914 AssertRC(rc2);
915 }
916 rc2 = HWACCMR3TermCPU(pVM);
917 AssertRC(rc2);
918 }
919 rc2 = CPUMR3TermCPU(pVM);
920 AssertRC(rc2);
921 }
922 LogFlow(("vmR3InitVMCpu: returns %Rrc\n", rc));
923 return rc;
924}
925
926
927/**
928 * Initializes all R0 components of the VM
929 */
930static int vmR3InitRing0(PVM pVM)
931{
932 LogFlow(("vmR3InitRing0:\n"));
933
934 /*
935 * Check for FAKE suplib mode.
936 */
937 int rc = VINF_SUCCESS;
938 const char *psz = RTEnvGet("VBOX_SUPLIB_FAKE");
939 if (!psz || strcmp(psz, "fake"))
940 {
941 /*
942 * Call the VMMR0 component and let it do the init.
943 */
944 rc = VMMR3InitR0(pVM);
945 }
946 else
947 Log(("vmR3InitRing0: skipping because of VBOX_SUPLIB_FAKE=fake\n"));
948
949 /*
950 * Do notifications and return.
951 */
952 if (RT_SUCCESS(rc))
953 rc = vmR3InitDoCompleted(pVM, VMINITCOMPLETED_RING0);
954
955 /** todo: move this to the VMINITCOMPLETED_RING0 notification handler once implemented */
956 if (RT_SUCCESS(rc))
957 rc = HWACCMR3InitFinalizeR0(pVM);
958
959 LogFlow(("vmR3InitRing0: returns %Rrc\n", rc));
960 return rc;
961}
962
963
964/**
965 * Initializes all GC components of the VM
966 */
967static int vmR3InitGC(PVM pVM)
968{
969 LogFlow(("vmR3InitGC:\n"));
970
971 /*
972 * Check for FAKE suplib mode.
973 */
974 int rc = VINF_SUCCESS;
975 const char *psz = RTEnvGet("VBOX_SUPLIB_FAKE");
976 if (!psz || strcmp(psz, "fake"))
977 {
978 /*
979 * Call the VMMR0 component and let it do the init.
980 */
981 rc = VMMR3InitRC(pVM);
982 }
983 else
984 Log(("vmR3InitGC: skipping because of VBOX_SUPLIB_FAKE=fake\n"));
985
986 /*
987 * Do notifications and return.
988 */
989 if (RT_SUCCESS(rc))
990 rc = vmR3InitDoCompleted(pVM, VMINITCOMPLETED_GC);
991 LogFlow(("vmR3InitGC: returns %Rrc\n", rc));
992 return rc;
993}
994
995
996/**
997 * Do init completed notifications.
998 * This notifications can fail.
999 *
1000 * @param pVM The VM handle.
1001 * @param enmWhat What's completed.
1002 */
1003static int vmR3InitDoCompleted(PVM pVM, VMINITCOMPLETED enmWhat)
1004{
1005 return VINF_SUCCESS;
1006}
1007
1008
1009/**
1010 * Calls the relocation functions for all VMM components so they can update
1011 * any GC pointers. When this function is called all the basic VM members
1012 * have been updated and the actual memory relocation have been done
1013 * by the PGM/MM.
1014 *
1015 * This is used both on init and on runtime relocations.
1016 *
1017 * @param pVM VM handle.
1018 * @param offDelta Relocation delta relative to old location.
1019 */
1020VMMR3DECL(void) VMR3Relocate(PVM pVM, RTGCINTPTR offDelta)
1021{
1022 LogFlow(("VMR3Relocate: offDelta=%RGv\n", offDelta));
1023
1024 /*
1025 * The order here is very important!
1026 */
1027 PGMR3Relocate(pVM, offDelta);
1028 PDMR3LdrRelocateU(pVM->pUVM, offDelta);
1029 PGMR3Relocate(pVM, 0); /* Repeat after PDM relocation. */
1030 CPUMR3Relocate(pVM);
1031 HWACCMR3Relocate(pVM);
1032 SELMR3Relocate(pVM);
1033 VMMR3Relocate(pVM, offDelta);
1034 SELMR3Relocate(pVM); /* !hack! fix stack! */
1035 TRPMR3Relocate(pVM, offDelta);
1036 PATMR3Relocate(pVM);
1037 CSAMR3Relocate(pVM, offDelta);
1038 IOMR3Relocate(pVM, offDelta);
1039 EMR3Relocate(pVM);
1040 TMR3Relocate(pVM, offDelta);
1041 DBGFR3Relocate(pVM, offDelta);
1042 PDMR3Relocate(pVM, offDelta);
1043}
1044
1045
1046/**
1047 * Power on the virtual machine.
1048 *
1049 * @returns 0 on success.
1050 * @returns VBox error code on failure.
1051 * @param pVM VM to power on.
1052 * @thread Any thread.
1053 * @vmstate Created
1054 * @vmstateto Running
1055 */
1056VMMR3DECL(int) VMR3PowerOn(PVM pVM)
1057{
1058 LogFlow(("VMR3PowerOn: pVM=%p\n", pVM));
1059
1060 /*
1061 * Validate input.
1062 */
1063 if (!pVM)
1064 {
1065 AssertMsgFailed(("Invalid VM pointer\n"));
1066 return VERR_INVALID_PARAMETER;
1067 }
1068
1069 /*
1070 * Request the operation in EMT.
1071 */
1072 PVMREQ pReq;
1073 int rc = VMR3ReqCall(pVM, 0 /* VCPU 0 */, &pReq, RT_INDEFINITE_WAIT, (PFNRT)vmR3PowerOn, 1, pVM);
1074 if (RT_SUCCESS(rc))
1075 {
1076 rc = pReq->iStatus;
1077 VMR3ReqFree(pReq);
1078 }
1079
1080 LogFlow(("VMR3PowerOn: returns %Rrc\n", rc));
1081 return rc;
1082}
1083
1084
1085/**
1086 * Power on the virtual machine.
1087 *
1088 * @returns 0 on success.
1089 * @returns VBox error code on failure.
1090 * @param pVM VM to power on.
1091 * @thread EMT
1092 */
1093static DECLCALLBACK(int) vmR3PowerOn(PVM pVM)
1094{
1095 LogFlow(("vmR3PowerOn: pVM=%p\n", pVM));
1096
1097 /*
1098 * Validate input.
1099 */
1100 if (pVM->enmVMState != VMSTATE_CREATED)
1101 {
1102 AssertMsgFailed(("Invalid VM state %d\n", pVM->enmVMState));
1103 return VERR_VM_INVALID_VM_STATE;
1104 }
1105
1106 /*
1107 * Change the state, notify the components and resume the execution.
1108 */
1109 vmR3SetState(pVM, VMSTATE_RUNNING);
1110 PDMR3PowerOn(pVM);
1111
1112 return VINF_SUCCESS;
1113}
1114
1115
1116/**
1117 * Suspends a running VM.
1118 *
1119 * @returns 0 on success.
1120 * @returns VBox error code on failure.
1121 * @param pVM VM to suspend.
1122 * @thread Any thread.
1123 * @vmstate Running
1124 * @vmstateto Suspended
1125 */
1126VMMR3DECL(int) VMR3Suspend(PVM pVM)
1127{
1128 LogFlow(("VMR3Suspend: pVM=%p\n", pVM));
1129
1130 /*
1131 * Validate input.
1132 */
1133 if (!pVM)
1134 {
1135 AssertMsgFailed(("Invalid VM pointer\n"));
1136 return VERR_INVALID_PARAMETER;
1137 }
1138
1139 /*
1140 * Request the operation in EMT. (in reverse order as VCPU 0 does the actual work)
1141 */
1142 PVMREQ pReq = NULL;
1143 int rc = VMR3ReqCall(pVM, VMCPUID_ALL_REVERSE, &pReq, RT_INDEFINITE_WAIT, (PFNRT)vmR3Suspend, 1, pVM);
1144 if (RT_SUCCESS(rc))
1145 {
1146 rc = pReq->iStatus;
1147 VMR3ReqFree(pReq);
1148 }
1149 else
1150 Assert(pReq == NULL);
1151
1152 LogFlow(("VMR3Suspend: returns %Rrc\n", rc));
1153 return rc;
1154}
1155
1156
1157/**
1158 * Suspends a running VM and prevent state saving until the VM is resumed or stopped.
1159 *
1160 * @returns 0 on success.
1161 * @returns VBox error code on failure.
1162 * @param pVM VM to suspend.
1163 * @thread Any thread.
1164 * @vmstate Running
1165 * @vmstateto Suspended
1166 */
1167VMMR3DECL(int) VMR3SuspendNoSave(PVM pVM)
1168{
1169 pVM->vm.s.fPreventSaveState = true;
1170 return VMR3Suspend(pVM);
1171}
1172
1173
1174/**
1175 * Suspends a running VM.
1176 *
1177 * @returns 0 on success.
1178 * @returns VBox error code on failure.
1179 * @param pVM VM to suspend.
1180 * @thread EMT
1181 */
1182static DECLCALLBACK(int) vmR3Suspend(PVM pVM)
1183{
1184 LogFlow(("vmR3Suspend: pVM=%p\n", pVM));
1185
1186 /*
1187 * Validate input.
1188 */
1189 if (pVM->enmVMState != VMSTATE_RUNNING)
1190 {
1191 AssertMsgFailed(("Invalid VM state %d\n", pVM->enmVMState));
1192 return VERR_VM_INVALID_VM_STATE;
1193 }
1194
1195 PVMCPU pVCpu = VMMGetCpu(pVM);
1196 /* Only VCPU 0 does the actual work. */
1197 if (pVCpu->idCpu != 0)
1198 return VINF_EM_SUSPEND;
1199
1200 /*
1201 * Change the state, notify the components and resume the execution.
1202 */
1203 vmR3SetState(pVM, VMSTATE_SUSPENDED);
1204 PDMR3Suspend(pVM);
1205
1206 return VINF_EM_SUSPEND;
1207}
1208
1209
1210/**
1211 * Resume VM execution.
1212 *
1213 * @returns 0 on success.
1214 * @returns VBox error code on failure.
1215 * @param pVM The VM to resume.
1216 * @thread Any thread.
1217 * @vmstate Suspended
1218 * @vmstateto Running
1219 */
1220VMMR3DECL(int) VMR3Resume(PVM pVM)
1221{
1222 LogFlow(("VMR3Resume: pVM=%p\n", pVM));
1223
1224 /*
1225 * Validate input.
1226 */
1227 if (!pVM)
1228 {
1229 AssertMsgFailed(("Invalid VM pointer\n"));
1230 return VERR_INVALID_PARAMETER;
1231 }
1232
1233 /*
1234 * Request the operation in EMT. (in VCPU order as VCPU 0 does the actual work)
1235 */
1236 PVMREQ pReq = NULL;
1237 int rc = VMR3ReqCall(pVM, VMCPUID_ALL, &pReq, RT_INDEFINITE_WAIT, (PFNRT)vmR3Resume, 1, pVM);
1238 if (RT_SUCCESS(rc))
1239 {
1240 rc = pReq->iStatus;
1241 VMR3ReqFree(pReq);
1242 }
1243 else
1244 Assert(pReq == NULL);
1245
1246 LogFlow(("VMR3Resume: returns %Rrc\n", rc));
1247 return rc;
1248}
1249
1250
1251/**
1252 * Resume VM execution.
1253 *
1254 * @returns 0 on success.
1255 * @returns VBox error code on failure.
1256 * @param pVM The VM to resume.
1257 * @thread EMT
1258 */
1259static DECLCALLBACK(int) vmR3Resume(PVM pVM)
1260{
1261 LogFlow(("vmR3Resume: pVM=%p\n", pVM));
1262
1263 /*
1264 * Validate input.
1265 */
1266 if (pVM->enmVMState != VMSTATE_SUSPENDED)
1267 {
1268 AssertMsgFailed(("Invalid VM state %d\n", pVM->enmVMState));
1269 return VERR_VM_INVALID_VM_STATE;
1270 }
1271
1272 PVMCPU pVCpu = VMMGetCpu(pVM);
1273 /* Only VCPU 0 does the actual work. */
1274 if (pVCpu->idCpu != 0)
1275 return VINF_EM_RESUME;
1276
1277 /*
1278 * Change the state, notify the components and resume the execution.
1279 */
1280 pVM->vm.s.fPreventSaveState = false;
1281 vmR3SetState(pVM, VMSTATE_RUNNING);
1282 PDMR3Resume(pVM);
1283
1284 return VINF_EM_RESUME;
1285}
1286
1287
1288/**
1289 * Save current VM state.
1290 *
1291 * To save and terminate the VM, the VM must be suspended before the call.
1292 *
1293 * @returns 0 on success.
1294 * @returns VBox error code on failure.
1295 * @param pVM VM which state should be saved.
1296 * @param pszFilename Name of the save state file.
1297 * @param pfnProgress Progress callback. Optional.
1298 * @param pvUser User argument for the progress callback.
1299 * @thread Any thread.
1300 * @vmstate Suspended
1301 * @vmstateto Unchanged state.
1302 */
1303VMMR3DECL(int) VMR3Save(PVM pVM, const char *pszFilename, PFNVMPROGRESS pfnProgress, void *pvUser)
1304{
1305 LogFlow(("VMR3Save: pVM=%p pszFilename=%p:{%s} pfnProgress=%p pvUser=%p\n", pVM, pszFilename, pszFilename, pfnProgress, pvUser));
1306
1307 /*
1308 * Validate input.
1309 */
1310 if (!pVM)
1311 {
1312 AssertMsgFailed(("Invalid VM pointer\n"));
1313 return VERR_INVALID_PARAMETER;
1314 }
1315 if (!pszFilename)
1316 {
1317 AssertMsgFailed(("Must specify a filename to save the state to, wise guy!\n"));
1318 return VERR_INVALID_PARAMETER;
1319 }
1320
1321 /*
1322 * Request the operation in EMT.
1323 */
1324 PVMREQ pReq;
1325 int rc = VMR3ReqCall(pVM, 0 /* VCPU 0 */, &pReq, RT_INDEFINITE_WAIT, (PFNRT)vmR3Save, 4, pVM, pszFilename, pfnProgress, pvUser);
1326 if (RT_SUCCESS(rc))
1327 {
1328 rc = pReq->iStatus;
1329 VMR3ReqFree(pReq);
1330 }
1331
1332 LogFlow(("VMR3Save: returns %Rrc\n", rc));
1333 return rc;
1334}
1335
1336
1337/**
1338 * Save current VM state.
1339 *
1340 * To save and terminate the VM, the VM must be suspended before the call.
1341 *
1342 * @returns 0 on success.
1343 * @returns VBox error code on failure.
1344 * @param pVM VM which state should be saved.
1345 * @param pszFilename Name of the save state file.
1346 * @param pfnProgress Progress callback. Optional.
1347 * @param pvUser User argument for the progress callback.
1348 * @thread EMT
1349 */
1350static DECLCALLBACK(int) vmR3Save(PVM pVM, const char *pszFilename, PFNVMPROGRESS pfnProgress, void *pvUser)
1351{
1352 LogFlow(("vmR3Save: pVM=%p pszFilename=%p:{%s} pfnProgress=%p pvUser=%p\n", pVM, pszFilename, pszFilename, pfnProgress, pvUser));
1353
1354 /*
1355 * Validate input.
1356 */
1357 if (pVM->enmVMState != VMSTATE_SUSPENDED)
1358 {
1359 AssertMsgFailed(("Invalid VM state %d\n", pVM->enmVMState));
1360 return VERR_VM_INVALID_VM_STATE;
1361 }
1362
1363 /* If we are in an inconsistent state, then we don't allow state saving. */
1364 if (pVM->vm.s.fPreventSaveState)
1365 {
1366 LogRel(("VMM: vmR3Save: saving the VM state is not allowed at this moment\n"));
1367 return VERR_VM_SAVE_STATE_NOT_ALLOWED;
1368 }
1369
1370 /*
1371 * Change the state and perform the save.
1372 */
1373 /** @todo implement progress support in SSM */
1374 vmR3SetState(pVM, VMSTATE_SAVING);
1375 int rc = SSMR3Save(pVM, pszFilename, SSMAFTER_CONTINUE, pfnProgress, pvUser);
1376 vmR3SetState(pVM, VMSTATE_SUSPENDED);
1377
1378 return rc;
1379}
1380
1381
1382/**
1383 * Loads a new VM state.
1384 *
1385 * To restore a saved state on VM startup, call this function and then
1386 * resume the VM instead of powering it on.
1387 *
1388 * @returns 0 on success.
1389 * @returns VBox error code on failure.
1390 * @param pVM VM which state should be saved.
1391 * @param pszFilename Name of the save state file.
1392 * @param pfnProgress Progress callback. Optional.
1393 * @param pvUser User argument for the progress callback.
1394 * @thread Any thread.
1395 * @vmstate Created, Suspended
1396 * @vmstateto Suspended
1397 */
1398VMMR3DECL(int) VMR3Load(PVM pVM, const char *pszFilename, PFNVMPROGRESS pfnProgress, void *pvUser)
1399{
1400 LogFlow(("VMR3Load: pVM=%p pszFilename=%p:{%s} pfnProgress=%p pvUser=%p\n", pVM, pszFilename, pszFilename, pfnProgress, pvUser));
1401
1402 /*
1403 * Validate input.
1404 */
1405 if (!pVM)
1406 {
1407 AssertMsgFailed(("Invalid VM pointer\n"));
1408 return VERR_INVALID_PARAMETER;
1409 }
1410 if (!pszFilename)
1411 {
1412 AssertMsgFailed(("Must specify a filename to load the state from, wise guy!\n"));
1413 return VERR_INVALID_PARAMETER;
1414 }
1415
1416 /*
1417 * Request the operation in EMT.
1418 */
1419 PVMREQ pReq;
1420 int rc = VMR3ReqCall(pVM, 0 /* VCPU 0 */, &pReq, RT_INDEFINITE_WAIT, (PFNRT)vmR3Load, 4, pVM, pszFilename, pfnProgress, pvUser);
1421 if (RT_SUCCESS(rc))
1422 {
1423 rc = pReq->iStatus;
1424 VMR3ReqFree(pReq);
1425 }
1426
1427 LogFlow(("VMR3Load: returns %Rrc\n", rc));
1428 return rc;
1429}
1430
1431
1432/**
1433 * Loads a new VM state.
1434 *
1435 * To restore a saved state on VM startup, call this function and then
1436 * resume the VM instead of powering it on.
1437 *
1438 * @returns 0 on success.
1439 * @returns VBox error code on failure.
1440 * @param pVM VM which state should be saved.
1441 * @param pszFilename Name of the save state file.
1442 * @param pfnProgress Progress callback. Optional.
1443 * @param pvUser User argument for the progress callback.
1444 * @thread EMT.
1445 */
1446static DECLCALLBACK(int) vmR3Load(PVM pVM, const char *pszFilename, PFNVMPROGRESS pfnProgress, void *pvUser)
1447{
1448 LogFlow(("vmR3Load: pVM=%p pszFilename=%p:{%s} pfnProgress=%p pvUser=%p\n", pVM, pszFilename, pszFilename, pfnProgress, pvUser));
1449
1450 /*
1451 * Validate input.
1452 */
1453 if ( pVM->enmVMState != VMSTATE_SUSPENDED
1454 && pVM->enmVMState != VMSTATE_CREATED)
1455 {
1456 AssertMsgFailed(("Invalid VM state %d\n", pVM->enmVMState));
1457 return VMSetError(pVM, VERR_VM_INVALID_VM_STATE, RT_SRC_POS, N_("Invalid VM state (%s) for restoring state from '%s'"),
1458 VMR3GetStateName(pVM->enmVMState), pszFilename);
1459 }
1460
1461 /*
1462 * Change the state and perform the load.
1463 */
1464 vmR3SetState(pVM, VMSTATE_LOADING);
1465 int rc = SSMR3Load(pVM, pszFilename, SSMAFTER_RESUME, pfnProgress, pvUser);
1466 if (RT_SUCCESS(rc))
1467 {
1468 /* Not paranoia anymore; the saved guest might use different hypervisor selectors. We must call VMR3Relocate. */
1469 VMR3Relocate(pVM, 0);
1470 vmR3SetState(pVM, VMSTATE_SUSPENDED);
1471 }
1472 else
1473 {
1474 vmR3SetState(pVM, VMSTATE_LOAD_FAILURE);
1475 rc = VMSetError(pVM, rc, RT_SRC_POS, N_("Unable to restore the virtual machine's saved state from '%s'. It may be damaged or from an older version of VirtualBox. Please discard the saved state before starting the virtual machine"), pszFilename);
1476 }
1477
1478 return rc;
1479}
1480
1481
1482/**
1483 * Power Off the VM.
1484 *
1485 * @returns 0 on success.
1486 * @returns VBox error code on failure.
1487 * @param pVM VM which should be destroyed.
1488 * @thread Any thread.
1489 * @vmstate Suspended, Running, Guru Meditation, Load Failure
1490 * @vmstateto Off
1491 */
1492VMMR3DECL(int) VMR3PowerOff(PVM pVM)
1493{
1494 LogFlow(("VMR3PowerOff: pVM=%p\n", pVM));
1495
1496 /*
1497 * Validate input.
1498 */
1499 if (!pVM)
1500 {
1501 AssertMsgFailed(("Invalid VM pointer\n"));
1502 return VERR_INVALID_PARAMETER;
1503 }
1504
1505 /*
1506 * Request the operation in EMT. (in reverse order as VCPU 0 does the actual work)
1507 */
1508 PVMREQ pReq = NULL;
1509 int rc = VMR3ReqCall(pVM, VMCPUID_ALL_REVERSE, &pReq, RT_INDEFINITE_WAIT, (PFNRT)vmR3PowerOff, 1, pVM);
1510 if (RT_SUCCESS(rc))
1511 {
1512 rc = pReq->iStatus;
1513 VMR3ReqFree(pReq);
1514 }
1515 else
1516 Assert(pReq == NULL);
1517
1518 LogFlow(("VMR3PowerOff: returns %Rrc\n", rc));
1519 return rc;
1520}
1521
1522
1523/**
1524 * Power Off the VM.
1525 *
1526 * @returns 0 on success.
1527 * @returns VBox error code on failure.
1528 * @param pVM VM which should be destroyed.
1529 * @thread EMT.
1530 */
1531static DECLCALLBACK(int) vmR3PowerOff(PVM pVM)
1532{
1533 LogFlow(("vmR3PowerOff: pVM=%p\n", pVM));
1534
1535 /*
1536 * Validate input.
1537 */
1538 if ( pVM->enmVMState != VMSTATE_RUNNING
1539 && pVM->enmVMState != VMSTATE_SUSPENDED
1540 && pVM->enmVMState != VMSTATE_LOAD_FAILURE
1541 && pVM->enmVMState != VMSTATE_GURU_MEDITATION)
1542 {
1543 AssertMsgFailed(("Invalid VM state %d\n", pVM->enmVMState));
1544 return VERR_VM_INVALID_VM_STATE;
1545 }
1546
1547 PVMCPU pVCpu = VMMGetCpu(pVM);
1548 /* Only VCPU 0 does the actual work. */
1549 if (pVCpu->idCpu != 0)
1550 return VINF_EM_OFF;
1551
1552 /*
1553 * For debugging purposes, we will log a summary of the guest state at this point.
1554 */
1555 if (pVM->enmVMState != VMSTATE_GURU_MEDITATION)
1556 {
1557 /* @todo SMP support? */
1558 PVMCPU pVCpu = VMMGetCpu(pVM);
1559
1560 /** @todo make the state dumping at VMR3PowerOff optional. */
1561 RTLogRelPrintf("****************** Guest state at power off ******************\n");
1562 DBGFR3Info(pVM, "cpumguest", "verbose", DBGFR3InfoLogRelHlp());
1563 RTLogRelPrintf("***\n");
1564 DBGFR3Info(pVM, "mode", NULL, DBGFR3InfoLogRelHlp());
1565 RTLogRelPrintf("***\n");
1566 DBGFR3Info(pVM, "activetimers", NULL, DBGFR3InfoLogRelHlp());
1567 RTLogRelPrintf("***\n");
1568 DBGFR3Info(pVM, "gdt", NULL, DBGFR3InfoLogRelHlp());
1569 /** @todo dump guest call stack. */
1570#if 1 // temporary while debugging #1589
1571 RTLogRelPrintf("***\n");
1572 uint32_t esp = CPUMGetGuestESP(pVCpu);
1573 if ( CPUMGetGuestSS(pVCpu) == 0
1574 && esp < _64K)
1575 {
1576 uint8_t abBuf[PAGE_SIZE];
1577 RTLogRelPrintf("***\n"
1578 "ss:sp=0000:%04x ", esp);
1579 uint32_t Start = esp & ~(uint32_t)63;
1580 int rc = PGMPhysSimpleReadGCPhys(pVM, abBuf, Start, 0x100);
1581 if (RT_SUCCESS(rc))
1582 RTLogRelPrintf("0000:%04x TO 0000:%04x:\n"
1583 "%.*Rhxd\n",
1584 Start, Start + 0x100 - 1,
1585 0x100, abBuf);
1586 else
1587 RTLogRelPrintf("rc=%Rrc\n", rc);
1588
1589 /* grub ... */
1590 if (esp < 0x2000 && esp > 0x1fc0)
1591 {
1592 rc = PGMPhysSimpleReadGCPhys(pVM, abBuf, 0x8000, 0x800);
1593 if (RT_SUCCESS(rc))
1594 RTLogRelPrintf("0000:8000 TO 0000:87ff:\n"
1595 "%.*Rhxd\n",
1596 0x800, abBuf);
1597 }
1598 /* microsoft cdrom hang ... */
1599 if (true)
1600 {
1601 rc = PGMPhysSimpleReadGCPhys(pVM, abBuf, 0x8000, 0x200);
1602 if (RT_SUCCESS(rc))
1603 RTLogRelPrintf("2000:0000 TO 2000:01ff:\n"
1604 "%.*Rhxd\n",
1605 0x200, abBuf);
1606 }
1607 }
1608#endif
1609 RTLogRelPrintf("************** End of Guest state at power off ***************\n");
1610 }
1611
1612 /*
1613 * Change the state to OFF and notify the components.
1614 */
1615 vmR3SetState(pVM, VMSTATE_OFF);
1616 PDMR3PowerOff(pVM);
1617
1618 return VINF_EM_OFF;
1619}
1620
1621
1622/**
1623 * Destroys the VM.
1624 * The VM must be powered off (or never really powered on) to call this function.
1625 * The VM handle is destroyed and can no longer be used up successful return.
1626 *
1627 * @returns VBox status code.
1628 * @param pVM VM which should be destroyed.
1629 * @thread Any thread but the emulation thread.
1630 * @vmstate Off, Created
1631 * @vmstateto N/A
1632 */
1633VMMR3DECL(int) VMR3Destroy(PVM pVM)
1634{
1635 LogFlow(("VMR3Destroy: pVM=%p\n", pVM));
1636
1637 /*
1638 * Validate input.
1639 */
1640 if (!pVM)
1641 return VERR_INVALID_PARAMETER;
1642 AssertPtrReturn(pVM, VERR_INVALID_POINTER);
1643 AssertMsgReturn( pVM->enmVMState == VMSTATE_OFF
1644 || pVM->enmVMState == VMSTATE_CREATED,
1645 ("Invalid VM state %d\n", pVM->enmVMState),
1646 VERR_VM_INVALID_VM_STATE);
1647
1648 /*
1649 * Change VM state to destroying and unlink the VM.
1650 */
1651 vmR3SetState(pVM, VMSTATE_DESTROYING);
1652
1653 /** @todo lock this when we start having multiple machines in a process... */
1654 PUVM pUVM = pVM->pUVM; AssertPtr(pUVM);
1655 if (g_pUVMsHead == pUVM)
1656 g_pUVMsHead = pUVM->pNext;
1657 else
1658 {
1659 PUVM pPrev = g_pUVMsHead;
1660 while (pPrev && pPrev->pNext != pUVM)
1661 pPrev = pPrev->pNext;
1662 AssertMsgReturn(pPrev, ("pUVM=%p / pVM=%p is INVALID!\n", pUVM, pVM), VERR_INVALID_PARAMETER);
1663
1664 pPrev->pNext = pUVM->pNext;
1665 }
1666 pUVM->pNext = NULL;
1667
1668 /*
1669 * Notify registered at destruction listeners.
1670 * (That's the debugger console.)
1671 */
1672 vmR3AtDtor(pVM);
1673
1674 /*
1675 * If we are the EMT of VCPU 0, then we'll delay the cleanup till later.
1676 */
1677 if (VMMGetCpuId(pVM) == 0)
1678 {
1679 pUVM->vm.s.fEMTDoesTheCleanup = true;
1680 pUVM->vm.s.fTerminateEMT = true;
1681 VM_FF_SET(pVM, VM_FF_TERMINATE);
1682
1683 /* Inform all other VCPUs too. */
1684 for (VMCPUID idCpu = 1; idCpu < pVM->cCPUs; idCpu++)
1685 {
1686 /*
1687 * Request EMT to do the larger part of the destruction.
1688 */
1689 PVMREQ pReq = NULL;
1690 int rc = VMR3ReqCallU(pUVM, idCpu, &pReq, RT_INDEFINITE_WAIT, 0, (PFNRT)vmR3Destroy, 1, pVM);
1691 if (RT_SUCCESS(rc))
1692 rc = pReq->iStatus;
1693 AssertRC(rc);
1694 VMR3ReqFree(pReq);
1695 }
1696 }
1697 else
1698 {
1699 /*
1700 * Request EMT to do the larger part of the destruction. (in reverse order as VCPU 0 does the real cleanup)
1701 */
1702 PVMREQ pReq = NULL;
1703 int rc = VMR3ReqCallU(pUVM, VMCPUID_ALL_REVERSE, &pReq, RT_INDEFINITE_WAIT, 0, (PFNRT)vmR3Destroy, 1, pVM);
1704 if (RT_SUCCESS(rc))
1705 rc = pReq->iStatus;
1706 AssertRC(rc);
1707 VMR3ReqFree(pReq);
1708
1709 /*
1710 * Now do the final bit where the heap and VM structures are freed up.
1711 * This will also wait 30 secs for the emulation threads to terminate.
1712 */
1713 vmR3DestroyUVM(pUVM, 30000);
1714 }
1715
1716 LogFlow(("VMR3Destroy: returns VINF_SUCCESS\n"));
1717 return VINF_SUCCESS;
1718}
1719
1720
1721/**
1722 * Internal destruction worker.
1723 *
1724 * This will do nearly all of the job, including sacking the EMT.
1725 *
1726 * @returns VBox status.
1727 * @param pVM VM handle.
1728 */
1729DECLCALLBACK(int) vmR3Destroy(PVM pVM)
1730{
1731 PUVM pUVM = pVM->pUVM;
1732 PVMCPU pVCpu = VMMGetCpu(pVM);
1733
1734 NOREF(pUVM);
1735 LogFlow(("vmR3Destroy: pVM=%p pUVM=%p\n", pVM, pUVM));
1736 VM_ASSERT_EMT(pVM);
1737
1738 /* Only VCPU 0 does the full cleanup. */
1739 if (pVCpu->idCpu != 0)
1740 return VINF_EM_TERMINATE;
1741
1742 /*
1743 * Dump statistics to the log.
1744 */
1745#if defined(VBOX_WITH_STATISTICS) || defined(LOG_ENABLED)
1746 RTLogFlags(NULL, "nodisabled nobuffered");
1747#endif
1748#ifdef VBOX_WITH_STATISTICS
1749 STAMR3Dump(pVM, "*");
1750#else
1751 LogRel(("************************* Statistics *************************\n"));
1752 STAMR3DumpToReleaseLog(pVM, "*");
1753 LogRel(("********************* End of statistics **********************\n"));
1754#endif
1755
1756 /*
1757 * Destroy the VM components.
1758 */
1759 int rc = TMR3Term(pVM);
1760 AssertRC(rc);
1761#ifdef VBOX_WITH_DEBUGGER
1762 rc = DBGCTcpTerminate(pVM, pUVM->vm.s.pvDBGC);
1763 pVM->pUVM->vm.s.pvDBGC = NULL;
1764#endif
1765 AssertRC(rc);
1766 rc = DBGFR3Term(pVM);
1767 AssertRC(rc);
1768 rc = PDMR3Term(pVM);
1769 AssertRC(rc);
1770 rc = EMR3Term(pVM);
1771 AssertRC(rc);
1772 rc = IOMR3Term(pVM);
1773 AssertRC(rc);
1774 rc = CSAMR3Term(pVM);
1775 AssertRC(rc);
1776 rc = PATMR3Term(pVM);
1777 AssertRC(rc);
1778 rc = TRPMR3Term(pVM);
1779 AssertRC(rc);
1780 rc = SELMR3Term(pVM);
1781 AssertRC(rc);
1782 rc = REMR3Term(pVM);
1783 AssertRC(rc);
1784 rc = HWACCMR3Term(pVM);
1785 AssertRC(rc);
1786 rc = PGMR3Term(pVM);
1787 AssertRC(rc);
1788 rc = VMMR3Term(pVM); /* Terminates the ring-0 code! */
1789 AssertRC(rc);
1790 rc = CPUMR3Term(pVM);
1791 AssertRC(rc);
1792 rc = PDMR3CritSectTerm(pVM);
1793 AssertRC(rc);
1794 rc = MMR3Term(pVM);
1795 AssertRC(rc);
1796
1797 /*
1798 * We're done in this thread (EMT).
1799 */
1800 ASMAtomicUoWriteBool(&pVM->pUVM->vm.s.fTerminateEMT, true);
1801 ASMAtomicWriteU32(&pVM->fGlobalForcedActions, VM_FF_TERMINATE);
1802 LogFlow(("vmR3Destroy: returning %Rrc\n", VINF_EM_TERMINATE));
1803 return VINF_EM_TERMINATE;
1804}
1805
1806
1807/**
1808 * Destroys the shared VM structure, leaving only UVM behind.
1809 *
1810 * This is called by EMT right before terminating.
1811 *
1812 * @param pUVM The UVM handle.
1813 */
1814void vmR3DestroyFinalBitFromEMT(PUVM pUVM)
1815{
1816 if (pUVM->pVM)
1817 {
1818 PVMCPU pVCpu = VMMGetCpu(pUVM->pVM);
1819
1820 /* VCPU 0 does all the cleanup work. */
1821 if (pVCpu->idCpu != 0)
1822 return;
1823
1824 /*
1825 * Modify state and then terminate MM.
1826 * (MM must be delayed until this point so we don't destroy the callbacks and the request packet.)
1827 */
1828 vmR3SetState(pUVM->pVM, VMSTATE_TERMINATED);
1829
1830 /*
1831 * Tell GVMM to destroy the VM and free its resources.
1832 */
1833 int rc = SUPCallVMMR0Ex(pUVM->pVM->pVMR0, 0 /* VCPU 0 */, VMMR0_DO_GVMM_DESTROY_VM, 0, NULL);
1834 AssertRC(rc);
1835 pUVM->pVM = NULL;
1836 }
1837
1838 /*
1839 * Did an EMT call VMR3Destroy and end up having to do all the work?
1840 */
1841 if (pUVM->vm.s.fEMTDoesTheCleanup)
1842 vmR3DestroyUVM(pUVM, 30000);
1843}
1844
1845
1846/**
1847 * Destroys the UVM portion.
1848 *
1849 * This is called as the final step in the VM destruction or as the cleanup
1850 * in case of a creation failure. If EMT called VMR3Destroy, meaning
1851 * VMINTUSERPERVM::fEMTDoesTheCleanup is true, it will call this as
1852 * vmR3DestroyFinalBitFromEMT completes.
1853 *
1854 * @param pVM VM Handle.
1855 * @param cMilliesEMTWait The number of milliseconds to wait for the emulation
1856 * threads.
1857 */
1858static void vmR3DestroyUVM(PUVM pUVM, uint32_t cMilliesEMTWait)
1859{
1860 /*
1861 * Signal termination of each the emulation threads and
1862 * wait for them to complete.
1863 */
1864 /* Signal them. */
1865 ASMAtomicUoWriteBool(&pUVM->vm.s.fTerminateEMT, true);
1866 for (VMCPUID i = 0; i < pUVM->cCpus; i++)
1867 {
1868 ASMAtomicUoWriteBool(&pUVM->aCpus[i].vm.s.fTerminateEMT, true);
1869 if (pUVM->pVM)
1870 VM_FF_SET(pUVM->pVM, VM_FF_TERMINATE);
1871 VMR3NotifyGlobalFFU(pUVM, VMNOTIFYFF_FLAGS_DONE_REM);
1872 RTSemEventSignal(pUVM->aCpus[i].vm.s.EventSemWait);
1873 }
1874
1875 /* Wait for them. */
1876 uint64_t NanoTS = RTTimeNanoTS();
1877 RTTHREAD hSelf = RTThreadSelf();
1878 ASMAtomicUoWriteBool(&pUVM->vm.s.fTerminateEMT, true);
1879 for (VMCPUID i = 0; i < pUVM->cCpus; i++)
1880 {
1881 RTTHREAD hThread = pUVM->aCpus[i].vm.s.ThreadEMT;
1882 if ( hThread != NIL_RTTHREAD
1883 && hThread != hSelf)
1884 {
1885 uint64_t cMilliesElapsed = (RTTimeNanoTS() - NanoTS) / 1000000;
1886 int rc2 = RTThreadWait(hThread,
1887 cMilliesElapsed < cMilliesEMTWait
1888 ? RT_MAX(cMilliesEMTWait - cMilliesElapsed, 2000)
1889 : 2000,
1890 NULL);
1891 if (rc2 == VERR_TIMEOUT) /* avoid the assertion when debugging. */
1892 rc2 = RTThreadWait(hThread, 1000, NULL);
1893 AssertLogRelMsgRC(rc2, ("i=%u rc=%Rrc\n", i, rc2));
1894 if (RT_SUCCESS(rc2))
1895 pUVM->aCpus[0].vm.s.ThreadEMT = NIL_RTTHREAD;
1896 }
1897 }
1898
1899 /* Cleanup the semaphores. */
1900 for (VMCPUID i = 0; i < pUVM->cCpus; i++)
1901 {
1902 RTSemEventDestroy(pUVM->aCpus[i].vm.s.EventSemWait);
1903 pUVM->aCpus[i].vm.s.EventSemWait = NIL_RTSEMEVENT;
1904 }
1905
1906 /*
1907 * Free the event semaphores associated with the request packets.
1908 */
1909 unsigned cReqs = 0;
1910 for (unsigned i = 0; i < RT_ELEMENTS(pUVM->vm.s.apReqFree); i++)
1911 {
1912 PVMREQ pReq = pUVM->vm.s.apReqFree[i];
1913 pUVM->vm.s.apReqFree[i] = NULL;
1914 for (; pReq; pReq = pReq->pNext, cReqs++)
1915 {
1916 pReq->enmState = VMREQSTATE_INVALID;
1917 RTSemEventDestroy(pReq->EventSem);
1918 }
1919 }
1920 Assert(cReqs == pUVM->vm.s.cReqFree); NOREF(cReqs);
1921
1922 /*
1923 * Kill all queued requests. (There really shouldn't be any!)
1924 */
1925 for (unsigned i = 0; i < 10; i++)
1926 {
1927 PVMREQ pReqHead = (PVMREQ)ASMAtomicXchgPtr((void *volatile *)&pUVM->vm.s.pReqs, NULL);
1928 AssertMsg(!pReqHead, ("This isn't supposed to happen! VMR3Destroy caller has to serialize this.\n"));
1929 if (!pReqHead)
1930 break;
1931 for (PVMREQ pReq = pReqHead; pReq; pReq = pReq->pNext)
1932 {
1933 ASMAtomicUoWriteSize(&pReq->iStatus, VERR_INTERNAL_ERROR);
1934 ASMAtomicWriteSize(&pReq->enmState, VMREQSTATE_INVALID);
1935 RTSemEventSignal(pReq->EventSem);
1936 RTThreadSleep(2);
1937 RTSemEventDestroy(pReq->EventSem);
1938 }
1939 /* give them a chance to respond before we free the request memory. */
1940 RTThreadSleep(32);
1941 }
1942
1943 /*
1944 * Now all queued VCPU requests (again, there shouldn't be any).
1945 */
1946 for (VMCPUID i = 0; i < pUVM->cCpus; i++)
1947 {
1948 PUVMCPU pUVCpu = &pUVM->aCpus[i];
1949
1950 for (unsigned i = 0; i < 10; i++)
1951 {
1952 PVMREQ pReqHead = (PVMREQ)ASMAtomicXchgPtr((void *volatile *)&pUVCpu->vm.s.pReqs, NULL);
1953 AssertMsg(!pReqHead, ("This isn't supposed to happen! VMR3Destroy caller has to serialize this.\n"));
1954 if (!pReqHead)
1955 break;
1956 for (PVMREQ pReq = pReqHead; pReq; pReq = pReq->pNext)
1957 {
1958 ASMAtomicUoWriteSize(&pReq->iStatus, VERR_INTERNAL_ERROR);
1959 ASMAtomicWriteSize(&pReq->enmState, VMREQSTATE_INVALID);
1960 RTSemEventSignal(pReq->EventSem);
1961 RTThreadSleep(2);
1962 RTSemEventDestroy(pReq->EventSem);
1963 }
1964 /* give them a chance to respond before we free the request memory. */
1965 RTThreadSleep(32);
1966 }
1967 }
1968
1969 /*
1970 * Make sure the VMMR0.r0 module and whatever else is unloaded.
1971 */
1972 PDMR3TermUVM(pUVM);
1973
1974 /*
1975 * Terminate the support library if initialized.
1976 */
1977 if (pUVM->vm.s.pSession)
1978 {
1979 int rc = SUPTerm();
1980 AssertRC(rc);
1981 pUVM->vm.s.pSession = NIL_RTR0PTR;
1982 }
1983
1984 /*
1985 * Destroy the MM heap and free the UVM structure.
1986 */
1987 MMR3TermUVM(pUVM);
1988 STAMR3TermUVM(pUVM);
1989
1990 RTTlsFree(pUVM->vm.s.idxTLS);
1991
1992 ASMAtomicUoWriteU32(&pUVM->u32Magic, UINT32_MAX);
1993 RTMemFree(pUVM);
1994
1995 RTLogFlush(NULL);
1996}
1997
1998
1999/**
2000 * Enumerates the VMs in this process.
2001 *
2002 * @returns Pointer to the next VM.
2003 * @returns NULL when no more VMs.
2004 * @param pVMPrev The previous VM
2005 * Use NULL to start the enumeration.
2006 */
2007VMMR3DECL(PVM) VMR3EnumVMs(PVM pVMPrev)
2008{
2009 /*
2010 * This is quick and dirty. It has issues with VM being
2011 * destroyed during the enumeration.
2012 */
2013 PUVM pNext;
2014 if (pVMPrev)
2015 pNext = pVMPrev->pUVM->pNext;
2016 else
2017 pNext = g_pUVMsHead;
2018 return pNext ? pNext->pVM : NULL;
2019}
2020
2021
2022/**
2023 * Registers an at VM destruction callback.
2024 *
2025 * @returns VBox status code.
2026 * @param pfnAtDtor Pointer to callback.
2027 * @param pvUser User argument.
2028 */
2029VMMR3DECL(int) VMR3AtDtorRegister(PFNVMATDTOR pfnAtDtor, void *pvUser)
2030{
2031 /*
2032 * Check if already registered.
2033 */
2034 VM_ATDTOR_LOCK();
2035 PVMATDTOR pCur = g_pVMAtDtorHead;
2036 while (pCur)
2037 {
2038 if (pfnAtDtor == pCur->pfnAtDtor)
2039 {
2040 VM_ATDTOR_UNLOCK();
2041 AssertMsgFailed(("Already registered at destruction callback %p!\n", pfnAtDtor));
2042 return VERR_INVALID_PARAMETER;
2043 }
2044
2045 /* next */
2046 pCur = pCur->pNext;
2047 }
2048 VM_ATDTOR_UNLOCK();
2049
2050 /*
2051 * Allocate new entry.
2052 */
2053 PVMATDTOR pVMAtDtor = (PVMATDTOR)RTMemAlloc(sizeof(*pVMAtDtor));
2054 if (!pVMAtDtor)
2055 return VERR_NO_MEMORY;
2056
2057 VM_ATDTOR_LOCK();
2058 pVMAtDtor->pfnAtDtor = pfnAtDtor;
2059 pVMAtDtor->pvUser = pvUser;
2060 pVMAtDtor->pNext = g_pVMAtDtorHead;
2061 g_pVMAtDtorHead = pVMAtDtor;
2062 VM_ATDTOR_UNLOCK();
2063
2064 return VINF_SUCCESS;
2065}
2066
2067
2068/**
2069 * Deregisters an at VM destruction callback.
2070 *
2071 * @returns VBox status code.
2072 * @param pfnAtDtor Pointer to callback.
2073 */
2074VMMR3DECL(int) VMR3AtDtorDeregister(PFNVMATDTOR pfnAtDtor)
2075{
2076 /*
2077 * Find it, unlink it and free it.
2078 */
2079 VM_ATDTOR_LOCK();
2080 PVMATDTOR pPrev = NULL;
2081 PVMATDTOR pCur = g_pVMAtDtorHead;
2082 while (pCur)
2083 {
2084 if (pfnAtDtor == pCur->pfnAtDtor)
2085 {
2086 if (pPrev)
2087 pPrev->pNext = pCur->pNext;
2088 else
2089 g_pVMAtDtorHead = pCur->pNext;
2090 pCur->pNext = NULL;
2091 VM_ATDTOR_UNLOCK();
2092
2093 RTMemFree(pCur);
2094 return VINF_SUCCESS;
2095 }
2096
2097 /* next */
2098 pPrev = pCur;
2099 pCur = pCur->pNext;
2100 }
2101 VM_ATDTOR_UNLOCK();
2102
2103 return VERR_INVALID_PARAMETER;
2104}
2105
2106
2107/**
2108 * Walks the list of at VM destructor callbacks.
2109 * @param pVM The VM which is about to be destroyed.
2110 */
2111static void vmR3AtDtor(PVM pVM)
2112{
2113 /*
2114 * Find it, unlink it and free it.
2115 */
2116 VM_ATDTOR_LOCK();
2117 for (PVMATDTOR pCur = g_pVMAtDtorHead; pCur; pCur = pCur->pNext)
2118 pCur->pfnAtDtor(pVM, pCur->pvUser);
2119 VM_ATDTOR_UNLOCK();
2120}
2121
2122
2123/**
2124 * Reset the current VM.
2125 *
2126 * @returns VBox status code.
2127 * @param pVM VM to reset.
2128 */
2129VMMR3DECL(int) VMR3Reset(PVM pVM)
2130{
2131 int rc = VINF_SUCCESS;
2132
2133 /*
2134 * Check the state.
2135 */
2136 if (!pVM)
2137 return VERR_INVALID_PARAMETER;
2138 if ( pVM->enmVMState != VMSTATE_RUNNING
2139 && pVM->enmVMState != VMSTATE_SUSPENDED)
2140 {
2141 AssertMsgFailed(("Invalid VM state %d\n", pVM->enmVMState));
2142 return VERR_VM_INVALID_VM_STATE;
2143 }
2144
2145 /*
2146 * Queue reset request to the emulation thread
2147 * and wait for it to be processed. (in reverse order as VCPU 0 does the real cleanup)
2148 */
2149 PVMREQ pReq = NULL;
2150 rc = VMR3ReqCall(pVM, VMCPUID_ALL_REVERSE, &pReq, RT_INDEFINITE_WAIT, (PFNRT)vmR3Reset, 1, pVM);
2151 /** @note Can this really happen?? */
2152 while (rc == VERR_TIMEOUT)
2153 rc = VMR3ReqWait(pReq, RT_INDEFINITE_WAIT);
2154
2155 if (RT_SUCCESS(rc))
2156 rc = pReq->iStatus;
2157 AssertRC(rc);
2158 VMR3ReqFree(pReq);
2159
2160 return rc;
2161}
2162
2163
2164/**
2165 * Worker which checks integrity of some internal structures.
2166 * This is yet another attempt to track down that AVL tree crash.
2167 */
2168static void vmR3CheckIntegrity(PVM pVM)
2169{
2170#ifdef VBOX_STRICT
2171 int rc = PGMR3CheckIntegrity(pVM);
2172 AssertReleaseRC(rc);
2173#endif
2174}
2175
2176
2177/**
2178 * Reset request processor.
2179 *
2180 * This is called by the emulation thread as a response to the
2181 * reset request issued by VMR3Reset().
2182 *
2183 * @returns VBox status code.
2184 * @param pVM VM to reset.
2185 */
2186static DECLCALLBACK(int) vmR3Reset(PVM pVM)
2187{
2188 PVMCPU pVCpu = VMMGetCpu(pVM);
2189
2190 /* Only VCPU 0 does the full cleanup. */
2191 if (pVCpu->idCpu != 0)
2192 return VINF_EM_RESET;
2193
2194 /*
2195 * As a safety precaution we temporarily change the state while resetting.
2196 * (If VMR3Reset was not called from EMT we might have change state... let's ignore that fact for now.)
2197 */
2198 VMSTATE enmVMState = pVM->enmVMState;
2199 Assert(enmVMState == VMSTATE_SUSPENDED || enmVMState == VMSTATE_RUNNING);
2200 vmR3SetState(pVM, VMSTATE_RESETTING);
2201 vmR3CheckIntegrity(pVM);
2202
2203
2204 /*
2205 * Reset the VM components.
2206 */
2207 PATMR3Reset(pVM);
2208 CSAMR3Reset(pVM);
2209 PGMR3Reset(pVM); /* We clear VM RAM in PGMR3Reset. It's vital PDMR3Reset is executed
2210 * _afterwards_. E.g. ACPI sets up RAM tables during init/reset. */
2211 MMR3Reset(pVM);
2212 PDMR3Reset(pVM);
2213 SELMR3Reset(pVM);
2214 TRPMR3Reset(pVM);
2215 vmR3AtResetU(pVM->pUVM);
2216 REMR3Reset(pVM);
2217 IOMR3Reset(pVM);
2218 CPUMR3Reset(pVM);
2219 TMR3Reset(pVM);
2220 EMR3Reset(pVM);
2221 HWACCMR3Reset(pVM); /* This must come *after* PATM, CSAM, CPUM, SELM and TRPM. */
2222
2223#ifdef LOG_ENABLED
2224 /*
2225 * Debug logging.
2226 */
2227 RTLogPrintf("\n\nThe VM was reset:\n");
2228 DBGFR3Info(pVM, "cpum", "verbose", NULL);
2229#endif
2230
2231 /*
2232 * Restore the state.
2233 */
2234 vmR3CheckIntegrity(pVM);
2235 Assert(pVM->enmVMState == VMSTATE_RESETTING);
2236 vmR3SetState(pVM, enmVMState);
2237
2238 return VINF_EM_RESET;
2239}
2240
2241
2242/**
2243 * Walks the list of at VM reset callbacks and calls them
2244 *
2245 * @returns VBox status code.
2246 * Any failure is fatal.
2247 * @param pUVM Pointe to the user mode VM structure.
2248 */
2249static int vmR3AtResetU(PUVM pUVM)
2250{
2251 /*
2252 * Walk the list and call them all.
2253 */
2254 int rc = VINF_SUCCESS;
2255 for (PVMATRESET pCur = pUVM->vm.s.pAtReset; pCur; pCur = pCur->pNext)
2256 {
2257 /* do the call */
2258 switch (pCur->enmType)
2259 {
2260 case VMATRESETTYPE_DEV:
2261 rc = pCur->u.Dev.pfnCallback(pCur->u.Dev.pDevIns, pCur->pvUser);
2262 break;
2263 case VMATRESETTYPE_INTERNAL:
2264 rc = pCur->u.Internal.pfnCallback(pUVM->pVM, pCur->pvUser);
2265 break;
2266 case VMATRESETTYPE_EXTERNAL:
2267 pCur->u.External.pfnCallback(pCur->pvUser);
2268 break;
2269 default:
2270 AssertMsgFailed(("Invalid at-reset type %d!\n", pCur->enmType));
2271 return VERR_INTERNAL_ERROR;
2272 }
2273
2274 if (RT_FAILURE(rc))
2275 {
2276 AssertMsgFailed(("At-reset handler %s failed with rc=%d\n", pCur->pszDesc, rc));
2277 return rc;
2278 }
2279 }
2280
2281 return VINF_SUCCESS;
2282}
2283
2284
2285/**
2286 * Internal registration function
2287 */
2288static int vmr3AtResetRegisterU(PUVM pUVM, void *pvUser, const char *pszDesc, PVMATRESET *ppNew)
2289{
2290 /*
2291 * Allocate restration structure.
2292 */
2293 PVMATRESET pNew = (PVMATRESET)MMR3HeapAllocU(pUVM, MM_TAG_VM, sizeof(*pNew));
2294 if (pNew)
2295 {
2296 /* fill data. */
2297 pNew->pszDesc = pszDesc;
2298 pNew->pvUser = pvUser;
2299
2300 /* insert */
2301 pNew->pNext = *pUVM->vm.s.ppAtResetNext;
2302 *pUVM->vm.s.ppAtResetNext = pNew;
2303 pUVM->vm.s.ppAtResetNext = &pNew->pNext;
2304
2305 *ppNew = pNew;
2306 return VINF_SUCCESS;
2307 }
2308 return VERR_NO_MEMORY;
2309}
2310
2311
2312/**
2313 * Registers an at VM reset callback.
2314 *
2315 * @returns VBox status code.
2316 * @param pVM The VM.
2317 * @param pDevInst Device instance.
2318 * @param pfnCallback Callback function.
2319 * @param pvUser User argument.
2320 * @param pszDesc Description (optional).
2321 */
2322VMMR3DECL(int) VMR3AtResetRegister(PVM pVM, PPDMDEVINS pDevInst, PFNVMATRESET pfnCallback, void *pvUser, const char *pszDesc)
2323{
2324 /*
2325 * Validate.
2326 */
2327 if (!pDevInst)
2328 {
2329 AssertMsgFailed(("pDevIns is NULL!\n"));
2330 return VERR_INVALID_PARAMETER;
2331 }
2332
2333 /*
2334 * Create the new entry.
2335 */
2336 PVMATRESET pNew;
2337 int rc = vmr3AtResetRegisterU(pVM->pUVM, pvUser, pszDesc, &pNew);
2338 if (RT_SUCCESS(rc))
2339 {
2340 /*
2341 * Fill in type data.
2342 */
2343 pNew->enmType = VMATRESETTYPE_DEV;
2344 pNew->u.Dev.pfnCallback = pfnCallback;
2345 pNew->u.Dev.pDevIns = pDevInst;
2346 }
2347
2348 return rc;
2349}
2350
2351
2352/**
2353 * Registers an at VM reset internal callback.
2354 *
2355 * @returns VBox status code.
2356 * @param pVM The VM.
2357 * @param pfnCallback Callback function.
2358 * @param pvUser User argument.
2359 * @param pszDesc Description (optional).
2360 */
2361VMMR3DECL(int) VMR3AtResetRegisterInternal(PVM pVM, PFNVMATRESETINT pfnCallback, void *pvUser, const char *pszDesc)
2362{
2363 /*
2364 * Validate.
2365 */
2366 if (!pfnCallback)
2367 {
2368 AssertMsgFailed(("pfnCallback is NULL!\n"));
2369 return VERR_INVALID_PARAMETER;
2370 }
2371
2372 /*
2373 * Create the new entry.
2374 */
2375 PVMATRESET pNew;
2376 int rc = vmr3AtResetRegisterU(pVM->pUVM, pvUser, pszDesc, &pNew);
2377 if (RT_SUCCESS(rc))
2378 {
2379 /*
2380 * Fill in type data.
2381 */
2382 pNew->enmType = VMATRESETTYPE_INTERNAL;
2383 pNew->u.Internal.pfnCallback = pfnCallback;
2384 }
2385
2386 return rc;
2387}
2388
2389
2390/**
2391 * Registers an at VM reset external callback.
2392 *
2393 * @returns VBox status code.
2394 * @param pVM The VM.
2395 * @param pfnCallback Callback function.
2396 * @param pvUser User argument.
2397 * @param pszDesc Description (optional).
2398 */
2399VMMR3DECL(int) VMR3AtResetRegisterExternal(PVM pVM, PFNVMATRESETEXT pfnCallback, void *pvUser, const char *pszDesc)
2400{
2401 /*
2402 * Validate.
2403 */
2404 if (!pfnCallback)
2405 {
2406 AssertMsgFailed(("pfnCallback is NULL!\n"));
2407 return VERR_INVALID_PARAMETER;
2408 }
2409
2410 /*
2411 * Create the new entry.
2412 */
2413 PVMATRESET pNew;
2414 int rc = vmr3AtResetRegisterU(pVM->pUVM, pvUser, pszDesc, &pNew);
2415 if (RT_SUCCESS(rc))
2416 {
2417 /*
2418 * Fill in type data.
2419 */
2420 pNew->enmType = VMATRESETTYPE_EXTERNAL;
2421 pNew->u.External.pfnCallback = pfnCallback;
2422 }
2423
2424 return rc;
2425}
2426
2427
2428/**
2429 * Unlinks and frees a callback.
2430 *
2431 * @returns Pointer to the next callback structure.
2432 * @param pUVM Pointer to the user mode VM structure.
2433 * @param pCur The one to free.
2434 * @param pPrev The one before pCur.
2435 */
2436static PVMATRESET vmr3AtResetFreeU(PUVM pUVM, PVMATRESET pCur, PVMATRESET pPrev)
2437{
2438 /*
2439 * Unlink it.
2440 */
2441 PVMATRESET pNext = pCur->pNext;
2442 if (pPrev)
2443 {
2444 pPrev->pNext = pNext;
2445 if (!pNext)
2446 pUVM->vm.s.ppAtResetNext = &pPrev->pNext;
2447 }
2448 else
2449 {
2450 pUVM->vm.s.pAtReset = pNext;
2451 if (!pNext)
2452 pUVM->vm.s.ppAtResetNext = &pUVM->vm.s.pAtReset;
2453 }
2454
2455 /*
2456 * Free it.
2457 */
2458 MMR3HeapFree(pCur);
2459
2460 return pNext;
2461}
2462
2463
2464/**
2465 * Deregisters an at VM reset callback.
2466 *
2467 * @returns VBox status code.
2468 * @param pVM The VM.
2469 * @param pDevIns Device instance.
2470 * @param pfnCallback Callback function.
2471 */
2472VMMR3DECL(int) VMR3AtResetDeregister(PVM pVM, PPDMDEVINS pDevIns, PFNVMATRESET pfnCallback)
2473{
2474 int rc = VERR_VM_ATRESET_NOT_FOUND;
2475 PVMATRESET pPrev = NULL;
2476 PVMATRESET pCur = pVM->pUVM->vm.s.pAtReset;
2477 while (pCur)
2478 {
2479 if ( pCur->enmType == VMATRESETTYPE_DEV
2480 && pCur->u.Dev.pDevIns == pDevIns
2481 && ( !pfnCallback
2482 || pCur->u.Dev.pfnCallback == pfnCallback))
2483 {
2484 pCur = vmr3AtResetFreeU(pVM->pUVM, pCur, pPrev);
2485 rc = VINF_SUCCESS;
2486 }
2487 else
2488 {
2489 pPrev = pCur;
2490 pCur = pCur->pNext;
2491 }
2492 }
2493
2494 AssertRC(rc);
2495 return rc;
2496}
2497
2498
2499/**
2500 * Deregisters an at VM reset internal callback.
2501 *
2502 * @returns VBox status code.
2503 * @param pVM The VM.
2504 * @param pfnCallback Callback function.
2505 */
2506VMMR3DECL(int) VMR3AtResetDeregisterInternal(PVM pVM, PFNVMATRESETINT pfnCallback)
2507{
2508 int rc = VERR_VM_ATRESET_NOT_FOUND;
2509 PVMATRESET pPrev = NULL;
2510 PVMATRESET pCur = pVM->pUVM->vm.s.pAtReset;
2511 while (pCur)
2512 {
2513 if ( pCur->enmType == VMATRESETTYPE_INTERNAL
2514 && pCur->u.Internal.pfnCallback == pfnCallback)
2515 {
2516 pCur = vmr3AtResetFreeU(pVM->pUVM, pCur, pPrev);
2517 rc = VINF_SUCCESS;
2518 }
2519 else
2520 {
2521 pPrev = pCur;
2522 pCur = pCur->pNext;
2523 }
2524 }
2525
2526 AssertRC(rc);
2527 return rc;
2528}
2529
2530
2531/**
2532 * Deregisters an at VM reset external callback.
2533 *
2534 * @returns VBox status code.
2535 * @param pVM The VM.
2536 * @param pfnCallback Callback function.
2537 */
2538VMMR3DECL(int) VMR3AtResetDeregisterExternal(PVM pVM, PFNVMATRESETEXT pfnCallback)
2539{
2540 int rc = VERR_VM_ATRESET_NOT_FOUND;
2541 PVMATRESET pPrev = NULL;
2542 PVMATRESET pCur = pVM->pUVM->vm.s.pAtReset;
2543 while (pCur)
2544 {
2545 if ( pCur->enmType == VMATRESETTYPE_INTERNAL
2546 && pCur->u.External.pfnCallback == pfnCallback)
2547 {
2548 pCur = vmr3AtResetFreeU(pVM->pUVM, pCur, pPrev);
2549 rc = VINF_SUCCESS;
2550 }
2551 else
2552 {
2553 pPrev = pCur;
2554 pCur = pCur->pNext;
2555 }
2556 }
2557
2558 AssertRC(rc);
2559 return rc;
2560}
2561
2562
2563/**
2564 * Gets the current VM state.
2565 *
2566 * @returns The current VM state.
2567 * @param pVM VM handle.
2568 * @thread Any
2569 */
2570VMMR3DECL(VMSTATE) VMR3GetState(PVM pVM)
2571{
2572 return pVM->enmVMState;
2573}
2574
2575
2576/**
2577 * Gets the state name string for a VM state.
2578 *
2579 * @returns Pointer to the state name. (readonly)
2580 * @param enmState The state.
2581 */
2582VMMR3DECL(const char *) VMR3GetStateName(VMSTATE enmState)
2583{
2584 switch (enmState)
2585 {
2586 case VMSTATE_CREATING: return "CREATING";
2587 case VMSTATE_CREATED: return "CREATED";
2588 case VMSTATE_RUNNING: return "RUNNING";
2589 case VMSTATE_LOADING: return "LOADING";
2590 case VMSTATE_LOAD_FAILURE: return "LOAD_FAILURE";
2591 case VMSTATE_SAVING: return "SAVING";
2592 case VMSTATE_SUSPENDED: return "SUSPENDED";
2593 case VMSTATE_RESETTING: return "RESETTING";
2594 case VMSTATE_GURU_MEDITATION: return "GURU_MEDITATION";
2595 case VMSTATE_OFF: return "OFF";
2596 case VMSTATE_DESTROYING: return "DESTROYING";
2597 case VMSTATE_TERMINATED: return "TERMINATED";
2598 default:
2599 AssertMsgFailed(("Unknown state %d\n", enmState));
2600 return "Unknown!\n";
2601 }
2602}
2603
2604
2605/**
2606 * Sets the current VM state.
2607 *
2608 * @returns The current VM state.
2609 * @param pVM VM handle.
2610 * @param enmStateNew The new state.
2611 */
2612void vmR3SetState(PVM pVM, VMSTATE enmStateNew)
2613{
2614 /*
2615 * Validate state machine transitions before doing the actual change.
2616 */
2617 VMSTATE enmStateOld = pVM->enmVMState;
2618 switch (enmStateOld)
2619 {
2620 case VMSTATE_OFF:
2621 Assert(enmStateNew != VMSTATE_GURU_MEDITATION);
2622 break;
2623
2624 default:
2625 /** @todo full validation. */
2626 break;
2627 }
2628
2629 pVM->enmVMState = enmStateNew;
2630 LogRel(("Changing the VM state from '%s' to '%s'.\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)));
2631
2632 /*
2633 * Call the at state change callbacks.
2634 */
2635 for (PVMATSTATE pCur = pVM->pUVM->vm.s.pAtState; pCur; pCur = pCur->pNext)
2636 {
2637 pCur->pfnAtState(pVM, enmStateNew, enmStateOld, pCur->pvUser);
2638 if ( pVM->enmVMState != enmStateNew
2639 && pVM->enmVMState == VMSTATE_DESTROYING)
2640 break;
2641 AssertMsg(pVM->enmVMState == enmStateNew,
2642 ("You are not allowed to change the state while in the change callback, except "
2643 "from destroying the VM. There are restrictions in the way the state changes "
2644 "are propagated up to the EM execution loop and it makes the program flow very "
2645 "difficult to follow.\n"));
2646 }
2647}
2648
2649
2650/**
2651 * Registers a VM state change callback.
2652 *
2653 * You are not allowed to call any function which changes the VM state from a
2654 * state callback, except VMR3Destroy().
2655 *
2656 * @returns VBox status code.
2657 * @param pVM VM handle.
2658 * @param pfnAtState Pointer to callback.
2659 * @param pvUser User argument.
2660 * @thread Any.
2661 */
2662VMMR3DECL(int) VMR3AtStateRegister(PVM pVM, PFNVMATSTATE pfnAtState, void *pvUser)
2663{
2664 LogFlow(("VMR3AtStateRegister: pfnAtState=%p pvUser=%p\n", pfnAtState, pvUser));
2665
2666 /*
2667 * Validate input.
2668 */
2669 if (!pfnAtState)
2670 {
2671 AssertMsgFailed(("callback is required\n"));
2672 return VERR_INVALID_PARAMETER;
2673 }
2674
2675 /*
2676 * Make sure we're in EMT (to avoid the logging).
2677 */
2678 PVMREQ pReq;
2679 int rc = VMR3ReqCall(pVM, VMCPUID_ANY, &pReq, RT_INDEFINITE_WAIT, (PFNRT)vmR3AtStateRegisterU, 3, pVM->pUVM, pfnAtState, pvUser);
2680 if (RT_FAILURE(rc))
2681 return rc;
2682 rc = pReq->iStatus;
2683 VMR3ReqFree(pReq);
2684
2685 LogFlow(("VMR3AtStateRegister: returns %Rrc\n", rc));
2686 return rc;
2687}
2688
2689
2690/**
2691 * Registers a VM state change callback.
2692 *
2693 * @returns VBox status code.
2694 * @param pUVM Pointer to the user mode VM structure.
2695 * @param pfnAtState Pointer to callback.
2696 * @param pvUser User argument.
2697 * @thread EMT
2698 */
2699static DECLCALLBACK(int) vmR3AtStateRegisterU(PUVM pUVM, PFNVMATSTATE pfnAtState, void *pvUser)
2700{
2701 /*
2702 * Allocate a new record.
2703 */
2704
2705 PVMATSTATE pNew = (PVMATSTATE)MMR3HeapAllocU(pUVM, MM_TAG_VM, sizeof(*pNew));
2706 if (!pNew)
2707 return VERR_NO_MEMORY;
2708
2709 /* fill */
2710 pNew->pfnAtState = pfnAtState;
2711 pNew->pvUser = pvUser;
2712
2713 /* insert */
2714 pNew->pNext = *pUVM->vm.s.ppAtStateNext;
2715 *pUVM->vm.s.ppAtStateNext = pNew;
2716 pUVM->vm.s.ppAtStateNext = &pNew->pNext;
2717
2718 return VINF_SUCCESS;
2719}
2720
2721
2722/**
2723 * Deregisters a VM state change callback.
2724 *
2725 * @returns VBox status code.
2726 * @param pVM VM handle.
2727 * @param pfnAtState Pointer to callback.
2728 * @param pvUser User argument.
2729 * @thread Any.
2730 */
2731VMMR3DECL(int) VMR3AtStateDeregister(PVM pVM, PFNVMATSTATE pfnAtState, void *pvUser)
2732{
2733 LogFlow(("VMR3AtStateDeregister: pfnAtState=%p pvUser=%p\n", pfnAtState, pvUser));
2734
2735 /*
2736 * Validate input.
2737 */
2738 if (!pfnAtState)
2739 {
2740 AssertMsgFailed(("callback is required\n"));
2741 return VERR_INVALID_PARAMETER;
2742 }
2743
2744 /*
2745 * Make sure we're in EMT (to avoid the logging).
2746 */
2747 PVMREQ pReq;
2748 int rc = VMR3ReqCall(pVM, VMCPUID_ANY, &pReq, RT_INDEFINITE_WAIT, (PFNRT)vmR3AtStateDeregisterU, 3, pVM->pUVM, pfnAtState, pvUser);
2749 if (RT_FAILURE(rc))
2750 return rc;
2751 rc = pReq->iStatus;
2752 VMR3ReqFree(pReq);
2753
2754 LogFlow(("VMR3AtStateDeregister: returns %Rrc\n", rc));
2755 return rc;
2756}
2757
2758
2759/**
2760 * Deregisters a VM state change callback.
2761 *
2762 * @returns VBox status code.
2763 * @param pUVM Pointer to the user mode VM structure.
2764 * @param pfnAtState Pointer to callback.
2765 * @param pvUser User argument.
2766 * @thread EMT
2767 */
2768static DECLCALLBACK(int) vmR3AtStateDeregisterU(PUVM pUVM, PFNVMATSTATE pfnAtState, void *pvUser)
2769{
2770 LogFlow(("vmR3AtStateDeregisterU: pfnAtState=%p pvUser=%p\n", pfnAtState, pvUser));
2771
2772 /*
2773 * Search the list for the entry.
2774 */
2775 PVMATSTATE pPrev = NULL;
2776 PVMATSTATE pCur = pUVM->vm.s.pAtState;
2777 while ( pCur
2778 && ( pCur->pfnAtState != pfnAtState
2779 || pCur->pvUser != pvUser))
2780 {
2781 pPrev = pCur;
2782 pCur = pCur->pNext;
2783 }
2784 if (!pCur)
2785 {
2786 AssertMsgFailed(("pfnAtState=%p was not found\n", pfnAtState));
2787 return VERR_FILE_NOT_FOUND;
2788 }
2789
2790 /*
2791 * Unlink it.
2792 */
2793 if (pPrev)
2794 {
2795 pPrev->pNext = pCur->pNext;
2796 if (!pCur->pNext)
2797 pUVM->vm.s.ppAtStateNext = &pPrev->pNext;
2798 }
2799 else
2800 {
2801 pUVM->vm.s.pAtState = pCur->pNext;
2802 if (!pCur->pNext)
2803 pUVM->vm.s.ppAtStateNext = &pUVM->vm.s.pAtState;
2804 }
2805
2806 /*
2807 * Free it.
2808 */
2809 pCur->pfnAtState = NULL;
2810 pCur->pNext = NULL;
2811 MMR3HeapFree(pCur);
2812
2813 return VINF_SUCCESS;
2814}
2815
2816
2817/**
2818 * Registers a VM error callback.
2819 *
2820 * @returns VBox status code.
2821 * @param pVM The VM handle.
2822 * @param pfnAtError Pointer to callback.
2823 * @param pvUser User argument.
2824 * @thread Any.
2825 */
2826VMMR3DECL(int) VMR3AtErrorRegister(PVM pVM, PFNVMATERROR pfnAtError, void *pvUser)
2827{
2828 return VMR3AtErrorRegisterU(pVM->pUVM, pfnAtError, pvUser);
2829}
2830
2831
2832/**
2833 * Registers a VM error callback.
2834 *
2835 * @returns VBox status code.
2836 * @param pUVM The VM handle.
2837 * @param pfnAtError Pointer to callback.
2838 * @param pvUser User argument.
2839 * @thread Any.
2840 */
2841VMMR3DECL(int) VMR3AtErrorRegisterU(PUVM pUVM, PFNVMATERROR pfnAtError, void *pvUser)
2842{
2843 LogFlow(("VMR3AtErrorRegister: pfnAtError=%p pvUser=%p\n", pfnAtError, pvUser));
2844 AssertPtrReturn(pfnAtError, VERR_INVALID_PARAMETER);
2845
2846 /*
2847 * Make sure we're in EMT (to avoid the logging).
2848 */
2849 PVMREQ pReq;
2850 int rc = VMR3ReqCallU(pUVM, VMCPUID_ANY, &pReq, RT_INDEFINITE_WAIT, 0, (PFNRT)vmR3AtErrorRegisterU, 3, pUVM, pfnAtError, pvUser);
2851 if (RT_FAILURE(rc))
2852 return rc;
2853 rc = pReq->iStatus;
2854 VMR3ReqFree(pReq);
2855
2856 LogFlow(("VMR3AtErrorRegister: returns %Rrc\n", rc));
2857 return rc;
2858}
2859
2860
2861/**
2862 * Registers a VM error callback.
2863 *
2864 * @returns VBox status code.
2865 * @param pUVM Pointer to the user mode VM structure.
2866 * @param pfnAtError Pointer to callback.
2867 * @param pvUser User argument.
2868 * @thread EMT
2869 */
2870static DECLCALLBACK(int) vmR3AtErrorRegisterU(PUVM pUVM, PFNVMATERROR pfnAtError, void *pvUser)
2871{
2872 /*
2873 * Allocate a new record.
2874 */
2875
2876 PVMATERROR pNew = (PVMATERROR)MMR3HeapAllocU(pUVM, MM_TAG_VM, sizeof(*pNew));
2877 if (!pNew)
2878 return VERR_NO_MEMORY;
2879
2880 /* fill */
2881 pNew->pfnAtError = pfnAtError;
2882 pNew->pvUser = pvUser;
2883
2884 /* insert */
2885 pNew->pNext = *pUVM->vm.s.ppAtErrorNext;
2886 *pUVM->vm.s.ppAtErrorNext = pNew;
2887 pUVM->vm.s.ppAtErrorNext = &pNew->pNext;
2888
2889 return VINF_SUCCESS;
2890}
2891
2892
2893/**
2894 * Deregisters a VM error callback.
2895 *
2896 * @returns VBox status code.
2897 * @param pVM The VM handle.
2898 * @param pfnAtError Pointer to callback.
2899 * @param pvUser User argument.
2900 * @thread Any.
2901 */
2902VMMR3DECL(int) VMR3AtErrorDeregister(PVM pVM, PFNVMATERROR pfnAtError, void *pvUser)
2903{
2904 LogFlow(("VMR3AtErrorDeregister: pfnAtError=%p pvUser=%p\n", pfnAtError, pvUser));
2905
2906 /*
2907 * Validate input.
2908 */
2909 if (!pfnAtError)
2910 {
2911 AssertMsgFailed(("callback is required\n"));
2912 return VERR_INVALID_PARAMETER;
2913 }
2914
2915 /*
2916 * Make sure we're in EMT (to avoid the logging).
2917 */
2918 PVMREQ pReq;
2919 int rc = VMR3ReqCall(pVM, VMCPUID_ANY, &pReq, RT_INDEFINITE_WAIT, (PFNRT)vmR3AtErrorDeregisterU, 3, pVM->pUVM, pfnAtError, pvUser);
2920 if (RT_FAILURE(rc))
2921 return rc;
2922 rc = pReq->iStatus;
2923 VMR3ReqFree(pReq);
2924
2925 LogFlow(("VMR3AtErrorDeregister: returns %Rrc\n", rc));
2926 return rc;
2927}
2928
2929
2930/**
2931 * Deregisters a VM error callback.
2932 *
2933 * @returns VBox status code.
2934 * @param pUVM Pointer to the user mode VM structure.
2935 * @param pfnAtError Pointer to callback.
2936 * @param pvUser User argument.
2937 * @thread EMT
2938 */
2939static DECLCALLBACK(int) vmR3AtErrorDeregisterU(PUVM pUVM, PFNVMATERROR pfnAtError, void *pvUser)
2940{
2941 LogFlow(("vmR3AtErrorDeregisterU: pfnAtError=%p pvUser=%p\n", pfnAtError, pvUser));
2942
2943 /*
2944 * Search the list for the entry.
2945 */
2946 PVMATERROR pPrev = NULL;
2947 PVMATERROR pCur = pUVM->vm.s.pAtError;
2948 while ( pCur
2949 && ( pCur->pfnAtError != pfnAtError
2950 || pCur->pvUser != pvUser))
2951 {
2952 pPrev = pCur;
2953 pCur = pCur->pNext;
2954 }
2955 if (!pCur)
2956 {
2957 AssertMsgFailed(("pfnAtError=%p was not found\n", pfnAtError));
2958 return VERR_FILE_NOT_FOUND;
2959 }
2960
2961 /*
2962 * Unlink it.
2963 */
2964 if (pPrev)
2965 {
2966 pPrev->pNext = pCur->pNext;
2967 if (!pCur->pNext)
2968 pUVM->vm.s.ppAtErrorNext = &pPrev->pNext;
2969 }
2970 else
2971 {
2972 pUVM->vm.s.pAtError = pCur->pNext;
2973 if (!pCur->pNext)
2974 pUVM->vm.s.ppAtErrorNext = &pUVM->vm.s.pAtError;
2975 }
2976
2977 /*
2978 * Free it.
2979 */
2980 pCur->pfnAtError = NULL;
2981 pCur->pNext = NULL;
2982 MMR3HeapFree(pCur);
2983
2984 return VINF_SUCCESS;
2985}
2986
2987
2988/**
2989 * Ellipsis to va_list wrapper for calling pfnAtError.
2990 */
2991static void vmR3SetErrorWorkerDoCall(PVM pVM, PVMATERROR pCur, int rc, RT_SRC_POS_DECL, const char *pszFormat, ...)
2992{
2993 va_list va;
2994 va_start(va, pszFormat);
2995 pCur->pfnAtError(pVM, pCur->pvUser, rc, RT_SRC_POS_ARGS, pszFormat, va);
2996 va_end(va);
2997}
2998
2999
3000/**
3001 * This is a worker function for GC and Ring-0 calls to VMSetError and VMSetErrorV.
3002 * The message is found in VMINT.
3003 *
3004 * @param pVM The VM handle.
3005 * @thread EMT.
3006 */
3007VMMR3DECL(void) VMR3SetErrorWorker(PVM pVM)
3008{
3009 VM_ASSERT_EMT(pVM);
3010 AssertReleaseMsgFailed(("And we have a winner! You get to implement Ring-0 and GC VMSetErrorV! Contrats!\n"));
3011
3012 /*
3013 * Unpack the error (if we managed to format one).
3014 */
3015 PVMERROR pErr = pVM->vm.s.pErrorR3;
3016 const char *pszFile = NULL;
3017 const char *pszFunction = NULL;
3018 uint32_t iLine = 0;
3019 const char *pszMessage;
3020 int32_t rc = VERR_MM_HYPER_NO_MEMORY;
3021 if (pErr)
3022 {
3023 AssertCompile(sizeof(const char) == sizeof(uint8_t));
3024 if (pErr->offFile)
3025 pszFile = (const char *)pErr + pErr->offFile;
3026 iLine = pErr->iLine;
3027 if (pErr->offFunction)
3028 pszFunction = (const char *)pErr + pErr->offFunction;
3029 if (pErr->offMessage)
3030 pszMessage = (const char *)pErr + pErr->offMessage;
3031 else
3032 pszMessage = "No message!";
3033 }
3034 else
3035 pszMessage = "No message! (Failed to allocate memory to put the error message in!)";
3036
3037 /*
3038 * Call the at error callbacks.
3039 */
3040 for (PVMATERROR pCur = pVM->pUVM->vm.s.pAtError; pCur; pCur = pCur->pNext)
3041 vmR3SetErrorWorkerDoCall(pVM, pCur, rc, RT_SRC_POS_ARGS, "%s", pszMessage);
3042}
3043
3044
3045/**
3046 * Creation time wrapper for vmR3SetErrorUV.
3047 *
3048 * @returns rc.
3049 * @param pUVM Pointer to the user mode VM structure.
3050 * @param rc The VBox status code.
3051 * @param RT_SRC_POS_DECL The source position of this error.
3052 * @param pszFormat Format string.
3053 * @param ... The arguments.
3054 * @thread Any thread.
3055 */
3056static int vmR3SetErrorU(PUVM pUVM, int rc, RT_SRC_POS_DECL, const char *pszFormat, ...)
3057{
3058 va_list va;
3059 va_start(va, pszFormat);
3060 vmR3SetErrorUV(pUVM, rc, pszFile, iLine, pszFunction, pszFormat, &va);
3061 va_end(va);
3062 return rc;
3063}
3064
3065
3066/**
3067 * Worker which calls everyone listening to the VM error messages.
3068 *
3069 * @param pUVM Pointer to the user mode VM structure.
3070 * @param rc The VBox status code.
3071 * @param RT_SRC_POS_DECL The source position of this error.
3072 * @param pszFormat Format string.
3073 * @param pArgs Pointer to the format arguments.
3074 * @thread EMT
3075 */
3076DECLCALLBACK(void) vmR3SetErrorUV(PUVM pUVM, int rc, RT_SRC_POS_DECL, const char *pszFormat, va_list *pArgs)
3077{
3078#ifdef LOG_ENABLED
3079 /*
3080 * Log the error.
3081 */
3082 RTLogPrintf("VMSetError: %s(%d) %s\n", pszFile, iLine, pszFunction);
3083 va_list va3;
3084 va_copy(va3, *pArgs);
3085 RTLogPrintfV(pszFormat, va3);
3086 va_end(va3);
3087 RTLogPrintf("\n");
3088#endif
3089
3090 /*
3091 * Make a copy of the message.
3092 */
3093 if (pUVM->pVM)
3094 vmSetErrorCopy(pUVM->pVM, rc, RT_SRC_POS_ARGS, pszFormat, *pArgs);
3095
3096 /*
3097 * Call the at error callbacks.
3098 */
3099 for (PVMATERROR pCur = pUVM->vm.s.pAtError; pCur; pCur = pCur->pNext)
3100 {
3101 va_list va2;
3102 va_copy(va2, *pArgs);
3103 pCur->pfnAtError(pUVM->pVM, pCur->pvUser, rc, RT_SRC_POS_ARGS, pszFormat, va2);
3104 va_end(va2);
3105 }
3106}
3107
3108
3109/**
3110 * Registers a VM runtime error callback.
3111 *
3112 * @returns VBox status code.
3113 * @param pVM The VM handle.
3114 * @param pfnAtRuntimeError Pointer to callback.
3115 * @param pvUser User argument.
3116 * @thread Any.
3117 */
3118VMMR3DECL(int) VMR3AtRuntimeErrorRegister(PVM pVM, PFNVMATRUNTIMEERROR pfnAtRuntimeError, void *pvUser)
3119{
3120 LogFlow(("VMR3AtRuntimeErrorRegister: pfnAtRuntimeError=%p pvUser=%p\n", pfnAtRuntimeError, pvUser));
3121
3122 /*
3123 * Validate input.
3124 */
3125 if (!pfnAtRuntimeError)
3126 {
3127 AssertMsgFailed(("callback is required\n"));
3128 return VERR_INVALID_PARAMETER;
3129 }
3130
3131 /*
3132 * Make sure we're in EMT (to avoid the logging).
3133 */
3134 PVMREQ pReq;
3135 int rc = VMR3ReqCall(pVM, VMCPUID_ANY, &pReq, RT_INDEFINITE_WAIT, (PFNRT)vmR3AtRuntimeErrorRegisterU, 3, pVM->pUVM, pfnAtRuntimeError, pvUser);
3136 if (RT_FAILURE(rc))
3137 return rc;
3138 rc = pReq->iStatus;
3139 VMR3ReqFree(pReq);
3140
3141 LogFlow(("VMR3AtRuntimeErrorRegister: returns %Rrc\n", rc));
3142 return rc;
3143}
3144
3145
3146/**
3147 * Registers a VM runtime error callback.
3148 *
3149 * @returns VBox status code.
3150 * @param pUVM Pointer to the user mode VM structure.
3151 * @param pfnAtRuntimeError Pointer to callback.
3152 * @param pvUser User argument.
3153 * @thread EMT
3154 */
3155static DECLCALLBACK(int) vmR3AtRuntimeErrorRegisterU(PUVM pUVM, PFNVMATRUNTIMEERROR pfnAtRuntimeError, void *pvUser)
3156{
3157 /*
3158 * Allocate a new record.
3159 */
3160
3161 PVMATRUNTIMEERROR pNew = (PVMATRUNTIMEERROR)MMR3HeapAllocU(pUVM, MM_TAG_VM, sizeof(*pNew));
3162 if (!pNew)
3163 return VERR_NO_MEMORY;
3164
3165 /* fill */
3166 pNew->pfnAtRuntimeError = pfnAtRuntimeError;
3167 pNew->pvUser = pvUser;
3168
3169 /* insert */
3170 pNew->pNext = *pUVM->vm.s.ppAtRuntimeErrorNext;
3171 *pUVM->vm.s.ppAtRuntimeErrorNext = pNew;
3172 pUVM->vm.s.ppAtRuntimeErrorNext = &pNew->pNext;
3173
3174 return VINF_SUCCESS;
3175}
3176
3177
3178/**
3179 * Deregisters a VM runtime error callback.
3180 *
3181 * @returns VBox status code.
3182 * @param pVM The VM handle.
3183 * @param pfnAtRuntimeError Pointer to callback.
3184 * @param pvUser User argument.
3185 * @thread Any.
3186 */
3187VMMR3DECL(int) VMR3AtRuntimeErrorDeregister(PVM pVM, PFNVMATRUNTIMEERROR pfnAtRuntimeError, void *pvUser)
3188{
3189 LogFlow(("VMR3AtRuntimeErrorDeregister: pfnAtRuntimeError=%p pvUser=%p\n", pfnAtRuntimeError, pvUser));
3190
3191 /*
3192 * Validate input.
3193 */
3194 if (!pfnAtRuntimeError)
3195 {
3196 AssertMsgFailed(("callback is required\n"));
3197 return VERR_INVALID_PARAMETER;
3198 }
3199
3200 /*
3201 * Make sure we're in EMT (to avoid the logging).
3202 */
3203 PVMREQ pReq;
3204 int rc = VMR3ReqCall(pVM, VMCPUID_ANY, &pReq, RT_INDEFINITE_WAIT, (PFNRT)vmR3AtRuntimeErrorDeregisterU, 3, pVM->pUVM, pfnAtRuntimeError, pvUser);
3205 if (RT_FAILURE(rc))
3206 return rc;
3207 rc = pReq->iStatus;
3208 VMR3ReqFree(pReq);
3209
3210 LogFlow(("VMR3AtRuntimeErrorDeregister: returns %Rrc\n", rc));
3211 return rc;
3212}
3213
3214
3215/**
3216 * Deregisters a VM runtime error callback.
3217 *
3218 * @returns VBox status code.
3219 * @param pUVM Pointer to the user mode VM structure.
3220 * @param pfnAtRuntimeError Pointer to callback.
3221 * @param pvUser User argument.
3222 * @thread EMT
3223 */
3224static DECLCALLBACK(int) vmR3AtRuntimeErrorDeregisterU(PUVM pUVM, PFNVMATRUNTIMEERROR pfnAtRuntimeError, void *pvUser)
3225{
3226 LogFlow(("vmR3AtRuntimeErrorDeregisterU: pfnAtRuntimeError=%p pvUser=%p\n", pfnAtRuntimeError, pvUser));
3227
3228 /*
3229 * Search the list for the entry.
3230 */
3231 PVMATRUNTIMEERROR pPrev = NULL;
3232 PVMATRUNTIMEERROR pCur = pUVM->vm.s.pAtRuntimeError;
3233 while ( pCur
3234 && ( pCur->pfnAtRuntimeError != pfnAtRuntimeError
3235 || pCur->pvUser != pvUser))
3236 {
3237 pPrev = pCur;
3238 pCur = pCur->pNext;
3239 }
3240 if (!pCur)
3241 {
3242 AssertMsgFailed(("pfnAtRuntimeError=%p was not found\n", pfnAtRuntimeError));
3243 return VERR_FILE_NOT_FOUND;
3244 }
3245
3246 /*
3247 * Unlink it.
3248 */
3249 if (pPrev)
3250 {
3251 pPrev->pNext = pCur->pNext;
3252 if (!pCur->pNext)
3253 pUVM->vm.s.ppAtRuntimeErrorNext = &pPrev->pNext;
3254 }
3255 else
3256 {
3257 pUVM->vm.s.pAtRuntimeError = pCur->pNext;
3258 if (!pCur->pNext)
3259 pUVM->vm.s.ppAtRuntimeErrorNext = &pUVM->vm.s.pAtRuntimeError;
3260 }
3261
3262 /*
3263 * Free it.
3264 */
3265 pCur->pfnAtRuntimeError = NULL;
3266 pCur->pNext = NULL;
3267 MMR3HeapFree(pCur);
3268
3269 return VINF_SUCCESS;
3270}
3271
3272
3273/**
3274 * Worker for VMR3SetRuntimeErrorWorker and vmR3SetRuntimeErrorV.
3275 *
3276 * This does the common parts after the error has been saved / retrieved.
3277 *
3278 * @returns VBox status code with modifications, see VMSetRuntimeErrorV.
3279 *
3280 * @param pVM The VM handle.
3281 * @param fFlags The error flags.
3282 * @param pszErrorId Error ID string.
3283 * @param pszFormat Format string.
3284 * @param pVa Pointer to the format arguments.
3285 */
3286static int vmR3SetRuntimeErrorCommon(PVM pVM, uint32_t fFlags, const char *pszErrorId, const char *pszFormat, va_list *pVa)
3287{
3288 LogRel(("VM: Raising runtime error '%s' (fFlags=%#x)\n", pszErrorId, fFlags));
3289
3290 /*
3291 * Take actions before the call.
3292 */
3293 int rc = VINF_SUCCESS;
3294 if (fFlags & VMSETRTERR_FLAGS_FATAL)
3295 /** @todo Add some special VM state for the FATAL variant that isn't resumable.
3296 * It's too risky for 2.2.0, do after branching. */
3297 rc = VMR3SuspendNoSave(pVM);
3298 else if (fFlags & VMSETRTERR_FLAGS_SUSPEND)
3299 rc = VMR3Suspend(pVM);
3300
3301 /*
3302 * Do the callback round.
3303 */
3304 for (PVMATRUNTIMEERROR pCur = pVM->pUVM->vm.s.pAtRuntimeError; pCur; pCur = pCur->pNext)
3305 {
3306 va_list va;
3307 va_copy(va, *pVa);
3308 pCur->pfnAtRuntimeError(pVM, pCur->pvUser, fFlags, pszErrorId, pszFormat, va);
3309 va_end(va);
3310 }
3311
3312 return rc;
3313}
3314
3315
3316/**
3317 * Ellipsis to va_list wrapper for calling vmR3SetRuntimeErrorCommon.
3318 */
3319static int vmR3SetRuntimeErrorCommonF(PVM pVM, uint32_t fFlags, const char *pszErrorId, const char *pszFormat, ...)
3320{
3321 va_list va;
3322 va_start(va, pszFormat);
3323 int rc = vmR3SetRuntimeErrorCommon(pVM, fFlags, pszErrorId, pszFormat, &va);
3324 va_end(va);
3325 return rc;
3326}
3327
3328
3329/**
3330 * This is a worker function for RC and Ring-0 calls to VMSetError and
3331 * VMSetErrorV.
3332 *
3333 * The message is found in VMINT.
3334 *
3335 * @returns VBox status code, see VMSetRuntimeError.
3336 * @param pVM The VM handle.
3337 * @thread EMT.
3338 */
3339VMMR3DECL(int) VMR3SetRuntimeErrorWorker(PVM pVM)
3340{
3341 VM_ASSERT_EMT(pVM);
3342 AssertReleaseMsgFailed(("And we have a winner! You get to implement Ring-0 and GC VMSetRuntimeErrorV! Congrats!\n"));
3343
3344 /*
3345 * Unpack the error (if we managed to format one).
3346 */
3347 const char *pszErrorId = "SetRuntimeError";
3348 const char *pszMessage = "No message!";
3349 uint32_t fFlags = VMSETRTERR_FLAGS_FATAL;
3350 PVMRUNTIMEERROR pErr = pVM->vm.s.pRuntimeErrorR3;
3351 if (pErr)
3352 {
3353 AssertCompile(sizeof(const char) == sizeof(uint8_t));
3354 if (pErr->offErrorId)
3355 pszErrorId = (const char *)pErr + pErr->offErrorId;
3356 if (pErr->offMessage)
3357 pszMessage = (const char *)pErr + pErr->offMessage;
3358 fFlags = pErr->fFlags;
3359 }
3360
3361 /*
3362 * Join cause with vmR3SetRuntimeErrorV.
3363 */
3364 return vmR3SetRuntimeErrorCommonF(pVM, fFlags, pszErrorId, "%s", pszMessage);
3365}
3366
3367
3368/**
3369 * Worker for VMSetRuntimeErrorV for doing the job on EMT in ring-3.
3370 *
3371 * @returns VBox status code with modifications, see VMSetRuntimeErrorV.
3372 *
3373 * @param pVM The VM handle.
3374 * @param fFlags The error flags.
3375 * @param pszErrorId Error ID string.
3376 * @param pszFormat Format string.
3377 * @param pVa Pointer to the format arguments.
3378 *
3379 * @thread EMT
3380 */
3381DECLCALLBACK(int) vmR3SetRuntimeErrorV(PVM pVM, uint32_t fFlags, const char *pszErrorId, const char *pszFormat, va_list *pVa)
3382{
3383 /*
3384 * Make a copy of the message.
3385 */
3386 va_list va2;
3387 va_copy(va2, *pVa);
3388 vmSetRuntimeErrorCopy(pVM, fFlags, pszErrorId, pszFormat, va2);
3389 va_end(va2);
3390
3391 /*
3392 * Join paths with VMR3SetRuntimeErrorWorker.
3393 */
3394 return vmR3SetRuntimeErrorCommon(pVM, fFlags, pszErrorId, pszFormat, pVa);
3395}
3396
3397
3398/**
3399 * Gets the ID virtual of the virtual CPU assoicated with the calling thread.
3400 *
3401 * @returns The CPU ID. NIL_VMCPUID if the thread isn't an EMT.
3402 *
3403 * @param pVM The VM handle.
3404 */
3405VMMR3DECL(RTCPUID) VMR3GetVMCPUId(PVM pVM)
3406{
3407 PUVMCPU pUVCpu = (PUVMCPU)RTTlsGet(pVM->pUVM->vm.s.idxTLS);
3408 return pUVCpu
3409 ? pUVCpu->idCpu
3410 : NIL_VMCPUID;
3411}
3412
3413
3414/**
3415 * Returns the native handle of the current EMT VMCPU thread.
3416 *
3417 * @returns Handle if this is an EMT thread; NIL_RTNATIVETHREAD otherwise
3418 * @param pVM The VM handle.
3419 * @thread EMT
3420 */
3421VMMR3DECL(RTNATIVETHREAD) VMR3GetVMCPUNativeThread(PVM pVM)
3422{
3423 PUVMCPU pUVCpu = (PUVMCPU)RTTlsGet(pVM->pUVM->vm.s.idxTLS);
3424
3425 if (!pUVCpu)
3426 return NIL_RTNATIVETHREAD;
3427
3428 return pUVCpu->vm.s.NativeThreadEMT;
3429}
3430
3431
3432/**
3433 * Returns the native handle of the current EMT VMCPU thread.
3434 *
3435 * @returns Handle if this is an EMT thread; NIL_RTNATIVETHREAD otherwise
3436 * @param pVM The VM handle.
3437 * @thread EMT
3438 */
3439VMMR3DECL(RTNATIVETHREAD) VMR3GetVMCPUNativeThreadU(PUVM pUVM)
3440{
3441 PUVMCPU pUVCpu = (PUVMCPU)RTTlsGet(pUVM->vm.s.idxTLS);
3442
3443 if (!pUVCpu)
3444 return NIL_RTNATIVETHREAD;
3445
3446 return pUVCpu->vm.s.NativeThreadEMT;
3447}
3448
3449
3450/**
3451 * Returns the handle of the current EMT VMCPU thread.
3452 *
3453 * @returns Handle if this is an EMT thread; NIL_RTNATIVETHREAD otherwise
3454 * @param pVM The VM handle.
3455 * @thread EMT
3456 */
3457VMMR3DECL(RTTHREAD) VMR3GetVMCPUThread(PVM pVM)
3458{
3459 PUVMCPU pUVCpu = (PUVMCPU)RTTlsGet(pVM->pUVM->vm.s.idxTLS);
3460
3461 if (!pUVCpu)
3462 return NIL_RTTHREAD;
3463
3464 return pUVCpu->vm.s.ThreadEMT;
3465}
3466
3467
3468/**
3469 * Returns the handle of the current EMT VMCPU thread.
3470 *
3471 * @returns Handle if this is an EMT thread; NIL_RTNATIVETHREAD otherwise
3472 * @param pVM The VM handle.
3473 * @thread EMT
3474 */
3475VMMR3DECL(RTTHREAD) VMR3GetVMCPUThreadU(PUVM pUVM)
3476{
3477 PUVMCPU pUVCpu = (PUVMCPU)RTTlsGet(pUVM->vm.s.idxTLS);
3478
3479 if (!pUVCpu)
3480 return NIL_RTTHREAD;
3481
3482 return pUVCpu->vm.s.ThreadEMT;
3483}
3484
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