VirtualBox

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

Last change on this file since 45728 was 45618, checked in by vboxsync, 12 years ago

Do HMR3Init first in vmR3InitRing3 so the other components can skip raw-mode bits during init.

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