VirtualBox

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

Last change on this file since 31362 was 31362, checked in by vboxsync, 14 years ago

Missing commit

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 143.2 KB
Line 
1/* $Id: VM.cpp 31362 2010-08-04 15:54:14Z vboxsync $ */
2/** @file
3 * VM - Virtual Machine
4 */
5
6/*
7 * Copyright (C) 2006-2010 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18/** @page pg_vm VM API
19 *
20 * This is the encapsulating bit. It provides the APIs that Main and VBoxBFE
21 * use to create a VMM instance for running a guest in. It also provides
22 * facilities for queuing request for execution in EMT (serialization purposes
23 * mostly) and for reporting error back to the VMM user (Main/VBoxBFE).
24 *
25 *
26 * @section sec_vm_design Design Critique / Things To Do
27 *
28 * In hindsight this component is a big design mistake, all this stuff really
29 * belongs in the VMM component. It just seemed like a kind of ok idea at a
30 * time when the VMM bit was a kind of vague. 'VM' also happend to be the name
31 * of the per-VM instance structure (see vm.h), so it kind of made sense.
32 * However as it turned out, VMM(.cpp) is almost empty all it provides in ring-3
33 * is some minor functionally and some "routing" services.
34 *
35 * Fixing this is just a matter of some more or less straight forward
36 * refactoring, the question is just when someone will get to it. Moving the EMT
37 * would be a good start.
38 *
39 */
40
41/*******************************************************************************
42* Header Files *
43*******************************************************************************/
44#define LOG_GROUP LOG_GROUP_VM
45#include <VBox/cfgm.h>
46#include <VBox/vmm.h>
47#include <VBox/gvmm.h>
48#include <VBox/mm.h>
49#include <VBox/cpum.h>
50#include <VBox/selm.h>
51#include <VBox/trpm.h>
52#include <VBox/dbgf.h>
53#include <VBox/pgm.h>
54#include <VBox/pdmapi.h>
55#include <VBox/pdmcritsect.h>
56#include <VBox/em.h>
57#include <VBox/rem.h>
58#include <VBox/tm.h>
59#include <VBox/stam.h>
60#include <VBox/patm.h>
61#include <VBox/csam.h>
62#include <VBox/iom.h>
63#include <VBox/ssm.h>
64#include <VBox/hwaccm.h>
65#include "VMInternal.h"
66#include <VBox/vm.h>
67#include <VBox/uvm.h>
68
69#include <VBox/sup.h>
70#include <VBox/dbg.h>
71#include <VBox/err.h>
72#include <VBox/param.h>
73#include <VBox/log.h>
74#include <iprt/assert.h>
75#include <iprt/alloc.h>
76#include <iprt/asm.h>
77#include <iprt/env.h>
78#include <iprt/string.h>
79#include <iprt/time.h>
80#include <iprt/semaphore.h>
81#include <iprt/thread.h>
82
83
84/*******************************************************************************
85* Structures and Typedefs *
86*******************************************************************************/
87/**
88 * VM destruction callback registration record.
89 */
90typedef struct VMATDTOR
91{
92 /** Pointer to the next record in the list. */
93 struct VMATDTOR *pNext;
94 /** Pointer to the callback function. */
95 PFNVMATDTOR pfnAtDtor;
96 /** The user argument. */
97 void *pvUser;
98} VMATDTOR;
99/** Pointer to a VM destruction callback registration record. */
100typedef VMATDTOR *PVMATDTOR;
101
102
103/*******************************************************************************
104* Global Variables *
105*******************************************************************************/
106/** Pointer to the list of VMs. */
107static PUVM g_pUVMsHead = NULL;
108
109/** Pointer to the list of at VM destruction callbacks. */
110static PVMATDTOR g_pVMAtDtorHead = NULL;
111/** Lock the g_pVMAtDtorHead list. */
112#define VM_ATDTOR_LOCK() do { } while (0)
113/** Unlock the g_pVMAtDtorHead list. */
114#define VM_ATDTOR_UNLOCK() do { } while (0)
115
116
117/*******************************************************************************
118* Internal Functions *
119*******************************************************************************/
120static int vmR3CreateUVM(uint32_t cCpus, PUVM *ppUVM);
121static int vmR3CreateU(PUVM pUVM, uint32_t cCpus, PFNCFGMCONSTRUCTOR pfnCFGMConstructor, void *pvUserCFGM);
122static int vmR3InitRing3(PVM pVM, PUVM pUVM);
123static int vmR3InitVMCpu(PVM pVM);
124static int vmR3InitRing0(PVM pVM);
125static int vmR3InitGC(PVM pVM);
126static int vmR3InitDoCompleted(PVM pVM, VMINITCOMPLETED enmWhat);
127static DECLCALLBACK(size_t) vmR3LogPrefixCallback(PRTLOGGER pLogger, char *pchBuf, size_t cchBuf, void *pvUser);
128static void vmR3DestroyUVM(PUVM pUVM, uint32_t cMilliesEMTWait);
129static void vmR3AtDtor(PVM pVM);
130static bool vmR3ValidateStateTransition(VMSTATE enmStateOld, VMSTATE enmStateNew);
131static void vmR3DoAtState(PVM pVM, PUVM pUVM, VMSTATE enmStateNew, VMSTATE enmStateOld);
132static int vmR3TrySetState(PVM pVM, const char *pszWho, unsigned cTransitions, ...);
133static void vmR3SetStateLocked(PVM pVM, PUVM pUVM, VMSTATE enmStateNew, VMSTATE enmStateOld);
134static void vmR3SetState(PVM pVM, VMSTATE enmStateNew, VMSTATE enmStateOld);
135static int vmR3SetErrorU(PUVM pUVM, int rc, RT_SRC_POS_DECL, const char *pszFormat, ...);
136
137
138/**
139 * Do global VMM init.
140 *
141 * @returns VBox status code.
142 */
143VMMR3DECL(int) VMR3GlobalInit(void)
144{
145 /*
146 * Only once.
147 */
148 static bool volatile s_fDone = false;
149 if (s_fDone)
150 return VINF_SUCCESS;
151
152 /*
153 * We're done.
154 */
155 s_fDone = true;
156 return VINF_SUCCESS;
157}
158
159
160
161/**
162 * Creates a virtual machine by calling the supplied configuration constructor.
163 *
164 * On successful returned the VM is powered, i.e. VMR3PowerOn() should be
165 * called to start the execution.
166 *
167 * @returns 0 on success.
168 * @returns VBox error code on failure.
169 * @param cCpus Number of virtual CPUs for the new VM.
170 * @param pfnVMAtError Pointer to callback function for setting VM
171 * errors. This was added as an implicit call to
172 * VMR3AtErrorRegister() since there is no way the
173 * caller can get to the VM handle early enough to
174 * do this on its own.
175 * This is called in the context of an EMT.
176 * @param pvUserVM The user argument passed to pfnVMAtError.
177 * @param pfnCFGMConstructor Pointer to callback function for constructing the VM configuration tree.
178 * This is called in the context of an EMT0.
179 * @param pvUserCFGM The user argument passed to pfnCFGMConstructor.
180 * @param ppVM Where to store the 'handle' of the created VM.
181 */
182VMMR3DECL(int) VMR3Create(uint32_t cCpus, PFNVMATERROR pfnVMAtError, void *pvUserVM, PFNCFGMCONSTRUCTOR pfnCFGMConstructor, void *pvUserCFGM, PVM *ppVM)
183{
184 LogFlow(("VMR3Create: cCpus=%RU32 pfnVMAtError=%p pvUserVM=%p pfnCFGMConstructor=%p pvUserCFGM=%p ppVM=%p\n",
185 cCpus, pfnVMAtError, pvUserVM, pfnCFGMConstructor, pvUserCFGM, ppVM));
186
187 /*
188 * Because of the current hackiness of the applications
189 * we'll have to initialize global stuff from here.
190 * Later the applications will take care of this in a proper way.
191 */
192 static bool fGlobalInitDone = false;
193 if (!fGlobalInitDone)
194 {
195 int rc = VMR3GlobalInit();
196 if (RT_FAILURE(rc))
197 return rc;
198 fGlobalInitDone = true;
199 }
200
201 /*
202 * Validate input.
203 */
204 AssertLogRelMsgReturn(cCpus > 0 && cCpus <= VMM_MAX_CPU_COUNT, ("%RU32\n", cCpus), VERR_TOO_MANY_CPUS);
205
206 /*
207 * Create the UVM so we can register the at-error callback
208 * and consoliate a bit of cleanup code.
209 */
210 PUVM pUVM = NULL; /* shuts up gcc */
211 int rc = vmR3CreateUVM(cCpus, &pUVM);
212 if (RT_FAILURE(rc))
213 return rc;
214 if (pfnVMAtError)
215 rc = VMR3AtErrorRegisterU(pUVM, pfnVMAtError, pvUserVM);
216 if (RT_SUCCESS(rc))
217 {
218 /*
219 * Initialize the support library creating the session for this VM.
220 */
221 rc = SUPR3Init(&pUVM->vm.s.pSession);
222 if (RT_SUCCESS(rc))
223 {
224 /*
225 * Call vmR3CreateU in the EMT thread and wait for it to finish.
226 *
227 * Note! VMCPUID_ANY is used here because VMR3ReqQueueU would have trouble
228 * submitting a request to a specific VCPU without a pVM. So, to make
229 * sure init is running on EMT(0), vmR3EmulationThreadWithId makes sure
230 * that only EMT(0) is servicing VMCPUID_ANY requests when pVM is NULL.
231 */
232 PVMREQ pReq;
233 rc = VMR3ReqCallU(pUVM, VMCPUID_ANY, &pReq, RT_INDEFINITE_WAIT, VMREQFLAGS_VBOX_STATUS,
234 (PFNRT)vmR3CreateU, 4, pUVM, cCpus, pfnCFGMConstructor, pvUserCFGM);
235 if (RT_SUCCESS(rc))
236 {
237 rc = pReq->iStatus;
238 VMR3ReqFree(pReq);
239 if (RT_SUCCESS(rc))
240 {
241 /*
242 * Success!
243 */
244 *ppVM = pUVM->pVM;
245 LogFlow(("VMR3Create: returns VINF_SUCCESS *ppVM=%p\n", *ppVM));
246 return VINF_SUCCESS;
247 }
248 }
249 else
250 AssertMsgFailed(("VMR3ReqCallU failed rc=%Rrc\n", rc));
251
252 /*
253 * An error occurred during VM creation. Set the error message directly
254 * using the initial callback, as the callback list doesn't exist yet.
255 */
256 const char *pszError = NULL;
257 switch (rc)
258 {
259 case VERR_VMX_IN_VMX_ROOT_MODE:
260#ifdef RT_OS_LINUX
261 pszError = N_("VirtualBox can't operate in VMX root mode. "
262 "Please disable the KVM kernel extension, recompile your kernel and reboot");
263#else
264 pszError = N_("VirtualBox can't operate in VMX root mode. Please close all other virtualization programs.");
265#endif
266 break;
267
268 case VERR_SVM_IN_USE:
269#ifdef RT_OS_LINUX
270 pszError = N_("VirtualBox can't enable the AMD-V extension. "
271 "Please disable the KVM kernel extension, recompile your kernel and reboot");
272#else
273 pszError = N_("VirtualBox can't enable the AMD-V extension. Please close all other virtualization programs.");
274#endif
275 break;
276
277 case VERR_VERSION_MISMATCH:
278 pszError = N_("VMMR0 driver version mismatch. Please terminate all VMs, make sure that "
279 "VBoxNetDHCP is not running and try again. If you still get this error, "
280 "re-install VirtualBox");
281 break;
282
283#ifdef RT_OS_LINUX
284 case VERR_SUPDRV_COMPONENT_NOT_FOUND:
285 pszError = N_("One of the kernel modules was not successfully loaded. Make sure "
286 "that no kernel modules from an older version of VirtualBox exist. "
287 "Then try to recompile and reload the kernel modules by executing "
288 "'/etc/init.d/vboxdrv setup' as root");
289 break;
290#endif
291
292 case VERR_RAW_MODE_INVALID_SMP:
293 pszError = N_("VT-x/AMD-V is either not available on your host or disabled. "
294 "VirtualBox requires this hardware extension to emulate more than one "
295 "guest CPU");
296 break;
297
298 case VERR_SUPDRV_KERNEL_TOO_OLD_FOR_VTX:
299#ifdef RT_OS_LINUX
300 pszError = N_("Because the host kernel is too old, VirtualBox cannot enable the VT-x "
301 "extension. Either upgrade your kernel to Linux 2.6.13 or later or disable "
302 "the VT-x extension in the VM settings. Note that without VT-x you have "
303 "to reduce the number of guest CPUs to one");
304#else
305 pszError = N_("Because the host kernel is too old, VirtualBox cannot enable the VT-x "
306 "extension. Either upgrade your kernel or disable the VT-x extension in the "
307 "VM settings. Note that without VT-x you have to reduce the number of guest "
308 "CPUs to one");
309#endif
310 break;
311
312 default:
313 pszError = N_("Unknown error creating VM");
314 break;
315 }
316 vmR3SetErrorU(pUVM, rc, RT_SRC_POS, pszError, rc);
317 }
318 else
319 {
320 /*
321 * An error occurred at support library initialization time (before the
322 * VM could be created). Set the error message directly using the
323 * initial callback, as the callback list doesn't exist yet.
324 */
325 const char *pszError;
326 switch (rc)
327 {
328 case VERR_VM_DRIVER_LOAD_ERROR:
329#ifdef RT_OS_LINUX
330 pszError = N_("VirtualBox kernel driver not loaded. The vboxdrv kernel module "
331 "was either not loaded or /dev/vboxdrv is not set up properly. "
332 "Re-setup the kernel module by executing "
333 "'/etc/init.d/vboxdrv setup' as root");
334#else
335 pszError = N_("VirtualBox kernel driver not loaded");
336#endif
337 break;
338 case VERR_VM_DRIVER_OPEN_ERROR:
339 pszError = N_("VirtualBox kernel driver cannot be opened");
340 break;
341 case VERR_VM_DRIVER_NOT_ACCESSIBLE:
342#ifdef VBOX_WITH_HARDENING
343 /* This should only happen if the executable wasn't hardened - bad code/build. */
344 pszError = N_("VirtualBox kernel driver not accessible, permission problem. "
345 "Re-install VirtualBox. If you are building it yourself, you "
346 "should make sure it installed correctly and that the setuid "
347 "bit is set on the executables calling VMR3Create.");
348#else
349 /* This should only happen when mixing builds or with the usual /dev/vboxdrv access issues. */
350# if defined(RT_OS_DARWIN)
351 pszError = N_("VirtualBox KEXT is not accessible, permission problem. "
352 "If you have built VirtualBox yourself, make sure that you do not "
353 "have the vboxdrv KEXT from a different build or installation loaded.");
354# elif defined(RT_OS_LINUX)
355 pszError = N_("VirtualBox kernel driver is not accessible, permission problem. "
356 "If you have built VirtualBox yourself, make sure that you do "
357 "not have the vboxdrv kernel module from a different build or "
358 "installation loaded. Also, make sure the vboxdrv udev rule gives "
359 "you the permission you need to access the device.");
360# elif defined(RT_OS_WINDOWS)
361 pszError = N_("VirtualBox kernel driver is not accessible, permission problem.");
362# else /* solaris, freebsd, ++. */
363 pszError = N_("VirtualBox kernel module is not accessible, permission problem. "
364 "If you have built VirtualBox yourself, make sure that you do "
365 "not have the vboxdrv kernel module from a different install loaded.");
366# endif
367#endif
368 break;
369 case VERR_INVALID_HANDLE: /** @todo track down and fix this error. */
370 case VERR_VM_DRIVER_NOT_INSTALLED:
371#ifdef RT_OS_LINUX
372 pszError = N_("VirtualBox kernel driver not installed. The vboxdrv kernel module "
373 "was either not loaded or /dev/vboxdrv was not created for some "
374 "reason. Re-setup the kernel module by executing "
375 "'/etc/init.d/vboxdrv setup' as root");
376#else
377 pszError = N_("VirtualBox kernel driver not installed");
378#endif
379 break;
380 case VERR_NO_MEMORY:
381 pszError = N_("VirtualBox support library out of memory");
382 break;
383 case VERR_VERSION_MISMATCH:
384 case VERR_VM_DRIVER_VERSION_MISMATCH:
385 pszError = N_("The VirtualBox support driver which is running is from a different "
386 "version of VirtualBox. You can correct this by stopping all "
387 "running instances of VirtualBox and reinstalling the software.");
388 break;
389 default:
390 pszError = N_("Unknown error initializing kernel driver");
391 AssertMsgFailed(("Add error message for rc=%d (%Rrc)\n", rc, rc));
392 }
393 vmR3SetErrorU(pUVM, rc, RT_SRC_POS, pszError, rc);
394 }
395 }
396
397 /* cleanup */
398 vmR3DestroyUVM(pUVM, 2000);
399 LogFlow(("VMR3Create: returns %Rrc\n", rc));
400 return rc;
401}
402
403
404/**
405 * Creates the UVM.
406 *
407 * This will not initialize the support library even if vmR3DestroyUVM
408 * will terminate that.
409 *
410 * @returns VBox status code.
411 * @param cCpus Number of virtual CPUs
412 * @param ppUVM Where to store the UVM pointer.
413 */
414static int vmR3CreateUVM(uint32_t cCpus, PUVM *ppUVM)
415{
416 uint32_t i;
417
418 /*
419 * Create and initialize the UVM.
420 */
421 PUVM pUVM = (PUVM)RTMemPageAllocZ(RT_OFFSETOF(UVM, aCpus[cCpus]));
422 AssertReturn(pUVM, VERR_NO_MEMORY);
423 pUVM->u32Magic = UVM_MAGIC;
424 pUVM->cCpus = cCpus;
425
426 AssertCompile(sizeof(pUVM->vm.s) <= sizeof(pUVM->vm.padding));
427
428 pUVM->vm.s.ppAtStateNext = &pUVM->vm.s.pAtState;
429 pUVM->vm.s.ppAtErrorNext = &pUVM->vm.s.pAtError;
430 pUVM->vm.s.ppAtRuntimeErrorNext = &pUVM->vm.s.pAtRuntimeError;
431
432 pUVM->vm.s.enmHaltMethod = VMHALTMETHOD_BOOTSTRAP;
433
434 /* Initialize the VMCPU array in the UVM. */
435 for (i = 0; i < cCpus; i++)
436 {
437 pUVM->aCpus[i].pUVM = pUVM;
438 pUVM->aCpus[i].idCpu = i;
439 }
440
441 /* Allocate a TLS entry to store the VMINTUSERPERVMCPU pointer. */
442 int rc = RTTlsAllocEx(&pUVM->vm.s.idxTLS, NULL);
443 AssertRC(rc);
444 if (RT_SUCCESS(rc))
445 {
446 /* Allocate a halt method event semaphore for each VCPU. */
447 for (i = 0; i < cCpus; i++)
448 pUVM->aCpus[i].vm.s.EventSemWait = NIL_RTSEMEVENT;
449 for (i = 0; i < cCpus; i++)
450 {
451 rc = RTSemEventCreate(&pUVM->aCpus[i].vm.s.EventSemWait);
452 if (RT_FAILURE(rc))
453 break;
454 }
455 if (RT_SUCCESS(rc))
456 {
457 rc = RTCritSectInit(&pUVM->vm.s.AtStateCritSect);
458 if (RT_SUCCESS(rc))
459 {
460 rc = RTCritSectInit(&pUVM->vm.s.AtErrorCritSect);
461 if (RT_SUCCESS(rc))
462 {
463 /*
464 * Init fundamental (sub-)components - STAM, MMR3Heap and PDMLdr.
465 */
466 rc = STAMR3InitUVM(pUVM);
467 if (RT_SUCCESS(rc))
468 {
469 rc = MMR3InitUVM(pUVM);
470 if (RT_SUCCESS(rc))
471 {
472 rc = PDMR3InitUVM(pUVM);
473 if (RT_SUCCESS(rc))
474 {
475 /*
476 * Start the emulation threads for all VMCPUs.
477 */
478 for (i = 0; i < cCpus; i++)
479 {
480 rc = RTThreadCreateF(&pUVM->aCpus[i].vm.s.ThreadEMT, vmR3EmulationThread, &pUVM->aCpus[i], _1M,
481 RTTHREADTYPE_EMULATION, RTTHREADFLAGS_WAITABLE,
482 cCpus > 1 ? "EMT-%u" : "EMT", i);
483 if (RT_FAILURE(rc))
484 break;
485
486 pUVM->aCpus[i].vm.s.NativeThreadEMT = RTThreadGetNative(pUVM->aCpus[i].vm.s.ThreadEMT);
487 }
488
489 if (RT_SUCCESS(rc))
490 {
491 *ppUVM = pUVM;
492 return VINF_SUCCESS;
493 }
494
495 /* bail out. */
496 while (i-- > 0)
497 {
498 /** @todo rainy day: terminate the EMTs. */
499 }
500 PDMR3TermUVM(pUVM);
501 }
502 MMR3TermUVM(pUVM);
503 }
504 STAMR3TermUVM(pUVM);
505 }
506 RTCritSectDelete(&pUVM->vm.s.AtErrorCritSect);
507 }
508 RTCritSectDelete(&pUVM->vm.s.AtStateCritSect);
509 }
510 }
511 for (i = 0; i < cCpus; i++)
512 {
513 RTSemEventDestroy(pUVM->aCpus[i].vm.s.EventSemWait);
514 pUVM->aCpus[i].vm.s.EventSemWait = NIL_RTSEMEVENT;
515 }
516 RTTlsFree(pUVM->vm.s.idxTLS);
517 }
518 RTMemPageFree(pUVM, sizeof(*pUVM));
519 return rc;
520}
521
522
523/**
524 * Creates and initializes the VM.
525 *
526 * @thread EMT
527 */
528static int vmR3CreateU(PUVM pUVM, uint32_t cCpus, PFNCFGMCONSTRUCTOR pfnCFGMConstructor, void *pvUserCFGM)
529{
530 int rc = VINF_SUCCESS;
531
532 /*
533 * Load the VMMR0.r0 module so that we can call GVMMR0CreateVM.
534 */
535 rc = PDMR3LdrLoadVMMR0U(pUVM);
536 if (RT_FAILURE(rc))
537 {
538 /** @todo we need a cleaner solution for this (VERR_VMX_IN_VMX_ROOT_MODE).
539 * bird: what about moving the message down here? Main picks the first message, right? */
540 if (rc == VERR_VMX_IN_VMX_ROOT_MODE)
541 return rc; /* proper error message set later on */
542 return vmR3SetErrorU(pUVM, rc, RT_SRC_POS, N_("Failed to load VMMR0.r0"));
543 }
544
545 /*
546 * Request GVMM to create a new VM for us.
547 */
548 GVMMCREATEVMREQ CreateVMReq;
549 CreateVMReq.Hdr.u32Magic = SUPVMMR0REQHDR_MAGIC;
550 CreateVMReq.Hdr.cbReq = sizeof(CreateVMReq);
551 CreateVMReq.pSession = pUVM->vm.s.pSession;
552 CreateVMReq.pVMR0 = NIL_RTR0PTR;
553 CreateVMReq.pVMR3 = NULL;
554 CreateVMReq.cCpus = cCpus;
555 rc = SUPR3CallVMMR0Ex(NIL_RTR0PTR, NIL_VMCPUID, VMMR0_DO_GVMM_CREATE_VM, 0, &CreateVMReq.Hdr);
556 if (RT_SUCCESS(rc))
557 {
558 PVM pVM = pUVM->pVM = CreateVMReq.pVMR3;
559 AssertRelease(VALID_PTR(pVM));
560 AssertRelease(pVM->pVMR0 == CreateVMReq.pVMR0);
561 AssertRelease(pVM->pSession == pUVM->vm.s.pSession);
562 AssertRelease(pVM->cCpus == cCpus);
563 AssertRelease(pVM->uCpuPriority == 100);
564 AssertRelease(pVM->offVMCPU == RT_UOFFSETOF(VM, aCpus));
565
566 Log(("VMR3Create: Created pUVM=%p pVM=%p pVMR0=%p hSelf=%#x cCpus=%RU32\n",
567 pUVM, pVM, pVM->pVMR0, pVM->hSelf, pVM->cCpus));
568
569 /*
570 * Initialize the VM structure and our internal data (VMINT).
571 */
572 pVM->pUVM = pUVM;
573
574 for (VMCPUID i = 0; i < pVM->cCpus; i++)
575 {
576 pVM->aCpus[i].pUVCpu = &pUVM->aCpus[i];
577 pVM->aCpus[i].idCpu = i;
578 pVM->aCpus[i].hNativeThread = pUVM->aCpus[i].vm.s.NativeThreadEMT;
579 Assert(pVM->aCpus[i].hNativeThread != NIL_RTNATIVETHREAD);
580
581 /* Initialized on the fly by page fusion. */
582 pVM->aCpus[i].hNativeThreadR0 = NIL_RTNATIVETHREAD;
583
584 pUVM->aCpus[i].pVCpu = &pVM->aCpus[i];
585 pUVM->aCpus[i].pVM = pVM;
586 }
587
588
589 /*
590 * Init the configuration.
591 */
592 rc = CFGMR3Init(pVM, pfnCFGMConstructor, pvUserCFGM);
593 if (RT_SUCCESS(rc))
594 {
595 PCFGMNODE pRoot = CFGMR3GetRoot(pVM);
596 rc = CFGMR3QueryBoolDef(pRoot, "HwVirtExtForced", &pVM->fHwVirtExtForced, false);
597 if (RT_SUCCESS(rc) && pVM->fHwVirtExtForced)
598 pVM->fHWACCMEnabled = true;
599
600 /*
601 * If executing in fake suplib mode disable RR3 and RR0 in the config.
602 */
603 const char *psz = RTEnvGet("VBOX_SUPLIB_FAKE");
604 if (psz && !strcmp(psz, "fake"))
605 {
606 CFGMR3RemoveValue(pRoot, "RawR3Enabled");
607 CFGMR3InsertInteger(pRoot, "RawR3Enabled", 0);
608 CFGMR3RemoveValue(pRoot, "RawR0Enabled");
609 CFGMR3InsertInteger(pRoot, "RawR0Enabled", 0);
610 }
611
612 /*
613 * Make sure the CPU count in the config data matches.
614 */
615 if (RT_SUCCESS(rc))
616 {
617 uint32_t cCPUsCfg;
618 rc = CFGMR3QueryU32Def(pRoot, "NumCPUs", &cCPUsCfg, 1);
619 AssertLogRelMsgRC(rc, ("Configuration error: Querying \"NumCPUs\" as integer failed, rc=%Rrc\n", rc));
620 if (RT_SUCCESS(rc) && cCPUsCfg != cCpus)
621 {
622 AssertLogRelMsgFailed(("Configuration error: \"NumCPUs\"=%RU32 and VMR3CreateVM::cCpus=%RU32 does not match!\n",
623 cCPUsCfg, cCpus));
624 rc = VERR_INVALID_PARAMETER;
625 }
626 }
627 if (RT_SUCCESS(rc))
628 {
629 rc = CFGMR3QueryU32Def(pRoot, "CpuPriority", &pVM->uCpuPriority, 100);
630 AssertLogRelMsgRC(rc, ("Configuration error: Querying \"CpuPriority\" as integer failed, rc=%Rrc\n", rc));
631
632 /*
633 * Init the ring-3 components and ring-3 per cpu data, finishing it off
634 * by a relocation round (intermediate context finalization will do this).
635 */
636 rc = vmR3InitRing3(pVM, pUVM);
637 if (RT_SUCCESS(rc))
638 {
639 rc = vmR3InitVMCpu(pVM);
640 if (RT_SUCCESS(rc))
641 rc = PGMR3FinalizeMappings(pVM);
642 if (RT_SUCCESS(rc))
643 {
644
645 LogFlow(("Ring-3 init succeeded\n"));
646
647 /*
648 * Init the Ring-0 components.
649 */
650 rc = vmR3InitRing0(pVM);
651 if (RT_SUCCESS(rc))
652 {
653 /* Relocate again, because some switcher fixups depends on R0 init results. */
654 VMR3Relocate(pVM, 0);
655
656#ifdef VBOX_WITH_DEBUGGER
657 /*
658 * Init the tcp debugger console if we're building
659 * with debugger support.
660 */
661 void *pvUser = NULL;
662 rc = DBGCTcpCreate(pVM, &pvUser);
663 if ( RT_SUCCESS(rc)
664 || rc == VERR_NET_ADDRESS_IN_USE)
665 {
666 pUVM->vm.s.pvDBGC = pvUser;
667#endif
668 /*
669 * Init the Guest Context components.
670 */
671 rc = vmR3InitGC(pVM);
672 if (RT_SUCCESS(rc))
673 {
674 /*
675 * Now we can safely set the VM halt method to default.
676 */
677 rc = vmR3SetHaltMethodU(pUVM, VMHALTMETHOD_DEFAULT);
678 if (RT_SUCCESS(rc))
679 {
680 /*
681 * Set the state and link into the global list.
682 */
683 vmR3SetState(pVM, VMSTATE_CREATED, VMSTATE_CREATING);
684 pUVM->pNext = g_pUVMsHead;
685 g_pUVMsHead = pUVM;
686
687#ifdef LOG_ENABLED
688 RTLogSetCustomPrefixCallback(NULL, vmR3LogPrefixCallback, pUVM);
689#endif
690 return VINF_SUCCESS;
691 }
692 }
693#ifdef VBOX_WITH_DEBUGGER
694 DBGCTcpTerminate(pVM, pUVM->vm.s.pvDBGC);
695 pUVM->vm.s.pvDBGC = NULL;
696 }
697#endif
698 //..
699 }
700 }
701 vmR3Destroy(pVM);
702 }
703 }
704 //..
705
706 /* Clean CFGM. */
707 int rc2 = CFGMR3Term(pVM);
708 AssertRC(rc2);
709 }
710
711 /*
712 * Do automatic cleanups while the VM structure is still alive and all
713 * references to it are still working.
714 */
715 PDMR3CritSectTerm(pVM);
716
717 /*
718 * Drop all references to VM and the VMCPU structures, then
719 * tell GVMM to destroy the VM.
720 */
721 pUVM->pVM = NULL;
722 for (VMCPUID i = 0; i < pUVM->cCpus; i++)
723 {
724 pUVM->aCpus[i].pVM = NULL;
725 pUVM->aCpus[i].pVCpu = NULL;
726 }
727 Assert(pUVM->vm.s.enmHaltMethod == VMHALTMETHOD_BOOTSTRAP);
728
729 if (pUVM->cCpus > 1)
730 {
731 /* Poke the other EMTs since they may have stale pVM and pVCpu references
732 on the stack (see VMR3WaitU for instance) if they've been awakened after
733 VM creation. */
734 for (VMCPUID i = 1; i < pUVM->cCpus; i++)
735 VMR3NotifyCpuFFU(&pUVM->aCpus[i], 0);
736 RTThreadSleep(RT_MIN(100 + 25 *(pUVM->cCpus - 1), 500)); /* very sophisticated */
737 }
738
739 int rc2 = SUPR3CallVMMR0Ex(CreateVMReq.pVMR0, 0 /*idCpu*/, VMMR0_DO_GVMM_DESTROY_VM, 0, NULL);
740 AssertRC(rc2);
741 }
742 else
743 vmR3SetErrorU(pUVM, rc, RT_SRC_POS, N_("VM creation failed (GVMM)"));
744
745 LogFlow(("vmR3CreateU: returns %Rrc\n", rc));
746 return rc;
747}
748
749
750/**
751 * Register the calling EMT with GVM.
752 *
753 * @returns VBox status code.
754 * @param pVM The VM handle.
755 * @param idCpu The Virtual CPU ID.
756 */
757static DECLCALLBACK(int) vmR3RegisterEMT(PVM pVM, VMCPUID idCpu)
758{
759 Assert(VMMGetCpuId(pVM) == idCpu);
760 int rc = SUPR3CallVMMR0Ex(pVM->pVMR0, idCpu, VMMR0_DO_GVMM_REGISTER_VMCPU, 0, NULL);
761 if (RT_FAILURE(rc))
762 LogRel(("idCpu=%u rc=%Rrc\n", idCpu, rc));
763 return rc;
764}
765
766
767/**
768 * Initializes all R3 components of the VM
769 */
770static int vmR3InitRing3(PVM pVM, PUVM pUVM)
771{
772 int rc;
773
774 /*
775 * Register the other EMTs with GVM.
776 */
777 for (VMCPUID idCpu = 1; idCpu < pVM->cCpus; idCpu++)
778 {
779 rc = VMR3ReqCallWaitU(pUVM, idCpu, (PFNRT)vmR3RegisterEMT, 2, pVM, idCpu);
780 if (RT_FAILURE(rc))
781 return rc;
782 }
783
784 /*
785 * Init all R3 components, the order here might be important.
786 */
787 rc = MMR3Init(pVM);
788 if (RT_SUCCESS(rc))
789 {
790 STAM_REG(pVM, &pVM->StatTotalInGC, STAMTYPE_PROFILE_ADV, "/PROF/VM/InGC", STAMUNIT_TICKS_PER_CALL, "Profiling the total time spent in GC.");
791 STAM_REG(pVM, &pVM->StatSwitcherToGC, STAMTYPE_PROFILE_ADV, "/PROF/VM/SwitchToGC", STAMUNIT_TICKS_PER_CALL, "Profiling switching to GC.");
792 STAM_REG(pVM, &pVM->StatSwitcherToHC, STAMTYPE_PROFILE_ADV, "/PROF/VM/SwitchToHC", STAMUNIT_TICKS_PER_CALL, "Profiling switching to HC.");
793 STAM_REG(pVM, &pVM->StatSwitcherSaveRegs, STAMTYPE_PROFILE_ADV, "/VM/Switcher/ToGC/SaveRegs", STAMUNIT_TICKS_PER_CALL,"Profiling switching to GC.");
794 STAM_REG(pVM, &pVM->StatSwitcherSysEnter, STAMTYPE_PROFILE_ADV, "/VM/Switcher/ToGC/SysEnter", STAMUNIT_TICKS_PER_CALL,"Profiling switching to GC.");
795 STAM_REG(pVM, &pVM->StatSwitcherDebug, STAMTYPE_PROFILE_ADV, "/VM/Switcher/ToGC/Debug", STAMUNIT_TICKS_PER_CALL,"Profiling switching to GC.");
796 STAM_REG(pVM, &pVM->StatSwitcherCR0, STAMTYPE_PROFILE_ADV, "/VM/Switcher/ToGC/CR0", STAMUNIT_TICKS_PER_CALL, "Profiling switching to GC.");
797 STAM_REG(pVM, &pVM->StatSwitcherCR4, STAMTYPE_PROFILE_ADV, "/VM/Switcher/ToGC/CR4", STAMUNIT_TICKS_PER_CALL, "Profiling switching to GC.");
798 STAM_REG(pVM, &pVM->StatSwitcherLgdt, STAMTYPE_PROFILE_ADV, "/VM/Switcher/ToGC/Lgdt", STAMUNIT_TICKS_PER_CALL, "Profiling switching to GC.");
799 STAM_REG(pVM, &pVM->StatSwitcherLidt, STAMTYPE_PROFILE_ADV, "/VM/Switcher/ToGC/Lidt", STAMUNIT_TICKS_PER_CALL, "Profiling switching to GC.");
800 STAM_REG(pVM, &pVM->StatSwitcherLldt, STAMTYPE_PROFILE_ADV, "/VM/Switcher/ToGC/Lldt", STAMUNIT_TICKS_PER_CALL, "Profiling switching to GC.");
801 STAM_REG(pVM, &pVM->StatSwitcherTSS, STAMTYPE_PROFILE_ADV, "/VM/Switcher/ToGC/TSS", STAMUNIT_TICKS_PER_CALL, "Profiling switching to GC.");
802 STAM_REG(pVM, &pVM->StatSwitcherJmpCR3, STAMTYPE_PROFILE_ADV, "/VM/Switcher/ToGC/JmpCR3", STAMUNIT_TICKS_PER_CALL,"Profiling switching to GC.");
803 STAM_REG(pVM, &pVM->StatSwitcherRstrRegs, STAMTYPE_PROFILE_ADV, "/VM/Switcher/ToGC/RstrRegs", STAMUNIT_TICKS_PER_CALL,"Profiling switching to GC.");
804
805 for (VMCPUID idCpu = 0; idCpu < pVM->cCpus; idCpu++)
806 {
807 rc = STAMR3RegisterF(pVM, &pUVM->aCpus[idCpu].vm.s.StatHaltYield, STAMTYPE_PROFILE, STAMVISIBILITY_ALWAYS, STAMUNIT_TICKS_PER_CALL, "Profiling halted state yielding.", "/PROF/VM/CPU%d/Halt/Yield", idCpu);
808 AssertRC(rc);
809 rc = STAMR3RegisterF(pVM, &pUVM->aCpus[idCpu].vm.s.StatHaltBlock, STAMTYPE_PROFILE, STAMVISIBILITY_ALWAYS, STAMUNIT_TICKS_PER_CALL, "Profiling halted state blocking.", "/PROF/VM/CPU%d/Halt/Block", idCpu);
810 AssertRC(rc);
811 rc = STAMR3RegisterF(pVM, &pUVM->aCpus[idCpu].vm.s.StatHaltTimers, STAMTYPE_PROFILE, STAMVISIBILITY_ALWAYS, STAMUNIT_TICKS_PER_CALL, "Profiling halted state timer tasks.", "/PROF/VM/CPU%d/Halt/Timers", idCpu);
812 AssertRC(rc);
813 }
814
815 STAM_REG(pVM, &pUVM->vm.s.StatReqAllocNew, STAMTYPE_COUNTER, "/VM/Req/AllocNew", STAMUNIT_OCCURENCES, "Number of VMR3ReqAlloc returning a new packet.");
816 STAM_REG(pVM, &pUVM->vm.s.StatReqAllocRaces, STAMTYPE_COUNTER, "/VM/Req/AllocRaces", STAMUNIT_OCCURENCES, "Number of VMR3ReqAlloc causing races.");
817 STAM_REG(pVM, &pUVM->vm.s.StatReqAllocRecycled, STAMTYPE_COUNTER, "/VM/Req/AllocRecycled", STAMUNIT_OCCURENCES, "Number of VMR3ReqAlloc returning a recycled packet.");
818 STAM_REG(pVM, &pUVM->vm.s.StatReqFree, STAMTYPE_COUNTER, "/VM/Req/Free", STAMUNIT_OCCURENCES, "Number of VMR3ReqFree calls.");
819 STAM_REG(pVM, &pUVM->vm.s.StatReqFreeOverflow, STAMTYPE_COUNTER, "/VM/Req/FreeOverflow", STAMUNIT_OCCURENCES, "Number of times the request was actually freed.");
820 STAM_REG(pVM, &pUVM->vm.s.StatReqProcessed, STAMTYPE_COUNTER, "/VM/Req/Processed", STAMUNIT_OCCURENCES, "Number of processed requests (any queue).");
821 STAM_REG(pVM, &pUVM->vm.s.StatReqMoreThan1, STAMTYPE_COUNTER, "/VM/Req/MoreThan1", STAMUNIT_OCCURENCES, "Number of times there are more than one request on the queue when processing it.");
822 STAM_REG(pVM, &pUVM->vm.s.StatReqPushBackRaces, STAMTYPE_COUNTER, "/VM/Req/PushBackRaces", STAMUNIT_OCCURENCES, "Number of push back races.");
823
824 rc = CPUMR3Init(pVM);
825 if (RT_SUCCESS(rc))
826 {
827 rc = HWACCMR3Init(pVM);
828 if (RT_SUCCESS(rc))
829 {
830 rc = PGMR3Init(pVM);
831 if (RT_SUCCESS(rc))
832 {
833 rc = REMR3Init(pVM);
834 if (RT_SUCCESS(rc))
835 {
836 rc = MMR3InitPaging(pVM);
837 if (RT_SUCCESS(rc))
838 rc = TMR3Init(pVM);
839 if (RT_SUCCESS(rc))
840 {
841 rc = VMMR3Init(pVM);
842 if (RT_SUCCESS(rc))
843 {
844 rc = SELMR3Init(pVM);
845 if (RT_SUCCESS(rc))
846 {
847 rc = TRPMR3Init(pVM);
848 if (RT_SUCCESS(rc))
849 {
850 rc = CSAMR3Init(pVM);
851 if (RT_SUCCESS(rc))
852 {
853 rc = PATMR3Init(pVM);
854 if (RT_SUCCESS(rc))
855 {
856 rc = IOMR3Init(pVM);
857 if (RT_SUCCESS(rc))
858 {
859 rc = EMR3Init(pVM);
860 if (RT_SUCCESS(rc))
861 {
862 rc = DBGFR3Init(pVM);
863 if (RT_SUCCESS(rc))
864 {
865 rc = PDMR3Init(pVM);
866 if (RT_SUCCESS(rc))
867 {
868 rc = PGMR3InitDynMap(pVM);
869 if (RT_SUCCESS(rc))
870 rc = MMR3HyperInitFinalize(pVM);
871 if (RT_SUCCESS(rc))
872 rc = PATMR3InitFinalize(pVM);
873 if (RT_SUCCESS(rc))
874 rc = PGMR3InitFinalize(pVM);
875 if (RT_SUCCESS(rc))
876 rc = SELMR3InitFinalize(pVM);
877 if (RT_SUCCESS(rc))
878 rc = TMR3InitFinalize(pVM);
879 if (RT_SUCCESS(rc))
880 rc = VMMR3InitFinalize(pVM);
881 if (RT_SUCCESS(rc))
882 rc = REMR3InitFinalize(pVM);
883 if (RT_SUCCESS(rc))
884 rc = vmR3InitDoCompleted(pVM, VMINITCOMPLETED_RING3);
885 if (RT_SUCCESS(rc))
886 {
887 LogFlow(("vmR3InitRing3: returns %Rrc\n", VINF_SUCCESS));
888 return VINF_SUCCESS;
889 }
890 int rc2 = PDMR3Term(pVM);
891 AssertRC(rc2);
892 }
893 int rc2 = DBGFR3Term(pVM);
894 AssertRC(rc2);
895 }
896 int rc2 = EMR3Term(pVM);
897 AssertRC(rc2);
898 }
899 int rc2 = IOMR3Term(pVM);
900 AssertRC(rc2);
901 }
902 int rc2 = PATMR3Term(pVM);
903 AssertRC(rc2);
904 }
905 int rc2 = CSAMR3Term(pVM);
906 AssertRC(rc2);
907 }
908 int rc2 = TRPMR3Term(pVM);
909 AssertRC(rc2);
910 }
911 int rc2 = SELMR3Term(pVM);
912 AssertRC(rc2);
913 }
914 int rc2 = VMMR3Term(pVM);
915 AssertRC(rc2);
916 }
917 int rc2 = TMR3Term(pVM);
918 AssertRC(rc2);
919 }
920 int rc2 = REMR3Term(pVM);
921 AssertRC(rc2);
922 }
923 int rc2 = PGMR3Term(pVM);
924 AssertRC(rc2);
925 }
926 int rc2 = HWACCMR3Term(pVM);
927 AssertRC(rc2);
928 }
929 //int rc2 = CPUMR3Term(pVM);
930 //AssertRC(rc2);
931 }
932 /* MMR3Term is not called here because it'll kill the heap. */
933 }
934
935 LogFlow(("vmR3InitRing3: returns %Rrc\n", rc));
936 return rc;
937}
938
939
940/**
941 * Initializes all VM CPU components of the VM
942 */
943static int vmR3InitVMCpu(PVM pVM)
944{
945 int rc = VINF_SUCCESS;
946 int rc2;
947
948 rc = CPUMR3InitCPU(pVM);
949 if (RT_SUCCESS(rc))
950 {
951 rc = HWACCMR3InitCPU(pVM);
952 if (RT_SUCCESS(rc))
953 {
954 rc = PGMR3InitCPU(pVM);
955 if (RT_SUCCESS(rc))
956 {
957 rc = TMR3InitCPU(pVM);
958 if (RT_SUCCESS(rc))
959 {
960 rc = VMMR3InitCPU(pVM);
961 if (RT_SUCCESS(rc))
962 {
963 rc = EMR3InitCPU(pVM);
964 if (RT_SUCCESS(rc))
965 {
966 LogFlow(("vmR3InitVMCpu: returns %Rrc\n", VINF_SUCCESS));
967 return VINF_SUCCESS;
968 }
969
970 rc2 = VMMR3TermCPU(pVM);
971 AssertRC(rc2);
972 }
973 rc2 = TMR3TermCPU(pVM);
974 AssertRC(rc2);
975 }
976 rc2 = PGMR3TermCPU(pVM);
977 AssertRC(rc2);
978 }
979 rc2 = HWACCMR3TermCPU(pVM);
980 AssertRC(rc2);
981 }
982 rc2 = CPUMR3TermCPU(pVM);
983 AssertRC(rc2);
984 }
985 LogFlow(("vmR3InitVMCpu: returns %Rrc\n", rc));
986 return rc;
987}
988
989
990/**
991 * Initializes all R0 components of the VM
992 */
993static int vmR3InitRing0(PVM pVM)
994{
995 LogFlow(("vmR3InitRing0:\n"));
996
997 /*
998 * Check for FAKE suplib mode.
999 */
1000 int rc = VINF_SUCCESS;
1001 const char *psz = RTEnvGet("VBOX_SUPLIB_FAKE");
1002 if (!psz || strcmp(psz, "fake"))
1003 {
1004 /*
1005 * Call the VMMR0 component and let it do the init.
1006 */
1007 rc = VMMR3InitR0(pVM);
1008 }
1009 else
1010 Log(("vmR3InitRing0: skipping because of VBOX_SUPLIB_FAKE=fake\n"));
1011
1012 /*
1013 * Do notifications and return.
1014 */
1015 if (RT_SUCCESS(rc))
1016 rc = vmR3InitDoCompleted(pVM, VMINITCOMPLETED_RING0);
1017
1018 /** @todo Move this to the VMINITCOMPLETED_RING0 notification handler. */
1019 if (RT_SUCCESS(rc))
1020 {
1021 rc = HWACCMR3InitFinalizeR0(pVM);
1022 CPUMR3SetHWVirtEx(pVM, HWACCMIsEnabled(pVM));
1023 }
1024
1025 LogFlow(("vmR3InitRing0: returns %Rrc\n", rc));
1026 return rc;
1027}
1028
1029
1030/**
1031 * Initializes all GC components of the VM
1032 */
1033static int vmR3InitGC(PVM pVM)
1034{
1035 LogFlow(("vmR3InitGC:\n"));
1036
1037 /*
1038 * Check for FAKE suplib mode.
1039 */
1040 int rc = VINF_SUCCESS;
1041 const char *psz = RTEnvGet("VBOX_SUPLIB_FAKE");
1042 if (!psz || strcmp(psz, "fake"))
1043 {
1044 /*
1045 * Call the VMMR0 component and let it do the init.
1046 */
1047 rc = VMMR3InitRC(pVM);
1048 }
1049 else
1050 Log(("vmR3InitGC: skipping because of VBOX_SUPLIB_FAKE=fake\n"));
1051
1052 /*
1053 * Do notifications and return.
1054 */
1055 if (RT_SUCCESS(rc))
1056 rc = vmR3InitDoCompleted(pVM, VMINITCOMPLETED_GC);
1057 LogFlow(("vmR3InitGC: returns %Rrc\n", rc));
1058 return rc;
1059}
1060
1061
1062/**
1063 * Do init completed notifications.
1064 * This notifications can fail.
1065 *
1066 * @param pVM The VM handle.
1067 * @param enmWhat What's completed.
1068 */
1069static int vmR3InitDoCompleted(PVM pVM, VMINITCOMPLETED enmWhat)
1070{
1071 return VINF_SUCCESS;
1072}
1073
1074
1075/**
1076 * Logger callback for inserting a custom prefix.
1077 *
1078 * @returns Number of chars written.
1079 * @param pLogger The logger.
1080 * @param pchBuf The output buffer.
1081 * @param cchBuf The output buffer size.
1082 * @param pvUser Pointer to the UVM structure.
1083 */
1084static DECLCALLBACK(size_t) vmR3LogPrefixCallback(PRTLOGGER pLogger, char *pchBuf, size_t cchBuf, void *pvUser)
1085{
1086 AssertReturn(cchBuf >= 2, 0);
1087 PUVM pUVM = (PUVM)pvUser;
1088 PUVMCPU pUVCpu = (PUVMCPU)RTTlsGet(pUVM->vm.s.idxTLS);
1089 if (pUVCpu)
1090 {
1091 static const char s_szHex[17] = "0123456789abcdef";
1092 VMCPUID const idCpu = pUVCpu->idCpu;
1093 pchBuf[1] = s_szHex[ idCpu & 15];
1094 pchBuf[0] = s_szHex[(idCpu >> 4) & 15];
1095 }
1096 else
1097 {
1098 pchBuf[0] = 'x';
1099 pchBuf[1] = 'y';
1100 }
1101
1102 return 2;
1103}
1104
1105
1106/**
1107 * Calls the relocation functions for all VMM components so they can update
1108 * any GC pointers. When this function is called all the basic VM members
1109 * have been updated and the actual memory relocation have been done
1110 * by the PGM/MM.
1111 *
1112 * This is used both on init and on runtime relocations.
1113 *
1114 * @param pVM VM handle.
1115 * @param offDelta Relocation delta relative to old location.
1116 */
1117VMMR3DECL(void) VMR3Relocate(PVM pVM, RTGCINTPTR offDelta)
1118{
1119 LogFlow(("VMR3Relocate: offDelta=%RGv\n", offDelta));
1120
1121 /*
1122 * The order here is very important!
1123 */
1124 PGMR3Relocate(pVM, offDelta);
1125 PDMR3LdrRelocateU(pVM->pUVM, offDelta);
1126 PGMR3Relocate(pVM, 0); /* Repeat after PDM relocation. */
1127 CPUMR3Relocate(pVM);
1128 HWACCMR3Relocate(pVM);
1129 SELMR3Relocate(pVM);
1130 VMMR3Relocate(pVM, offDelta);
1131 SELMR3Relocate(pVM); /* !hack! fix stack! */
1132 TRPMR3Relocate(pVM, offDelta);
1133 PATMR3Relocate(pVM);
1134 CSAMR3Relocate(pVM, offDelta);
1135 IOMR3Relocate(pVM, offDelta);
1136 EMR3Relocate(pVM);
1137 TMR3Relocate(pVM, offDelta);
1138 DBGFR3Relocate(pVM, offDelta);
1139 PDMR3Relocate(pVM, offDelta);
1140}
1141
1142
1143/**
1144 * EMT rendezvous worker for VMR3PowerOn.
1145 *
1146 * @returns VERR_VM_INVALID_VM_STATE or VINF_SUCCESS. (This is a strict return
1147 * code, see FNVMMEMTRENDEZVOUS.)
1148 *
1149 * @param pVM The VM handle.
1150 * @param pVCpu The VMCPU handle of the EMT.
1151 * @param pvUser Ignored.
1152 */
1153static DECLCALLBACK(VBOXSTRICTRC) vmR3PowerOn(PVM pVM, PVMCPU pVCpu, void *pvUser)
1154{
1155 LogFlow(("vmR3PowerOn: pVM=%p pVCpu=%p/#%u\n", pVM, pVCpu, pVCpu->idCpu));
1156 Assert(!pvUser); NOREF(pvUser);
1157
1158 /*
1159 * The first thread thru here tries to change the state. We shouldn't be
1160 * called again if this fails.
1161 */
1162 if (pVCpu->idCpu == pVM->cCpus - 1)
1163 {
1164 int rc = vmR3TrySetState(pVM, "VMR3PowerOn", 1, VMSTATE_POWERING_ON, VMSTATE_CREATED);
1165 if (RT_FAILURE(rc))
1166 return rc;
1167 }
1168
1169 VMSTATE enmVMState = VMR3GetState(pVM);
1170 AssertMsgReturn(enmVMState == VMSTATE_POWERING_ON,
1171 ("%s\n", VMR3GetStateName(enmVMState)),
1172 VERR_INTERNAL_ERROR_4);
1173
1174 /*
1175 * All EMTs changes their state to started.
1176 */
1177 VMCPU_SET_STATE(pVCpu, VMCPUSTATE_STARTED);
1178
1179 /*
1180 * EMT(0) is last thru here and it will make the notification calls
1181 * and advance the state.
1182 */
1183 if (pVCpu->idCpu == 0)
1184 {
1185 PDMR3PowerOn(pVM);
1186 vmR3SetState(pVM, VMSTATE_RUNNING, VMSTATE_POWERING_ON);
1187 }
1188
1189 return VINF_SUCCESS;
1190}
1191
1192
1193/**
1194 * Powers on the virtual machine.
1195 *
1196 * @returns VBox status code.
1197 *
1198 * @param pVM The VM to power on.
1199 *
1200 * @thread Any thread.
1201 * @vmstate Created
1202 * @vmstateto PoweringOn+Running
1203 */
1204VMMR3DECL(int) VMR3PowerOn(PVM pVM)
1205{
1206 LogFlow(("VMR3PowerOn: pVM=%p\n", pVM));
1207 VM_ASSERT_VALID_EXT_RETURN(pVM, VERR_INVALID_VM_HANDLE);
1208
1209 /*
1210 * Gather all the EMTs to reduce the init TSC drift and keep
1211 * the state changing APIs a bit uniform.
1212 */
1213 int rc = VMMR3EmtRendezvous(pVM, VMMEMTRENDEZVOUS_FLAGS_TYPE_DESCENDING | VMMEMTRENDEZVOUS_FLAGS_STOP_ON_ERROR,
1214 vmR3PowerOn, NULL);
1215 LogFlow(("VMR3PowerOn: returns %Rrc\n", rc));
1216 return rc;
1217}
1218
1219
1220/**
1221 * Does the suspend notifications.
1222 *
1223 * @param pVM The VM handle.
1224 * @thread EMT(0)
1225 */
1226static void vmR3SuspendDoWork(PVM pVM)
1227{
1228 PDMR3Suspend(pVM);
1229}
1230
1231
1232/**
1233 * EMT rendezvous worker for VMR3Suspend.
1234 *
1235 * @returns VERR_VM_INVALID_VM_STATE or VINF_EM_SUSPEND. (This is a strict
1236 * return code, see FNVMMEMTRENDEZVOUS.)
1237 *
1238 * @param pVM The VM handle.
1239 * @param pVCpu The VMCPU handle of the EMT.
1240 * @param pvUser Ignored.
1241 */
1242static DECLCALLBACK(VBOXSTRICTRC) vmR3Suspend(PVM pVM, PVMCPU pVCpu, void *pvUser)
1243{
1244 LogFlow(("vmR3Suspend: pVM=%p pVCpu=%p/#%u\n", pVM, pVCpu, pVCpu->idCpu));
1245 Assert(!pvUser); NOREF(pvUser);
1246
1247 /*
1248 * The first EMT switches the state to suspending. If this fails because
1249 * something was racing us in one way or the other, there will be no more
1250 * calls and thus the state assertion below is not going to annoy anyone.
1251 */
1252 if (pVCpu->idCpu == pVM->cCpus - 1)
1253 {
1254 int rc = vmR3TrySetState(pVM, "VMR3Suspend", 2,
1255 VMSTATE_SUSPENDING, VMSTATE_RUNNING,
1256 VMSTATE_SUSPENDING_EXT_LS, VMSTATE_RUNNING_LS);
1257 if (RT_FAILURE(rc))
1258 return rc;
1259 }
1260
1261 VMSTATE enmVMState = VMR3GetState(pVM);
1262 AssertMsgReturn( enmVMState == VMSTATE_SUSPENDING
1263 || enmVMState == VMSTATE_SUSPENDING_EXT_LS,
1264 ("%s\n", VMR3GetStateName(enmVMState)),
1265 VERR_INTERNAL_ERROR_4);
1266
1267 /*
1268 * EMT(0) does the actually suspending *after* all the other CPUs have
1269 * been thru here.
1270 */
1271 if (pVCpu->idCpu == 0)
1272 {
1273 vmR3SuspendDoWork(pVM);
1274
1275 int rc = vmR3TrySetState(pVM, "VMR3Suspend", 2,
1276 VMSTATE_SUSPENDED, VMSTATE_SUSPENDING,
1277 VMSTATE_SUSPENDED_EXT_LS, VMSTATE_SUSPENDING_EXT_LS);
1278 if (RT_FAILURE(rc))
1279 return VERR_INTERNAL_ERROR_3;
1280 }
1281
1282 return VINF_EM_SUSPEND;
1283}
1284
1285
1286/**
1287 * Suspends a running VM.
1288 *
1289 * @returns VBox status code. When called on EMT, this will be a strict status
1290 * code that has to be propagated up the call stack.
1291 *
1292 * @param pVM The VM to suspend.
1293 *
1294 * @thread Any thread.
1295 * @vmstate Running or RunningLS
1296 * @vmstateto Suspending + Suspended or SuspendingExtLS + SuspendedExtLS
1297 */
1298VMMR3DECL(int) VMR3Suspend(PVM pVM)
1299{
1300 LogFlow(("VMR3Suspend: pVM=%p\n", pVM));
1301 VM_ASSERT_VALID_EXT_RETURN(pVM, VERR_INVALID_VM_HANDLE);
1302
1303 /*
1304 * Gather all the EMTs to make sure there are no races before
1305 * changing the VM state.
1306 */
1307 int rc = VMMR3EmtRendezvous(pVM, VMMEMTRENDEZVOUS_FLAGS_TYPE_DESCENDING | VMMEMTRENDEZVOUS_FLAGS_STOP_ON_ERROR,
1308 vmR3Suspend, NULL);
1309 LogFlow(("VMR3Suspend: returns %Rrc\n", rc));
1310 return rc;
1311}
1312
1313
1314/**
1315 * EMT rendezvous worker for VMR3Resume.
1316 *
1317 * @returns VERR_VM_INVALID_VM_STATE or VINF_EM_RESUME. (This is a strict
1318 * return code, see FNVMMEMTRENDEZVOUS.)
1319 *
1320 * @param pVM The VM handle.
1321 * @param pVCpu The VMCPU handle of the EMT.
1322 * @param pvUser Ignored.
1323 */
1324static DECLCALLBACK(VBOXSTRICTRC) vmR3Resume(PVM pVM, PVMCPU pVCpu, void *pvUser)
1325{
1326 LogFlow(("vmR3Resume: pVM=%p pVCpu=%p/#%u\n", pVM, pVCpu, pVCpu->idCpu));
1327 Assert(!pvUser); NOREF(pvUser);
1328
1329 /*
1330 * The first thread thru here tries to change the state. We shouldn't be
1331 * called again if this fails.
1332 */
1333 if (pVCpu->idCpu == pVM->cCpus - 1)
1334 {
1335 int rc = vmR3TrySetState(pVM, "VMR3Resume", 1, VMSTATE_RESUMING, VMSTATE_SUSPENDED);
1336 if (RT_FAILURE(rc))
1337 return rc;
1338 }
1339
1340 VMSTATE enmVMState = VMR3GetState(pVM);
1341 AssertMsgReturn(enmVMState == VMSTATE_RESUMING,
1342 ("%s\n", VMR3GetStateName(enmVMState)),
1343 VERR_INTERNAL_ERROR_4);
1344
1345#if 0
1346 /*
1347 * All EMTs changes their state to started.
1348 */
1349 VMCPU_SET_STATE(pVCpu, VMCPUSTATE_STARTED);
1350#endif
1351
1352 /*
1353 * EMT(0) is last thru here and it will make the notification calls
1354 * and advance the state.
1355 */
1356 if (pVCpu->idCpu == 0)
1357 {
1358 PDMR3Resume(pVM);
1359 vmR3SetState(pVM, VMSTATE_RUNNING, VMSTATE_RESUMING);
1360 pVM->vm.s.fTeleportedAndNotFullyResumedYet = false;
1361 }
1362
1363 return VINF_EM_RESUME;
1364}
1365
1366
1367/**
1368 * Resume VM execution.
1369 *
1370 * @returns VBox status code. When called on EMT, this will be a strict status
1371 * code that has to be propagated up the call stack.
1372 *
1373 * @param pVM The VM to resume.
1374 *
1375 * @thread Any thread.
1376 * @vmstate Suspended
1377 * @vmstateto Running
1378 */
1379VMMR3DECL(int) VMR3Resume(PVM pVM)
1380{
1381 LogFlow(("VMR3Resume: pVM=%p\n", pVM));
1382 VM_ASSERT_VALID_EXT_RETURN(pVM, VERR_INVALID_VM_HANDLE);
1383
1384 /*
1385 * Gather all the EMTs to make sure there are no races before
1386 * changing the VM state.
1387 */
1388 int rc = VMMR3EmtRendezvous(pVM, VMMEMTRENDEZVOUS_FLAGS_TYPE_DESCENDING | VMMEMTRENDEZVOUS_FLAGS_STOP_ON_ERROR,
1389 vmR3Resume, NULL);
1390 LogFlow(("VMR3Resume: returns %Rrc\n", rc));
1391 return rc;
1392}
1393
1394
1395/**
1396 * EMT rendezvous worker for VMR3Save and VMR3Teleport that suspends the VM
1397 * after the live step has been completed.
1398 *
1399 * @returns VERR_VM_INVALID_VM_STATE or VINF_EM_RESUME. (This is a strict
1400 * return code, see FNVMMEMTRENDEZVOUS.)
1401 *
1402 * @param pVM The VM handle.
1403 * @param pVCpu The VMCPU handle of the EMT.
1404 * @param pvUser The pfSuspended argument of vmR3SaveTeleport.
1405 */
1406static DECLCALLBACK(VBOXSTRICTRC) vmR3LiveDoSuspend(PVM pVM, PVMCPU pVCpu, void *pvUser)
1407{
1408 LogFlow(("vmR3LiveDoSuspend: pVM=%p pVCpu=%p/#%u\n", pVM, pVCpu, pVCpu->idCpu));
1409 bool *pfSuspended = (bool *)pvUser;
1410
1411 /*
1412 * The first thread thru here tries to change the state. We shouldn't be
1413 * called again if this fails.
1414 */
1415 if (pVCpu->idCpu == pVM->cCpus - 1U)
1416 {
1417 PUVM pUVM = pVM->pUVM;
1418 int rc;
1419
1420 RTCritSectEnter(&pUVM->vm.s.AtStateCritSect);
1421 VMSTATE enmVMState = pVM->enmVMState;
1422 switch (enmVMState)
1423 {
1424 case VMSTATE_RUNNING_LS:
1425 vmR3SetStateLocked(pVM, pUVM, VMSTATE_SUSPENDING_LS, VMSTATE_RUNNING_LS);
1426 rc = VINF_SUCCESS;
1427 break;
1428
1429 case VMSTATE_SUSPENDED_EXT_LS:
1430 case VMSTATE_SUSPENDED_LS: /* (via reset) */
1431 rc = VINF_SUCCESS;
1432 break;
1433
1434 case VMSTATE_DEBUGGING_LS:
1435 rc = VERR_TRY_AGAIN;
1436 break;
1437
1438 case VMSTATE_OFF_LS:
1439 vmR3SetStateLocked(pVM, pUVM, VMSTATE_OFF, VMSTATE_OFF_LS);
1440 rc = VERR_SSM_LIVE_POWERED_OFF;
1441 break;
1442
1443 case VMSTATE_FATAL_ERROR_LS:
1444 vmR3SetStateLocked(pVM, pUVM, VMSTATE_FATAL_ERROR, VMSTATE_FATAL_ERROR_LS);
1445 rc = VERR_SSM_LIVE_FATAL_ERROR;
1446 break;
1447
1448 case VMSTATE_GURU_MEDITATION_LS:
1449 vmR3SetStateLocked(pVM, pUVM, VMSTATE_GURU_MEDITATION, VMSTATE_GURU_MEDITATION_LS);
1450 rc = VERR_SSM_LIVE_GURU_MEDITATION;
1451 break;
1452
1453 case VMSTATE_POWERING_OFF_LS:
1454 case VMSTATE_SUSPENDING_EXT_LS:
1455 case VMSTATE_RESETTING_LS:
1456 default:
1457 AssertMsgFailed(("%s\n", VMR3GetStateName(enmVMState)));
1458 rc = VERR_INTERNAL_ERROR_3;
1459 break;
1460 }
1461 RTCritSectLeave(&pUVM->vm.s.AtStateCritSect);
1462 if (RT_FAILURE(rc))
1463 {
1464 LogFlow(("vmR3LiveDoSuspend: returns %Rrc (state was %s)\n", rc, VMR3GetStateName(enmVMState)));
1465 return rc;
1466 }
1467 }
1468
1469 VMSTATE enmVMState = VMR3GetState(pVM);
1470 AssertMsgReturn(enmVMState == VMSTATE_SUSPENDING_LS,
1471 ("%s\n", VMR3GetStateName(enmVMState)),
1472 VERR_INTERNAL_ERROR_4);
1473
1474 /*
1475 * Only EMT(0) have work to do since it's last thru here.
1476 */
1477 if (pVCpu->idCpu == 0)
1478 {
1479 vmR3SuspendDoWork(pVM);
1480 int rc = vmR3TrySetState(pVM, "VMR3Suspend", 1,
1481 VMSTATE_SUSPENDED_LS, VMSTATE_SUSPENDING_LS);
1482 if (RT_FAILURE(rc))
1483 return VERR_INTERNAL_ERROR_3;
1484
1485 *pfSuspended = true;
1486 }
1487
1488 return VINF_EM_SUSPEND;
1489}
1490
1491
1492/**
1493 * EMT rendezvous worker that VMR3Save and VMR3Teleport uses to clean up a
1494 * SSMR3LiveDoStep1 failure.
1495 *
1496 * Doing this as a rendezvous operation avoids all annoying transition
1497 * states.
1498 *
1499 * @returns VERR_VM_INVALID_VM_STATE, VINF_SUCCESS or some specific VERR_SSM_*
1500 * status code. (This is a strict return code, see FNVMMEMTRENDEZVOUS.)
1501 *
1502 * @param pVM The VM handle.
1503 * @param pVCpu The VMCPU handle of the EMT.
1504 * @param pvUser The pfSuspended argument of vmR3SaveTeleport.
1505 */
1506static DECLCALLBACK(VBOXSTRICTRC) vmR3LiveDoStep1Cleanup(PVM pVM, PVMCPU pVCpu, void *pvUser)
1507{
1508 LogFlow(("vmR3LiveDoStep1Cleanup: pVM=%p pVCpu=%p/#%u\n", pVM, pVCpu, pVCpu->idCpu));
1509 bool *pfSuspended = (bool *)pvUser;
1510 NOREF(pVCpu);
1511
1512 int rc = vmR3TrySetState(pVM, "vmR3LiveDoStep1Cleanup", 8,
1513 VMSTATE_OFF, VMSTATE_OFF_LS, /* 1 */
1514 VMSTATE_FATAL_ERROR, VMSTATE_FATAL_ERROR_LS, /* 2 */
1515 VMSTATE_GURU_MEDITATION, VMSTATE_GURU_MEDITATION_LS, /* 3 */
1516 VMSTATE_SUSPENDED, VMSTATE_SUSPENDED_LS, /* 4 */
1517 VMSTATE_SUSPENDED, VMSTATE_SAVING,
1518 VMSTATE_SUSPENDED, VMSTATE_SUSPENDED_EXT_LS,
1519 VMSTATE_RUNNING, VMSTATE_RUNNING_LS,
1520 VMSTATE_DEBUGGING, VMSTATE_DEBUGGING_LS);
1521 if (rc == 1)
1522 rc = VERR_SSM_LIVE_POWERED_OFF;
1523 else if (rc == 2)
1524 rc = VERR_SSM_LIVE_FATAL_ERROR;
1525 else if (rc == 3)
1526 rc = VERR_SSM_LIVE_GURU_MEDITATION;
1527 else if (rc == 4)
1528 {
1529 *pfSuspended = true;
1530 rc = VINF_SUCCESS;
1531 }
1532 else if (rc > 0)
1533 rc = VINF_SUCCESS;
1534 return rc;
1535}
1536
1537
1538/**
1539 * EMT(0) worker for VMR3Save and VMR3Teleport that completes the live save.
1540 *
1541 * @returns VBox status code.
1542 * @retval VINF_SSM_LIVE_SUSPENDED if VMR3Suspend was called.
1543 *
1544 * @param pVM The VM handle.
1545 * @param pSSM The handle of saved state operation.
1546 *
1547 * @thread EMT(0)
1548 */
1549static DECLCALLBACK(int) vmR3LiveDoStep2(PVM pVM, PSSMHANDLE pSSM)
1550{
1551 LogFlow(("vmR3LiveDoStep2: pVM=%p pSSM=%p\n", pVM, pSSM));
1552 VM_ASSERT_EMT0(pVM);
1553
1554 /*
1555 * Advance the state and mark if VMR3Suspend was called.
1556 */
1557 int rc = VINF_SUCCESS;
1558 VMSTATE enmVMState = VMR3GetState(pVM);
1559 if (enmVMState == VMSTATE_SUSPENDED_LS)
1560 vmR3SetState(pVM, VMSTATE_SAVING, VMSTATE_SUSPENDED_LS);
1561 else
1562 {
1563 if (enmVMState != VMSTATE_SAVING)
1564 vmR3SetState(pVM, VMSTATE_SAVING, VMSTATE_SUSPENDED_EXT_LS);
1565 rc = VINF_SSM_LIVE_SUSPENDED;
1566 }
1567
1568 /*
1569 * Finish up and release the handle. Careful with the status codes.
1570 */
1571 int rc2 = SSMR3LiveDoStep2(pSSM);
1572 if (rc == VINF_SUCCESS || (RT_FAILURE(rc2) && RT_SUCCESS(rc)))
1573 rc = rc2;
1574
1575 rc2 = SSMR3LiveDone(pSSM);
1576 if (rc == VINF_SUCCESS || (RT_FAILURE(rc2) && RT_SUCCESS(rc)))
1577 rc = rc2;
1578
1579 /*
1580 * Advance to the final state and return.
1581 */
1582 vmR3SetState(pVM, VMSTATE_SUSPENDED, VMSTATE_SAVING);
1583 Assert(rc > VINF_EM_LAST || rc < VINF_EM_FIRST);
1584 return rc;
1585}
1586
1587
1588/**
1589 * Worker for vmR3SaveTeleport that validates the state and calls SSMR3Save or
1590 * SSMR3LiveSave.
1591 *
1592 * @returns VBox status code.
1593 *
1594 * @param pVM The VM handle.
1595 * @param cMsMaxDowntime The maximum downtime given as milliseconds.
1596 * @param pszFilename The name of the file. NULL if pStreamOps is used.
1597 * @param pStreamOps The stream methods. NULL if pszFilename is used.
1598 * @param pvStreamOpsUser The user argument to the stream methods.
1599 * @param enmAfter What to do afterwards.
1600 * @param pfnProgress Progress callback. Optional.
1601 * @param pvProgressUser User argument for the progress callback.
1602 * @param ppSSM Where to return the saved state handle in case of a
1603 * live snapshot scenario.
1604 * @thread EMT
1605 */
1606static DECLCALLBACK(int) vmR3Save(PVM pVM, uint32_t cMsMaxDowntime, const char *pszFilename, PCSSMSTRMOPS pStreamOps, void *pvStreamOpsUser,
1607 SSMAFTER enmAfter, PFNVMPROGRESS pfnProgress, void *pvProgressUser, PSSMHANDLE *ppSSM)
1608{
1609 LogFlow(("vmR3Save: pVM=%p cMsMaxDowntime=%u pszFilename=%p:{%s} pStreamOps=%p pvStreamOpsUser=%p enmAfter=%d pfnProgress=%p pvProgressUser=%p ppSSM=%p\n",
1610 pVM, cMsMaxDowntime, pszFilename, pszFilename, pStreamOps, pvStreamOpsUser, enmAfter, pfnProgress, pvProgressUser, ppSSM));
1611
1612 /*
1613 * Validate input.
1614 */
1615 AssertPtrNull(pszFilename);
1616 AssertPtrNull(pStreamOps);
1617 AssertPtr(pVM);
1618 Assert( enmAfter == SSMAFTER_DESTROY
1619 || enmAfter == SSMAFTER_CONTINUE
1620 || enmAfter == SSMAFTER_TELEPORT);
1621 AssertPtr(ppSSM);
1622 *ppSSM = NULL;
1623
1624 /*
1625 * Change the state and perform/start the saving.
1626 */
1627 int rc = vmR3TrySetState(pVM, "VMR3Save", 2,
1628 VMSTATE_SAVING, VMSTATE_SUSPENDED,
1629 VMSTATE_RUNNING_LS, VMSTATE_RUNNING);
1630 if (rc == 1 && enmAfter != SSMAFTER_TELEPORT)
1631 {
1632 Assert(!pStreamOps);
1633 rc = SSMR3Save(pVM, pszFilename, enmAfter, pfnProgress, pvProgressUser);
1634 vmR3SetState(pVM, VMSTATE_SUSPENDED, VMSTATE_SAVING);
1635 }
1636 else if (rc == 2 || enmAfter == SSMAFTER_TELEPORT)
1637 {
1638 if (enmAfter == SSMAFTER_TELEPORT)
1639 pVM->vm.s.fTeleportedAndNotFullyResumedYet = true;
1640 rc = SSMR3LiveSave(pVM, cMsMaxDowntime, pszFilename, pStreamOps, pvStreamOpsUser,
1641 enmAfter, pfnProgress, pvProgressUser, ppSSM);
1642 /* (We're not subject to cancellation just yet.) */
1643 }
1644 else
1645 Assert(RT_FAILURE(rc));
1646 return rc;
1647}
1648
1649
1650/**
1651 * Commmon worker for VMR3Save and VMR3Teleport.
1652 *
1653 * @returns VBox status code.
1654 *
1655 * @param pVM The VM handle.
1656 * @param cMsMaxDowntime The maximum downtime given as milliseconds.
1657 * @param pszFilename The name of the file. NULL if pStreamOps is used.
1658 * @param pStreamOps The stream methods. NULL if pszFilename is used.
1659 * @param pvStreamOpsUser The user argument to the stream methods.
1660 * @param enmAfter What to do afterwards.
1661 * @param pfnProgress Progress callback. Optional.
1662 * @param pvProgressUser User argument for the progress callback.
1663 * @param pfSuspended Set if we suspended the VM.
1664 *
1665 * @thread Non-EMT
1666 */
1667static int vmR3SaveTeleport(PVM pVM, uint32_t cMsMaxDowntime,
1668 const char *pszFilename, PCSSMSTRMOPS pStreamOps, void *pvStreamOpsUser,
1669 SSMAFTER enmAfter, PFNVMPROGRESS pfnProgress, void *pvProgressUser, bool *pfSuspended)
1670{
1671 /*
1672 * Request the operation in EMT(0).
1673 */
1674 PSSMHANDLE pSSM;
1675 int rc = VMR3ReqCallWaitU(pVM->pUVM, 0 /*idDstCpu*/,
1676 (PFNRT)vmR3Save, 9, pVM, cMsMaxDowntime, pszFilename, pStreamOps, pvStreamOpsUser,
1677 enmAfter, pfnProgress, pvProgressUser, &pSSM);
1678 if ( RT_SUCCESS(rc)
1679 && pSSM)
1680 {
1681 /*
1682 * Live snapshot.
1683 *
1684 * The state handling here is kind of tricky, doing it on EMT(0) helps
1685 * a bit. See the VMSTATE diagram for details.
1686 */
1687 rc = SSMR3LiveDoStep1(pSSM);
1688 if (RT_SUCCESS(rc))
1689 {
1690 if (VMR3GetState(pVM) != VMSTATE_SAVING)
1691 for (;;)
1692 {
1693 /* Try suspend the VM. */
1694 rc = VMMR3EmtRendezvous(pVM, VMMEMTRENDEZVOUS_FLAGS_TYPE_DESCENDING | VMMEMTRENDEZVOUS_FLAGS_STOP_ON_ERROR,
1695 vmR3LiveDoSuspend, pfSuspended);
1696 if (rc != VERR_TRY_AGAIN)
1697 break;
1698
1699 /* Wait for the state to change. */
1700 RTThreadSleep(250); /** @todo Live Migration: fix this polling wait by some smart use of multiple release event semaphores.. */
1701 }
1702 if (RT_SUCCESS(rc))
1703 rc = VMR3ReqCallWaitU(pVM->pUVM, 0 /*idDstCpu*/, (PFNRT)vmR3LiveDoStep2, 2, pVM, pSSM);
1704 else
1705 {
1706 int rc2 = VMR3ReqCallWaitU(pVM->pUVM, 0 /*idDstCpu*/, (PFNRT)SSMR3LiveDone, 1, pSSM);
1707 AssertMsg(rc2 == rc, ("%Rrc != %Rrc\n", rc2, rc));
1708 }
1709 }
1710 else
1711 {
1712 int rc2 = VMR3ReqCallWaitU(pVM->pUVM, 0 /*idDstCpu*/, (PFNRT)SSMR3LiveDone, 1, pSSM);
1713 AssertMsg(rc2 == rc, ("%Rrc != %Rrc\n", rc2, rc));
1714
1715 rc2 = VMMR3EmtRendezvous(pVM, VMMEMTRENDEZVOUS_FLAGS_TYPE_ONCE, vmR3LiveDoStep1Cleanup, pfSuspended);
1716 if (RT_FAILURE(rc2) && rc == VERR_SSM_CANCELLED)
1717 rc = rc2;
1718 }
1719 }
1720
1721 return rc;
1722}
1723
1724
1725/**
1726 * Save current VM state.
1727 *
1728 * Can be used for both saving the state and creating snapshots.
1729 *
1730 * When called for a VM in the Running state, the saved state is created live
1731 * and the VM is only suspended when the final part of the saving is preformed.
1732 * The VM state will not be restored to Running in this case and it's up to the
1733 * caller to call VMR3Resume if this is desirable. (The rational is that the
1734 * caller probably wish to reconfigure the disks before resuming the VM.)
1735 *
1736 * @returns VBox status code.
1737 *
1738 * @param pVM The VM which state should be saved.
1739 * @param pszFilename The name of the save state file.
1740 * @param fContinueAfterwards Whether continue execution afterwards or not.
1741 * When in doubt, set this to true.
1742 * @param pfnProgress Progress callback. Optional.
1743 * @param pvUser User argument for the progress callback.
1744 * @param pfSuspended Set if we suspended the VM.
1745 *
1746 * @thread Non-EMT.
1747 * @vmstate Suspended or Running
1748 * @vmstateto Saving+Suspended or
1749 * RunningLS+SuspeningLS+SuspendedLS+Saving+Suspended.
1750 */
1751VMMR3DECL(int) VMR3Save(PVM pVM, const char *pszFilename, bool fContinueAfterwards,
1752 PFNVMPROGRESS pfnProgress, void *pvUser, bool *pfSuspended)
1753{
1754 LogFlow(("VMR3Save: pVM=%p pszFilename=%p:{%s} fContinueAfterwards=%RTbool pfnProgress=%p pvUser=%p pfSuspended=%p\n",
1755 pVM, pszFilename, pszFilename, fContinueAfterwards, pfnProgress, pvUser, pfSuspended));
1756
1757 /*
1758 * Validate input.
1759 */
1760 AssertPtr(pfSuspended);
1761 *pfSuspended = false;
1762 VM_ASSERT_VALID_EXT_RETURN(pVM, VERR_INVALID_VM_HANDLE);
1763 VM_ASSERT_OTHER_THREAD(pVM);
1764 AssertPtrReturn(pszFilename, VERR_INVALID_POINTER);
1765 AssertReturn(*pszFilename, VERR_INVALID_PARAMETER);
1766 AssertPtrNullReturn(pfnProgress, VERR_INVALID_POINTER);
1767
1768 /*
1769 * Join paths with VMR3Teleport.
1770 */
1771 SSMAFTER enmAfter = fContinueAfterwards ? SSMAFTER_CONTINUE : SSMAFTER_DESTROY;
1772 int rc = vmR3SaveTeleport(pVM, 250 /*cMsMaxDowntime*/,
1773 pszFilename, NULL /*pStreamOps*/, NULL /*pvStreamOpsUser*/,
1774 enmAfter, pfnProgress, pvUser, pfSuspended);
1775 LogFlow(("VMR3Save: returns %Rrc (*pfSuspended=%RTbool)\n", rc, *pfSuspended));
1776 return rc;
1777}
1778
1779
1780/**
1781 * Teleport the VM (aka live migration).
1782 *
1783 * @returns VBox status code.
1784 *
1785 * @param pVM The VM which state should be saved.
1786 * @param cMsMaxDowntime The maximum downtime given as milliseconds.
1787 * @param pStreamOps The stream methods.
1788 * @param pvStreamOpsUser The user argument to the stream methods.
1789 * @param pfnProgress Progress callback. Optional.
1790 * @param pvProgressUser User argument for the progress callback.
1791 * @param pfSuspended Set if we suspended the VM.
1792 *
1793 * @thread Non-EMT.
1794 * @vmstate Suspended or Running
1795 * @vmstateto Saving+Suspended or
1796 * RunningLS+SuspeningLS+SuspendedLS+Saving+Suspended.
1797 */
1798VMMR3DECL(int) VMR3Teleport(PVM pVM, uint32_t cMsMaxDowntime, PCSSMSTRMOPS pStreamOps, void *pvStreamOpsUser,
1799 PFNVMPROGRESS pfnProgress, void *pvProgressUser, bool *pfSuspended)
1800{
1801 LogFlow(("VMR3Teleport: pVM=%p cMsMaxDowntime=%u pStreamOps=%p pvStreamOps=%p pfnProgress=%p pvProgressUser=%p\n",
1802 pVM, cMsMaxDowntime, pStreamOps, pvStreamOpsUser, pfnProgress, pvProgressUser));
1803
1804 /*
1805 * Validate input.
1806 */
1807 AssertPtr(pfSuspended);
1808 *pfSuspended = false;
1809 VM_ASSERT_VALID_EXT_RETURN(pVM, VERR_INVALID_VM_HANDLE);
1810 VM_ASSERT_OTHER_THREAD(pVM);
1811 AssertPtrReturn(pStreamOps, VERR_INVALID_POINTER);
1812 AssertPtrNullReturn(pfnProgress, VERR_INVALID_POINTER);
1813
1814 /*
1815 * Join paths with VMR3Save.
1816 */
1817 int rc = vmR3SaveTeleport(pVM, cMsMaxDowntime,
1818 NULL /*pszFilename*/, pStreamOps, pvStreamOpsUser,
1819 SSMAFTER_TELEPORT, pfnProgress, pvProgressUser, pfSuspended);
1820 LogFlow(("VMR3Teleport: returns %Rrc (*pfSuspended=%RTbool)\n", rc, *pfSuspended));
1821 return rc;
1822}
1823
1824
1825
1826/**
1827 * EMT(0) worker for VMR3LoadFromFile and VMR3LoadFromStream.
1828 *
1829 * @returns VBox status code.
1830 *
1831 * @param pVM The VM handle.
1832 * @param pszFilename The name of the file. NULL if pStreamOps is used.
1833 * @param pStreamOps The stream methods. NULL if pszFilename is used.
1834 * @param pvStreamOpsUser The user argument to the stream methods.
1835 * @param pfnProgress Progress callback. Optional.
1836 * @param pvUser User argument for the progress callback.
1837 * @param fTeleporting Indicates whether we're teleporting or not.
1838 *
1839 * @thread EMT.
1840 */
1841static DECLCALLBACK(int) vmR3Load(PVM pVM, const char *pszFilename, PCSSMSTRMOPS pStreamOps, void *pvStreamOpsUser,
1842 PFNVMPROGRESS pfnProgress, void *pvProgressUser, bool fTeleporting)
1843{
1844 LogFlow(("vmR3Load: pVM=%p pszFilename=%p:{%s} pStreamOps=%p pvStreamOpsUser=%p pfnProgress=%p pvProgressUser=%p fTeleporting=%RTbool\n",
1845 pVM, pszFilename, pszFilename, pStreamOps, pvStreamOpsUser, pfnProgress, pvProgressUser, fTeleporting));
1846
1847 /*
1848 * Validate input (paranoia).
1849 */
1850 AssertPtr(pVM);
1851 AssertPtrNull(pszFilename);
1852 AssertPtrNull(pStreamOps);
1853 AssertPtrNull(pfnProgress);
1854
1855 /*
1856 * Change the state and perform the load.
1857 *
1858 * Always perform a relocation round afterwards to make sure hypervisor
1859 * selectors and such are correct.
1860 */
1861 int rc = vmR3TrySetState(pVM, "VMR3Load", 2,
1862 VMSTATE_LOADING, VMSTATE_CREATED,
1863 VMSTATE_LOADING, VMSTATE_SUSPENDED);
1864 if (RT_FAILURE(rc))
1865 return rc;
1866 pVM->vm.s.fTeleportedAndNotFullyResumedYet = fTeleporting;
1867
1868 uint32_t cErrorsPriorToSave = VMR3GetErrorCount(pVM);
1869 rc = SSMR3Load(pVM, pszFilename, pStreamOps, pvStreamOpsUser, SSMAFTER_RESUME, pfnProgress, pvProgressUser);
1870 if (RT_SUCCESS(rc))
1871 {
1872 VMR3Relocate(pVM, 0 /*offDelta*/);
1873 vmR3SetState(pVM, VMSTATE_SUSPENDED, VMSTATE_LOADING);
1874 }
1875 else
1876 {
1877 pVM->vm.s.fTeleportedAndNotFullyResumedYet = false;
1878 vmR3SetState(pVM, VMSTATE_LOAD_FAILURE, VMSTATE_LOADING);
1879 if (cErrorsPriorToSave == VMR3GetErrorCount(pVM))
1880 rc = VMSetError(pVM, rc, RT_SRC_POS,
1881 N_("Unable to restore the virtual machine's saved state from '%s'. "
1882 "It may be damaged or from an older version of VirtualBox. "
1883 "Please discard the saved state before starting the virtual machine"),
1884 pszFilename);
1885 }
1886
1887 return rc;
1888}
1889
1890
1891/**
1892 * Loads a VM state into a newly created VM or a one that is suspended.
1893 *
1894 * To restore a saved state on VM startup, call this function and then resume
1895 * the VM instead of powering it on.
1896 *
1897 * @returns VBox status code.
1898 *
1899 * @param pVM The VM handle.
1900 * @param pszFilename The name of the save state file.
1901 * @param pfnProgress Progress callback. Optional.
1902 * @param pvUser User argument for the progress callback.
1903 *
1904 * @thread Any thread.
1905 * @vmstate Created, Suspended
1906 * @vmstateto Loading+Suspended
1907 */
1908VMMR3DECL(int) VMR3LoadFromFile(PVM pVM, const char *pszFilename, PFNVMPROGRESS pfnProgress, void *pvUser)
1909{
1910 LogFlow(("VMR3LoadFromFile: pVM=%p pszFilename=%p:{%s} pfnProgress=%p pvUser=%p\n",
1911 pVM, pszFilename, pszFilename, pfnProgress, pvUser));
1912
1913 /*
1914 * Validate input.
1915 */
1916 VM_ASSERT_VALID_EXT_RETURN(pVM, VERR_INVALID_VM_HANDLE);
1917 AssertPtrReturn(pszFilename, VERR_INVALID_POINTER);
1918
1919 /*
1920 * Forward the request to EMT(0). No need to setup a rendezvous here
1921 * since there is no execution taking place when this call is allowed.
1922 */
1923 int rc = VMR3ReqCallWaitU(pVM->pUVM, 0 /*idDstCpu*/, (PFNRT)vmR3Load, 7,
1924 pVM, pszFilename, (uintptr_t)NULL /*pStreamOps*/, (uintptr_t)NULL /*pvStreamOpsUser*/, pfnProgress, pvUser,
1925 false /*fTeleporting*/);
1926 LogFlow(("VMR3LoadFromFile: returns %Rrc\n", rc));
1927 return rc;
1928}
1929
1930
1931/**
1932 * VMR3LoadFromFile for arbritrary file streams.
1933 *
1934 * @returns VBox status code.
1935 *
1936 * @param pVM The VM handle.
1937 * @param pStreamOps The stream methods.
1938 * @param pvStreamOpsUser The user argument to the stream methods.
1939 * @param pfnProgress Progress callback. Optional.
1940 * @param pvProgressUser User argument for the progress callback.
1941 *
1942 * @thread Any thread.
1943 * @vmstate Created, Suspended
1944 * @vmstateto Loading+Suspended
1945 */
1946VMMR3DECL(int) VMR3LoadFromStream(PVM pVM, PCSSMSTRMOPS pStreamOps, void *pvStreamOpsUser,
1947 PFNVMPROGRESS pfnProgress, void *pvProgressUser)
1948{
1949 LogFlow(("VMR3LoadFromStream: pVM=%p pStreamOps=%p pvStreamOpsUser=%p pfnProgress=%p pvProgressUser=%p\n",
1950 pVM, pStreamOps, pvStreamOpsUser, pfnProgress, pvProgressUser));
1951
1952 /*
1953 * Validate input.
1954 */
1955 VM_ASSERT_VALID_EXT_RETURN(pVM, VERR_INVALID_VM_HANDLE);
1956 AssertPtrReturn(pStreamOps, VERR_INVALID_POINTER);
1957
1958 /*
1959 * Forward the request to EMT(0). No need to setup a rendezvous here
1960 * since there is no execution taking place when this call is allowed.
1961 */
1962 int rc = VMR3ReqCallWaitU(pVM->pUVM, 0 /*idDstCpu*/, (PFNRT)vmR3Load, 7,
1963 pVM, (uintptr_t)NULL /*pszFilename*/, pStreamOps, pvStreamOpsUser, pfnProgress, pvProgressUser,
1964 true /*fTeleporting*/);
1965 LogFlow(("VMR3LoadFromStream: returns %Rrc\n", rc));
1966 return rc;
1967}
1968
1969
1970/**
1971 * EMT rendezvous worker for VMR3PowerOff.
1972 *
1973 * @returns VERR_VM_INVALID_VM_STATE or VINF_EM_OFF. (This is a strict
1974 * return code, see FNVMMEMTRENDEZVOUS.)
1975 *
1976 * @param pVM The VM handle.
1977 * @param pVCpu The VMCPU handle of the EMT.
1978 * @param pvUser Ignored.
1979 */
1980static DECLCALLBACK(VBOXSTRICTRC) vmR3PowerOff(PVM pVM, PVMCPU pVCpu, void *pvUser)
1981{
1982 LogFlow(("vmR3PowerOff: pVM=%p pVCpu=%p/#%u\n", pVM, pVCpu, pVCpu->idCpu));
1983 Assert(!pvUser); NOREF(pvUser);
1984
1985 /*
1986 * The first EMT thru here will change the state to PoweringOff.
1987 */
1988 if (pVCpu->idCpu == pVM->cCpus - 1)
1989 {
1990 int rc = vmR3TrySetState(pVM, "VMR3PowerOff", 11,
1991 VMSTATE_POWERING_OFF, VMSTATE_RUNNING, /* 1 */
1992 VMSTATE_POWERING_OFF, VMSTATE_SUSPENDED, /* 2 */
1993 VMSTATE_POWERING_OFF, VMSTATE_DEBUGGING, /* 3 */
1994 VMSTATE_POWERING_OFF, VMSTATE_LOAD_FAILURE, /* 4 */
1995 VMSTATE_POWERING_OFF, VMSTATE_GURU_MEDITATION, /* 5 */
1996 VMSTATE_POWERING_OFF, VMSTATE_FATAL_ERROR, /* 6 */
1997 VMSTATE_POWERING_OFF, VMSTATE_CREATED, /* 7 */ /** @todo update the diagram! */
1998 VMSTATE_POWERING_OFF_LS, VMSTATE_RUNNING_LS, /* 8 */
1999 VMSTATE_POWERING_OFF_LS, VMSTATE_DEBUGGING_LS, /* 9 */
2000 VMSTATE_POWERING_OFF_LS, VMSTATE_GURU_MEDITATION_LS,/* 10 */
2001 VMSTATE_POWERING_OFF_LS, VMSTATE_FATAL_ERROR_LS); /* 11 */
2002 if (RT_FAILURE(rc))
2003 return rc;
2004 if (rc >= 7)
2005 SSMR3Cancel(pVM);
2006 }
2007
2008 /*
2009 * Check the state.
2010 */
2011 VMSTATE enmVMState = VMR3GetState(pVM);
2012 AssertMsgReturn( enmVMState == VMSTATE_POWERING_OFF
2013 || enmVMState == VMSTATE_POWERING_OFF_LS,
2014 ("%s\n", VMR3GetStateName(enmVMState)),
2015 VERR_VM_INVALID_VM_STATE);
2016
2017 /*
2018 * EMT(0) does the actual power off work here *after* all the other EMTs
2019 * have been thru and entered the STOPPED state.
2020 */
2021 VMCPU_SET_STATE(pVCpu, VMCPUSTATE_STOPPED);
2022 if (pVCpu->idCpu == 0)
2023 {
2024 /*
2025 * For debugging purposes, we will log a summary of the guest state at this point.
2026 */
2027 if (enmVMState != VMSTATE_GURU_MEDITATION)
2028 {
2029 /** @todo SMP support? */
2030 /** @todo make the state dumping at VMR3PowerOff optional. */
2031 RTLogRelPrintf("****************** Guest state at power off ******************\n");
2032 DBGFR3Info(pVM, "cpumguest", "verbose", DBGFR3InfoLogRelHlp());
2033 RTLogRelPrintf("***\n");
2034 DBGFR3Info(pVM, "mode", NULL, DBGFR3InfoLogRelHlp());
2035 RTLogRelPrintf("***\n");
2036 DBGFR3Info(pVM, "activetimers", NULL, DBGFR3InfoLogRelHlp());
2037 RTLogRelPrintf("***\n");
2038 DBGFR3Info(pVM, "gdt", NULL, DBGFR3InfoLogRelHlp());
2039 /** @todo dump guest call stack. */
2040#if 1 // "temporary" while debugging #1589
2041 RTLogRelPrintf("***\n");
2042 uint32_t esp = CPUMGetGuestESP(pVCpu);
2043 if ( CPUMGetGuestSS(pVCpu) == 0
2044 && esp < _64K)
2045 {
2046 uint8_t abBuf[PAGE_SIZE];
2047 RTLogRelPrintf("***\n"
2048 "ss:sp=0000:%04x ", esp);
2049 uint32_t Start = esp & ~(uint32_t)63;
2050 int rc = PGMPhysSimpleReadGCPhys(pVM, abBuf, Start, 0x100);
2051 if (RT_SUCCESS(rc))
2052 RTLogRelPrintf("0000:%04x TO 0000:%04x:\n"
2053 "%.*Rhxd\n",
2054 Start, Start + 0x100 - 1,
2055 0x100, abBuf);
2056 else
2057 RTLogRelPrintf("rc=%Rrc\n", rc);
2058
2059 /* grub ... */
2060 if (esp < 0x2000 && esp > 0x1fc0)
2061 {
2062 rc = PGMPhysSimpleReadGCPhys(pVM, abBuf, 0x8000, 0x800);
2063 if (RT_SUCCESS(rc))
2064 RTLogRelPrintf("0000:8000 TO 0000:87ff:\n"
2065 "%.*Rhxd\n",
2066 0x800, abBuf);
2067 }
2068 /* microsoft cdrom hang ... */
2069 if (true)
2070 {
2071 rc = PGMPhysSimpleReadGCPhys(pVM, abBuf, 0x8000, 0x200);
2072 if (RT_SUCCESS(rc))
2073 RTLogRelPrintf("2000:0000 TO 2000:01ff:\n"
2074 "%.*Rhxd\n",
2075 0x200, abBuf);
2076 }
2077 }
2078#endif
2079 RTLogRelPrintf("************** End of Guest state at power off ***************\n");
2080 }
2081
2082 /*
2083 * Perform the power off notifications and advance the state to
2084 * Off or OffLS.
2085 */
2086 PDMR3PowerOff(pVM);
2087
2088 PUVM pUVM = pVM->pUVM;
2089 RTCritSectEnter(&pUVM->vm.s.AtStateCritSect);
2090 enmVMState = pVM->enmVMState;
2091 if (enmVMState == VMSTATE_POWERING_OFF_LS)
2092 vmR3SetStateLocked(pVM, pUVM, VMSTATE_OFF_LS, VMSTATE_POWERING_OFF_LS);
2093 else
2094 vmR3SetStateLocked(pVM, pUVM, VMSTATE_OFF, VMSTATE_POWERING_OFF);
2095 RTCritSectLeave(&pUVM->vm.s.AtStateCritSect);
2096 }
2097 return VINF_EM_OFF;
2098}
2099
2100
2101/**
2102 * Power off the VM.
2103 *
2104 * @returns VBox status code. When called on EMT, this will be a strict status
2105 * code that has to be propagated up the call stack.
2106 *
2107 * @param pVM The handle of the VM to be powered off.
2108 *
2109 * @thread Any thread.
2110 * @vmstate Suspended, Running, Guru Meditation, Load Failure
2111 * @vmstateto Off or OffLS
2112 */
2113VMMR3DECL(int) VMR3PowerOff(PVM pVM)
2114{
2115 LogFlow(("VMR3PowerOff: pVM=%p\n", pVM));
2116 VM_ASSERT_VALID_EXT_RETURN(pVM, VERR_INVALID_VM_HANDLE);
2117
2118 /*
2119 * Gather all the EMTs to make sure there are no races before
2120 * changing the VM state.
2121 */
2122 int rc = VMMR3EmtRendezvous(pVM, VMMEMTRENDEZVOUS_FLAGS_TYPE_DESCENDING | VMMEMTRENDEZVOUS_FLAGS_STOP_ON_ERROR,
2123 vmR3PowerOff, NULL);
2124 LogFlow(("VMR3PowerOff: returns %Rrc\n", rc));
2125 return rc;
2126}
2127
2128
2129/**
2130 * Destroys the VM.
2131 *
2132 * The VM must be powered off (or never really powered on) to call this
2133 * function. The VM handle is destroyed and can no longer be used up successful
2134 * return.
2135 *
2136 * @returns VBox status code.
2137 *
2138 * @param pVM The handle of the VM which should be destroyed.
2139 *
2140 * @thread Any none emulation thread.
2141 * @vmstate Off, Created
2142 * @vmstateto N/A
2143 */
2144VMMR3DECL(int) VMR3Destroy(PVM pVM)
2145{
2146 LogFlow(("VMR3Destroy: pVM=%p\n", pVM));
2147
2148 /*
2149 * Validate input.
2150 */
2151 if (!pVM)
2152 return VERR_INVALID_PARAMETER;
2153 VM_ASSERT_VALID_EXT_RETURN(pVM, VERR_INVALID_VM_HANDLE);
2154 AssertLogRelReturn(!VM_IS_EMT(pVM), VERR_VM_THREAD_IS_EMT);
2155
2156 /*
2157 * Change VM state to destroying and unlink the VM.
2158 */
2159 int rc = vmR3TrySetState(pVM, "VMR3Destroy", 1, VMSTATE_DESTROYING, VMSTATE_OFF);
2160 if (RT_FAILURE(rc))
2161 return rc;
2162
2163 /** @todo lock this when we start having multiple machines in a process... */
2164 PUVM pUVM = pVM->pUVM; AssertPtr(pUVM);
2165 if (g_pUVMsHead == pUVM)
2166 g_pUVMsHead = pUVM->pNext;
2167 else
2168 {
2169 PUVM pPrev = g_pUVMsHead;
2170 while (pPrev && pPrev->pNext != pUVM)
2171 pPrev = pPrev->pNext;
2172 AssertMsgReturn(pPrev, ("pUVM=%p / pVM=%p is INVALID!\n", pUVM, pVM), VERR_INVALID_PARAMETER);
2173
2174 pPrev->pNext = pUVM->pNext;
2175 }
2176 pUVM->pNext = NULL;
2177
2178 /*
2179 * Notify registered at destruction listeners.
2180 */
2181 vmR3AtDtor(pVM);
2182
2183 /*
2184 * Call vmR3Destroy on each of the EMTs ending with EMT(0) doing the bulk
2185 * of the cleanup.
2186 */
2187 /* vmR3Destroy on all EMTs, ending with EMT(0). */
2188 rc = VMR3ReqCallWaitU(pUVM, VMCPUID_ALL_REVERSE, (PFNRT)vmR3Destroy, 1, pVM);
2189 AssertLogRelRC(rc);
2190
2191 /* Wait for EMTs and destroy the UVM. */
2192 vmR3DestroyUVM(pUVM, 30000);
2193
2194 LogFlow(("VMR3Destroy: returns VINF_SUCCESS\n"));
2195 return VINF_SUCCESS;
2196}
2197
2198
2199/**
2200 * Internal destruction worker.
2201 *
2202 * This is either called from VMR3Destroy via VMR3ReqCallU or from
2203 * vmR3EmulationThreadWithId when EMT(0) terminates after having called
2204 * VMR3Destroy().
2205 *
2206 * When called on EMT(0), it will performed the great bulk of the destruction.
2207 * When called on the other EMTs, they will do nothing and the whole purpose is
2208 * to return VINF_EM_TERMINATE so they break out of their run loops.
2209 *
2210 * @returns VINF_EM_TERMINATE.
2211 * @param pVM The VM handle.
2212 */
2213DECLCALLBACK(int) vmR3Destroy(PVM pVM)
2214{
2215 PUVM pUVM = pVM->pUVM;
2216 PVMCPU pVCpu = VMMGetCpu(pVM);
2217 Assert(pVCpu);
2218 LogFlow(("vmR3Destroy: pVM=%p pUVM=%p pVCpu=%p idCpu=%u\n", pVM, pUVM, pVCpu, pVCpu->idCpu));
2219
2220 /*
2221 * Only VCPU 0 does the full cleanup (last).
2222 */
2223 if (pVCpu->idCpu == 0)
2224 {
2225 /*
2226 * Dump statistics to the log.
2227 */
2228#if defined(VBOX_WITH_STATISTICS) || defined(LOG_ENABLED)
2229 RTLogFlags(NULL, "nodisabled nobuffered");
2230#endif
2231#ifdef VBOX_WITH_STATISTICS
2232 STAMR3Dump(pVM, "*");
2233#else
2234 LogRel(("************************* Statistics *************************\n"));
2235 STAMR3DumpToReleaseLog(pVM, "*");
2236 LogRel(("********************* End of statistics **********************\n"));
2237#endif
2238
2239 /*
2240 * Destroy the VM components.
2241 */
2242 int rc = TMR3Term(pVM);
2243 AssertRC(rc);
2244#ifdef VBOX_WITH_DEBUGGER
2245 rc = DBGCTcpTerminate(pVM, pUVM->vm.s.pvDBGC);
2246 pUVM->vm.s.pvDBGC = NULL;
2247#endif
2248 AssertRC(rc);
2249 rc = DBGFR3Term(pVM);
2250 AssertRC(rc);
2251 rc = PDMR3Term(pVM);
2252 AssertRC(rc);
2253 rc = EMR3Term(pVM);
2254 AssertRC(rc);
2255 rc = IOMR3Term(pVM);
2256 AssertRC(rc);
2257 rc = CSAMR3Term(pVM);
2258 AssertRC(rc);
2259 rc = PATMR3Term(pVM);
2260 AssertRC(rc);
2261 rc = TRPMR3Term(pVM);
2262 AssertRC(rc);
2263 rc = SELMR3Term(pVM);
2264 AssertRC(rc);
2265 rc = REMR3Term(pVM);
2266 AssertRC(rc);
2267 rc = HWACCMR3Term(pVM);
2268 AssertRC(rc);
2269 rc = PGMR3Term(pVM);
2270 AssertRC(rc);
2271 rc = VMMR3Term(pVM); /* Terminates the ring-0 code! */
2272 AssertRC(rc);
2273 rc = CPUMR3Term(pVM);
2274 AssertRC(rc);
2275 SSMR3Term(pVM);
2276 rc = PDMR3CritSectTerm(pVM);
2277 AssertRC(rc);
2278 rc = MMR3Term(pVM);
2279 AssertRC(rc);
2280
2281 /*
2282 * We're done, tell the other EMTs to quit.
2283 */
2284 ASMAtomicUoWriteBool(&pUVM->vm.s.fTerminateEMT, true);
2285 ASMAtomicWriteU32(&pVM->fGlobalForcedActions, VM_FF_CHECK_VM_STATE); /* Can't hurt... */
2286 LogFlow(("vmR3Destroy: returning %Rrc\n", VINF_EM_TERMINATE));
2287 }
2288 return VINF_EM_TERMINATE;
2289}
2290
2291
2292/**
2293 * Destroys the UVM portion.
2294 *
2295 * This is called as the final step in the VM destruction or as the cleanup
2296 * in case of a creation failure.
2297 *
2298 * @param pVM VM Handle.
2299 * @param cMilliesEMTWait The number of milliseconds to wait for the emulation
2300 * threads.
2301 */
2302static void vmR3DestroyUVM(PUVM pUVM, uint32_t cMilliesEMTWait)
2303{
2304 /*
2305 * Signal termination of each the emulation threads and
2306 * wait for them to complete.
2307 */
2308 /* Signal them. */
2309 ASMAtomicUoWriteBool(&pUVM->vm.s.fTerminateEMT, true);
2310 if (pUVM->pVM)
2311 VM_FF_SET(pUVM->pVM, VM_FF_CHECK_VM_STATE); /* Can't hurt... */
2312 for (VMCPUID i = 0; i < pUVM->cCpus; i++)
2313 {
2314 VMR3NotifyGlobalFFU(pUVM, VMNOTIFYFF_FLAGS_DONE_REM);
2315 RTSemEventSignal(pUVM->aCpus[i].vm.s.EventSemWait);
2316 }
2317
2318 /* Wait for them. */
2319 uint64_t NanoTS = RTTimeNanoTS();
2320 RTTHREAD hSelf = RTThreadSelf();
2321 ASMAtomicUoWriteBool(&pUVM->vm.s.fTerminateEMT, true);
2322 for (VMCPUID i = 0; i < pUVM->cCpus; i++)
2323 {
2324 RTTHREAD hThread = pUVM->aCpus[i].vm.s.ThreadEMT;
2325 if ( hThread != NIL_RTTHREAD
2326 && hThread != hSelf)
2327 {
2328 uint64_t cMilliesElapsed = (RTTimeNanoTS() - NanoTS) / 1000000;
2329 int rc2 = RTThreadWait(hThread,
2330 cMilliesElapsed < cMilliesEMTWait
2331 ? RT_MAX(cMilliesEMTWait - cMilliesElapsed, 2000)
2332 : 2000,
2333 NULL);
2334 if (rc2 == VERR_TIMEOUT) /* avoid the assertion when debugging. */
2335 rc2 = RTThreadWait(hThread, 1000, NULL);
2336 AssertLogRelMsgRC(rc2, ("i=%u rc=%Rrc\n", i, rc2));
2337 if (RT_SUCCESS(rc2))
2338 pUVM->aCpus[0].vm.s.ThreadEMT = NIL_RTTHREAD;
2339 }
2340 }
2341
2342 /* Cleanup the semaphores. */
2343 for (VMCPUID i = 0; i < pUVM->cCpus; i++)
2344 {
2345 RTSemEventDestroy(pUVM->aCpus[i].vm.s.EventSemWait);
2346 pUVM->aCpus[i].vm.s.EventSemWait = NIL_RTSEMEVENT;
2347 }
2348
2349 /*
2350 * Free the event semaphores associated with the request packets.
2351 */
2352 unsigned cReqs = 0;
2353 for (unsigned i = 0; i < RT_ELEMENTS(pUVM->vm.s.apReqFree); i++)
2354 {
2355 PVMREQ pReq = pUVM->vm.s.apReqFree[i];
2356 pUVM->vm.s.apReqFree[i] = NULL;
2357 for (; pReq; pReq = pReq->pNext, cReqs++)
2358 {
2359 pReq->enmState = VMREQSTATE_INVALID;
2360 RTSemEventDestroy(pReq->EventSem);
2361 }
2362 }
2363 Assert(cReqs == pUVM->vm.s.cReqFree); NOREF(cReqs);
2364
2365 /*
2366 * Kill all queued requests. (There really shouldn't be any!)
2367 */
2368 for (unsigned i = 0; i < 10; i++)
2369 {
2370 PVMREQ pReqHead = ASMAtomicXchgPtrT(&pUVM->vm.s.pReqs, NULL, PVMREQ);
2371 AssertMsg(!pReqHead, ("This isn't supposed to happen! VMR3Destroy caller has to serialize this.\n"));
2372 if (!pReqHead)
2373 break;
2374 for (PVMREQ pReq = pReqHead; pReq; pReq = pReq->pNext)
2375 {
2376 ASMAtomicUoWriteSize(&pReq->iStatus, VERR_INTERNAL_ERROR);
2377 ASMAtomicWriteSize(&pReq->enmState, VMREQSTATE_INVALID);
2378 RTSemEventSignal(pReq->EventSem);
2379 RTThreadSleep(2);
2380 RTSemEventDestroy(pReq->EventSem);
2381 }
2382 /* give them a chance to respond before we free the request memory. */
2383 RTThreadSleep(32);
2384 }
2385
2386 /*
2387 * Now all queued VCPU requests (again, there shouldn't be any).
2388 */
2389 for (VMCPUID idCpu = 0; idCpu < pUVM->cCpus; idCpu++)
2390 {
2391 PUVMCPU pUVCpu = &pUVM->aCpus[idCpu];
2392
2393 for (unsigned i = 0; i < 10; i++)
2394 {
2395 PVMREQ pReqHead = ASMAtomicXchgPtrT(&pUVCpu->vm.s.pReqs, NULL, PVMREQ);
2396 AssertMsg(!pReqHead, ("This isn't supposed to happen! VMR3Destroy caller has to serialize this.\n"));
2397 if (!pReqHead)
2398 break;
2399 for (PVMREQ pReq = pReqHead; pReq; pReq = pReq->pNext)
2400 {
2401 ASMAtomicUoWriteSize(&pReq->iStatus, VERR_INTERNAL_ERROR);
2402 ASMAtomicWriteSize(&pReq->enmState, VMREQSTATE_INVALID);
2403 RTSemEventSignal(pReq->EventSem);
2404 RTThreadSleep(2);
2405 RTSemEventDestroy(pReq->EventSem);
2406 }
2407 /* give them a chance to respond before we free the request memory. */
2408 RTThreadSleep(32);
2409 }
2410 }
2411
2412 /*
2413 * Make sure the VMMR0.r0 module and whatever else is unloaded.
2414 */
2415 PDMR3TermUVM(pUVM);
2416
2417 /*
2418 * Terminate the support library if initialized.
2419 */
2420 if (pUVM->vm.s.pSession)
2421 {
2422 int rc = SUPR3Term(false /*fForced*/);
2423 AssertRC(rc);
2424 pUVM->vm.s.pSession = NIL_RTR0PTR;
2425 }
2426
2427 /*
2428 * Destroy the MM heap and free the UVM structure.
2429 */
2430 MMR3TermUVM(pUVM);
2431 STAMR3TermUVM(pUVM);
2432
2433#ifdef LOG_ENABLED
2434 RTLogSetCustomPrefixCallback(NULL, NULL, NULL);
2435#endif
2436 RTTlsFree(pUVM->vm.s.idxTLS);
2437
2438 ASMAtomicUoWriteU32(&pUVM->u32Magic, UINT32_MAX);
2439 RTMemPageFree(pUVM, sizeof(*pUVM));
2440
2441 RTLogFlush(NULL);
2442}
2443
2444
2445/**
2446 * Enumerates the VMs in this process.
2447 *
2448 * @returns Pointer to the next VM.
2449 * @returns NULL when no more VMs.
2450 * @param pVMPrev The previous VM
2451 * Use NULL to start the enumeration.
2452 */
2453VMMR3DECL(PVM) VMR3EnumVMs(PVM pVMPrev)
2454{
2455 /*
2456 * This is quick and dirty. It has issues with VM being
2457 * destroyed during the enumeration.
2458 */
2459 PUVM pNext;
2460 if (pVMPrev)
2461 pNext = pVMPrev->pUVM->pNext;
2462 else
2463 pNext = g_pUVMsHead;
2464 return pNext ? pNext->pVM : NULL;
2465}
2466
2467
2468/**
2469 * Registers an at VM destruction callback.
2470 *
2471 * @returns VBox status code.
2472 * @param pfnAtDtor Pointer to callback.
2473 * @param pvUser User argument.
2474 */
2475VMMR3DECL(int) VMR3AtDtorRegister(PFNVMATDTOR pfnAtDtor, void *pvUser)
2476{
2477 /*
2478 * Check if already registered.
2479 */
2480 VM_ATDTOR_LOCK();
2481 PVMATDTOR pCur = g_pVMAtDtorHead;
2482 while (pCur)
2483 {
2484 if (pfnAtDtor == pCur->pfnAtDtor)
2485 {
2486 VM_ATDTOR_UNLOCK();
2487 AssertMsgFailed(("Already registered at destruction callback %p!\n", pfnAtDtor));
2488 return VERR_INVALID_PARAMETER;
2489 }
2490
2491 /* next */
2492 pCur = pCur->pNext;
2493 }
2494 VM_ATDTOR_UNLOCK();
2495
2496 /*
2497 * Allocate new entry.
2498 */
2499 PVMATDTOR pVMAtDtor = (PVMATDTOR)RTMemAlloc(sizeof(*pVMAtDtor));
2500 if (!pVMAtDtor)
2501 return VERR_NO_MEMORY;
2502
2503 VM_ATDTOR_LOCK();
2504 pVMAtDtor->pfnAtDtor = pfnAtDtor;
2505 pVMAtDtor->pvUser = pvUser;
2506 pVMAtDtor->pNext = g_pVMAtDtorHead;
2507 g_pVMAtDtorHead = pVMAtDtor;
2508 VM_ATDTOR_UNLOCK();
2509
2510 return VINF_SUCCESS;
2511}
2512
2513
2514/**
2515 * Deregisters an at VM destruction callback.
2516 *
2517 * @returns VBox status code.
2518 * @param pfnAtDtor Pointer to callback.
2519 */
2520VMMR3DECL(int) VMR3AtDtorDeregister(PFNVMATDTOR pfnAtDtor)
2521{
2522 /*
2523 * Find it, unlink it and free it.
2524 */
2525 VM_ATDTOR_LOCK();
2526 PVMATDTOR pPrev = NULL;
2527 PVMATDTOR pCur = g_pVMAtDtorHead;
2528 while (pCur)
2529 {
2530 if (pfnAtDtor == pCur->pfnAtDtor)
2531 {
2532 if (pPrev)
2533 pPrev->pNext = pCur->pNext;
2534 else
2535 g_pVMAtDtorHead = pCur->pNext;
2536 pCur->pNext = NULL;
2537 VM_ATDTOR_UNLOCK();
2538
2539 RTMemFree(pCur);
2540 return VINF_SUCCESS;
2541 }
2542
2543 /* next */
2544 pPrev = pCur;
2545 pCur = pCur->pNext;
2546 }
2547 VM_ATDTOR_UNLOCK();
2548
2549 return VERR_INVALID_PARAMETER;
2550}
2551
2552
2553/**
2554 * Walks the list of at VM destructor callbacks.
2555 * @param pVM The VM which is about to be destroyed.
2556 */
2557static void vmR3AtDtor(PVM pVM)
2558{
2559 /*
2560 * Find it, unlink it and free it.
2561 */
2562 VM_ATDTOR_LOCK();
2563 for (PVMATDTOR pCur = g_pVMAtDtorHead; pCur; pCur = pCur->pNext)
2564 pCur->pfnAtDtor(pVM, pCur->pvUser);
2565 VM_ATDTOR_UNLOCK();
2566}
2567
2568
2569/**
2570 * Worker which checks integrity of some internal structures.
2571 * This is yet another attempt to track down that AVL tree crash.
2572 */
2573static void vmR3CheckIntegrity(PVM pVM)
2574{
2575#ifdef VBOX_STRICT
2576 int rc = PGMR3CheckIntegrity(pVM);
2577 AssertReleaseRC(rc);
2578#endif
2579}
2580
2581
2582/**
2583 * EMT rendezvous worker for VMR3Reset.
2584 *
2585 * This is called by the emulation threads as a response to the reset request
2586 * issued by VMR3Reset().
2587 *
2588 * @returns VERR_VM_INVALID_VM_STATE, VINF_EM_RESET or VINF_EM_SUSPEND. (This
2589 * is a strict return code, see FNVMMEMTRENDEZVOUS.)
2590 *
2591 * @param pVM The VM handle.
2592 * @param pVCpu The VMCPU handle of the EMT.
2593 * @param pvUser Ignored.
2594 */
2595static DECLCALLBACK(VBOXSTRICTRC) vmR3Reset(PVM pVM, PVMCPU pVCpu, void *pvUser)
2596{
2597 Assert(!pvUser); NOREF(pvUser);
2598
2599 /*
2600 * The first EMT will try change the state to resetting. If this fails,
2601 * we won't get called for the other EMTs.
2602 */
2603 if (pVCpu->idCpu == pVM->cCpus - 1)
2604 {
2605 int rc = vmR3TrySetState(pVM, "VMR3Reset", 3,
2606 VMSTATE_RESETTING, VMSTATE_RUNNING,
2607 VMSTATE_RESETTING, VMSTATE_SUSPENDED,
2608 VMSTATE_RESETTING_LS, VMSTATE_RUNNING_LS);
2609 if (RT_FAILURE(rc))
2610 return rc;
2611 }
2612
2613 /*
2614 * Check the state.
2615 */
2616 VMSTATE enmVMState = VMR3GetState(pVM);
2617 AssertLogRelMsgReturn( enmVMState == VMSTATE_RESETTING
2618 || enmVMState == VMSTATE_RESETTING_LS,
2619 ("%s\n", VMR3GetStateName(enmVMState)),
2620 VERR_INTERNAL_ERROR_4);
2621
2622 /*
2623 * EMT(0) does the full cleanup *after* all the other EMTs has been
2624 * thru here and been told to enter the EMSTATE_WAIT_SIPI state.
2625 *
2626 * Because there are per-cpu reset routines and order may/is important,
2627 * the following sequence looks a bit ugly...
2628 */
2629 if (pVCpu->idCpu == 0)
2630 vmR3CheckIntegrity(pVM);
2631
2632 /* Reset the VCpu state. */
2633 VMCPU_ASSERT_STATE(pVCpu, VMCPUSTATE_STARTED);
2634
2635 /* Clear all pending forced actions. */
2636 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_ALL_MASK & ~VMCPU_FF_REQUEST);
2637
2638 /*
2639 * Reset the VM components.
2640 */
2641 if (pVCpu->idCpu == 0)
2642 {
2643 PATMR3Reset(pVM);
2644 CSAMR3Reset(pVM);
2645 PGMR3Reset(pVM); /* We clear VM RAM in PGMR3Reset. It's vital PDMR3Reset is executed
2646 * _afterwards_. E.g. ACPI sets up RAM tables during init/reset. */
2647/** @todo PGMR3Reset should be called after PDMR3Reset really, because we'll trash OS <-> hardware
2648 * communication structures residing in RAM when done in the other order. I.e. the device must be
2649 * quiesced first, then we clear the memory and plan tables. Probably have to make these things
2650 * explicit in some way, some memory setup pass or something.
2651 * (Example: DevAHCI may assert if memory is zeroed before it've read the FIS.)
2652 *
2653 * @bugref{4467}
2654 */
2655 MMR3Reset(pVM);
2656 PDMR3Reset(pVM);
2657 SELMR3Reset(pVM);
2658 TRPMR3Reset(pVM);
2659 REMR3Reset(pVM);
2660 IOMR3Reset(pVM);
2661 CPUMR3Reset(pVM);
2662 }
2663 CPUMR3ResetCpu(pVCpu);
2664 if (pVCpu->idCpu == 0)
2665 {
2666 TMR3Reset(pVM);
2667 EMR3Reset(pVM);
2668 HWACCMR3Reset(pVM); /* This must come *after* PATM, CSAM, CPUM, SELM and TRPM. */
2669
2670#ifdef LOG_ENABLED
2671 /*
2672 * Debug logging.
2673 */
2674 RTLogPrintf("\n\nThe VM was reset:\n");
2675 DBGFR3Info(pVM, "cpum", "verbose", NULL);
2676#endif
2677
2678 /*
2679 * Since EMT(0) is the last to go thru here, it will advance the state.
2680 * When a live save is active, we will move on to SuspendingLS but
2681 * leave it for VMR3Reset to do the actual suspending due to deadlock risks.
2682 */
2683 PUVM pUVM = pVM->pUVM;
2684 RTCritSectEnter(&pUVM->vm.s.AtStateCritSect);
2685 enmVMState = pVM->enmVMState;
2686 if (enmVMState == VMSTATE_RESETTING)
2687 {
2688 if (pUVM->vm.s.enmPrevVMState == VMSTATE_SUSPENDED)
2689 vmR3SetStateLocked(pVM, pUVM, VMSTATE_SUSPENDED, VMSTATE_RESETTING);
2690 else
2691 vmR3SetStateLocked(pVM, pUVM, VMSTATE_RUNNING, VMSTATE_RESETTING);
2692 }
2693 else
2694 vmR3SetStateLocked(pVM, pUVM, VMSTATE_SUSPENDING_LS, VMSTATE_RESETTING_LS);
2695 RTCritSectLeave(&pUVM->vm.s.AtStateCritSect);
2696
2697 vmR3CheckIntegrity(pVM);
2698
2699 /*
2700 * Do the suspend bit as well.
2701 * It only requires some EMT(0) work at present.
2702 */
2703 if (enmVMState != VMSTATE_RESETTING)
2704 {
2705 vmR3SuspendDoWork(pVM);
2706 vmR3SetState(pVM, VMSTATE_SUSPENDED_LS, VMSTATE_SUSPENDING_LS);
2707 }
2708 }
2709
2710 return enmVMState == VMSTATE_RESETTING
2711 ? VINF_EM_RESET
2712 : VINF_EM_SUSPEND; /** @todo VINF_EM_SUSPEND has lower priority than VINF_EM_RESET, so fix races. Perhaps add a new code for this combined case. */
2713}
2714
2715
2716/**
2717 * Reset the current VM.
2718 *
2719 * @returns VBox status code.
2720 * @param pVM VM to reset.
2721 */
2722VMMR3DECL(int) VMR3Reset(PVM pVM)
2723{
2724 LogFlow(("VMR3Reset:\n"));
2725 VM_ASSERT_VALID_EXT_RETURN(pVM, VERR_INVALID_VM_HANDLE);
2726
2727 /*
2728 * Gather all the EMTs to make sure there are no races before
2729 * changing the VM state.
2730 */
2731 int rc = VMMR3EmtRendezvous(pVM, VMMEMTRENDEZVOUS_FLAGS_TYPE_DESCENDING | VMMEMTRENDEZVOUS_FLAGS_STOP_ON_ERROR,
2732 vmR3Reset, NULL);
2733 LogFlow(("VMR3Reset: returns %Rrc\n", rc));
2734 return rc;
2735}
2736
2737
2738/**
2739 * Gets the current VM state.
2740 *
2741 * @returns The current VM state.
2742 * @param pVM VM handle.
2743 * @thread Any
2744 */
2745VMMR3DECL(VMSTATE) VMR3GetState(PVM pVM)
2746{
2747 return pVM->enmVMState;
2748}
2749
2750
2751/**
2752 * Gets the state name string for a VM state.
2753 *
2754 * @returns Pointer to the state name. (readonly)
2755 * @param enmState The state.
2756 */
2757VMMR3DECL(const char *) VMR3GetStateName(VMSTATE enmState)
2758{
2759 switch (enmState)
2760 {
2761 case VMSTATE_CREATING: return "CREATING";
2762 case VMSTATE_CREATED: return "CREATED";
2763 case VMSTATE_LOADING: return "LOADING";
2764 case VMSTATE_POWERING_ON: return "POWERING_ON";
2765 case VMSTATE_RESUMING: return "RESUMING";
2766 case VMSTATE_RUNNING: return "RUNNING";
2767 case VMSTATE_RUNNING_LS: return "RUNNING_LS";
2768 case VMSTATE_RESETTING: return "RESETTING";
2769 case VMSTATE_RESETTING_LS: return "RESETTING_LS";
2770 case VMSTATE_SUSPENDED: return "SUSPENDED";
2771 case VMSTATE_SUSPENDED_LS: return "SUSPENDED_LS";
2772 case VMSTATE_SUSPENDED_EXT_LS: return "SUSPENDED_EXT_LS";
2773 case VMSTATE_SUSPENDING: return "SUSPENDING";
2774 case VMSTATE_SUSPENDING_LS: return "SUSPENDING_LS";
2775 case VMSTATE_SUSPENDING_EXT_LS: return "SUSPENDING_EXT_LS";
2776 case VMSTATE_SAVING: return "SAVING";
2777 case VMSTATE_DEBUGGING: return "DEBUGGING";
2778 case VMSTATE_DEBUGGING_LS: return "DEBUGGING_LS";
2779 case VMSTATE_POWERING_OFF: return "POWERING_OFF";
2780 case VMSTATE_POWERING_OFF_LS: return "POWERING_OFF_LS";
2781 case VMSTATE_FATAL_ERROR: return "FATAL_ERROR";
2782 case VMSTATE_FATAL_ERROR_LS: return "FATAL_ERROR_LS";
2783 case VMSTATE_GURU_MEDITATION: return "GURU_MEDITATION";
2784 case VMSTATE_GURU_MEDITATION_LS:return "GURU_MEDITATION_LS";
2785 case VMSTATE_LOAD_FAILURE: return "LOAD_FAILURE";
2786 case VMSTATE_OFF: return "OFF";
2787 case VMSTATE_OFF_LS: return "OFF_LS";
2788 case VMSTATE_DESTROYING: return "DESTROYING";
2789 case VMSTATE_TERMINATED: return "TERMINATED";
2790
2791 default:
2792 AssertMsgFailed(("Unknown state %d\n", enmState));
2793 return "Unknown!\n";
2794 }
2795}
2796
2797
2798/**
2799 * Validates the state transition in strict builds.
2800 *
2801 * @returns true if valid, false if not.
2802 *
2803 * @param enmStateOld The old (current) state.
2804 * @param enmStateNew The proposed new state.
2805 *
2806 * @remarks The reference for this is found in doc/vp/VMM.vpp, the VMSTATE
2807 * diagram (under State Machine Diagram).
2808 */
2809static bool vmR3ValidateStateTransition(VMSTATE enmStateOld, VMSTATE enmStateNew)
2810{
2811#ifdef VBOX_STRICT
2812 switch (enmStateOld)
2813 {
2814 case VMSTATE_CREATING:
2815 AssertMsgReturn(enmStateNew == VMSTATE_CREATED, ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2816 break;
2817
2818 case VMSTATE_CREATED:
2819 AssertMsgReturn( enmStateNew == VMSTATE_LOADING
2820 || enmStateNew == VMSTATE_POWERING_ON
2821 || enmStateNew == VMSTATE_POWERING_OFF
2822 , ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2823 break;
2824
2825 case VMSTATE_LOADING:
2826 AssertMsgReturn( enmStateNew == VMSTATE_SUSPENDED
2827 || enmStateNew == VMSTATE_LOAD_FAILURE
2828 , ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2829 break;
2830
2831 case VMSTATE_POWERING_ON:
2832 AssertMsgReturn( enmStateNew == VMSTATE_RUNNING
2833 /*|| enmStateNew == VMSTATE_FATAL_ERROR ?*/
2834 , ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2835 break;
2836
2837 case VMSTATE_RESUMING:
2838 AssertMsgReturn( enmStateNew == VMSTATE_RUNNING
2839 /*|| enmStateNew == VMSTATE_FATAL_ERROR ?*/
2840 , ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2841 break;
2842
2843 case VMSTATE_RUNNING:
2844 AssertMsgReturn( enmStateNew == VMSTATE_POWERING_OFF
2845 || enmStateNew == VMSTATE_SUSPENDING
2846 || enmStateNew == VMSTATE_RESETTING
2847 || enmStateNew == VMSTATE_RUNNING_LS
2848 || enmStateNew == VMSTATE_DEBUGGING
2849 || enmStateNew == VMSTATE_FATAL_ERROR
2850 || enmStateNew == VMSTATE_GURU_MEDITATION
2851 , ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2852 break;
2853
2854 case VMSTATE_RUNNING_LS:
2855 AssertMsgReturn( enmStateNew == VMSTATE_POWERING_OFF_LS
2856 || enmStateNew == VMSTATE_SUSPENDING_LS
2857 || enmStateNew == VMSTATE_SUSPENDING_EXT_LS
2858 || enmStateNew == VMSTATE_RESETTING_LS
2859 || enmStateNew == VMSTATE_RUNNING
2860 || enmStateNew == VMSTATE_DEBUGGING_LS
2861 || enmStateNew == VMSTATE_FATAL_ERROR_LS
2862 || enmStateNew == VMSTATE_GURU_MEDITATION_LS
2863 , ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2864 break;
2865
2866 case VMSTATE_RESETTING:
2867 AssertMsgReturn(enmStateNew == VMSTATE_RUNNING, ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2868 break;
2869
2870 case VMSTATE_RESETTING_LS:
2871 AssertMsgReturn( enmStateNew == VMSTATE_SUSPENDING_LS
2872 , ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2873 break;
2874
2875 case VMSTATE_SUSPENDING:
2876 AssertMsgReturn(enmStateNew == VMSTATE_SUSPENDED, ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2877 break;
2878
2879 case VMSTATE_SUSPENDING_LS:
2880 AssertMsgReturn( enmStateNew == VMSTATE_SUSPENDING
2881 || enmStateNew == VMSTATE_SUSPENDED_LS
2882 , ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2883 break;
2884
2885 case VMSTATE_SUSPENDING_EXT_LS:
2886 AssertMsgReturn( enmStateNew == VMSTATE_SUSPENDING
2887 || enmStateNew == VMSTATE_SUSPENDED_EXT_LS
2888 , ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2889 break;
2890
2891 case VMSTATE_SUSPENDED:
2892 AssertMsgReturn( enmStateNew == VMSTATE_POWERING_OFF
2893 || enmStateNew == VMSTATE_SAVING
2894 || enmStateNew == VMSTATE_RESETTING
2895 || enmStateNew == VMSTATE_RESUMING
2896 || enmStateNew == VMSTATE_LOADING
2897 , ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2898 break;
2899
2900 case VMSTATE_SUSPENDED_LS:
2901 AssertMsgReturn( enmStateNew == VMSTATE_SUSPENDED
2902 || enmStateNew == VMSTATE_SAVING
2903 , ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2904 break;
2905
2906 case VMSTATE_SUSPENDED_EXT_LS:
2907 AssertMsgReturn( enmStateNew == VMSTATE_SUSPENDED
2908 || enmStateNew == VMSTATE_SAVING
2909 , ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2910 break;
2911
2912 case VMSTATE_SAVING:
2913 AssertMsgReturn(enmStateNew == VMSTATE_SUSPENDED, ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2914 break;
2915
2916 case VMSTATE_DEBUGGING:
2917 AssertMsgReturn( enmStateNew == VMSTATE_RUNNING
2918 || enmStateNew == VMSTATE_POWERING_OFF
2919 , ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2920 break;
2921
2922 case VMSTATE_DEBUGGING_LS:
2923 AssertMsgReturn( enmStateNew == VMSTATE_DEBUGGING
2924 || enmStateNew == VMSTATE_RUNNING_LS
2925 || enmStateNew == VMSTATE_POWERING_OFF_LS
2926 , ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2927 break;
2928
2929 case VMSTATE_POWERING_OFF:
2930 AssertMsgReturn(enmStateNew == VMSTATE_OFF, ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2931 break;
2932
2933 case VMSTATE_POWERING_OFF_LS:
2934 AssertMsgReturn( enmStateNew == VMSTATE_POWERING_OFF
2935 || enmStateNew == VMSTATE_OFF_LS
2936 , ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2937 break;
2938
2939 case VMSTATE_OFF:
2940 AssertMsgReturn(enmStateNew == VMSTATE_DESTROYING, ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2941 break;
2942
2943 case VMSTATE_OFF_LS:
2944 AssertMsgReturn(enmStateNew == VMSTATE_OFF, ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2945 break;
2946
2947 case VMSTATE_FATAL_ERROR:
2948 AssertMsgReturn(enmStateNew == VMSTATE_POWERING_OFF, ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2949 break;
2950
2951 case VMSTATE_FATAL_ERROR_LS:
2952 AssertMsgReturn( enmStateNew == VMSTATE_FATAL_ERROR
2953 || enmStateNew == VMSTATE_POWERING_OFF_LS
2954 , ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2955 break;
2956
2957 case VMSTATE_GURU_MEDITATION:
2958 AssertMsgReturn( enmStateNew == VMSTATE_DEBUGGING
2959 || enmStateNew == VMSTATE_POWERING_OFF
2960 , ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2961 break;
2962
2963 case VMSTATE_GURU_MEDITATION_LS:
2964 AssertMsgReturn( enmStateNew == VMSTATE_GURU_MEDITATION
2965 || enmStateNew == VMSTATE_DEBUGGING_LS
2966 || enmStateNew == VMSTATE_POWERING_OFF_LS
2967 , ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2968 break;
2969
2970 case VMSTATE_LOAD_FAILURE:
2971 AssertMsgReturn(enmStateNew == VMSTATE_POWERING_OFF, ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2972 break;
2973
2974 case VMSTATE_DESTROYING:
2975 AssertMsgReturn(enmStateNew == VMSTATE_TERMINATED, ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2976 break;
2977
2978 case VMSTATE_TERMINATED:
2979 default:
2980 AssertMsgFailedReturn(("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2981 break;
2982 }
2983#endif /* VBOX_STRICT */
2984 return true;
2985}
2986
2987
2988/**
2989 * Does the state change callouts.
2990 *
2991 * The caller owns the AtStateCritSect.
2992 *
2993 * @param pVM The VM handle.
2994 * @param pUVM The UVM handle.
2995 * @param enmStateNew The New state.
2996 * @param enmStateOld The old state.
2997 */
2998static void vmR3DoAtState(PVM pVM, PUVM pUVM, VMSTATE enmStateNew, VMSTATE enmStateOld)
2999{
3000 LogRel(("Changing the VM state from '%s' to '%s'.\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)));
3001
3002 for (PVMATSTATE pCur = pUVM->vm.s.pAtState; pCur; pCur = pCur->pNext)
3003 {
3004 pCur->pfnAtState(pVM, enmStateNew, enmStateOld, pCur->pvUser);
3005 if ( enmStateNew != VMSTATE_DESTROYING
3006 && pVM->enmVMState == VMSTATE_DESTROYING)
3007 break;
3008 AssertMsg(pVM->enmVMState == enmStateNew,
3009 ("You are not allowed to change the state while in the change callback, except "
3010 "from destroying the VM. There are restrictions in the way the state changes "
3011 "are propagated up to the EM execution loop and it makes the program flow very "
3012 "difficult to follow. (%s, expected %s, old %s)\n",
3013 VMR3GetStateName(pVM->enmVMState), VMR3GetStateName(enmStateNew),
3014 VMR3GetStateName(enmStateOld)));
3015 }
3016}
3017
3018
3019/**
3020 * Sets the current VM state, with the AtStatCritSect already entered.
3021 *
3022 * @param pVM The VM handle.
3023 * @param pUVM The UVM handle.
3024 * @param enmStateNew The new state.
3025 * @param enmStateOld The old state.
3026 */
3027static void vmR3SetStateLocked(PVM pVM, PUVM pUVM, VMSTATE enmStateNew, VMSTATE enmStateOld)
3028{
3029 vmR3ValidateStateTransition(enmStateOld, enmStateNew);
3030
3031 AssertMsg(pVM->enmVMState == enmStateOld,
3032 ("%s != %s\n", VMR3GetStateName(pVM->enmVMState), VMR3GetStateName(enmStateOld)));
3033 pUVM->vm.s.enmPrevVMState = enmStateOld;
3034 pVM->enmVMState = enmStateNew;
3035 VM_FF_CLEAR(pVM, VM_FF_CHECK_VM_STATE);
3036
3037 vmR3DoAtState(pVM, pUVM, enmStateNew, enmStateOld);
3038}
3039
3040
3041/**
3042 * Sets the current VM state.
3043 *
3044 * @param pVM VM handle.
3045 * @param enmStateNew The new state.
3046 * @param enmStateOld The old state (for asserting only).
3047 */
3048static void vmR3SetState(PVM pVM, VMSTATE enmStateNew, VMSTATE enmStateOld)
3049{
3050 PUVM pUVM = pVM->pUVM;
3051 RTCritSectEnter(&pUVM->vm.s.AtStateCritSect);
3052
3053 AssertMsg(pVM->enmVMState == enmStateOld,
3054 ("%s != %s\n", VMR3GetStateName(pVM->enmVMState), VMR3GetStateName(enmStateOld)));
3055 vmR3SetStateLocked(pVM, pUVM, enmStateNew, pVM->enmVMState);
3056
3057 RTCritSectLeave(&pUVM->vm.s.AtStateCritSect);
3058}
3059
3060
3061/**
3062 * Tries to perform a state transition.
3063 *
3064 * @returns The 1-based ordinal of the succeeding transition.
3065 * VERR_VM_INVALID_VM_STATE and Assert+LogRel on failure.
3066 *
3067 * @param pVM The VM handle.
3068 * @param pszWho Who is trying to change it.
3069 * @param cTransitions The number of transitions in the ellipsis.
3070 * @param ... Transition pairs; new, old.
3071 */
3072static int vmR3TrySetState(PVM pVM, const char *pszWho, unsigned cTransitions, ...)
3073{
3074 va_list va;
3075 VMSTATE enmStateNew = VMSTATE_CREATED;
3076 VMSTATE enmStateOld = VMSTATE_CREATED;
3077
3078#ifdef VBOX_STRICT
3079 /*
3080 * Validate the input first.
3081 */
3082 va_start(va, cTransitions);
3083 for (unsigned i = 0; i < cTransitions; i++)
3084 {
3085 enmStateNew = (VMSTATE)va_arg(va, /*VMSTATE*/int);
3086 enmStateOld = (VMSTATE)va_arg(va, /*VMSTATE*/int);
3087 vmR3ValidateStateTransition(enmStateOld, enmStateNew);
3088 }
3089 va_end(va);
3090#endif
3091
3092 /*
3093 * Grab the lock and see if any of the proposed transisions works out.
3094 */
3095 va_start(va, cTransitions);
3096 int rc = VERR_VM_INVALID_VM_STATE;
3097 PUVM pUVM = pVM->pUVM;
3098 RTCritSectEnter(&pUVM->vm.s.AtStateCritSect);
3099
3100 VMSTATE enmStateCur = pVM->enmVMState;
3101
3102 for (unsigned i = 0; i < cTransitions; i++)
3103 {
3104 enmStateNew = (VMSTATE)va_arg(va, /*VMSTATE*/int);
3105 enmStateOld = (VMSTATE)va_arg(va, /*VMSTATE*/int);
3106 if (enmStateCur == enmStateOld)
3107 {
3108 vmR3SetStateLocked(pVM, pUVM, enmStateNew, enmStateOld);
3109 rc = i + 1;
3110 break;
3111 }
3112 }
3113
3114 if (RT_FAILURE(rc))
3115 {
3116 /*
3117 * Complain about it.
3118 */
3119 if (cTransitions == 1)
3120 {
3121 LogRel(("%s: %s -> %s failed, because the VM state is actually %s\n",
3122 pszWho, VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew), VMR3GetStateName(enmStateCur)));
3123 VMSetError(pVM, VERR_VM_INVALID_VM_STATE, RT_SRC_POS,
3124 N_("%s failed because the VM state is %s instead of %s"),
3125 pszWho, VMR3GetStateName(enmStateCur), VMR3GetStateName(enmStateOld));
3126 AssertMsgFailed(("%s: %s -> %s failed, because the VM state is actually %s\n",
3127 pszWho, VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew), VMR3GetStateName(enmStateCur)));
3128 }
3129 else
3130 {
3131 va_end(va);
3132 va_start(va, cTransitions);
3133 LogRel(("%s:\n", pszWho));
3134 for (unsigned i = 0; i < cTransitions; i++)
3135 {
3136 enmStateNew = (VMSTATE)va_arg(va, /*VMSTATE*/int);
3137 enmStateOld = (VMSTATE)va_arg(va, /*VMSTATE*/int);
3138 LogRel(("%s%s -> %s",
3139 i ? ", " : " ", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)));
3140 }
3141 LogRel((" failed, because the VM state is actually %s\n", VMR3GetStateName(enmStateCur)));
3142 VMSetError(pVM, VERR_VM_INVALID_VM_STATE, RT_SRC_POS,
3143 N_("%s failed because the current VM state, %s, was not found in the state transition table"),
3144 pszWho, VMR3GetStateName(enmStateCur), VMR3GetStateName(enmStateOld));
3145 AssertMsgFailed(("%s - state=%s, see release log for full details. Check the cTransitions passed us.\n",
3146 pszWho, VMR3GetStateName(enmStateCur)));
3147 }
3148 }
3149
3150 RTCritSectLeave(&pUVM->vm.s.AtStateCritSect);
3151 va_end(va);
3152 Assert(rc > 0 || rc < 0);
3153 return rc;
3154}
3155
3156
3157/**
3158 * Flag a guru meditation ... a hack.
3159 *
3160 * @param pVM The VM handle
3161 *
3162 * @todo Rewrite this part. The guru meditation should be flagged
3163 * immediately by the VMM and not by VMEmt.cpp when it's all over.
3164 */
3165void vmR3SetGuruMeditation(PVM pVM)
3166{
3167 PUVM pUVM = pVM->pUVM;
3168 RTCritSectEnter(&pUVM->vm.s.AtStateCritSect);
3169
3170 VMSTATE enmStateCur = pVM->enmVMState;
3171 if (enmStateCur == VMSTATE_RUNNING)
3172 vmR3SetStateLocked(pVM, pUVM, VMSTATE_GURU_MEDITATION, VMSTATE_RUNNING);
3173 else if (enmStateCur == VMSTATE_RUNNING_LS)
3174 {
3175 vmR3SetStateLocked(pVM, pUVM, VMSTATE_GURU_MEDITATION_LS, VMSTATE_RUNNING_LS);
3176 SSMR3Cancel(pVM);
3177 }
3178
3179 RTCritSectLeave(&pUVM->vm.s.AtStateCritSect);
3180}
3181
3182
3183/**
3184 * Called by vmR3EmulationThreadWithId just before the VM structure is freed.
3185 *
3186 * @param pVM The VM handle.
3187 */
3188void vmR3SetTerminated(PVM pVM)
3189{
3190 vmR3SetState(pVM, VMSTATE_TERMINATED, VMSTATE_DESTROYING);
3191}
3192
3193
3194/**
3195 * Checks if the VM was teleported and hasn't been fully resumed yet.
3196 *
3197 * This applies to both sides of the teleportation since we may leave a working
3198 * clone behind and the user is allowed to resume this...
3199 *
3200 * @returns true / false.
3201 * @param pVM The VM handle.
3202 * @thread Any thread.
3203 */
3204VMMR3DECL(bool) VMR3TeleportedAndNotFullyResumedYet(PVM pVM)
3205{
3206 VM_ASSERT_VALID_EXT_RETURN(pVM, false);
3207 return pVM->vm.s.fTeleportedAndNotFullyResumedYet;
3208}
3209
3210
3211/**
3212 * Registers a VM state change callback.
3213 *
3214 * You are not allowed to call any function which changes the VM state from a
3215 * state callback.
3216 *
3217 * @returns VBox status code.
3218 * @param pVM VM handle.
3219 * @param pfnAtState Pointer to callback.
3220 * @param pvUser User argument.
3221 * @thread Any.
3222 */
3223VMMR3DECL(int) VMR3AtStateRegister(PVM pVM, PFNVMATSTATE pfnAtState, void *pvUser)
3224{
3225 LogFlow(("VMR3AtStateRegister: pfnAtState=%p pvUser=%p\n", pfnAtState, pvUser));
3226
3227 /*
3228 * Validate input.
3229 */
3230 AssertPtrReturn(pfnAtState, VERR_INVALID_PARAMETER);
3231 VM_ASSERT_VALID_EXT_RETURN(pVM, VERR_INVALID_VM_HANDLE);
3232
3233 /*
3234 * Allocate a new record.
3235 */
3236 PUVM pUVM = pVM->pUVM;
3237 PVMATSTATE pNew = (PVMATSTATE)MMR3HeapAllocU(pUVM, MM_TAG_VM, sizeof(*pNew));
3238 if (!pNew)
3239 return VERR_NO_MEMORY;
3240
3241 /* fill */
3242 pNew->pfnAtState = pfnAtState;
3243 pNew->pvUser = pvUser;
3244
3245 /* insert */
3246 RTCritSectEnter(&pUVM->vm.s.AtStateCritSect);
3247 pNew->pNext = *pUVM->vm.s.ppAtStateNext;
3248 *pUVM->vm.s.ppAtStateNext = pNew;
3249 pUVM->vm.s.ppAtStateNext = &pNew->pNext;
3250 RTCritSectLeave(&pUVM->vm.s.AtStateCritSect);
3251
3252 return VINF_SUCCESS;
3253}
3254
3255
3256/**
3257 * Deregisters a VM state change callback.
3258 *
3259 * @returns VBox status code.
3260 * @param pVM VM handle.
3261 * @param pfnAtState Pointer to callback.
3262 * @param pvUser User argument.
3263 * @thread Any.
3264 */
3265VMMR3DECL(int) VMR3AtStateDeregister(PVM pVM, PFNVMATSTATE pfnAtState, void *pvUser)
3266{
3267 LogFlow(("VMR3AtStateDeregister: pfnAtState=%p pvUser=%p\n", pfnAtState, pvUser));
3268
3269 /*
3270 * Validate input.
3271 */
3272 AssertPtrReturn(pfnAtState, VERR_INVALID_PARAMETER);
3273 VM_ASSERT_VALID_EXT_RETURN(pVM, VERR_INVALID_VM_HANDLE);
3274
3275 PUVM pUVM = pVM->pUVM;
3276 RTCritSectEnter(&pUVM->vm.s.AtStateCritSect);
3277
3278 /*
3279 * Search the list for the entry.
3280 */
3281 PVMATSTATE pPrev = NULL;
3282 PVMATSTATE pCur = pUVM->vm.s.pAtState;
3283 while ( pCur
3284 && ( pCur->pfnAtState != pfnAtState
3285 || pCur->pvUser != pvUser))
3286 {
3287 pPrev = pCur;
3288 pCur = pCur->pNext;
3289 }
3290 if (!pCur)
3291 {
3292 AssertMsgFailed(("pfnAtState=%p was not found\n", pfnAtState));
3293 RTCritSectLeave(&pUVM->vm.s.AtStateCritSect);
3294 return VERR_FILE_NOT_FOUND;
3295 }
3296
3297 /*
3298 * Unlink it.
3299 */
3300 if (pPrev)
3301 {
3302 pPrev->pNext = pCur->pNext;
3303 if (!pCur->pNext)
3304 pUVM->vm.s.ppAtStateNext = &pPrev->pNext;
3305 }
3306 else
3307 {
3308 pUVM->vm.s.pAtState = pCur->pNext;
3309 if (!pCur->pNext)
3310 pUVM->vm.s.ppAtStateNext = &pUVM->vm.s.pAtState;
3311 }
3312
3313 RTCritSectLeave(&pUVM->vm.s.AtStateCritSect);
3314
3315 /*
3316 * Free it.
3317 */
3318 pCur->pfnAtState = NULL;
3319 pCur->pNext = NULL;
3320 MMR3HeapFree(pCur);
3321
3322 return VINF_SUCCESS;
3323}
3324
3325
3326/**
3327 * Registers a VM error callback.
3328 *
3329 * @returns VBox status code.
3330 * @param pVM The VM handle.
3331 * @param pfnAtError Pointer to callback.
3332 * @param pvUser User argument.
3333 * @thread Any.
3334 */
3335VMMR3DECL(int) VMR3AtErrorRegister(PVM pVM, PFNVMATERROR pfnAtError, void *pvUser)
3336{
3337 return VMR3AtErrorRegisterU(pVM->pUVM, pfnAtError, pvUser);
3338}
3339
3340
3341/**
3342 * Registers a VM error callback.
3343 *
3344 * @returns VBox status code.
3345 * @param pUVM The VM handle.
3346 * @param pfnAtError Pointer to callback.
3347 * @param pvUser User argument.
3348 * @thread Any.
3349 */
3350VMMR3DECL(int) VMR3AtErrorRegisterU(PUVM pUVM, PFNVMATERROR pfnAtError, void *pvUser)
3351{
3352 LogFlow(("VMR3AtErrorRegister: pfnAtError=%p pvUser=%p\n", pfnAtError, pvUser));
3353
3354 /*
3355 * Validate input.
3356 */
3357 AssertPtrReturn(pfnAtError, VERR_INVALID_PARAMETER);
3358 UVM_ASSERT_VALID_EXT_RETURN(pUVM, VERR_INVALID_VM_HANDLE);
3359
3360 /*
3361 * Allocate a new record.
3362 */
3363 PVMATERROR pNew = (PVMATERROR)MMR3HeapAllocU(pUVM, MM_TAG_VM, sizeof(*pNew));
3364 if (!pNew)
3365 return VERR_NO_MEMORY;
3366
3367 /* fill */
3368 pNew->pfnAtError = pfnAtError;
3369 pNew->pvUser = pvUser;
3370
3371 /* insert */
3372 RTCritSectEnter(&pUVM->vm.s.AtErrorCritSect);
3373 pNew->pNext = *pUVM->vm.s.ppAtErrorNext;
3374 *pUVM->vm.s.ppAtErrorNext = pNew;
3375 pUVM->vm.s.ppAtErrorNext = &pNew->pNext;
3376 RTCritSectLeave(&pUVM->vm.s.AtErrorCritSect);
3377
3378 return VINF_SUCCESS;
3379}
3380
3381
3382/**
3383 * Deregisters a VM error callback.
3384 *
3385 * @returns VBox status code.
3386 * @param pVM The VM handle.
3387 * @param pfnAtError Pointer to callback.
3388 * @param pvUser User argument.
3389 * @thread Any.
3390 */
3391VMMR3DECL(int) VMR3AtErrorDeregister(PVM pVM, PFNVMATERROR pfnAtError, void *pvUser)
3392{
3393 LogFlow(("VMR3AtErrorDeregister: pfnAtError=%p pvUser=%p\n", pfnAtError, pvUser));
3394
3395 /*
3396 * Validate input.
3397 */
3398 AssertPtrReturn(pfnAtError, VERR_INVALID_PARAMETER);
3399 VM_ASSERT_VALID_EXT_RETURN(pVM, VERR_INVALID_VM_HANDLE);
3400
3401 PUVM pUVM = pVM->pUVM;
3402 RTCritSectEnter(&pUVM->vm.s.AtErrorCritSect);
3403
3404 /*
3405 * Search the list for the entry.
3406 */
3407 PVMATERROR pPrev = NULL;
3408 PVMATERROR pCur = pUVM->vm.s.pAtError;
3409 while ( pCur
3410 && ( pCur->pfnAtError != pfnAtError
3411 || pCur->pvUser != pvUser))
3412 {
3413 pPrev = pCur;
3414 pCur = pCur->pNext;
3415 }
3416 if (!pCur)
3417 {
3418 AssertMsgFailed(("pfnAtError=%p was not found\n", pfnAtError));
3419 RTCritSectLeave(&pUVM->vm.s.AtErrorCritSect);
3420 return VERR_FILE_NOT_FOUND;
3421 }
3422
3423 /*
3424 * Unlink it.
3425 */
3426 if (pPrev)
3427 {
3428 pPrev->pNext = pCur->pNext;
3429 if (!pCur->pNext)
3430 pUVM->vm.s.ppAtErrorNext = &pPrev->pNext;
3431 }
3432 else
3433 {
3434 pUVM->vm.s.pAtError = pCur->pNext;
3435 if (!pCur->pNext)
3436 pUVM->vm.s.ppAtErrorNext = &pUVM->vm.s.pAtError;
3437 }
3438
3439 RTCritSectLeave(&pUVM->vm.s.AtErrorCritSect);
3440
3441 /*
3442 * Free it.
3443 */
3444 pCur->pfnAtError = NULL;
3445 pCur->pNext = NULL;
3446 MMR3HeapFree(pCur);
3447
3448 return VINF_SUCCESS;
3449}
3450
3451
3452/**
3453 * Ellipsis to va_list wrapper for calling pfnAtError.
3454 */
3455static void vmR3SetErrorWorkerDoCall(PVM pVM, PVMATERROR pCur, int rc, RT_SRC_POS_DECL, const char *pszFormat, ...)
3456{
3457 va_list va;
3458 va_start(va, pszFormat);
3459 pCur->pfnAtError(pVM, pCur->pvUser, rc, RT_SRC_POS_ARGS, pszFormat, va);
3460 va_end(va);
3461}
3462
3463
3464/**
3465 * This is a worker function for GC and Ring-0 calls to VMSetError and VMSetErrorV.
3466 * The message is found in VMINT.
3467 *
3468 * @param pVM The VM handle.
3469 * @thread EMT.
3470 */
3471VMMR3DECL(void) VMR3SetErrorWorker(PVM pVM)
3472{
3473 VM_ASSERT_EMT(pVM);
3474 AssertReleaseMsgFailed(("And we have a winner! You get to implement Ring-0 and GC VMSetErrorV! Contrats!\n"));
3475
3476 /*
3477 * Unpack the error (if we managed to format one).
3478 */
3479 PVMERROR pErr = pVM->vm.s.pErrorR3;
3480 const char *pszFile = NULL;
3481 const char *pszFunction = NULL;
3482 uint32_t iLine = 0;
3483 const char *pszMessage;
3484 int32_t rc = VERR_MM_HYPER_NO_MEMORY;
3485 if (pErr)
3486 {
3487 AssertCompile(sizeof(const char) == sizeof(uint8_t));
3488 if (pErr->offFile)
3489 pszFile = (const char *)pErr + pErr->offFile;
3490 iLine = pErr->iLine;
3491 if (pErr->offFunction)
3492 pszFunction = (const char *)pErr + pErr->offFunction;
3493 if (pErr->offMessage)
3494 pszMessage = (const char *)pErr + pErr->offMessage;
3495 else
3496 pszMessage = "No message!";
3497 }
3498 else
3499 pszMessage = "No message! (Failed to allocate memory to put the error message in!)";
3500
3501 /*
3502 * Call the at error callbacks.
3503 */
3504 PUVM pUVM = pVM->pUVM;
3505 RTCritSectEnter(&pUVM->vm.s.AtErrorCritSect);
3506 ASMAtomicIncU32(&pUVM->vm.s.cRuntimeErrors);
3507 for (PVMATERROR pCur = pUVM->vm.s.pAtError; pCur; pCur = pCur->pNext)
3508 vmR3SetErrorWorkerDoCall(pVM, pCur, rc, RT_SRC_POS_ARGS, "%s", pszMessage);
3509 RTCritSectLeave(&pUVM->vm.s.AtErrorCritSect);
3510}
3511
3512
3513/**
3514 * Gets the number of errors raised via VMSetError.
3515 *
3516 * This can be used avoid double error messages.
3517 *
3518 * @returns The error count.
3519 * @param pVM The VM handle.
3520 */
3521VMMR3DECL(uint32_t) VMR3GetErrorCount(PVM pVM)
3522{
3523 return pVM->pUVM->vm.s.cErrors;
3524}
3525
3526
3527/**
3528 * Creation time wrapper for vmR3SetErrorUV.
3529 *
3530 * @returns rc.
3531 * @param pUVM Pointer to the user mode VM structure.
3532 * @param rc The VBox status code.
3533 * @param RT_SRC_POS_DECL The source position of this error.
3534 * @param pszFormat Format string.
3535 * @param ... The arguments.
3536 * @thread Any thread.
3537 */
3538static int vmR3SetErrorU(PUVM pUVM, int rc, RT_SRC_POS_DECL, const char *pszFormat, ...)
3539{
3540 va_list va;
3541 va_start(va, pszFormat);
3542 vmR3SetErrorUV(pUVM, rc, pszFile, iLine, pszFunction, pszFormat, &va);
3543 va_end(va);
3544 return rc;
3545}
3546
3547
3548/**
3549 * Worker which calls everyone listening to the VM error messages.
3550 *
3551 * @param pUVM Pointer to the user mode VM structure.
3552 * @param rc The VBox status code.
3553 * @param RT_SRC_POS_DECL The source position of this error.
3554 * @param pszFormat Format string.
3555 * @param pArgs Pointer to the format arguments.
3556 * @thread EMT
3557 */
3558DECLCALLBACK(void) vmR3SetErrorUV(PUVM pUVM, int rc, RT_SRC_POS_DECL, const char *pszFormat, va_list *pArgs)
3559{
3560 /*
3561 * Log the error.
3562 */
3563 va_list va3;
3564 va_copy(va3, *pArgs);
3565 RTLogRelPrintf("VMSetError: %s(%d) %s; rc=%Rrc\n"
3566 "VMSetError: %N\n",
3567 pszFile, iLine, pszFunction, rc,
3568 pszFormat, &va3);
3569 va_end(va3);
3570
3571#ifdef LOG_ENABLED
3572 va_copy(va3, *pArgs);
3573 RTLogPrintf("VMSetError: %s(%d) %s; rc=%Rrc\n"
3574 "%N\n",
3575 pszFile, iLine, pszFunction, rc,
3576 pszFormat, &va3);
3577 va_end(va3);
3578#endif
3579
3580 /*
3581 * Make a copy of the message.
3582 */
3583 if (pUVM->pVM)
3584 vmSetErrorCopy(pUVM->pVM, rc, RT_SRC_POS_ARGS, pszFormat, *pArgs);
3585
3586 /*
3587 * Call the at error callbacks.
3588 */
3589 bool fCalledSomeone = false;
3590 RTCritSectEnter(&pUVM->vm.s.AtErrorCritSect);
3591 ASMAtomicIncU32(&pUVM->vm.s.cErrors);
3592 for (PVMATERROR pCur = pUVM->vm.s.pAtError; pCur; pCur = pCur->pNext)
3593 {
3594 va_list va2;
3595 va_copy(va2, *pArgs);
3596 pCur->pfnAtError(pUVM->pVM, pCur->pvUser, rc, RT_SRC_POS_ARGS, pszFormat, va2);
3597 va_end(va2);
3598 fCalledSomeone = true;
3599 }
3600 RTCritSectLeave(&pUVM->vm.s.AtErrorCritSect);
3601}
3602
3603
3604/**
3605 * Registers a VM runtime error callback.
3606 *
3607 * @returns VBox status code.
3608 * @param pVM The VM handle.
3609 * @param pfnAtRuntimeError Pointer to callback.
3610 * @param pvUser User argument.
3611 * @thread Any.
3612 */
3613VMMR3DECL(int) VMR3AtRuntimeErrorRegister(PVM pVM, PFNVMATRUNTIMEERROR pfnAtRuntimeError, void *pvUser)
3614{
3615 LogFlow(("VMR3AtRuntimeErrorRegister: pfnAtRuntimeError=%p pvUser=%p\n", pfnAtRuntimeError, pvUser));
3616
3617 /*
3618 * Validate input.
3619 */
3620 AssertPtrReturn(pfnAtRuntimeError, VERR_INVALID_PARAMETER);
3621 VM_ASSERT_VALID_EXT_RETURN(pVM, VERR_INVALID_VM_HANDLE);
3622
3623 /*
3624 * Allocate a new record.
3625 */
3626 PUVM pUVM = pVM->pUVM;
3627 PVMATRUNTIMEERROR pNew = (PVMATRUNTIMEERROR)MMR3HeapAllocU(pUVM, MM_TAG_VM, sizeof(*pNew));
3628 if (!pNew)
3629 return VERR_NO_MEMORY;
3630
3631 /* fill */
3632 pNew->pfnAtRuntimeError = pfnAtRuntimeError;
3633 pNew->pvUser = pvUser;
3634
3635 /* insert */
3636 RTCritSectEnter(&pUVM->vm.s.AtErrorCritSect);
3637 pNew->pNext = *pUVM->vm.s.ppAtRuntimeErrorNext;
3638 *pUVM->vm.s.ppAtRuntimeErrorNext = pNew;
3639 pUVM->vm.s.ppAtRuntimeErrorNext = &pNew->pNext;
3640 RTCritSectLeave(&pUVM->vm.s.AtErrorCritSect);
3641
3642 return VINF_SUCCESS;
3643}
3644
3645
3646/**
3647 * Deregisters a VM runtime error callback.
3648 *
3649 * @returns VBox status code.
3650 * @param pVM The VM handle.
3651 * @param pfnAtRuntimeError Pointer to callback.
3652 * @param pvUser User argument.
3653 * @thread Any.
3654 */
3655VMMR3DECL(int) VMR3AtRuntimeErrorDeregister(PVM pVM, PFNVMATRUNTIMEERROR pfnAtRuntimeError, void *pvUser)
3656{
3657 LogFlow(("VMR3AtRuntimeErrorDeregister: pfnAtRuntimeError=%p pvUser=%p\n", pfnAtRuntimeError, pvUser));
3658
3659 /*
3660 * Validate input.
3661 */
3662 AssertPtrReturn(pfnAtRuntimeError, VERR_INVALID_PARAMETER);
3663 VM_ASSERT_VALID_EXT_RETURN(pVM, VERR_INVALID_VM_HANDLE);
3664
3665 PUVM pUVM = pVM->pUVM;
3666 RTCritSectEnter(&pUVM->vm.s.AtErrorCritSect);
3667
3668 /*
3669 * Search the list for the entry.
3670 */
3671 PVMATRUNTIMEERROR pPrev = NULL;
3672 PVMATRUNTIMEERROR pCur = pUVM->vm.s.pAtRuntimeError;
3673 while ( pCur
3674 && ( pCur->pfnAtRuntimeError != pfnAtRuntimeError
3675 || pCur->pvUser != pvUser))
3676 {
3677 pPrev = pCur;
3678 pCur = pCur->pNext;
3679 }
3680 if (!pCur)
3681 {
3682 AssertMsgFailed(("pfnAtRuntimeError=%p was not found\n", pfnAtRuntimeError));
3683 RTCritSectLeave(&pUVM->vm.s.AtErrorCritSect);
3684 return VERR_FILE_NOT_FOUND;
3685 }
3686
3687 /*
3688 * Unlink it.
3689 */
3690 if (pPrev)
3691 {
3692 pPrev->pNext = pCur->pNext;
3693 if (!pCur->pNext)
3694 pUVM->vm.s.ppAtRuntimeErrorNext = &pPrev->pNext;
3695 }
3696 else
3697 {
3698 pUVM->vm.s.pAtRuntimeError = pCur->pNext;
3699 if (!pCur->pNext)
3700 pUVM->vm.s.ppAtRuntimeErrorNext = &pUVM->vm.s.pAtRuntimeError;
3701 }
3702
3703 RTCritSectLeave(&pUVM->vm.s.AtErrorCritSect);
3704
3705 /*
3706 * Free it.
3707 */
3708 pCur->pfnAtRuntimeError = NULL;
3709 pCur->pNext = NULL;
3710 MMR3HeapFree(pCur);
3711
3712 return VINF_SUCCESS;
3713}
3714
3715
3716/**
3717 * EMT rendezvous worker that vmR3SetRuntimeErrorCommon uses to safely change
3718 * the state to FatalError(LS).
3719 *
3720 * @returns VERR_VM_INVALID_VM_STATE or VINF_EM_SUSPENED. (This is a strict
3721 * return code, see FNVMMEMTRENDEZVOUS.)
3722 *
3723 * @param pVM The VM handle.
3724 * @param pVCpu The VMCPU handle of the EMT.
3725 * @param pvUser Ignored.
3726 */
3727static DECLCALLBACK(VBOXSTRICTRC) vmR3SetRuntimeErrorChangeState(PVM pVM, PVMCPU pVCpu, void *pvUser)
3728{
3729 NOREF(pVCpu);
3730 Assert(!pvUser); NOREF(pvUser);
3731
3732 /*
3733 * The first EMT thru here changes the state.
3734 */
3735 if (pVCpu->idCpu == pVM->cCpus - 1)
3736 {
3737 int rc = vmR3TrySetState(pVM, "VMSetRuntimeError", 2,
3738 VMSTATE_FATAL_ERROR, VMSTATE_RUNNING,
3739 VMSTATE_FATAL_ERROR_LS, VMSTATE_RUNNING_LS);
3740 if (RT_FAILURE(rc))
3741 return rc;
3742 if (rc == 2)
3743 SSMR3Cancel(pVM);
3744
3745 VM_FF_SET(pVM, VM_FF_CHECK_VM_STATE);
3746 }
3747
3748 /* This'll make sure we get out of whereever we are (e.g. REM). */
3749 return VINF_EM_SUSPEND;
3750}
3751
3752
3753/**
3754 * Worker for VMR3SetRuntimeErrorWorker and vmR3SetRuntimeErrorV.
3755 *
3756 * This does the common parts after the error has been saved / retrieved.
3757 *
3758 * @returns VBox status code with modifications, see VMSetRuntimeErrorV.
3759 *
3760 * @param pVM The VM handle.
3761 * @param fFlags The error flags.
3762 * @param pszErrorId Error ID string.
3763 * @param pszFormat Format string.
3764 * @param pVa Pointer to the format arguments.
3765 */
3766static int vmR3SetRuntimeErrorCommon(PVM pVM, uint32_t fFlags, const char *pszErrorId, const char *pszFormat, va_list *pVa)
3767{
3768 LogRel(("VM: Raising runtime error '%s' (fFlags=%#x)\n", pszErrorId, fFlags));
3769
3770 /*
3771 * Take actions before the call.
3772 */
3773 int rc;
3774 if (fFlags & VMSETRTERR_FLAGS_FATAL)
3775 rc = VMMR3EmtRendezvous(pVM, VMMEMTRENDEZVOUS_FLAGS_TYPE_DESCENDING | VMMEMTRENDEZVOUS_FLAGS_STOP_ON_ERROR,
3776 vmR3SetRuntimeErrorChangeState, NULL);
3777 else if (fFlags & VMSETRTERR_FLAGS_SUSPEND)
3778 rc = VMR3Suspend(pVM);
3779 else
3780 rc = VINF_SUCCESS;
3781
3782 /*
3783 * Do the callback round.
3784 */
3785 PUVM pUVM = pVM->pUVM;
3786 RTCritSectEnter(&pUVM->vm.s.AtErrorCritSect);
3787 ASMAtomicIncU32(&pUVM->vm.s.cRuntimeErrors);
3788 for (PVMATRUNTIMEERROR pCur = pUVM->vm.s.pAtRuntimeError; pCur; pCur = pCur->pNext)
3789 {
3790 va_list va;
3791 va_copy(va, *pVa);
3792 pCur->pfnAtRuntimeError(pVM, pCur->pvUser, fFlags, pszErrorId, pszFormat, va);
3793 va_end(va);
3794 }
3795 RTCritSectLeave(&pUVM->vm.s.AtErrorCritSect);
3796
3797 return rc;
3798}
3799
3800
3801/**
3802 * Ellipsis to va_list wrapper for calling vmR3SetRuntimeErrorCommon.
3803 */
3804static int vmR3SetRuntimeErrorCommonF(PVM pVM, uint32_t fFlags, const char *pszErrorId, const char *pszFormat, ...)
3805{
3806 va_list va;
3807 va_start(va, pszFormat);
3808 int rc = vmR3SetRuntimeErrorCommon(pVM, fFlags, pszErrorId, pszFormat, &va);
3809 va_end(va);
3810 return rc;
3811}
3812
3813
3814/**
3815 * This is a worker function for RC and Ring-0 calls to VMSetError and
3816 * VMSetErrorV.
3817 *
3818 * The message is found in VMINT.
3819 *
3820 * @returns VBox status code, see VMSetRuntimeError.
3821 * @param pVM The VM handle.
3822 * @thread EMT.
3823 */
3824VMMR3DECL(int) VMR3SetRuntimeErrorWorker(PVM pVM)
3825{
3826 VM_ASSERT_EMT(pVM);
3827 AssertReleaseMsgFailed(("And we have a winner! You get to implement Ring-0 and GC VMSetRuntimeErrorV! Congrats!\n"));
3828
3829 /*
3830 * Unpack the error (if we managed to format one).
3831 */
3832 const char *pszErrorId = "SetRuntimeError";
3833 const char *pszMessage = "No message!";
3834 uint32_t fFlags = VMSETRTERR_FLAGS_FATAL;
3835 PVMRUNTIMEERROR pErr = pVM->vm.s.pRuntimeErrorR3;
3836 if (pErr)
3837 {
3838 AssertCompile(sizeof(const char) == sizeof(uint8_t));
3839 if (pErr->offErrorId)
3840 pszErrorId = (const char *)pErr + pErr->offErrorId;
3841 if (pErr->offMessage)
3842 pszMessage = (const char *)pErr + pErr->offMessage;
3843 fFlags = pErr->fFlags;
3844 }
3845
3846 /*
3847 * Join cause with vmR3SetRuntimeErrorV.
3848 */
3849 return vmR3SetRuntimeErrorCommonF(pVM, fFlags, pszErrorId, "%s", pszMessage);
3850}
3851
3852
3853/**
3854 * Worker for VMSetRuntimeErrorV for doing the job on EMT in ring-3.
3855 *
3856 * @returns VBox status code with modifications, see VMSetRuntimeErrorV.
3857 *
3858 * @param pVM The VM handle.
3859 * @param fFlags The error flags.
3860 * @param pszErrorId Error ID string.
3861 * @param pszMessage The error message residing the MM heap.
3862 *
3863 * @thread EMT
3864 */
3865DECLCALLBACK(int) vmR3SetRuntimeError(PVM pVM, uint32_t fFlags, const char *pszErrorId, char *pszMessage)
3866{
3867#if 0 /** @todo make copy of the error msg. */
3868 /*
3869 * Make a copy of the message.
3870 */
3871 va_list va2;
3872 va_copy(va2, *pVa);
3873 vmSetRuntimeErrorCopy(pVM, fFlags, pszErrorId, pszFormat, va2);
3874 va_end(va2);
3875#endif
3876
3877 /*
3878 * Join paths with VMR3SetRuntimeErrorWorker.
3879 */
3880 int rc = vmR3SetRuntimeErrorCommonF(pVM, fFlags, pszErrorId, "%s", pszMessage);
3881 MMR3HeapFree(pszMessage);
3882 return rc;
3883}
3884
3885
3886/**
3887 * Worker for VMSetRuntimeErrorV for doing the job on EMT in ring-3.
3888 *
3889 * @returns VBox status code with modifications, see VMSetRuntimeErrorV.
3890 *
3891 * @param pVM The VM handle.
3892 * @param fFlags The error flags.
3893 * @param pszErrorId Error ID string.
3894 * @param pszFormat Format string.
3895 * @param pVa Pointer to the format arguments.
3896 *
3897 * @thread EMT
3898 */
3899DECLCALLBACK(int) vmR3SetRuntimeErrorV(PVM pVM, uint32_t fFlags, const char *pszErrorId, const char *pszFormat, va_list *pVa)
3900{
3901 /*
3902 * Make a copy of the message.
3903 */
3904 va_list va2;
3905 va_copy(va2, *pVa);
3906 vmSetRuntimeErrorCopy(pVM, fFlags, pszErrorId, pszFormat, va2);
3907 va_end(va2);
3908
3909 /*
3910 * Join paths with VMR3SetRuntimeErrorWorker.
3911 */
3912 return vmR3SetRuntimeErrorCommon(pVM, fFlags, pszErrorId, pszFormat, pVa);
3913}
3914
3915
3916/**
3917 * Gets the number of runtime errors raised via VMR3SetRuntimeError.
3918 *
3919 * This can be used avoid double error messages.
3920 *
3921 * @returns The runtime error count.
3922 * @param pVM The VM handle.
3923 */
3924VMMR3DECL(uint32_t) VMR3GetRuntimeErrorCount(PVM pVM)
3925{
3926 return pVM->pUVM->vm.s.cRuntimeErrors;
3927}
3928
3929
3930/**
3931 * Gets the ID virtual of the virtual CPU assoicated with the calling thread.
3932 *
3933 * @returns The CPU ID. NIL_VMCPUID if the thread isn't an EMT.
3934 *
3935 * @param pVM The VM handle.
3936 */
3937VMMR3DECL(RTCPUID) VMR3GetVMCPUId(PVM pVM)
3938{
3939 PUVMCPU pUVCpu = (PUVMCPU)RTTlsGet(pVM->pUVM->vm.s.idxTLS);
3940 return pUVCpu
3941 ? pUVCpu->idCpu
3942 : NIL_VMCPUID;
3943}
3944
3945
3946/**
3947 * Returns the native handle of the current EMT VMCPU thread.
3948 *
3949 * @returns Handle if this is an EMT thread; NIL_RTNATIVETHREAD otherwise
3950 * @param pVM The VM handle.
3951 * @thread EMT
3952 */
3953VMMR3DECL(RTNATIVETHREAD) VMR3GetVMCPUNativeThread(PVM pVM)
3954{
3955 PUVMCPU pUVCpu = (PUVMCPU)RTTlsGet(pVM->pUVM->vm.s.idxTLS);
3956
3957 if (!pUVCpu)
3958 return NIL_RTNATIVETHREAD;
3959
3960 return pUVCpu->vm.s.NativeThreadEMT;
3961}
3962
3963
3964/**
3965 * Returns the native handle of the current EMT VMCPU thread.
3966 *
3967 * @returns Handle if this is an EMT thread; NIL_RTNATIVETHREAD otherwise
3968 * @param pVM The VM handle.
3969 * @thread EMT
3970 */
3971VMMR3DECL(RTNATIVETHREAD) VMR3GetVMCPUNativeThreadU(PUVM pUVM)
3972{
3973 PUVMCPU pUVCpu = (PUVMCPU)RTTlsGet(pUVM->vm.s.idxTLS);
3974
3975 if (!pUVCpu)
3976 return NIL_RTNATIVETHREAD;
3977
3978 return pUVCpu->vm.s.NativeThreadEMT;
3979}
3980
3981
3982/**
3983 * Returns the handle of the current EMT VMCPU thread.
3984 *
3985 * @returns Handle if this is an EMT thread; NIL_RTNATIVETHREAD otherwise
3986 * @param pVM The VM handle.
3987 * @thread EMT
3988 */
3989VMMR3DECL(RTTHREAD) VMR3GetVMCPUThread(PVM pVM)
3990{
3991 PUVMCPU pUVCpu = (PUVMCPU)RTTlsGet(pVM->pUVM->vm.s.idxTLS);
3992
3993 if (!pUVCpu)
3994 return NIL_RTTHREAD;
3995
3996 return pUVCpu->vm.s.ThreadEMT;
3997}
3998
3999
4000/**
4001 * Returns the handle of the current EMT VMCPU thread.
4002 *
4003 * @returns Handle if this is an EMT thread; NIL_RTNATIVETHREAD otherwise
4004 * @param pVM The VM handle.
4005 * @thread EMT
4006 */
4007VMMR3DECL(RTTHREAD) VMR3GetVMCPUThreadU(PUVM pUVM)
4008{
4009 PUVMCPU pUVCpu = (PUVMCPU)RTTlsGet(pUVM->vm.s.idxTLS);
4010
4011 if (!pUVCpu)
4012 return NIL_RTTHREAD;
4013
4014 return pUVCpu->vm.s.ThreadEMT;
4015}
4016
4017
4018/**
4019 * Return the package and core id of a CPU.
4020 *
4021 * @returns VBOX status code.
4022 * @param pVM The VM to operate on.
4023 * @param idCpu Virtual CPU to get the ID from.
4024 * @param pidCpuCore Where to store the core ID of the virtual CPU.
4025 * @param pidCpuPackage Where to store the package ID of the virtual CPU.
4026 *
4027 */
4028VMMR3DECL(int) VMR3GetCpuCoreAndPackageIdFromCpuId(PVM pVM, VMCPUID idCpu, uint32_t *pidCpuCore, uint32_t *pidCpuPackage)
4029{
4030 if (idCpu >= pVM->cCpus)
4031 return VERR_INVALID_CPU_ID;
4032
4033#ifdef VBOX_WITH_MULTI_CORE
4034 *pidCpuCore = idCpu;
4035 *pidCpuPackage = 0;
4036#else
4037 *pidCpuCore = 0;
4038 *pidCpuPackage = idCpu;
4039#endif
4040
4041 return VINF_SUCCESS;
4042}
4043
4044
4045/**
4046 * Worker for VMR3HotUnplugCpu.
4047 *
4048 * @returns VINF_EM_WAIT_SPIP (strict status code).
4049 * @param pVM The VM handle.
4050 * @param idCpu The current CPU.
4051 */
4052static DECLCALLBACK(int) vmR3HotUnplugCpu(PVM pVM, VMCPUID idCpu)
4053{
4054 PVMCPU pVCpu = VMMGetCpuById(pVM, idCpu);
4055 VMCPU_ASSERT_EMT(pVCpu);
4056
4057 /*
4058 * Reset per CPU resources.
4059 *
4060 * Actually only needed for VT-x because the CPU seems to be still in some
4061 * paged mode and startup fails after a new hot plug event. SVM works fine
4062 * even without this.
4063 */
4064 Log(("vmR3HotUnplugCpu for VCPU %u\n", idCpu));
4065 PGMR3ResetUnpluggedCpu(pVM, pVCpu);
4066 PDMR3ResetCpu(pVCpu);
4067 TRPMR3ResetCpu(pVCpu);
4068 CPUMR3ResetCpu(pVCpu);
4069 EMR3ResetCpu(pVCpu);
4070 HWACCMR3ResetCpu(pVCpu);
4071 return VINF_EM_WAIT_SIPI;
4072}
4073
4074
4075/**
4076 * Hot-unplugs a CPU from the guest.
4077 *
4078 * @returns VBox status code.
4079 * @param pVM The VM to operate on.
4080 * @param idCpu Virtual CPU to perform the hot unplugging operation on.
4081 */
4082VMMR3DECL(int) VMR3HotUnplugCpu(PVM pVM, VMCPUID idCpu)
4083{
4084 AssertReturn(idCpu < pVM->cCpus, VERR_INVALID_CPU_ID);
4085
4086 /** @todo r=bird: Don't destroy the EMT, it'll break VMMR3EmtRendezvous and
4087 * broadcast requests. Just note down somewhere that the CPU is
4088 * offline and send it to SPIP wait. Maybe modify VMCPUSTATE and push
4089 * it out of the EM loops when offline. */
4090 return VMR3ReqCallNoWaitU(pVM->pUVM, idCpu, (PFNRT)vmR3HotUnplugCpu, 2, pVM, idCpu);
4091}
4092
4093
4094/**
4095 * Hot-plugs a CPU on the guest.
4096 *
4097 * @returns VBox status code.
4098 * @param pVM The VM to operate on.
4099 * @param idCpu Virtual CPU to perform the hot plugging operation on.
4100 */
4101VMMR3DECL(int) VMR3HotPlugCpu(PVM pVM, VMCPUID idCpu)
4102{
4103 AssertReturn(idCpu < pVM->cCpus, VERR_INVALID_CPU_ID);
4104
4105 /** @todo r-bird: Just mark it online and make sure it waits on SPIP. */
4106 return VINF_SUCCESS;
4107}
4108
4109
4110/**
4111 * Changes the VCPU priority.
4112 *
4113 * @returns VBox status code.
4114 * @param pVM The VM to operate on.
4115 * @param ulCpuPriority New CPU priority
4116 */
4117VMMR3DECL(int) VMR3SetCpuPriority(PVM pVM, unsigned ulCpuPriority)
4118{
4119 AssertReturn(ulCpuPriority > 0 && ulCpuPriority <= 100, VERR_INVALID_PARAMETER);
4120
4121 Log(("VMR3SetCpuPriority: new priority = %d\n", ulCpuPriority));
4122 /* Note: not called from EMT. */
4123 pVM->uCpuPriority = ulCpuPriority;
4124 return VINF_SUCCESS;
4125}
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