VirtualBox

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

Last change on this file since 70951 was 70948, checked in by vboxsync, 7 years ago

VMM: Added a bMainExecutionEngine member to the VM structure for use instead of fHMEnabled and fNEMEnabled. Changed a lot of HMIsEnabled invocations to use the new macros VM_IS_RAW_MODE_ENABLED and VM_IS_HM_OR_NEM_ENABLED. Eliminated fHMEnabledFixed. Fixed inverted test for raw-mode debug register sanity checking. Some other minor cleanups.

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

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