VirtualBox

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

Last change on this file since 39895 was 39402, checked in by vboxsync, 13 years ago

VMM: don't use generic IPE status codes, use specific ones. Part 1.

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

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