VirtualBox

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

最後變更 在這個檔案從52675是 52675,由 vboxsync 提交於 11 年 前

VMM/GIM: Fix circular dependency between PDM and GIM init. routines.

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

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette