VirtualBox

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

Last change on this file since 82968 was 82968, checked in by vboxsync, 4 years ago

Copyright year updates by scm.

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

© 2023 Oracle
ContactPrivacy policyTerms of Use