VirtualBox

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

Last change on this file since 45018 was 45006, checked in by vboxsync, 12 years ago

DBGF/DBGC: Fixing power off problems.

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