VirtualBox

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

Last change on this file since 45530 was 45528, checked in by vboxsync, 12 years ago

VBOX_WITH_RAW_MODE changes.

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