VirtualBox

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

Last change on this file since 72544 was 72343, checked in by vboxsync, 7 years ago

VMM,ConsoleImpl2: NEM and 64-bit guests. Sync NXE state with PGM. bugref:9044

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

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