VirtualBox

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

Last change on this file since 28688 was 28317, checked in by vboxsync, 15 years ago

RTMemPageFree + all users: Added size parameter to RTMemPageFree so we can avoid tracking structures when using mmap/munmap.

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