VirtualBox

source: vbox/trunk/src/VBox/VMM/VMMR0/GVMMR0.cpp@ 13742

Last change on this file since 13742 was 13742, checked in by vboxsync, 16 years ago

Some initial VM data restructuring.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id Revision
File size: 54.6 KB
Line 
1/* $Id: GVMMR0.cpp 13742 2008-11-03 12:19:40Z vboxsync $ */
2/** @file
3 * GVMM - Global VM Manager.
4 */
5
6/*
7 * Copyright (C) 2007 Sun Microsystems, Inc.
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 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
18 * Clara, CA 95054 USA or visit http://www.sun.com if you need
19 * additional information or have any questions.
20 */
21
22
23/** @page pg_gvmm GVMM - The Global VM Manager
24 *
25 * The Global VM Manager lives in ring-0. It's main function at the moment
26 * is to manage a list of all running VMs, keep a ring-0 only structure (GVM)
27 * for each of them, and assign them unique identifiers (so GMM can track
28 * page owners). The idea for the future is to add an idle priority kernel
29 * thread that can take care of tasks like page sharing.
30 *
31 * The GVMM will create a ring-0 object for each VM when it's registered,
32 * this is both for session cleanup purposes and for having a point where
33 * it's possible to implement usage polices later (in SUPR0ObjRegister).
34 */
35
36
37/*******************************************************************************
38* Header Files *
39*******************************************************************************/
40#define LOG_GROUP LOG_GROUP_GVMM
41#include <VBox/gvmm.h>
42#include "GVMMR0Internal.h"
43#include <VBox/gvm.h>
44#include <VBox/vm.h>
45#include <VBox/err.h>
46#include <iprt/alloc.h>
47#include <iprt/semaphore.h>
48#include <iprt/time.h>
49#include <VBox/log.h>
50#include <iprt/thread.h>
51#include <iprt/param.h>
52#include <iprt/string.h>
53#include <iprt/assert.h>
54#include <iprt/mem.h>
55#include <iprt/memobj.h>
56
57
58/*******************************************************************************
59* Structures and Typedefs *
60*******************************************************************************/
61
62/**
63 * Global VM handle.
64 */
65typedef struct GVMHANDLE
66{
67 /** The index of the next handle in the list (free or used). (0 is nil.) */
68 uint16_t volatile iNext;
69 /** Our own index / handle value. */
70 uint16_t iSelf;
71 /** The pointer to the ring-0 only (aka global) VM structure. */
72 PGVM pGVM;
73 /** The ring-0 mapping of the shared VM instance data. */
74 PVM pVM;
75 /** The virtual machine object. */
76 void *pvObj;
77 /** The session this VM is associated with. */
78 PSUPDRVSESSION pSession;
79 /** The ring-0 handle of the EMT thread.
80 * This is used for assertions and similar cases where we need to find the VM handle. */
81 RTNATIVETHREAD hEMT;
82} GVMHANDLE;
83/** Pointer to a global VM handle. */
84typedef GVMHANDLE *PGVMHANDLE;
85
86/**
87 * The GVMM instance data.
88 */
89typedef struct GVMM
90{
91 /** Eyecatcher / magic. */
92 uint32_t u32Magic;
93 /** The index of the head of the free handle chain. (0 is nil.) */
94 uint16_t volatile iFreeHead;
95 /** The index of the head of the active handle chain. (0 is nil.) */
96 uint16_t volatile iUsedHead;
97 /** The number of VMs. */
98 uint16_t volatile cVMs;
99// /** The number of halted EMT threads. */
100// uint16_t volatile cHaltedEMTs;
101 /** The lock used to serialize VM creation, destruction and associated events that
102 * isn't performance critical. Owners may acquire the list lock. */
103 RTSEMFASTMUTEX CreateDestroyLock;
104 /** The lock used to serialize used list updates and accesses.
105 * This indirectly includes scheduling since the scheduler will have to walk the
106 * used list to examin running VMs. Owners may not acquire any other locks. */
107 RTSEMFASTMUTEX UsedLock;
108 /** The handle array.
109 * The size of this array defines the maximum number of currently running VMs.
110 * The first entry is unused as it represents the NIL handle. */
111 GVMHANDLE aHandles[128];
112
113 /** @gcfgm{/GVMM/cVMsMeansCompany, 32-bit, 0, UINT32_MAX, 1}
114 * The number of VMs that means we no longer consider ourselves alone on a CPU/Core.
115 */
116 uint32_t cVMsMeansCompany;
117 /** @gcfgm{/GVMM/MinSleepAlone,32-bit, 0, 100000000, 750000, ns}
118 * The minimum sleep time for when we're alone, in nano seconds.
119 */
120 uint32_t nsMinSleepAlone;
121 /** @gcfgm{/GVMM/MinSleepCompany,32-bit,0, 100000000, 15000, ns}
122 * The minimum sleep time for when we've got company, in nano seconds.
123 */
124 uint32_t nsMinSleepCompany;
125 /** @gcfgm{/GVMM/EarlyWakeUp1, 32-bit, 0, 100000000, 25000, ns}
126 * The limit for the first round of early wakeups, given in nano seconds.
127 */
128 uint32_t nsEarlyWakeUp1;
129 /** @gcfgm{/GVMM/EarlyWakeUp2, 32-bit, 0, 100000000, 50000, ns}
130 * The limit for the second round of early wakeups, given in nano seconds.
131 */
132 uint32_t nsEarlyWakeUp2;
133} GVMM;
134/** Pointer to the GVMM instance data. */
135typedef GVMM *PGVMM;
136
137/** The GVMM::u32Magic value (Charlie Haden). */
138#define GVMM_MAGIC 0x19370806
139
140
141
142/*******************************************************************************
143* Global Variables *
144*******************************************************************************/
145/** Pointer to the GVMM instance data.
146 * (Just my general dislike for global variables.) */
147static PGVMM g_pGVMM = NULL;
148
149/** Macro for obtaining and validating the g_pGVMM pointer.
150 * On failure it will return from the invoking function with the specified return value.
151 *
152 * @param pGVMM The name of the pGVMM variable.
153 * @param rc The return value on failure. Use VERR_INTERNAL_ERROR for
154 * VBox status codes.
155 */
156#define GVMM_GET_VALID_INSTANCE(pGVMM, rc) \
157 do { \
158 (pGVMM) = g_pGVMM;\
159 AssertPtrReturn((pGVMM), (rc)); \
160 AssertMsgReturn((pGVMM)->u32Magic == GVMM_MAGIC, ("%p - %#x\n", (pGVMM), (pGVMM)->u32Magic), (rc)); \
161 } while (0)
162
163/** Macro for obtaining and validating the g_pGVMM pointer, void function variant.
164 * On failure it will return from the invoking function.
165 *
166 * @param pGVMM The name of the pGVMM variable.
167 */
168#define GVMM_GET_VALID_INSTANCE_VOID(pGVMM) \
169 do { \
170 (pGVMM) = g_pGVMM;\
171 AssertPtrReturnVoid((pGVMM)); \
172 AssertMsgReturnVoid((pGVMM)->u32Magic == GVMM_MAGIC, ("%p - %#x\n", (pGVMM), (pGVMM)->u32Magic)); \
173 } while (0)
174
175
176/*******************************************************************************
177* Internal Functions *
178*******************************************************************************/
179static void gvmmR0InitPerVMData(PGVM pGVM);
180static DECLCALLBACK(void) gvmmR0HandleObjDestructor(void *pvObj, void *pvGVMM, void *pvHandle);
181static int gvmmR0ByVM(PVM pVM, PGVM *ppGVM, PGVMM *ppGVMM, bool fTakeUsedLock);
182static int gvmmR0ByVMAndEMT(PVM pVM, PGVM *ppGVM, PGVMM *ppGVMM);
183
184
185/**
186 * Initializes the GVMM.
187 *
188 * This is called while owninng the loader sempahore (see supdrvIOCtl_LdrLoad()).
189 *
190 * @returns VBox status code.
191 */
192GVMMR0DECL(int) GVMMR0Init(void)
193{
194 LogFlow(("GVMMR0Init:\n"));
195
196 /*
197 * Allocate and initialize the instance data.
198 */
199 PGVMM pGVMM = (PGVMM)RTMemAllocZ(sizeof(*pGVMM));
200 if (!pGVMM)
201 return VERR_NO_MEMORY;
202 int rc = RTSemFastMutexCreate(&pGVMM->CreateDestroyLock);
203 if (RT_SUCCESS(rc))
204 {
205 rc = RTSemFastMutexCreate(&pGVMM->UsedLock);
206 if (RT_SUCCESS(rc))
207 {
208 pGVMM->u32Magic = GVMM_MAGIC;
209 pGVMM->iUsedHead = 0;
210 pGVMM->iFreeHead = 1;
211
212 /* the nil handle */
213 pGVMM->aHandles[0].iSelf = 0;
214 pGVMM->aHandles[0].iNext = 0;
215
216 /* the tail */
217 unsigned i = RT_ELEMENTS(pGVMM->aHandles) - 1;
218 pGVMM->aHandles[i].iSelf = i;
219 pGVMM->aHandles[i].iNext = 0; /* nil */
220
221 /* the rest */
222 while (i-- > 1)
223 {
224 pGVMM->aHandles[i].iSelf = i;
225 pGVMM->aHandles[i].iNext = i + 1;
226 }
227
228 /* The default configuration values. */
229 pGVMM->cVMsMeansCompany = 1; /** @todo should be adjusted to relative to the cpu count or something... */
230 pGVMM->nsMinSleepAlone = 750000 /* ns (0.750 ms) */; /** @todo this should be adjusted to be 75% (or something) of the scheduler granularity... */
231 pGVMM->nsMinSleepCompany = 15000 /* ns (0.015 ms) */;
232 pGVMM->nsEarlyWakeUp1 = 25000 /* ns (0.025 ms) */;
233 pGVMM->nsEarlyWakeUp2 = 50000 /* ns (0.050 ms) */;
234
235 g_pGVMM = pGVMM;
236 LogFlow(("GVMMR0Init: pGVMM=%p\n", pGVMM));
237 return VINF_SUCCESS;
238 }
239
240 RTSemFastMutexDestroy(pGVMM->CreateDestroyLock);
241 }
242
243 RTMemFree(pGVMM);
244 return rc;
245}
246
247
248/**
249 * Terminates the GVM.
250 *
251 * This is called while owning the loader semaphore (see supdrvLdrFree()).
252 * And unless something is wrong, there should be absolutely no VMs
253 * registered at this point.
254 */
255GVMMR0DECL(void) GVMMR0Term(void)
256{
257 LogFlow(("GVMMR0Term:\n"));
258
259 PGVMM pGVMM = g_pGVMM;
260 g_pGVMM = NULL;
261 if (RT_UNLIKELY(!VALID_PTR(pGVMM)))
262 {
263 SUPR0Printf("GVMMR0Term: pGVMM=%p\n", pGVMM);
264 return;
265 }
266
267 pGVMM->u32Magic++;
268
269 RTSemFastMutexDestroy(pGVMM->UsedLock);
270 pGVMM->UsedLock = NIL_RTSEMFASTMUTEX;
271 RTSemFastMutexDestroy(pGVMM->CreateDestroyLock);
272 pGVMM->CreateDestroyLock = NIL_RTSEMFASTMUTEX;
273
274 pGVMM->iFreeHead = 0;
275 if (pGVMM->iUsedHead)
276 {
277 SUPR0Printf("GVMMR0Term: iUsedHead=%#x! (cVMs=%#x)\n", pGVMM->iUsedHead, pGVMM->cVMs);
278 pGVMM->iUsedHead = 0;
279 }
280
281 RTMemFree(pGVMM);
282}
283
284
285/**
286 * A quick hack for setting global config values.
287 *
288 * @returns VBox status code.
289 *
290 * @param pSession The session handle. Used for authentication.
291 * @param pszName The variable name.
292 * @param u64Value The new value.
293 */
294GVMMR0DECL(int) GVMMR0SetConfig(PSUPDRVSESSION pSession, const char *pszName, uint64_t u64Value)
295{
296 /*
297 * Validate input.
298 */
299 PGVMM pGVMM;
300 GVMM_GET_VALID_INSTANCE(pGVMM, VERR_INTERNAL_ERROR);
301 AssertPtrReturn(pSession, VERR_INVALID_HANDLE);
302 AssertPtrReturn(pszName, VERR_INVALID_POINTER);
303
304 /*
305 * String switch time!
306 */
307 if (strncmp(pszName, "/GVMM/", sizeof("/GVMM/") - 1))
308 return VERR_CFGM_VALUE_NOT_FOUND; /* borrow status codes from CFGM... */
309 int rc = VINF_SUCCESS;
310 pszName += sizeof("/GVMM/") - 1;
311 if (!strcmp(pszName, "cVMsMeansCompany"))
312 {
313 if (u64Value <= UINT32_MAX)
314 pGVMM->cVMsMeansCompany = u64Value;
315 else
316 rc = VERR_OUT_OF_RANGE;
317 }
318 else if (!strcmp(pszName, "MinSleepAlone"))
319 {
320 if (u64Value <= 100000000)
321 pGVMM->nsMinSleepAlone = u64Value;
322 else
323 rc = VERR_OUT_OF_RANGE;
324 }
325 else if (!strcmp(pszName, "MinSleepCompany"))
326 {
327 if (u64Value <= 100000000)
328 pGVMM->nsMinSleepCompany = u64Value;
329 else
330 rc = VERR_OUT_OF_RANGE;
331 }
332 else if (!strcmp(pszName, "EarlyWakeUp1"))
333 {
334 if (u64Value <= 100000000)
335 pGVMM->nsEarlyWakeUp1 = u64Value;
336 else
337 rc = VERR_OUT_OF_RANGE;
338 }
339 else if (!strcmp(pszName, "EarlyWakeUp2"))
340 {
341 if (u64Value <= 100000000)
342 pGVMM->nsEarlyWakeUp2 = u64Value;
343 else
344 rc = VERR_OUT_OF_RANGE;
345 }
346 else
347 rc = VERR_CFGM_VALUE_NOT_FOUND;
348 return rc;
349}
350
351
352/**
353 * A quick hack for getting global config values.
354 *
355 * @returns VBox status code.
356 *
357 * @param pSession The session handle. Used for authentication.
358 * @param pszName The variable name.
359 * @param u64Value The new value.
360 */
361GVMMR0DECL(int) GVMMR0QueryConfig(PSUPDRVSESSION pSession, const char *pszName, uint64_t *pu64Value)
362{
363 /*
364 * Validate input.
365 */
366 PGVMM pGVMM;
367 GVMM_GET_VALID_INSTANCE(pGVMM, VERR_INTERNAL_ERROR);
368 AssertPtrReturn(pSession, VERR_INVALID_HANDLE);
369 AssertPtrReturn(pszName, VERR_INVALID_POINTER);
370 AssertPtrReturn(pu64Value, VERR_INVALID_POINTER);
371
372 /*
373 * String switch time!
374 */
375 if (strncmp(pszName, "/GVMM/", sizeof("/GVMM/") - 1))
376 return VERR_CFGM_VALUE_NOT_FOUND; /* borrow status codes from CFGM... */
377 int rc = VINF_SUCCESS;
378 pszName += sizeof("/GVMM/") - 1;
379 if (!strcmp(pszName, "cVMsMeansCompany"))
380 *pu64Value = pGVMM->cVMsMeansCompany;
381 else if (!strcmp(pszName, "MinSleepAlone"))
382 *pu64Value = pGVMM->nsMinSleepAlone;
383 else if (!strcmp(pszName, "MinSleepCompany"))
384 *pu64Value = pGVMM->nsMinSleepCompany;
385 else if (!strcmp(pszName, "EarlyWakeUp1"))
386 *pu64Value = pGVMM->nsEarlyWakeUp1;
387 else if (!strcmp(pszName, "EarlyWakeUp2"))
388 *pu64Value = pGVMM->nsEarlyWakeUp2;
389 else
390 rc = VERR_CFGM_VALUE_NOT_FOUND;
391 return rc;
392}
393
394
395/**
396 * Try acquire the 'used' lock.
397 *
398 * @returns IPRT status code, see RTSemFastMutexRequest.
399 * @param pGVMM The GVMM instance data.
400 */
401DECLINLINE(int) gvmmR0UsedLock(PGVMM pGVMM)
402{
403 LogFlow(("++gvmmR0UsedLock(%p)\n", pGVMM));
404 int rc = RTSemFastMutexRequest(pGVMM->UsedLock);
405 LogFlow(("gvmmR0UsedLock(%p)->%Rrc\n", pGVMM, rc));
406 return rc;
407}
408
409
410/**
411 * Release the 'used' lock.
412 *
413 * @returns IPRT status code, see RTSemFastMutexRelease.
414 * @param pGVMM The GVMM instance data.
415 */
416DECLINLINE(int) gvmmR0UsedUnlock(PGVMM pGVMM)
417{
418 LogFlow(("--gvmmR0UsedUnlock(%p)\n", pGVMM));
419 int rc = RTSemFastMutexRelease(pGVMM->UsedLock);
420 AssertRC(rc);
421 return rc;
422}
423
424
425/**
426 * Try acquire the 'create & destroy' lock.
427 *
428 * @returns IPRT status code, see RTSemFastMutexRequest.
429 * @param pGVMM The GVMM instance data.
430 */
431DECLINLINE(int) gvmmR0CreateDestroyLock(PGVMM pGVMM)
432{
433 LogFlow(("++gvmmR0CreateDestroyLock(%p)\n", pGVMM));
434 int rc = RTSemFastMutexRequest(pGVMM->CreateDestroyLock);
435 LogFlow(("gvmmR0CreateDestroyLock(%p)->%Rrc\n", pGVMM, rc));
436 return rc;
437}
438
439
440/**
441 * Release the 'create & destroy' lock.
442 *
443 * @returns IPRT status code, see RTSemFastMutexRequest.
444 * @param pGVMM The GVMM instance data.
445 */
446DECLINLINE(int) gvmmR0CreateDestroyUnlock(PGVMM pGVMM)
447{
448 LogFlow(("--gvmmR0CreateDestroyUnlock(%p)\n", pGVMM));
449 int rc = RTSemFastMutexRelease(pGVMM->CreateDestroyLock);
450 AssertRC(rc);
451 return rc;
452}
453
454
455/**
456 * Request wrapper for the GVMMR0CreateVM API.
457 *
458 * @returns VBox status code.
459 * @param pReq The request buffer.
460 */
461GVMMR0DECL(int) GVMMR0CreateVMReq(PGVMMCREATEVMREQ pReq)
462{
463 /*
464 * Validate the request.
465 */
466 if (!VALID_PTR(pReq))
467 return VERR_INVALID_POINTER;
468 if (pReq->Hdr.cbReq != sizeof(*pReq))
469 return VERR_INVALID_PARAMETER;
470 if (!VALID_PTR(pReq->pSession))
471 return VERR_INVALID_POINTER;
472 if ( pReq->cCPUs == 0
473 || pReq->cCPUs > VMCPU_MAX_CPU_COUNT)
474 return VERR_INVALID_PARAMETER;
475
476 /*
477 * Execute it.
478 */
479 PVM pVM;
480 pReq->pVMR0 = NULL;
481 pReq->pVMR3 = NIL_RTR3PTR;
482 int rc = GVMMR0CreateVM(pReq->pSession, pReq->cCPUs, &pVM);
483 if (RT_SUCCESS(rc))
484 {
485 pReq->pVMR0 = pVM;
486 pReq->pVMR3 = pVM->pVMR3;
487 }
488 return rc;
489}
490
491
492/**
493 * Allocates the VM structure and registers it with GVM.
494 *
495 * The caller will become the VM owner and there by the EMT.
496 *
497 * @returns VBox status code.
498 * @param pSession The support driver session.
499 * @param cCPUs Number of virtual CPUs for the new VM.
500 * @param ppVM Where to store the pointer to the VM structure.
501 *
502 * @thread EMT.
503 */
504GVMMR0DECL(int) GVMMR0CreateVM(PSUPDRVSESSION pSession, uint32_t cCPUs, PVM *ppVM)
505{
506 LogFlow(("GVMMR0CreateVM: pSession=%p\n", pSession));
507 PGVMM pGVMM;
508 GVMM_GET_VALID_INSTANCE(pGVMM, VERR_INTERNAL_ERROR);
509
510 AssertPtrReturn(ppVM, VERR_INVALID_POINTER);
511 *ppVM = NULL;
512
513 RTNATIVETHREAD hEMT = RTThreadNativeSelf();
514 AssertReturn(hEMT != NIL_RTNATIVETHREAD, VERR_INTERNAL_ERROR);
515
516 /*
517 * The whole allocation process is protected by the lock.
518 */
519 int rc = gvmmR0CreateDestroyLock(pGVMM);
520 AssertRCReturn(rc, rc);
521
522 /*
523 * Allocate a handle first so we don't waste resources unnecessarily.
524 */
525 uint16_t iHandle = pGVMM->iFreeHead;
526 if (iHandle)
527 {
528 PGVMHANDLE pHandle = &pGVMM->aHandles[iHandle];
529
530 /* consistency checks, a bit paranoid as always. */
531 if ( !pHandle->pVM
532 && !pHandle->pGVM
533 && !pHandle->pvObj
534 && pHandle->iSelf == iHandle)
535 {
536 pHandle->pvObj = SUPR0ObjRegister(pSession, SUPDRVOBJTYPE_VM, gvmmR0HandleObjDestructor, pGVMM, pHandle);
537 if (pHandle->pvObj)
538 {
539 /*
540 * Move the handle from the free to used list and perform permission checks.
541 */
542 rc = gvmmR0UsedLock(pGVMM);
543 AssertRC(rc);
544
545 pGVMM->iFreeHead = pHandle->iNext;
546 pHandle->iNext = pGVMM->iUsedHead;
547 pGVMM->iUsedHead = iHandle;
548 pGVMM->cVMs++;
549
550 pHandle->pVM = NULL;
551 pHandle->pGVM = NULL;
552 pHandle->pSession = pSession;
553 pHandle->hEMT = NIL_RTNATIVETHREAD;
554
555 gvmmR0UsedUnlock(pGVMM);
556
557 rc = SUPR0ObjVerifyAccess(pHandle->pvObj, pSession, NULL);
558 if (RT_SUCCESS(rc))
559 {
560 /*
561 * Allocate the global VM structure (GVM) and initialize it.
562 */
563 PGVM pGVM = (PGVM)RTMemAllocZ(sizeof(*pGVM));
564 if (pGVM)
565 {
566 pGVM->u32Magic = GVM_MAGIC;
567 pGVM->hSelf = iHandle;
568 pGVM->hEMT = NIL_RTNATIVETHREAD;
569 pGVM->pVM = NULL;
570
571 gvmmR0InitPerVMData(pGVM);
572 /* GMMR0InitPerVMData(pGVM); - later */
573
574 /*
575 * Allocate the shared VM structure and associated page array.
576 */
577 const size_t cPages = RT_ALIGN(sizeof(VM) + sizeof(VMCPU) * (cCPUs - 1), PAGE_SIZE) >> PAGE_SHIFT;
578 rc = RTR0MemObjAllocLow(&pGVM->gvmm.s.VMMemObj, cPages << PAGE_SHIFT, false /* fExecutable */);
579 if (RT_SUCCESS(rc))
580 {
581 PVM pVM = (PVM)RTR0MemObjAddress(pGVM->gvmm.s.VMMemObj); AssertPtr(pVM);
582 memset(pVM, 0, cPages << PAGE_SHIFT);
583 pVM->enmVMState = VMSTATE_CREATING;
584 pVM->pVMR0 = pVM;
585 pVM->pSession = pSession;
586 pVM->hSelf = iHandle;
587
588 rc = RTR0MemObjAllocPage(&pGVM->gvmm.s.VMPagesMemObj, cPages * sizeof(SUPPAGE), false /* fExecutable */);
589 if (RT_SUCCESS(rc))
590 {
591 PSUPPAGE paPages = (PSUPPAGE)RTR0MemObjAddress(pGVM->gvmm.s.VMPagesMemObj); AssertPtr(paPages);
592 for (size_t iPage = 0; iPage < cPages; iPage++)
593 {
594 paPages[iPage].uReserved = 0;
595 paPages[iPage].Phys = RTR0MemObjGetPagePhysAddr(pGVM->gvmm.s.VMMemObj, iPage);
596 Assert(paPages[iPage].Phys != NIL_RTHCPHYS);
597 }
598
599 /*
600 * Map them into ring-3.
601 */
602 rc = RTR0MemObjMapUser(&pGVM->gvmm.s.VMMapObj, pGVM->gvmm.s.VMMemObj, (RTR3PTR)-1, 0,
603 RTMEM_PROT_READ | RTMEM_PROT_WRITE, NIL_RTR0PROCESS);
604 if (RT_SUCCESS(rc))
605 {
606 pVM->pVMR3 = RTR0MemObjAddressR3(pGVM->gvmm.s.VMMapObj);
607 AssertPtr((void *)pVM->pVMR3);
608
609 /** @todo SMP - need to get the cpu count and initialize all the VM pointers. */
610 pVM->aCpus[0].pVMR0 = pVM;
611 pVM->aCpus[0].pVMR3 = pVM->pVMR3;
612
613 rc = RTR0MemObjMapUser(&pGVM->gvmm.s.VMPagesMapObj, pGVM->gvmm.s.VMPagesMemObj, (RTR3PTR)-1, 0,
614 RTMEM_PROT_READ | RTMEM_PROT_WRITE, NIL_RTR0PROCESS);
615 if (RT_SUCCESS(rc))
616 {
617 pVM->paVMPagesR3 = RTR0MemObjAddressR3(pGVM->gvmm.s.VMPagesMapObj);
618 AssertPtr((void *)pVM->paVMPagesR3);
619
620 /* complete the handle - take the UsedLock sem just to be careful. */
621 rc = gvmmR0UsedLock(pGVMM);
622 AssertRC(rc);
623
624 pHandle->pVM = pVM;
625 pHandle->pGVM = pGVM;
626 pHandle->hEMT = hEMT;
627 pGVM->pVM = pVM;
628 pGVM->hEMT = hEMT;
629
630 gvmmR0UsedUnlock(pGVMM);
631 gvmmR0CreateDestroyUnlock(pGVMM);
632
633 *ppVM = pVM;
634 Log(("GVMMR0CreateVM: pVM=%p pVMR3=%p pGVM=%p hGVM=%d\n", pVM, pVM->pVMR3, pGVM, iHandle));
635 return VINF_SUCCESS;
636 }
637
638 RTR0MemObjFree(pGVM->gvmm.s.VMMapObj, false /* fFreeMappings */);
639 pGVM->gvmm.s.VMMapObj = NIL_RTR0MEMOBJ;
640 }
641 RTR0MemObjFree(pGVM->gvmm.s.VMPagesMemObj, false /* fFreeMappings */);
642 pGVM->gvmm.s.VMPagesMemObj = NIL_RTR0MEMOBJ;
643 }
644 RTR0MemObjFree(pGVM->gvmm.s.VMMemObj, false /* fFreeMappings */);
645 pGVM->gvmm.s.VMMemObj = NIL_RTR0MEMOBJ;
646 }
647 }
648 }
649 /* else: The user wasn't permitted to create this VM. */
650
651 /*
652 * The handle will be freed by gvmmR0HandleObjDestructor as we release the
653 * object reference here. A little extra mess because of non-recursive lock.
654 */
655 void *pvObj = pHandle->pvObj;
656 pHandle->pvObj = NULL;
657 gvmmR0CreateDestroyUnlock(pGVMM);
658
659 SUPR0ObjRelease(pvObj, pSession);
660
661 SUPR0Printf("GVMMR0CreateVM: failed, rc=%d\n", rc);
662 return rc;
663 }
664
665 rc = VERR_NO_MEMORY;
666 }
667 else
668 rc = VERR_INTERNAL_ERROR;
669 }
670 else
671 rc = VERR_GVM_TOO_MANY_VMS;
672
673 gvmmR0CreateDestroyUnlock(pGVMM);
674 return rc;
675}
676
677
678/**
679 * Initializes the per VM data belonging to GVMM.
680 *
681 * @param pGVM Pointer to the global VM structure.
682 */
683static void gvmmR0InitPerVMData(PGVM pGVM)
684{
685 AssertCompile(RT_SIZEOFMEMB(GVM,gvmm.s) <= RT_SIZEOFMEMB(GVM,gvmm.padding));
686 Assert(RT_SIZEOFMEMB(GVM,gvmm.s) <= RT_SIZEOFMEMB(GVM,gvmm.padding));
687 pGVM->gvmm.s.VMMemObj = NIL_RTR0MEMOBJ;
688 pGVM->gvmm.s.VMMapObj = NIL_RTR0MEMOBJ;
689 pGVM->gvmm.s.VMPagesMemObj = NIL_RTR0MEMOBJ;
690 pGVM->gvmm.s.VMPagesMapObj = NIL_RTR0MEMOBJ;
691 pGVM->gvmm.s.HaltEventMulti = NIL_RTSEMEVENTMULTI;
692}
693
694
695/**
696 * Does the VM initialization.
697 *
698 * @returns VBox status code.
699 * @param pVM Pointer to the shared VM structure.
700 */
701GVMMR0DECL(int) GVMMR0InitVM(PVM pVM)
702{
703 LogFlow(("GVMMR0InitVM: pVM=%p\n", pVM));
704
705 /*
706 * Validate the VM structure, state and handle.
707 */
708 PGVM pGVM;
709 PGVMM pGVMM;
710 int rc = gvmmR0ByVMAndEMT(pVM, &pGVM, &pGVMM);
711 if (RT_SUCCESS(rc))
712 {
713 if (pGVM->gvmm.s.HaltEventMulti == NIL_RTSEMEVENTMULTI)
714 {
715 rc = RTSemEventMultiCreate(&pGVM->gvmm.s.HaltEventMulti);
716 if (RT_FAILURE(rc))
717 pGVM->gvmm.s.HaltEventMulti = NIL_RTSEMEVENTMULTI;
718 }
719 else
720 rc = VERR_WRONG_ORDER;
721 }
722
723 LogFlow(("GVMMR0InitVM: returns %Rrc\n", rc));
724 return rc;
725}
726
727
728/**
729 * Destroys the VM, freeing all associated resources (the ring-0 ones anyway).
730 *
731 * This is call from the vmR3DestroyFinalBit and from a error path in VMR3Create,
732 * and the caller is not the EMT thread, unfortunately. For security reasons, it
733 * would've been nice if the caller was actually the EMT thread or that we somehow
734 * could've associated the calling thread with the VM up front.
735 *
736 * @returns VBox status code.
737 * @param pVM Where to store the pointer to the VM structure.
738 *
739 * @thread EMT if it's associated with the VM, otherwise any thread.
740 */
741GVMMR0DECL(int) GVMMR0DestroyVM(PVM pVM)
742{
743 LogFlow(("GVMMR0DestroyVM: pVM=%p\n", pVM));
744 PGVMM pGVMM;
745 GVMM_GET_VALID_INSTANCE(pGVMM, VERR_INTERNAL_ERROR);
746
747
748 /*
749 * Validate the VM structure, state and caller.
750 */
751 AssertPtrReturn(pVM, VERR_INVALID_POINTER);
752 AssertReturn(!((uintptr_t)pVM & PAGE_OFFSET_MASK), VERR_INVALID_POINTER);
753 AssertMsgReturn(pVM->enmVMState >= VMSTATE_CREATING && pVM->enmVMState <= VMSTATE_TERMINATED, ("%d\n", pVM->enmVMState), VERR_WRONG_ORDER);
754
755 uint32_t hGVM = pVM->hSelf;
756 AssertReturn(hGVM != NIL_GVM_HANDLE, VERR_INVALID_HANDLE);
757 AssertReturn(hGVM < RT_ELEMENTS(pGVMM->aHandles), VERR_INVALID_HANDLE);
758
759 PGVMHANDLE pHandle = &pGVMM->aHandles[hGVM];
760 AssertReturn(pHandle->pVM == pVM, VERR_NOT_OWNER);
761
762 RTNATIVETHREAD hSelf = RTThreadNativeSelf();
763 AssertReturn(pHandle->hEMT == hSelf || pHandle->hEMT == NIL_RTNATIVETHREAD, VERR_NOT_OWNER);
764
765 /*
766 * Lookup the handle and destroy the object.
767 * Since the lock isn't recursive and we'll have to leave it before dereferencing the
768 * object, we take some precautions against racing callers just in case...
769 */
770 int rc = gvmmR0CreateDestroyLock(pGVMM);
771 AssertRC(rc);
772
773 /* be careful here because we might theoretically be racing someone else cleaning up. */
774 if ( pHandle->pVM == pVM
775 && ( pHandle->hEMT == hSelf
776 || pHandle->hEMT == NIL_RTNATIVETHREAD)
777 && VALID_PTR(pHandle->pvObj)
778 && VALID_PTR(pHandle->pSession)
779 && VALID_PTR(pHandle->pGVM)
780 && pHandle->pGVM->u32Magic == GVM_MAGIC)
781 {
782 void *pvObj = pHandle->pvObj;
783 pHandle->pvObj = NULL;
784 gvmmR0CreateDestroyUnlock(pGVMM);
785
786 SUPR0ObjRelease(pvObj, pHandle->pSession);
787 }
788 else
789 {
790 SUPR0Printf("GVMMR0DestroyVM: pHandle=%p:{.pVM=%p, hEMT=%p, .pvObj=%p} pVM=%p hSelf=%p\n",
791 pHandle, pHandle->pVM, pHandle->hEMT, pHandle->pvObj, pVM, hSelf);
792 gvmmR0CreateDestroyUnlock(pGVMM);
793 rc = VERR_INTERNAL_ERROR;
794 }
795
796 return rc;
797}
798
799
800/**
801 * Handle destructor.
802 *
803 * @param pvGVMM The GVM instance pointer.
804 * @param pvHandle The handle pointer.
805 */
806static DECLCALLBACK(void) gvmmR0HandleObjDestructor(void *pvObj, void *pvGVMM, void *pvHandle)
807{
808 LogFlow(("gvmmR0HandleObjDestructor: %p %p %p\n", pvObj, pvGVMM, pvHandle));
809
810 /*
811 * Some quick, paranoid, input validation.
812 */
813 PGVMHANDLE pHandle = (PGVMHANDLE)pvHandle;
814 AssertPtr(pHandle);
815 PGVMM pGVMM = (PGVMM)pvGVMM;
816 Assert(pGVMM == g_pGVMM);
817 const uint16_t iHandle = pHandle - &pGVMM->aHandles[0];
818 if ( !iHandle
819 || iHandle >= RT_ELEMENTS(pGVMM->aHandles)
820 || iHandle != pHandle->iSelf)
821 {
822 SUPR0Printf("GVM: handle %d is out of range or corrupt (iSelf=%d)!\n", iHandle, pHandle->iSelf);
823 return;
824 }
825
826 int rc = gvmmR0CreateDestroyLock(pGVMM);
827 AssertRC(rc);
828 rc = gvmmR0UsedLock(pGVMM);
829 AssertRC(rc);
830
831 /*
832 * This is a tad slow but a doubly linked list is too much hazzle.
833 */
834 if (RT_UNLIKELY(pHandle->iNext >= RT_ELEMENTS(pGVMM->aHandles)))
835 {
836 SUPR0Printf("GVM: used list index %d is out of range!\n", pHandle->iNext);
837 gvmmR0UsedUnlock(pGVMM);
838 gvmmR0CreateDestroyUnlock(pGVMM);
839 return;
840 }
841
842 if (pGVMM->iUsedHead == iHandle)
843 pGVMM->iUsedHead = pHandle->iNext;
844 else
845 {
846 uint16_t iPrev = pGVMM->iUsedHead;
847 int c = RT_ELEMENTS(pGVMM->aHandles) + 2;
848 while (iPrev)
849 {
850 if (RT_UNLIKELY(iPrev >= RT_ELEMENTS(pGVMM->aHandles)))
851 {
852 SUPR0Printf("GVM: used list index %d is out of range!\n");
853 gvmmR0UsedUnlock(pGVMM);
854 gvmmR0CreateDestroyUnlock(pGVMM);
855 return;
856 }
857 if (RT_UNLIKELY(c-- <= 0))
858 {
859 iPrev = 0;
860 break;
861 }
862
863 if (pGVMM->aHandles[iPrev].iNext == iHandle)
864 break;
865 iPrev = pGVMM->aHandles[iPrev].iNext;
866 }
867 if (!iPrev)
868 {
869 SUPR0Printf("GVM: can't find the handle previous previous of %d!\n", pHandle->iSelf);
870 gvmmR0UsedUnlock(pGVMM);
871 gvmmR0CreateDestroyUnlock(pGVMM);
872 return;
873 }
874
875 Assert(pGVMM->aHandles[iPrev].iNext == iHandle);
876 pGVMM->aHandles[iPrev].iNext = pHandle->iNext;
877 }
878 pHandle->iNext = 0;
879 pGVMM->cVMs--;
880
881 gvmmR0UsedUnlock(pGVMM);
882
883 /*
884 * Do the global cleanup round.
885 */
886 PGVM pGVM = pHandle->pGVM;
887 if ( VALID_PTR(pGVM)
888 && pGVM->u32Magic == GVM_MAGIC)
889 {
890 /// @todo GMMR0CleanupVM(pGVM);
891
892 /*
893 * Do the GVMM cleanup - must be done last.
894 */
895 /* The VM and VM pages mappings/allocations. */
896 if (pGVM->gvmm.s.VMPagesMapObj != NIL_RTR0MEMOBJ)
897 {
898 rc = RTR0MemObjFree(pGVM->gvmm.s.VMPagesMapObj, false /* fFreeMappings */); AssertRC(rc);
899 pGVM->gvmm.s.VMPagesMapObj = NIL_RTR0MEMOBJ;
900 }
901
902 if (pGVM->gvmm.s.VMMapObj != NIL_RTR0MEMOBJ)
903 {
904 rc = RTR0MemObjFree(pGVM->gvmm.s.VMMapObj, false /* fFreeMappings */); AssertRC(rc);
905 pGVM->gvmm.s.VMMapObj = NIL_RTR0MEMOBJ;
906 }
907
908 if (pGVM->gvmm.s.VMPagesMemObj != NIL_RTR0MEMOBJ)
909 {
910 rc = RTR0MemObjFree(pGVM->gvmm.s.VMPagesMemObj, false /* fFreeMappings */); AssertRC(rc);
911 pGVM->gvmm.s.VMPagesMemObj = NIL_RTR0MEMOBJ;
912 }
913
914 if (pGVM->gvmm.s.VMMemObj != NIL_RTR0MEMOBJ)
915 {
916 rc = RTR0MemObjFree(pGVM->gvmm.s.VMMemObj, false /* fFreeMappings */); AssertRC(rc);
917 pGVM->gvmm.s.VMMemObj = NIL_RTR0MEMOBJ;
918 }
919
920 if (pGVM->gvmm.s.HaltEventMulti != NIL_RTSEMEVENTMULTI)
921 {
922 rc = RTSemEventMultiDestroy(pGVM->gvmm.s.HaltEventMulti); AssertRC(rc);
923 pGVM->gvmm.s.HaltEventMulti = NIL_RTSEMEVENTMULTI;
924 }
925
926 /* the GVM structure itself. */
927 pGVM->u32Magic++;
928 RTMemFree(pGVM);
929 }
930 /* else: GVMMR0CreateVM cleanup. */
931
932 /*
933 * Free the handle.
934 * Reacquire the UsedLock here to since we're updating handle fields.
935 */
936 rc = gvmmR0UsedLock(pGVMM);
937 AssertRC(rc);
938
939 pHandle->iNext = pGVMM->iFreeHead;
940 pGVMM->iFreeHead = iHandle;
941 ASMAtomicXchgPtr((void * volatile *)&pHandle->pGVM, NULL);
942 ASMAtomicXchgPtr((void * volatile *)&pHandle->pVM, NULL);
943 ASMAtomicXchgPtr((void * volatile *)&pHandle->pvObj, NULL);
944 ASMAtomicXchgPtr((void * volatile *)&pHandle->pSession, NULL);
945 ASMAtomicXchgSize(&pHandle->hEMT, NIL_RTNATIVETHREAD);
946
947 gvmmR0UsedUnlock(pGVMM);
948 gvmmR0CreateDestroyUnlock(pGVMM);
949 LogFlow(("gvmmR0HandleObjDestructor: returns\n"));
950}
951
952
953/**
954 * Lookup a GVM structure by its handle.
955 *
956 * @returns The GVM pointer on success, NULL on failure.
957 * @param hGVM The global VM handle. Asserts on bad handle.
958 */
959GVMMR0DECL(PGVM) GVMMR0ByHandle(uint32_t hGVM)
960{
961 PGVMM pGVMM;
962 GVMM_GET_VALID_INSTANCE(pGVMM, NULL);
963
964 /*
965 * Validate.
966 */
967 AssertReturn(hGVM != NIL_GVM_HANDLE, NULL);
968 AssertReturn(hGVM < RT_ELEMENTS(pGVMM->aHandles), NULL);
969
970 /*
971 * Look it up.
972 */
973 PGVMHANDLE pHandle = &pGVMM->aHandles[hGVM];
974 AssertPtrReturn(pHandle->pVM, NULL);
975 AssertPtrReturn(pHandle->pvObj, NULL);
976 PGVM pGVM = pHandle->pGVM;
977 AssertPtrReturn(pGVM, NULL);
978 AssertReturn(pGVM->pVM == pHandle->pVM, NULL);
979
980 return pHandle->pGVM;
981}
982
983
984/**
985 * Lookup a GVM structure by the shared VM structure.
986 *
987 * @returns VBox status code.
988 * @param pVM The shared VM structure (the ring-0 mapping).
989 * @param ppGVM Where to store the GVM pointer.
990 * @param ppGVMM Where to store the pointer to the GVMM instance data.
991 * @param fTakeUsedLock Whether to take the used lock or not.
992 * Be very careful if not taking the lock as it's possible that
993 * the VM will disappear then.
994 *
995 * @remark This will not assert on an invalid pVM but try return sliently.
996 */
997static int gvmmR0ByVM(PVM pVM, PGVM *ppGVM, PGVMM *ppGVMM, bool fTakeUsedLock)
998{
999 PGVMM pGVMM;
1000 GVMM_GET_VALID_INSTANCE(pGVMM, VERR_INTERNAL_ERROR);
1001
1002 /*
1003 * Validate.
1004 */
1005 if (RT_UNLIKELY( !VALID_PTR(pVM)
1006 || ((uintptr_t)pVM & PAGE_OFFSET_MASK)))
1007 return VERR_INVALID_POINTER;
1008 if (RT_UNLIKELY( pVM->enmVMState < VMSTATE_CREATING
1009 || pVM->enmVMState >= VMSTATE_TERMINATED))
1010 return VERR_INVALID_POINTER;
1011
1012 uint16_t hGVM = pVM->hSelf;
1013 if (RT_UNLIKELY( hGVM == NIL_GVM_HANDLE
1014 || hGVM >= RT_ELEMENTS(pGVMM->aHandles)))
1015 return VERR_INVALID_HANDLE;
1016
1017 /*
1018 * Look it up.
1019 */
1020 PGVMHANDLE pHandle = &pGVMM->aHandles[hGVM];
1021 PGVM pGVM;
1022 if (fTakeUsedLock)
1023 {
1024 int rc = gvmmR0UsedLock(pGVMM);
1025 AssertRCReturn(rc, rc);
1026
1027 pGVM = pHandle->pGVM;
1028 if (RT_UNLIKELY( pHandle->pVM != pVM
1029 || !VALID_PTR(pHandle->pvObj)
1030 || !VALID_PTR(pGVM)
1031 || pGVM->pVM != pVM))
1032 {
1033 gvmmR0UsedUnlock(pGVMM);
1034 return VERR_INVALID_HANDLE;
1035 }
1036 }
1037 else
1038 {
1039 if (RT_UNLIKELY(pHandle->pVM != pVM))
1040 return VERR_INVALID_HANDLE;
1041 if (RT_UNLIKELY(!VALID_PTR(pHandle->pvObj)))
1042 return VERR_INVALID_HANDLE;
1043
1044 pGVM = pHandle->pGVM;
1045 if (RT_UNLIKELY(!VALID_PTR(pGVM)))
1046 return VERR_INVALID_HANDLE;
1047 if (RT_UNLIKELY(pGVM->pVM != pVM))
1048 return VERR_INVALID_HANDLE;
1049 }
1050
1051 *ppGVM = pGVM;
1052 *ppGVMM = pGVMM;
1053 return VINF_SUCCESS;
1054}
1055
1056
1057/**
1058 * Lookup a GVM structure by the shared VM structure.
1059 *
1060 * @returns The GVM pointer on success, NULL on failure.
1061 * @param pVM The shared VM structure (the ring-0 mapping).
1062 *
1063 * @remark This will not take the 'used'-lock because it doesn't do
1064 * nesting and this function will be used from under the lock.
1065 */
1066GVMMR0DECL(PGVM) GVMMR0ByVM(PVM pVM)
1067{
1068 PGVMM pGVMM;
1069 PGVM pGVM;
1070 int rc = gvmmR0ByVM(pVM, &pGVM, &pGVMM, false /* fTakeUsedLock */);
1071 if (RT_SUCCESS(rc))
1072 return pGVM;
1073 AssertRC(rc);
1074 return NULL;
1075}
1076
1077
1078/**
1079 * Lookup a GVM structure by the shared VM structure
1080 * and ensuring that the caller is the EMT thread.
1081 *
1082 * @returns VBox status code.
1083 * @param pVM The shared VM structure (the ring-0 mapping).
1084 * @param ppGVM Where to store the GVM pointer.
1085 * @param ppGVMM Where to store the pointer to the GVMM instance data.
1086 * @thread EMT
1087 *
1088 * @remark This will assert in failure paths.
1089 */
1090static int gvmmR0ByVMAndEMT(PVM pVM, PGVM *ppGVM, PGVMM *ppGVMM)
1091{
1092 PGVMM pGVMM;
1093 GVMM_GET_VALID_INSTANCE(pGVMM, VERR_INTERNAL_ERROR);
1094
1095 /*
1096 * Validate.
1097 */
1098 AssertPtrReturn(pVM, VERR_INVALID_POINTER);
1099 AssertReturn(!((uintptr_t)pVM & PAGE_OFFSET_MASK), VERR_INVALID_POINTER);
1100
1101 uint16_t hGVM = pVM->hSelf;
1102 AssertReturn(hGVM != NIL_GVM_HANDLE, VERR_INVALID_HANDLE);
1103 AssertReturn(hGVM < RT_ELEMENTS(pGVMM->aHandles), VERR_INVALID_HANDLE);
1104
1105 /*
1106 * Look it up.
1107 */
1108 PGVMHANDLE pHandle = &pGVMM->aHandles[hGVM];
1109 RTNATIVETHREAD hAllegedEMT = RTThreadNativeSelf();
1110 AssertMsgReturn(pHandle->hEMT == hAllegedEMT, ("hEMT %x hAllegedEMT %x\n", pHandle->hEMT, hAllegedEMT), VERR_NOT_OWNER);
1111 AssertReturn(pHandle->pVM == pVM, VERR_NOT_OWNER);
1112 AssertPtrReturn(pHandle->pvObj, VERR_INTERNAL_ERROR);
1113
1114 PGVM pGVM = pHandle->pGVM;
1115 AssertPtrReturn(pGVM, VERR_INTERNAL_ERROR);
1116 AssertReturn(pGVM->pVM == pVM, VERR_INTERNAL_ERROR);
1117 AssertReturn(pGVM->hEMT == hAllegedEMT, VERR_INTERNAL_ERROR);
1118
1119 *ppGVM = pGVM;
1120 *ppGVMM = pGVMM;
1121 return VINF_SUCCESS;
1122}
1123
1124
1125/**
1126 * Lookup a GVM structure by the shared VM structure
1127 * and ensuring that the caller is the EMT thread.
1128 *
1129 * @returns VBox status code.
1130 * @param pVM The shared VM structure (the ring-0 mapping).
1131 * @param ppGVM Where to store the GVM pointer.
1132 * @thread EMT
1133 */
1134GVMMR0DECL(int) GVMMR0ByVMAndEMT(PVM pVM, PGVM *ppGVM)
1135{
1136 AssertPtrReturn(ppGVM, VERR_INVALID_POINTER);
1137 PGVMM pGVMM;
1138 return gvmmR0ByVMAndEMT(pVM, ppGVM, &pGVMM);
1139}
1140
1141
1142/**
1143 * Lookup a VM by its global handle.
1144 *
1145 * @returns The VM handle on success, NULL on failure.
1146 * @param hGVM The global VM handle. Asserts on bad handle.
1147 */
1148GVMMR0DECL(PVM) GVMMR0GetVMByHandle(uint32_t hGVM)
1149{
1150 PGVM pGVM = GVMMR0ByHandle(hGVM);
1151 return pGVM ? pGVM->pVM : NULL;
1152}
1153
1154
1155/**
1156 * Looks up the VM belonging to the specified EMT thread.
1157 *
1158 * This is used by the assertion machinery in VMMR0.cpp to avoid causing
1159 * unnecessary kernel panics when the EMT thread hits an assertion. The
1160 * call may or not be an EMT thread.
1161 *
1162 * @returns The VM handle on success, NULL on failure.
1163 * @param hEMT The native thread handle of the EMT.
1164 * NIL_RTNATIVETHREAD means the current thread
1165 */
1166GVMMR0DECL(PVM) GVMMR0GetVMByEMT(RTNATIVETHREAD hEMT)
1167{
1168 /*
1169 * No Assertions here as we're usually called in a AssertMsgN or
1170 * RTAssert* context.
1171 */
1172 PGVMM pGVMM = g_pGVMM;
1173 if ( !VALID_PTR(pGVMM)
1174 || pGVMM->u32Magic != GVMM_MAGIC)
1175 return NULL;
1176
1177 if (hEMT == NIL_RTNATIVETHREAD)
1178 hEMT = RTThreadNativeSelf();
1179
1180 /*
1181 * Search the handles in a linear fashion as we don't dare take the lock (assert).
1182 */
1183 for (unsigned i = 1; i < RT_ELEMENTS(pGVMM->aHandles); i++)
1184 if ( pGVMM->aHandles[i].hEMT == hEMT
1185 && pGVMM->aHandles[i].iSelf == i
1186 && VALID_PTR(pGVMM->aHandles[i].pvObj)
1187 && VALID_PTR(pGVMM->aHandles[i].pVM))
1188 return pGVMM->aHandles[i].pVM;
1189
1190 return NULL;
1191}
1192
1193
1194/**
1195 * This is will wake up expired and soon-to-be expired VMs.
1196 *
1197 * @returns Number of VMs that has been woken up.
1198 * @param pGVMM Pointer to the GVMM instance data.
1199 * @param u64Now The current time.
1200 */
1201static unsigned gvmmR0SchedDoWakeUps(PGVMM pGVMM, uint64_t u64Now)
1202{
1203 /*
1204 * The first pass will wake up VMs which has actually expired
1205 * and look for VMs that should be woken up in the 2nd and 3rd passes.
1206 */
1207 unsigned cWoken = 0;
1208 unsigned cHalted = 0;
1209 unsigned cTodo2nd = 0;
1210 unsigned cTodo3rd = 0;
1211 for (unsigned i = pGVMM->iUsedHead, cGuard = 0;
1212 i != NIL_GVM_HANDLE && i < RT_ELEMENTS(pGVMM->aHandles);
1213 i = pGVMM->aHandles[i].iNext)
1214 {
1215 PGVM pCurGVM = pGVMM->aHandles[i].pGVM;
1216 if ( VALID_PTR(pCurGVM)
1217 && pCurGVM->u32Magic == GVM_MAGIC)
1218 {
1219 uint64_t u64 = pCurGVM->gvmm.s.u64HaltExpire;
1220 if (u64)
1221 {
1222 if (u64 <= u64Now)
1223 {
1224 if (ASMAtomicXchgU64(&pCurGVM->gvmm.s.u64HaltExpire, 0))
1225 {
1226 int rc = RTSemEventMultiSignal(pCurGVM->gvmm.s.HaltEventMulti);
1227 AssertRC(rc);
1228 cWoken++;
1229 }
1230 }
1231 else
1232 {
1233 cHalted++;
1234 if (u64 <= u64Now + pGVMM->nsEarlyWakeUp1)
1235 cTodo2nd++;
1236 else if (u64 <= u64Now + pGVMM->nsEarlyWakeUp2)
1237 cTodo3rd++;
1238 }
1239 }
1240 }
1241 AssertLogRelBreak(cGuard++ < RT_ELEMENTS(pGVMM->aHandles));
1242 }
1243
1244 if (cTodo2nd)
1245 {
1246 for (unsigned i = pGVMM->iUsedHead, cGuard = 0;
1247 i != NIL_GVM_HANDLE && i < RT_ELEMENTS(pGVMM->aHandles);
1248 i = pGVMM->aHandles[i].iNext)
1249 {
1250 PGVM pCurGVM = pGVMM->aHandles[i].pGVM;
1251 if ( VALID_PTR(pCurGVM)
1252 && pCurGVM->u32Magic == GVM_MAGIC
1253 && pCurGVM->gvmm.s.u64HaltExpire
1254 && pCurGVM->gvmm.s.u64HaltExpire <= u64Now + pGVMM->nsEarlyWakeUp1)
1255 {
1256 if (ASMAtomicXchgU64(&pCurGVM->gvmm.s.u64HaltExpire, 0))
1257 {
1258 int rc = RTSemEventMultiSignal(pCurGVM->gvmm.s.HaltEventMulti);
1259 AssertRC(rc);
1260 cWoken++;
1261 }
1262 }
1263 AssertLogRelBreak(cGuard++ < RT_ELEMENTS(pGVMM->aHandles));
1264 }
1265 }
1266
1267 if (cTodo3rd)
1268 {
1269 for (unsigned i = pGVMM->iUsedHead, cGuard = 0;
1270 i != NIL_GVM_HANDLE && i < RT_ELEMENTS(pGVMM->aHandles);
1271 i = pGVMM->aHandles[i].iNext)
1272 {
1273 PGVM pCurGVM = pGVMM->aHandles[i].pGVM;
1274 if ( VALID_PTR(pCurGVM)
1275 && pCurGVM->u32Magic == GVM_MAGIC
1276 && pCurGVM->gvmm.s.u64HaltExpire
1277 && pCurGVM->gvmm.s.u64HaltExpire <= u64Now + pGVMM->nsEarlyWakeUp2)
1278 {
1279 if (ASMAtomicXchgU64(&pCurGVM->gvmm.s.u64HaltExpire, 0))
1280 {
1281 int rc = RTSemEventMultiSignal(pCurGVM->gvmm.s.HaltEventMulti);
1282 AssertRC(rc);
1283 cWoken++;
1284 }
1285 }
1286 AssertLogRelBreak(cGuard++ < RT_ELEMENTS(pGVMM->aHandles));
1287 }
1288 }
1289
1290 return cWoken;
1291}
1292
1293
1294/**
1295 * Halt the EMT thread.
1296 *
1297 * @returns VINF_SUCCESS normal wakeup (timeout or kicked by other thread).
1298 * VERR_INTERRUPTED if a signal was scheduled for the thread.
1299 * @param pVM Pointer to the shared VM structure.
1300 * @param u64ExpireGipTime The time for the sleep to expire expressed as GIP time.
1301 * @thread EMT.
1302 */
1303GVMMR0DECL(int) GVMMR0SchedHalt(PVM pVM, uint64_t u64ExpireGipTime)
1304{
1305 LogFlow(("GVMMR0SchedHalt: pVM=%p\n", pVM));
1306
1307 /*
1308 * Validate the VM structure, state and handle.
1309 */
1310 PGVMM pGVMM;
1311 PGVM pGVM;
1312 int rc = gvmmR0ByVMAndEMT(pVM, &pGVM, &pGVMM);
1313 if (RT_FAILURE(rc))
1314 return rc;
1315 pGVM->gvmm.s.StatsSched.cHaltCalls++;
1316
1317 Assert(!pGVM->gvmm.s.u64HaltExpire);
1318
1319 /*
1320 * Take the UsedList semaphore, get the current time
1321 * and check if anyone needs waking up.
1322 * Interrupts must NOT be disabled at this point because we ask for GIP time!
1323 */
1324 rc = gvmmR0UsedLock(pGVMM);
1325 AssertRC(rc);
1326
1327 pGVM->gvmm.s.iCpuEmt = ASMGetApicId();
1328
1329 Assert(ASMGetFlags() & X86_EFL_IF);
1330 const uint64_t u64Now = RTTimeNanoTS(); /* (GIP time) */
1331 pGVM->gvmm.s.StatsSched.cHaltWakeUps += gvmmR0SchedDoWakeUps(pGVMM, u64Now);
1332
1333 /*
1334 * Go to sleep if we must...
1335 */
1336 if ( u64Now < u64ExpireGipTime
1337 && u64ExpireGipTime - u64Now > (pGVMM->cVMs > pGVMM->cVMsMeansCompany
1338 ? pGVMM->nsMinSleepCompany
1339 : pGVMM->nsMinSleepAlone))
1340 {
1341 pGVM->gvmm.s.StatsSched.cHaltBlocking++;
1342 ASMAtomicXchgU64(&pGVM->gvmm.s.u64HaltExpire, u64ExpireGipTime);
1343 gvmmR0UsedUnlock(pGVMM);
1344
1345 uint32_t cMillies = (u64ExpireGipTime - u64Now) / 1000000;
1346 rc = RTSemEventMultiWaitNoResume(pGVM->gvmm.s.HaltEventMulti, cMillies ? cMillies : 1);
1347 ASMAtomicXchgU64(&pGVM->gvmm.s.u64HaltExpire, 0);
1348 if (rc == VERR_TIMEOUT)
1349 {
1350 pGVM->gvmm.s.StatsSched.cHaltTimeouts++;
1351 rc = VINF_SUCCESS;
1352 }
1353 }
1354 else
1355 {
1356 pGVM->gvmm.s.StatsSched.cHaltNotBlocking++;
1357 gvmmR0UsedUnlock(pGVMM);
1358 }
1359
1360 /* Make sure false wake up calls (gvmmR0SchedDoWakeUps) cause us to spin. */
1361 RTSemEventMultiReset(pGVM->gvmm.s.HaltEventMulti);
1362
1363 return rc;
1364}
1365
1366
1367/**
1368 * Wakes up the halted EMT thread so it can service a pending request.
1369 *
1370 * @returns VINF_SUCCESS if not yielded.
1371 * VINF_GVM_NOT_BLOCKED if the EMT thread wasn't blocked.
1372 * @param pVM Pointer to the shared VM structure.
1373 * @thread Any but EMT.
1374 */
1375GVMMR0DECL(int) GVMMR0SchedWakeUp(PVM pVM)
1376{
1377 /*
1378 * Validate input and take the UsedLock.
1379 */
1380 PGVM pGVM;
1381 PGVMM pGVMM;
1382 int rc = gvmmR0ByVM(pVM, &pGVM, &pGVMM, true /* fTakeUsedLock */);
1383 if (RT_SUCCESS(rc))
1384 {
1385 pGVM->gvmm.s.StatsSched.cWakeUpCalls++;
1386
1387 /*
1388 * Signal the semaphore regardless of whether it's current blocked on it.
1389 *
1390 * The reason for this is that there is absolutely no way we can be 100%
1391 * certain that it isn't *about* go to go to sleep on it and just got
1392 * delayed a bit en route. So, we will always signal the semaphore when
1393 * the it is flagged as halted in the VMM.
1394 */
1395 if (pGVM->gvmm.s.u64HaltExpire)
1396 {
1397 rc = VINF_SUCCESS;
1398 ASMAtomicXchgU64(&pGVM->gvmm.s.u64HaltExpire, 0);
1399 }
1400 else
1401 {
1402 rc = VINF_GVM_NOT_BLOCKED;
1403 pGVM->gvmm.s.StatsSched.cWakeUpNotHalted++;
1404 }
1405
1406 int rc2 = RTSemEventMultiSignal(pGVM->gvmm.s.HaltEventMulti);
1407 AssertRC(rc2);
1408
1409 /*
1410 * While we're here, do a round of scheduling.
1411 */
1412 Assert(ASMGetFlags() & X86_EFL_IF);
1413 const uint64_t u64Now = RTTimeNanoTS(); /* (GIP time) */
1414 pGVM->gvmm.s.StatsSched.cWakeUpWakeUps += gvmmR0SchedDoWakeUps(pGVMM, u64Now);
1415
1416
1417 rc2 = gvmmR0UsedUnlock(pGVMM);
1418 AssertRC(rc2);
1419 }
1420
1421 LogFlow(("GVMMR0SchedWakeUp: returns %Rrc\n", rc));
1422 return rc;
1423}
1424
1425
1426/**
1427 * Poll the schedule to see if someone else should get a chance to run.
1428 *
1429 * This is a bit hackish and will not work too well if the machine is
1430 * under heavy load from non-VM processes.
1431 *
1432 * @returns VINF_SUCCESS if not yielded.
1433 * VINF_GVM_YIELDED if an attempt to switch to a different VM task was made.
1434 * @param pVM Pointer to the shared VM structure.
1435 * @param u64ExpireGipTime The time for the sleep to expire expressed as GIP time.
1436 * @param fYield Whether to yield or not.
1437 * This is for when we're spinning in the halt loop.
1438 * @thread EMT.
1439 */
1440GVMMR0DECL(int) GVMMR0SchedPoll(PVM pVM, bool fYield)
1441{
1442 /*
1443 * Validate input.
1444 */
1445 PGVM pGVM;
1446 PGVMM pGVMM;
1447 int rc = gvmmR0ByVMAndEMT(pVM, &pGVM, &pGVMM);
1448 if (RT_SUCCESS(rc))
1449 {
1450 rc = gvmmR0UsedLock(pGVMM);
1451 AssertRC(rc);
1452 pGVM->gvmm.s.StatsSched.cPollCalls++;
1453
1454 Assert(ASMGetFlags() & X86_EFL_IF);
1455 const uint64_t u64Now = RTTimeNanoTS(); /* (GIP time) */
1456
1457 if (!fYield)
1458 pGVM->gvmm.s.StatsSched.cPollWakeUps += gvmmR0SchedDoWakeUps(pGVMM, u64Now);
1459 else
1460 {
1461 /** @todo implement this... */
1462 rc = VERR_NOT_IMPLEMENTED;
1463 }
1464
1465 gvmmR0UsedUnlock(pGVMM);
1466 }
1467
1468 LogFlow(("GVMMR0SchedWakeUp: returns %Rrc\n", rc));
1469 return rc;
1470}
1471
1472
1473
1474/**
1475 * Retrieves the GVMM statistics visible to the caller.
1476 *
1477 * @returns VBox status code.
1478 *
1479 * @param pStats Where to put the statistics.
1480 * @param pSession The current session.
1481 * @param pVM The VM to obtain statistics for. Optional.
1482 */
1483GVMMR0DECL(int) GVMMR0QueryStatistics(PGVMMSTATS pStats, PSUPDRVSESSION pSession, PVM pVM)
1484{
1485 LogFlow(("GVMMR0QueryStatistics: pStats=%p pSession=%p pVM=%p\n", pStats, pSession, pVM));
1486
1487 /*
1488 * Validate input.
1489 */
1490 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
1491 AssertPtrReturn(pStats, VERR_INVALID_POINTER);
1492 pStats->cVMs = 0; /* (crash before taking the sem...) */
1493
1494 /*
1495 * Take the lock and get the VM statistics.
1496 */
1497 PGVMM pGVMM;
1498 if (pVM)
1499 {
1500 PGVM pGVM;
1501 int rc = gvmmR0ByVM(pVM, &pGVM, &pGVMM, true /*fTakeUsedLock*/);
1502 if (RT_FAILURE(rc))
1503 return rc;
1504 pStats->SchedVM = pGVM->gvmm.s.StatsSched;
1505 }
1506 else
1507 {
1508 GVMM_GET_VALID_INSTANCE(pGVMM, VERR_INTERNAL_ERROR);
1509 memset(&pStats->SchedVM, 0, sizeof(pStats->SchedVM));
1510
1511 int rc = gvmmR0UsedLock(pGVMM);
1512 AssertRCReturn(rc, rc);
1513 }
1514
1515 /*
1516 * Enumerate the VMs and add the ones visibile to the statistics.
1517 */
1518 pStats->cVMs = 0;
1519 memset(&pStats->SchedSum, 0, sizeof(pStats->SchedSum));
1520
1521 for (unsigned i = pGVMM->iUsedHead;
1522 i != NIL_GVM_HANDLE && i < RT_ELEMENTS(pGVMM->aHandles);
1523 i = pGVMM->aHandles[i].iNext)
1524 {
1525 PGVM pGVM = pGVMM->aHandles[i].pGVM;
1526 void *pvObj = pGVMM->aHandles[i].pvObj;
1527 if ( VALID_PTR(pvObj)
1528 && VALID_PTR(pGVM)
1529 && pGVM->u32Magic == GVM_MAGIC
1530 && RT_SUCCESS(SUPR0ObjVerifyAccess(pvObj, pSession, NULL)))
1531 {
1532 pStats->cVMs++;
1533
1534 pStats->SchedSum.cHaltCalls += pGVM->gvmm.s.StatsSched.cHaltCalls;
1535 pStats->SchedSum.cHaltBlocking += pGVM->gvmm.s.StatsSched.cHaltBlocking;
1536 pStats->SchedSum.cHaltTimeouts += pGVM->gvmm.s.StatsSched.cHaltTimeouts;
1537 pStats->SchedSum.cHaltNotBlocking += pGVM->gvmm.s.StatsSched.cHaltNotBlocking;
1538 pStats->SchedSum.cHaltWakeUps += pGVM->gvmm.s.StatsSched.cHaltWakeUps;
1539
1540 pStats->SchedSum.cWakeUpCalls += pGVM->gvmm.s.StatsSched.cWakeUpCalls;
1541 pStats->SchedSum.cWakeUpNotHalted += pGVM->gvmm.s.StatsSched.cWakeUpNotHalted;
1542 pStats->SchedSum.cWakeUpWakeUps += pGVM->gvmm.s.StatsSched.cWakeUpWakeUps;
1543
1544 pStats->SchedSum.cPollCalls += pGVM->gvmm.s.StatsSched.cPollCalls;
1545 pStats->SchedSum.cPollHalts += pGVM->gvmm.s.StatsSched.cPollHalts;
1546 pStats->SchedSum.cPollWakeUps += pGVM->gvmm.s.StatsSched.cPollWakeUps;
1547 }
1548 }
1549
1550 gvmmR0UsedUnlock(pGVMM);
1551
1552 return VINF_SUCCESS;
1553}
1554
1555
1556/**
1557 * VMMR0 request wrapper for GVMMR0QueryStatistics.
1558 *
1559 * @returns see GVMMR0QueryStatistics.
1560 * @param pVM Pointer to the shared VM structure. Optional.
1561 * @param pReq The request packet.
1562 */
1563GVMMR0DECL(int) GVMMR0QueryStatisticsReq(PVM pVM, PGVMMQUERYSTATISTICSSREQ pReq)
1564{
1565 /*
1566 * Validate input and pass it on.
1567 */
1568 AssertPtrReturn(pReq, VERR_INVALID_POINTER);
1569 AssertMsgReturn(pReq->Hdr.cbReq == sizeof(*pReq), ("%#x != %#x\n", pReq->Hdr.cbReq, sizeof(*pReq)), VERR_INVALID_PARAMETER);
1570
1571 return GVMMR0QueryStatistics(&pReq->Stats, pReq->pSession, pVM);
1572}
1573
1574
1575/**
1576 * Resets the specified GVMM statistics.
1577 *
1578 * @returns VBox status code.
1579 *
1580 * @param pStats Which statistics to reset, that is, non-zero fields indicates which to reset.
1581 * @param pSession The current session.
1582 * @param pVM The VM to reset statistics for. Optional.
1583 */
1584GVMMR0DECL(int) GVMMR0ResetStatistics(PCGVMMSTATS pStats, PSUPDRVSESSION pSession, PVM pVM)
1585{
1586 LogFlow(("GVMMR0ResetStatistics: pStats=%p pSession=%p pVM=%p\n", pStats, pSession, pVM));
1587
1588 /*
1589 * Validate input.
1590 */
1591 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
1592 AssertPtrReturn(pStats, VERR_INVALID_POINTER);
1593
1594 /*
1595 * Take the lock and get the VM statistics.
1596 */
1597 PGVMM pGVMM;
1598 if (pVM)
1599 {
1600 PGVM pGVM;
1601 int rc = gvmmR0ByVM(pVM, &pGVM, &pGVMM, true /*fTakeUsedLock*/);
1602 if (RT_FAILURE(rc))
1603 return rc;
1604# define MAYBE_RESET_FIELD(field) \
1605 do { if (pStats->SchedVM. field ) { pGVM->gvmm.s.StatsSched. field = 0; } } while (0)
1606 MAYBE_RESET_FIELD(cHaltCalls);
1607 MAYBE_RESET_FIELD(cHaltBlocking);
1608 MAYBE_RESET_FIELD(cHaltTimeouts);
1609 MAYBE_RESET_FIELD(cHaltNotBlocking);
1610 MAYBE_RESET_FIELD(cHaltWakeUps);
1611 MAYBE_RESET_FIELD(cWakeUpCalls);
1612 MAYBE_RESET_FIELD(cWakeUpNotHalted);
1613 MAYBE_RESET_FIELD(cWakeUpWakeUps);
1614 MAYBE_RESET_FIELD(cPollCalls);
1615 MAYBE_RESET_FIELD(cPollHalts);
1616 MAYBE_RESET_FIELD(cPollWakeUps);
1617# undef MAYBE_RESET_FIELD
1618 }
1619 else
1620 {
1621 GVMM_GET_VALID_INSTANCE(pGVMM, VERR_INTERNAL_ERROR);
1622
1623 int rc = gvmmR0UsedLock(pGVMM);
1624 AssertRCReturn(rc, rc);
1625 }
1626
1627 /*
1628 * Enumerate the VMs and add the ones visibile to the statistics.
1629 */
1630 if (ASMMemIsAll8(&pStats->SchedSum, sizeof(pStats->SchedSum), 0))
1631 {
1632 for (unsigned i = pGVMM->iUsedHead;
1633 i != NIL_GVM_HANDLE && i < RT_ELEMENTS(pGVMM->aHandles);
1634 i = pGVMM->aHandles[i].iNext)
1635 {
1636 PGVM pGVM = pGVMM->aHandles[i].pGVM;
1637 void *pvObj = pGVMM->aHandles[i].pvObj;
1638 if ( VALID_PTR(pvObj)
1639 && VALID_PTR(pGVM)
1640 && pGVM->u32Magic == GVM_MAGIC
1641 && RT_SUCCESS(SUPR0ObjVerifyAccess(pvObj, pSession, NULL)))
1642 {
1643# define MAYBE_RESET_FIELD(field) \
1644 do { if (pStats->SchedSum. field ) { pGVM->gvmm.s.StatsSched. field = 0; } } while (0)
1645 MAYBE_RESET_FIELD(cHaltCalls);
1646 MAYBE_RESET_FIELD(cHaltBlocking);
1647 MAYBE_RESET_FIELD(cHaltTimeouts);
1648 MAYBE_RESET_FIELD(cHaltNotBlocking);
1649 MAYBE_RESET_FIELD(cHaltWakeUps);
1650 MAYBE_RESET_FIELD(cWakeUpCalls);
1651 MAYBE_RESET_FIELD(cWakeUpNotHalted);
1652 MAYBE_RESET_FIELD(cWakeUpWakeUps);
1653 MAYBE_RESET_FIELD(cPollCalls);
1654 MAYBE_RESET_FIELD(cPollHalts);
1655 MAYBE_RESET_FIELD(cPollWakeUps);
1656# undef MAYBE_RESET_FIELD
1657 }
1658 }
1659 }
1660
1661 gvmmR0UsedUnlock(pGVMM);
1662
1663 return VINF_SUCCESS;
1664}
1665
1666
1667/**
1668 * VMMR0 request wrapper for GVMMR0ResetStatistics.
1669 *
1670 * @returns see GVMMR0ResetStatistics.
1671 * @param pVM Pointer to the shared VM structure. Optional.
1672 * @param pReq The request packet.
1673 */
1674GVMMR0DECL(int) GVMMR0ResetStatisticsReq(PVM pVM, PGVMMRESETSTATISTICSSREQ pReq)
1675{
1676 /*
1677 * Validate input and pass it on.
1678 */
1679 AssertPtrReturn(pReq, VERR_INVALID_POINTER);
1680 AssertMsgReturn(pReq->Hdr.cbReq == sizeof(*pReq), ("%#x != %#x\n", pReq->Hdr.cbReq, sizeof(*pReq)), VERR_INVALID_PARAMETER);
1681
1682 return GVMMR0ResetStatistics(&pReq->Stats, pReq->pSession, pVM);
1683}
1684
Note: See TracBrowser for help on using the repository browser.

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