VirtualBox

source: vbox/trunk/src/VBox/HostDrivers/Support/SUPDRVShared.c@ 5999

Last change on this file since 5999 was 5999, checked in by vboxsync, 17 years ago

The Giant CDDL Dual-License Header Change.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 140.0 KB
Line 
1/* $Revision: 5999 $ */
2/** @file
3 * VirtualBox Support Driver - Shared code.
4 */
5
6/*
7 * Copyright (C) 2006-2007 innotek GmbH
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 * The contents of this file may alternatively be used under the terms
18 * of the Common Development and Distribution License Version 1.0
19 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the
20 * VirtualBox OSE distribution, in which case the provisions of the
21 * CDDL are applicable instead of those of the GPL.
22 *
23 * You may elect to license modified versions of this file under the
24 * terms and conditions of either the GPL or the CDDL or both.
25 */
26
27
28/*******************************************************************************
29* Header Files *
30*******************************************************************************/
31#include "SUPDRV.h"
32#ifndef PAGE_SHIFT
33# include <iprt/param.h>
34#endif
35#include <iprt/alloc.h>
36#include <iprt/semaphore.h>
37#include <iprt/spinlock.h>
38#include <iprt/thread.h>
39#include <iprt/process.h>
40#include <iprt/log.h>
41
42
43/*******************************************************************************
44* Defined Constants And Macros *
45*******************************************************************************/
46/* from x86.h - clashes with linux thus this duplication */
47#undef X86_CR0_PG
48#define X86_CR0_PG RT_BIT(31)
49#undef X86_CR0_PE
50#define X86_CR0_PE RT_BIT(0)
51#undef X86_CPUID_AMD_FEATURE_EDX_NX
52#define X86_CPUID_AMD_FEATURE_EDX_NX RT_BIT(20)
53#undef MSR_K6_EFER
54#define MSR_K6_EFER 0xc0000080
55#undef MSR_K6_EFER_NXE
56#define MSR_K6_EFER_NXE RT_BIT(11)
57#undef MSR_K6_EFER_LMA
58#define MSR_K6_EFER_LMA RT_BIT(10)
59#undef X86_CR4_PGE
60#define X86_CR4_PGE RT_BIT(7)
61#undef X86_CR4_PAE
62#define X86_CR4_PAE RT_BIT(5)
63#undef X86_CPUID_AMD_FEATURE_EDX_LONG_MODE
64#define X86_CPUID_AMD_FEATURE_EDX_LONG_MODE RT_BIT(29)
65
66
67/** The frequency by which we recalculate the u32UpdateHz and
68 * u32UpdateIntervalNS GIP members. The value must be a power of 2. */
69#define GIP_UPDATEHZ_RECALC_FREQ 0x800
70
71/**
72 * Validates a session pointer.
73 *
74 * @returns true/false accordingly.
75 * @param pSession The session.
76 */
77#define SUP_IS_SESSION_VALID(pSession) \
78 ( VALID_PTR(pSession) \
79 && pSession->u32Cookie == BIRD_INV)
80
81
82/*******************************************************************************
83* Global Variables *
84*******************************************************************************/
85/**
86 * Array of the R0 SUP API.
87 */
88static SUPFUNC g_aFunctions[] =
89{
90 /* name function */
91 { "SUPR0ObjRegister", (void *)SUPR0ObjRegister },
92 { "SUPR0ObjAddRef", (void *)SUPR0ObjAddRef },
93 { "SUPR0ObjRelease", (void *)SUPR0ObjRelease },
94 { "SUPR0ObjVerifyAccess", (void *)SUPR0ObjVerifyAccess },
95 { "SUPR0LockMem", (void *)SUPR0LockMem },
96 { "SUPR0UnlockMem", (void *)SUPR0UnlockMem },
97 { "SUPR0ContAlloc", (void *)SUPR0ContAlloc },
98 { "SUPR0ContFree", (void *)SUPR0ContFree },
99 { "SUPR0LowAlloc", (void *)SUPR0LowAlloc },
100 { "SUPR0LowFree", (void *)SUPR0LowFree },
101 { "SUPR0MemAlloc", (void *)SUPR0MemAlloc },
102 { "SUPR0MemGetPhys", (void *)SUPR0MemGetPhys },
103 { "SUPR0MemFree", (void *)SUPR0MemFree },
104 { "SUPR0PageAlloc", (void *)SUPR0PageAlloc },
105 { "SUPR0PageFree", (void *)SUPR0PageFree },
106 { "SUPR0Printf", (void *)SUPR0Printf },
107 { "RTMemAlloc", (void *)RTMemAlloc },
108 { "RTMemAllocZ", (void *)RTMemAllocZ },
109 { "RTMemFree", (void *)RTMemFree },
110 /*{ "RTMemDup", (void *)RTMemDup },*/
111 { "RTMemRealloc", (void *)RTMemRealloc },
112 { "RTR0MemObjAllocLow", (void *)RTR0MemObjAllocLow },
113 { "RTR0MemObjAllocPage", (void *)RTR0MemObjAllocPage },
114 { "RTR0MemObjAllocPhys", (void *)RTR0MemObjAllocPhys },
115 { "RTR0MemObjAllocPhysNC", (void *)RTR0MemObjAllocPhysNC },
116 { "RTR0MemObjLockUser", (void *)RTR0MemObjLockUser },
117 { "RTR0MemObjMapKernel", (void *)RTR0MemObjMapKernel },
118 { "RTR0MemObjMapUser", (void *)RTR0MemObjMapUser },
119 { "RTR0MemObjAddress", (void *)RTR0MemObjAddress },
120 { "RTR0MemObjAddressR3", (void *)RTR0MemObjAddressR3 },
121 { "RTR0MemObjSize", (void *)RTR0MemObjSize },
122 { "RTR0MemObjIsMapping", (void *)RTR0MemObjIsMapping },
123 { "RTR0MemObjGetPagePhysAddr", (void *)RTR0MemObjGetPagePhysAddr },
124 { "RTR0MemObjFree", (void *)RTR0MemObjFree },
125/* These doesn't work yet on linux - use fast mutexes!
126 { "RTSemMutexCreate", (void *)RTSemMutexCreate },
127 { "RTSemMutexRequest", (void *)RTSemMutexRequest },
128 { "RTSemMutexRelease", (void *)RTSemMutexRelease },
129 { "RTSemMutexDestroy", (void *)RTSemMutexDestroy },
130*/
131 { "RTSemFastMutexCreate", (void *)RTSemFastMutexCreate },
132 { "RTSemFastMutexDestroy", (void *)RTSemFastMutexDestroy },
133 { "RTSemFastMutexRequest", (void *)RTSemFastMutexRequest },
134 { "RTSemFastMutexRelease", (void *)RTSemFastMutexRelease },
135 { "RTSemEventCreate", (void *)RTSemEventCreate },
136 { "RTSemEventSignal", (void *)RTSemEventSignal },
137 { "RTSemEventWait", (void *)RTSemEventWait },
138 { "RTSemEventWaitNoResume", (void *)RTSemEventWaitNoResume },
139 { "RTSemEventDestroy", (void *)RTSemEventDestroy },
140 { "RTSemEventMultiCreate", (void *)RTSemEventMultiCreate },
141 { "RTSemEventMultiSignal", (void *)RTSemEventMultiSignal },
142 { "RTSemEventMultiReset", (void *)RTSemEventMultiReset },
143 { "RTSemEventMultiWait", (void *)RTSemEventMultiWait },
144 { "RTSemEventMultiWaitNoResume", (void *)RTSemEventMultiWaitNoResume },
145 { "RTSemEventMultiDestroy", (void *)RTSemEventMultiDestroy },
146 { "RTSpinlockCreate", (void *)RTSpinlockCreate },
147 { "RTSpinlockDestroy", (void *)RTSpinlockDestroy },
148 { "RTSpinlockAcquire", (void *)RTSpinlockAcquire },
149 { "RTSpinlockRelease", (void *)RTSpinlockRelease },
150 { "RTSpinlockAcquireNoInts", (void *)RTSpinlockAcquireNoInts },
151 { "RTSpinlockReleaseNoInts", (void *)RTSpinlockReleaseNoInts },
152 { "RTThreadNativeSelf", (void *)RTThreadNativeSelf },
153 { "RTThreadSleep", (void *)RTThreadSleep },
154 { "RTThreadYield", (void *)RTThreadYield },
155#if 0 /* Thread APIs, Part 2. */
156 { "RTThreadSelf", (void *)RTThreadSelf },
157 { "RTThreadCreate", (void *)RTThreadCreate },
158 { "RTThreadGetNative", (void *)RTThreadGetNative },
159 { "RTThreadWait", (void *)RTThreadWait },
160 { "RTThreadWaitNoResume", (void *)RTThreadWaitNoResume },
161 { "RTThreadGetName", (void *)RTThreadGetName },
162 { "RTThreadSelfName", (void *)RTThreadSelfName },
163 { "RTThreadGetType", (void *)RTThreadGetType },
164 { "RTThreadUserSignal", (void *)RTThreadUserSignal },
165 { "RTThreadUserReset", (void *)RTThreadUserReset },
166 { "RTThreadUserWait", (void *)RTThreadUserWait },
167 { "RTThreadUserWaitNoResume", (void *)RTThreadUserWaitNoResume },
168#endif
169 { "RTLogDefaultInstance", (void *)RTLogDefaultInstance },
170 { "RTLogRelDefaultInstance", (void *)RTLogRelDefaultInstance },
171 { "RTLogSetDefaultInstanceThread", (void *)RTLogSetDefaultInstanceThread },
172 { "RTLogLogger", (void *)RTLogLogger },
173 { "RTLogLoggerEx", (void *)RTLogLoggerEx },
174 { "RTLogLoggerExV", (void *)RTLogLoggerExV },
175 { "RTLogPrintf", (void *)RTLogPrintf },
176 { "RTLogPrintfV", (void *)RTLogPrintfV },
177 { "AssertMsg1", (void *)AssertMsg1 },
178 { "AssertMsg2", (void *)AssertMsg2 },
179};
180
181
182/*******************************************************************************
183* Internal Functions *
184*******************************************************************************/
185static int supdrvMemAdd(PSUPDRVMEMREF pMem, PSUPDRVSESSION pSession);
186static int supdrvMemRelease(PSUPDRVSESSION pSession, RTHCUINTPTR uPtr, SUPDRVMEMREFTYPE eType);
187#ifdef VBOX_WITH_IDT_PATCHING
188static int supdrvIOCtl_IdtInstall(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPIDTINSTALL pReq);
189static PSUPDRVPATCH supdrvIdtPatchOne(PSUPDRVDEVEXT pDevExt, PSUPDRVPATCH pPatch);
190static int supdrvIOCtl_IdtRemoveAll(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession);
191static void supdrvIdtRemoveOne(PSUPDRVDEVEXT pDevExt, PSUPDRVPATCH pPatch);
192static void supdrvIdtWrite(volatile void *pvIdtEntry, const SUPDRVIDTE *pNewIDTEntry);
193#endif /* VBOX_WITH_IDT_PATCHING */
194static int supdrvIOCtl_LdrOpen(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPLDROPEN pReq);
195static int supdrvIOCtl_LdrLoad(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPLDRLOAD pReq);
196static int supdrvIOCtl_LdrFree(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPLDRFREE pReq);
197static int supdrvIOCtl_LdrGetSymbol(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPLDRGETSYMBOL pReq);
198static int supdrvLdrSetR0EP(PSUPDRVDEVEXT pDevExt, void *pvVMMR0, void *pvVMMR0EntryInt, void *pvVMMR0EntryFast, void *pvVMMR0EntryEx);
199static void supdrvLdrUnsetR0EP(PSUPDRVDEVEXT pDevExt);
200static void supdrvLdrAddUsage(PSUPDRVSESSION pSession, PSUPDRVLDRIMAGE pImage);
201static void supdrvLdrFree(PSUPDRVDEVEXT pDevExt, PSUPDRVLDRIMAGE pImage);
202static SUPPAGINGMODE supdrvIOCtl_GetPagingMode(void);
203static SUPGIPMODE supdrvGipDeterminTscMode(void);
204#ifdef RT_OS_WINDOWS
205static int supdrvPageGetPhys(PSUPDRVSESSION pSession, RTR3PTR pvR3, uint32_t cPages, PRTHCPHYS paPages);
206static bool supdrvPageWasLockedByPageAlloc(PSUPDRVSESSION pSession, RTR3PTR pvR3);
207#endif
208#ifdef USE_NEW_OS_INTERFACE_FOR_GIP
209static int supdrvGipCreate(PSUPDRVDEVEXT pDevExt);
210static void supdrvGipDestroy(PSUPDRVDEVEXT pDevExt);
211static DECLCALLBACK(void) supdrvGipTimer(PRTTIMER pTimer, void *pvUser);
212#endif
213
214
215/**
216 * Initializes the device extentsion structure.
217 *
218 * @returns IPRT status code.
219 * @param pDevExt The device extension to initialize.
220 */
221int VBOXCALL supdrvInitDevExt(PSUPDRVDEVEXT pDevExt)
222{
223 /*
224 * Initialize it.
225 */
226 int rc;
227 memset(pDevExt, 0, sizeof(*pDevExt));
228 rc = RTSpinlockCreate(&pDevExt->Spinlock);
229 if (!rc)
230 {
231 rc = RTSemFastMutexCreate(&pDevExt->mtxLdr);
232 if (!rc)
233 {
234 rc = RTSemFastMutexCreate(&pDevExt->mtxGip);
235 if (!rc)
236 {
237#ifdef USE_NEW_OS_INTERFACE_FOR_GIP
238 rc = supdrvGipCreate(pDevExt);
239 if (RT_SUCCESS(rc))
240 {
241 pDevExt->u32Cookie = BIRD; /** @todo make this random? */
242 return VINF_SUCCESS;
243 }
244#else
245 pDevExt->u32Cookie = BIRD;
246 return VINF_SUCCESS;
247#endif
248 }
249 RTSemFastMutexDestroy(pDevExt->mtxLdr);
250 pDevExt->mtxLdr = NIL_RTSEMFASTMUTEX;
251 }
252 RTSpinlockDestroy(pDevExt->Spinlock);
253 pDevExt->Spinlock = NIL_RTSPINLOCK;
254 }
255 return rc;
256}
257
258
259/**
260 * Delete the device extension (e.g. cleanup members).
261 *
262 * @param pDevExt The device extension to delete.
263 */
264void VBOXCALL supdrvDeleteDevExt(PSUPDRVDEVEXT pDevExt)
265{
266#ifdef VBOX_WITH_IDT_PATCHING
267 PSUPDRVPATCH pPatch;
268#endif
269 PSUPDRVOBJ pObj;
270 PSUPDRVUSAGE pUsage;
271
272 /*
273 * Kill mutexes and spinlocks.
274 */
275 RTSemFastMutexDestroy(pDevExt->mtxGip);
276 pDevExt->mtxGip = NIL_RTSEMFASTMUTEX;
277 RTSemFastMutexDestroy(pDevExt->mtxLdr);
278 pDevExt->mtxLdr = NIL_RTSEMFASTMUTEX;
279 RTSpinlockDestroy(pDevExt->Spinlock);
280 pDevExt->Spinlock = NIL_RTSPINLOCK;
281
282 /*
283 * Free lists.
284 */
285#ifdef VBOX_WITH_IDT_PATCHING
286 /* patches */
287 /** @todo make sure we don't uninstall patches which has been patched by someone else. */
288 pPatch = pDevExt->pIdtPatchesFree;
289 pDevExt->pIdtPatchesFree = NULL;
290 while (pPatch)
291 {
292 void *pvFree = pPatch;
293 pPatch = pPatch->pNext;
294 RTMemExecFree(pvFree);
295 }
296#endif /* VBOX_WITH_IDT_PATCHING */
297
298 /* objects. */
299 pObj = pDevExt->pObjs;
300#if !defined(DEBUG_bird) || !defined(RT_OS_LINUX) /* breaks unloading, temporary, remove me! */
301 Assert(!pObj); /* (can trigger on forced unloads) */
302#endif
303 pDevExt->pObjs = NULL;
304 while (pObj)
305 {
306 void *pvFree = pObj;
307 pObj = pObj->pNext;
308 RTMemFree(pvFree);
309 }
310
311 /* usage records. */
312 pUsage = pDevExt->pUsageFree;
313 pDevExt->pUsageFree = NULL;
314 while (pUsage)
315 {
316 void *pvFree = pUsage;
317 pUsage = pUsage->pNext;
318 RTMemFree(pvFree);
319 }
320
321#ifdef USE_NEW_OS_INTERFACE_FOR_GIP
322 /* kill the GIP */
323 supdrvGipDestroy(pDevExt);
324#endif
325}
326
327
328/**
329 * Create session.
330 *
331 * @returns IPRT status code.
332 * @param pDevExt Device extension.
333 * @param ppSession Where to store the pointer to the session data.
334 */
335int VBOXCALL supdrvCreateSession(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION *ppSession)
336{
337 /*
338 * Allocate memory for the session data.
339 */
340 int rc = VERR_NO_MEMORY;
341 PSUPDRVSESSION pSession = *ppSession = (PSUPDRVSESSION)RTMemAllocZ(sizeof(*pSession));
342 if (pSession)
343 {
344 /* Initialize session data. */
345 rc = RTSpinlockCreate(&pSession->Spinlock);
346 if (!rc)
347 {
348 Assert(pSession->Spinlock != NIL_RTSPINLOCK);
349 pSession->pDevExt = pDevExt;
350 pSession->u32Cookie = BIRD_INV;
351 /*pSession->pLdrUsage = NULL;
352 pSession->pPatchUsage = NULL;
353 pSession->pUsage = NULL;
354 pSession->pGip = NULL;
355 pSession->fGipReferenced = false;
356 pSession->Bundle.cUsed = 0 */
357
358 dprintf(("Created session %p initial cookie=%#x\n", pSession, pSession->u32Cookie));
359 return VINF_SUCCESS;
360 }
361
362 RTMemFree(pSession);
363 *ppSession = NULL;
364 }
365
366 dprintf(("Failed to create spinlock, rc=%d!\n", rc));
367 return rc;
368}
369
370
371/**
372 * Shared code for cleaning up a session.
373 *
374 * @param pDevExt Device extension.
375 * @param pSession Session data.
376 * This data will be freed by this routine.
377 */
378void VBOXCALL supdrvCloseSession(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession)
379{
380 /*
381 * Cleanup the session first.
382 */
383 supdrvCleanupSession(pDevExt, pSession);
384
385 /*
386 * Free the rest of the session stuff.
387 */
388 RTSpinlockDestroy(pSession->Spinlock);
389 pSession->Spinlock = NIL_RTSPINLOCK;
390 pSession->pDevExt = NULL;
391 RTMemFree(pSession);
392 dprintf2(("supdrvCloseSession: returns\n"));
393}
394
395
396/**
397 * Shared code for cleaning up a session (but not quite freeing it).
398 *
399 * This is primarily intended for MAC OS X where we have to clean up the memory
400 * stuff before the file handle is closed.
401 *
402 * @param pDevExt Device extension.
403 * @param pSession Session data.
404 * This data will be freed by this routine.
405 */
406void VBOXCALL supdrvCleanupSession(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession)
407{
408 PSUPDRVBUNDLE pBundle;
409 dprintf(("supdrvCleanupSession: pSession=%p\n", pSession));
410
411 /*
412 * Remove logger instances related to this session.
413 * (This assumes the dprintf and dprintf2 macros doesn't use the normal logging.)
414 */
415 RTLogSetDefaultInstanceThread(NULL, (uintptr_t)pSession);
416
417#ifdef VBOX_WITH_IDT_PATCHING
418 /*
419 * Uninstall any IDT patches installed for this session.
420 */
421 supdrvIOCtl_IdtRemoveAll(pDevExt, pSession);
422#endif
423
424 /*
425 * Release object references made in this session.
426 * In theory there should be noone racing us in this session.
427 */
428 dprintf2(("release objects - start\n"));
429 if (pSession->pUsage)
430 {
431 RTSPINLOCKTMP SpinlockTmp = RTSPINLOCKTMP_INITIALIZER;
432 PSUPDRVUSAGE pUsage;
433 RTSpinlockAcquire(pDevExt->Spinlock, &SpinlockTmp);
434
435 while ((pUsage = pSession->pUsage) != NULL)
436 {
437 PSUPDRVOBJ pObj = pUsage->pObj;
438 pSession->pUsage = pUsage->pNext;
439
440 AssertMsg(pUsage->cUsage >= 1 && pObj->cUsage >= pUsage->cUsage, ("glob %d; sess %d\n", pObj->cUsage, pUsage->cUsage));
441 if (pUsage->cUsage < pObj->cUsage)
442 {
443 pObj->cUsage -= pUsage->cUsage;
444 RTSpinlockRelease(pDevExt->Spinlock, &SpinlockTmp);
445 }
446 else
447 {
448 /* Destroy the object and free the record. */
449 if (pDevExt->pObjs == pObj)
450 pDevExt->pObjs = pObj->pNext;
451 else
452 {
453 PSUPDRVOBJ pObjPrev;
454 for (pObjPrev = pDevExt->pObjs; pObjPrev; pObjPrev = pObjPrev->pNext)
455 if (pObjPrev->pNext == pObj)
456 {
457 pObjPrev->pNext = pObj->pNext;
458 break;
459 }
460 Assert(pObjPrev);
461 }
462 RTSpinlockRelease(pDevExt->Spinlock, &SpinlockTmp);
463
464 if (pObj->pfnDestructor)
465 pObj->pfnDestructor(pObj, pObj->pvUser1, pObj->pvUser2);
466 RTMemFree(pObj);
467 }
468
469 /* free it and continue. */
470 RTMemFree(pUsage);
471
472 RTSpinlockAcquire(pDevExt->Spinlock, &SpinlockTmp);
473 }
474
475 RTSpinlockRelease(pDevExt->Spinlock, &SpinlockTmp);
476 AssertMsg(!pSession->pUsage, ("Some buster reregistered an object during desturction!\n"));
477 }
478 dprintf2(("release objects - done\n"));
479
480 /*
481 * Release memory allocated in the session.
482 *
483 * We do not serialize this as we assume that the application will
484 * not allocated memory while closing the file handle object.
485 */
486 dprintf2(("freeing memory:\n"));
487 pBundle = &pSession->Bundle;
488 while (pBundle)
489 {
490 PSUPDRVBUNDLE pToFree;
491 unsigned i;
492
493 /*
494 * Check and unlock all entries in the bundle.
495 */
496 for (i = 0; i < RT_ELEMENTS(pBundle->aMem); i++)
497 {
498 if (pBundle->aMem[i].MemObj != NIL_RTR0MEMOBJ)
499 {
500 int rc;
501 dprintf2(("eType=%d pvR0=%p pvR3=%p cb=%ld\n", pBundle->aMem[i].eType, RTR0MemObjAddress(pBundle->aMem[i].MemObj),
502 (void *)RTR0MemObjAddressR3(pBundle->aMem[i].MapObjR3), (long)RTR0MemObjSize(pBundle->aMem[i].MemObj)));
503 if (pBundle->aMem[i].MapObjR3 != NIL_RTR0MEMOBJ)
504 {
505 rc = RTR0MemObjFree(pBundle->aMem[i].MapObjR3, false);
506 AssertRC(rc); /** @todo figure out how to handle this. */
507 pBundle->aMem[i].MapObjR3 = NIL_RTR0MEMOBJ;
508 }
509 rc = RTR0MemObjFree(pBundle->aMem[i].MemObj, false);
510 AssertRC(rc); /** @todo figure out how to handle this. */
511 pBundle->aMem[i].MemObj = NIL_RTR0MEMOBJ;
512 pBundle->aMem[i].eType = MEMREF_TYPE_UNUSED;
513 }
514 }
515
516 /*
517 * Advance and free previous bundle.
518 */
519 pToFree = pBundle;
520 pBundle = pBundle->pNext;
521
522 pToFree->pNext = NULL;
523 pToFree->cUsed = 0;
524 if (pToFree != &pSession->Bundle)
525 RTMemFree(pToFree);
526 }
527 dprintf2(("freeing memory - done\n"));
528
529 /*
530 * Loaded images needs to be dereferenced and possibly freed up.
531 */
532 RTSemFastMutexRequest(pDevExt->mtxLdr);
533 dprintf2(("freeing images:\n"));
534 if (pSession->pLdrUsage)
535 {
536 PSUPDRVLDRUSAGE pUsage = pSession->pLdrUsage;
537 pSession->pLdrUsage = NULL;
538 while (pUsage)
539 {
540 void *pvFree = pUsage;
541 PSUPDRVLDRIMAGE pImage = pUsage->pImage;
542 if (pImage->cUsage > pUsage->cUsage)
543 pImage->cUsage -= pUsage->cUsage;
544 else
545 supdrvLdrFree(pDevExt, pImage);
546 pUsage->pImage = NULL;
547 pUsage = pUsage->pNext;
548 RTMemFree(pvFree);
549 }
550 }
551 RTSemFastMutexRelease(pDevExt->mtxLdr);
552 dprintf2(("freeing images - done\n"));
553
554 /*
555 * Unmap the GIP.
556 */
557 dprintf2(("umapping GIP:\n"));
558#ifdef USE_NEW_OS_INTERFACE_FOR_GIP
559 if (pSession->GipMapObjR3 != NIL_RTR0MEMOBJ)
560#else
561 if (pSession->pGip)
562#endif
563 {
564 SUPR0GipUnmap(pSession);
565#ifndef USE_NEW_OS_INTERFACE_FOR_GIP
566 pSession->pGip = NULL;
567#endif
568 pSession->fGipReferenced = 0;
569 }
570 dprintf2(("umapping GIP - done\n"));
571}
572
573
574/**
575 * Fast path I/O Control worker.
576 *
577 * @returns VBox status code that should be passed down to ring-3 unchanged.
578 * @param uIOCtl Function number.
579 * @param pDevExt Device extention.
580 * @param pSession Session data.
581 */
582int VBOXCALL supdrvIOCtlFast(uintptr_t uIOCtl, PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession)
583{
584 int rc;
585
586 /*
587 * We check the two prereqs after doing this only to allow the compiler to optimize things better.
588 */
589 if (RT_LIKELY(pSession->pVM && pDevExt->pfnVMMR0EntryFast))
590 {
591 switch (uIOCtl)
592 {
593 case SUP_IOCTL_FAST_DO_RAW_RUN:
594 rc = pDevExt->pfnVMMR0EntryFast(pSession->pVM, SUP_VMMR0_DO_RAW_RUN);
595 break;
596 case SUP_IOCTL_FAST_DO_HWACC_RUN:
597 rc = pDevExt->pfnVMMR0EntryFast(pSession->pVM, SUP_VMMR0_DO_HWACC_RUN);
598 break;
599 case SUP_IOCTL_FAST_DO_NOP:
600 rc = pDevExt->pfnVMMR0EntryFast(pSession->pVM, SUP_VMMR0_DO_NOP);
601 break;
602 default:
603 rc = VERR_INTERNAL_ERROR;
604 break;
605 }
606 }
607 else
608 rc = VERR_INTERNAL_ERROR;
609
610 return rc;
611}
612
613
614/**
615 * I/O Control worker.
616 *
617 * @returns 0 on success.
618 * @returns VERR_INVALID_PARAMETER if the request is invalid.
619 *
620 * @param uIOCtl Function number.
621 * @param pDevExt Device extention.
622 * @param pSession Session data.
623 * @param pReqHdr The request header.
624 */
625int VBOXCALL supdrvIOCtl(uintptr_t uIOCtl, PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPREQHDR pReqHdr)
626{
627 /*
628 * Validate the request.
629 */
630 /* this first check could probably be omitted as its also done by the OS specific code... */
631 if (RT_UNLIKELY( (pReqHdr->fFlags & SUPREQHDR_FLAGS_MAGIC_MASK) != SUPREQHDR_FLAGS_MAGIC
632 || pReqHdr->cbIn < sizeof(*pReqHdr)
633 || pReqHdr->cbOut < sizeof(*pReqHdr)))
634 {
635 OSDBGPRINT(("vboxdrv: Bad ioctl request header; cbIn=%#lx cbOut=%#lx fFlags=%#lx\n",
636 (long)pReqHdr->cbIn, (long)pReqHdr->cbOut, (long)pReqHdr->fFlags));
637 return VERR_INVALID_PARAMETER;
638 }
639 if (RT_UNLIKELY(uIOCtl == SUP_IOCTL_COOKIE))
640 {
641 if (pReqHdr->u32Cookie != SUPCOOKIE_INITIAL_COOKIE)
642 {
643 OSDBGPRINT(("SUP_IOCTL_COOKIE: bad cookie %#lx\n", (long)pReqHdr->u32Cookie));
644 return VERR_INVALID_PARAMETER;
645 }
646 }
647 else if (RT_UNLIKELY( pReqHdr->u32Cookie != pDevExt->u32Cookie
648 || pReqHdr->u32SessionCookie != pSession->u32Cookie))
649 {
650 OSDBGPRINT(("vboxdrv: bad cookie %#lx / %#lx.\n", (long)pReqHdr->u32Cookie, (long)pReqHdr->u32SessionCookie));
651 return VERR_INVALID_PARAMETER;
652 }
653
654/*
655 * Validation macros
656 */
657#define REQ_CHECK_SIZES_EX(Name, cbInExpect, cbOutExpect) \
658 do { \
659 if (RT_UNLIKELY(pReqHdr->cbIn != (cbInExpect) || pReqHdr->cbOut != (cbOutExpect))) \
660 { \
661 OSDBGPRINT(( #Name ": Invalid input/output sizes. cbIn=%ld expected %ld. cbOut=%ld expected %ld.\n", \
662 (long)pReq->Hdr.cbIn, (long)(cbInExpect), (long)pReq->Hdr.cbOut, (long)(cbOutExpect))); \
663 return pReq->Hdr.rc = VERR_INVALID_PARAMETER; \
664 } \
665 } while (0)
666
667#define REQ_CHECK_SIZES(Name) REQ_CHECK_SIZES_EX(Name, Name ## _SIZE_IN, Name ## _SIZE_OUT)
668
669#define REQ_CHECK_SIZE_IN(Name, cbInExpect) \
670 do { \
671 if (RT_UNLIKELY(pReqHdr->cbIn != (cbInExpect))) \
672 { \
673 OSDBGPRINT(( #Name ": Invalid input/output sizes. cbIn=%ld expected %ld.\n", \
674 (long)pReq->Hdr.cbIn, (long)(cbInExpect))); \
675 return pReq->Hdr.rc = VERR_INVALID_PARAMETER; \
676 } \
677 } while (0)
678
679#define REQ_CHECK_SIZE_OUT(Name, cbOutExpect) \
680 do { \
681 if (RT_UNLIKELY(pReqHdr->cbOut != (cbOutExpect))) \
682 { \
683 OSDBGPRINT(( #Name ": Invalid input/output sizes. cbOut=%ld expected %ld.\n", \
684 (long)pReq->Hdr.cbOut, (long)(cbOutExpect))); \
685 return pReq->Hdr.rc = VERR_INVALID_PARAMETER; \
686 } \
687 } while (0)
688
689#define REQ_CHECK_EXPR(Name, expr) \
690 do { \
691 if (RT_UNLIKELY(!(expr))) \
692 { \
693 OSDBGPRINT(( #Name ": %s\n", #expr)); \
694 return pReq->Hdr.rc = VERR_INVALID_PARAMETER; \
695 } \
696 } while (0)
697
698#define REQ_CHECK_EXPR_FMT(expr, fmt) \
699 do { \
700 if (RT_UNLIKELY(!(expr))) \
701 { \
702 OSDBGPRINT( fmt ); \
703 return pReq->Hdr.rc = VERR_INVALID_PARAMETER; \
704 } \
705 } while (0)
706
707
708 /*
709 * The switch.
710 */
711 switch (SUP_CTL_CODE_NO_SIZE(uIOCtl))
712 {
713 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_COOKIE):
714 {
715 PSUPCOOKIE pReq = (PSUPCOOKIE)pReqHdr;
716 REQ_CHECK_SIZES(SUP_IOCTL_COOKIE);
717 if (strncmp(pReq->u.In.szMagic, SUPCOOKIE_MAGIC, sizeof(pReq->u.In.szMagic)))
718 {
719 OSDBGPRINT(("SUP_IOCTL_COOKIE: invalid magic %.16s\n", pReq->u.In.szMagic));
720 pReq->Hdr.rc = VERR_INVALID_MAGIC;
721 return 0;
722 }
723
724#if 0
725 /*
726 * Call out to the OS specific code and let it do permission checks on the
727 * client process.
728 */
729 if (!supdrvOSValidateClientProcess(pDevExt, pSession))
730 {
731 pReq->u.Out.u32Cookie = 0xffffffff;
732 pReq->u.Out.u32SessionCookie = 0xffffffff;
733 pReq->u.Out.u32SessionVersion = 0xffffffff;
734 pReq->u.Out.u32DriverVersion = SUPDRVIOC_VERSION;
735 pReq->u.Out.pSession = NULL;
736 pReq->u.Out.cFunctions = 0;
737 pReq->Hdr.rc = VERR_PERMISSION_DENIED;
738 return 0;
739 }
740#endif
741
742 /*
743 * Match the version.
744 * The current logic is very simple, match the major interface version.
745 */
746 if ( pReq->u.In.u32MinVersion > SUPDRVIOC_VERSION
747 || (pReq->u.In.u32MinVersion & 0xffff0000) != (SUPDRVIOC_VERSION & 0xffff0000))
748 {
749 OSDBGPRINT(("SUP_IOCTL_COOKIE: Version mismatch. Requested: %#x Min: %#x Current: %#x\n",
750 pReq->u.In.u32ReqVersion, pReq->u.In.u32MinVersion, SUPDRVIOC_VERSION));
751 pReq->u.Out.u32Cookie = 0xffffffff;
752 pReq->u.Out.u32SessionCookie = 0xffffffff;
753 pReq->u.Out.u32SessionVersion = 0xffffffff;
754 pReq->u.Out.u32DriverVersion = SUPDRVIOC_VERSION;
755 pReq->u.Out.pSession = NULL;
756 pReq->u.Out.cFunctions = 0;
757 pReq->Hdr.rc = VERR_VERSION_MISMATCH;
758 return 0;
759 }
760
761 /*
762 * Fill in return data and be gone.
763 * N.B. The first one to change SUPDRVIOC_VERSION shall makes sure that
764 * u32SessionVersion <= u32ReqVersion!
765 */
766 /** @todo Somehow validate the client and negotiate a secure cookie... */
767 pReq->u.Out.u32Cookie = pDevExt->u32Cookie;
768 pReq->u.Out.u32SessionCookie = pSession->u32Cookie;
769 pReq->u.Out.u32SessionVersion = SUPDRVIOC_VERSION;
770 pReq->u.Out.u32DriverVersion = SUPDRVIOC_VERSION;
771 pReq->u.Out.pSession = pSession;
772 pReq->u.Out.cFunctions = sizeof(g_aFunctions) / sizeof(g_aFunctions[0]);
773 pReq->Hdr.rc = VINF_SUCCESS;
774 return 0;
775 }
776
777 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_QUERY_FUNCS(0)):
778 {
779 /* validate */
780 PSUPQUERYFUNCS pReq = (PSUPQUERYFUNCS)pReqHdr;
781 REQ_CHECK_SIZES_EX(SUP_IOCTL_QUERY_FUNCS, SUP_IOCTL_QUERY_FUNCS_SIZE_IN, SUP_IOCTL_QUERY_FUNCS_SIZE_OUT(RT_ELEMENTS(g_aFunctions)));
782
783 /* execute */
784 pReq->u.Out.cFunctions = RT_ELEMENTS(g_aFunctions);
785 memcpy(&pReq->u.Out.aFunctions[0], g_aFunctions, sizeof(g_aFunctions));
786 pReq->Hdr.rc = VINF_SUCCESS;
787 return 0;
788 }
789
790 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_IDT_INSTALL):
791 {
792 /* validate */
793 PSUPIDTINSTALL pReq = (PSUPIDTINSTALL)pReqHdr;
794 REQ_CHECK_SIZES(SUP_IOCTL_IDT_INSTALL);
795
796 /* execute */
797#ifdef VBOX_WITH_IDT_PATCHING
798 pReq->Hdr.rc = supdrvIOCtl_IdtInstall(pDevExt, pSession, pReq);
799#else
800 pReq->u.Out.u8Idt = 3;
801 pReq->Hdr.rc = VERR_NOT_SUPPORTED;
802#endif
803 return 0;
804 }
805
806 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_IDT_REMOVE):
807 {
808 /* validate */
809 PSUPIDTREMOVE pReq = (PSUPIDTREMOVE)pReqHdr;
810 REQ_CHECK_SIZES(SUP_IOCTL_IDT_REMOVE);
811
812 /* execute */
813#ifdef VBOX_WITH_IDT_PATCHING
814 pReq->Hdr.rc = supdrvIOCtl_IdtRemoveAll(pDevExt, pSession);
815#else
816 pReq->Hdr.rc = VERR_NOT_SUPPORTED;
817#endif
818 return 0;
819 }
820
821 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_PAGE_LOCK):
822 {
823 /* validate */
824 PSUPPAGELOCK pReq = (PSUPPAGELOCK)pReqHdr;
825 REQ_CHECK_SIZE_IN(SUP_IOCTL_PAGE_LOCK, SUP_IOCTL_PAGE_LOCK_SIZE_IN);
826 REQ_CHECK_SIZE_OUT(SUP_IOCTL_PAGE_LOCK, SUP_IOCTL_PAGE_LOCK_SIZE_OUT(pReq->u.In.cPages));
827 REQ_CHECK_EXPR(SUP_IOCTL_PAGE_LOCK, pReq->u.In.cPages > 0);
828 REQ_CHECK_EXPR(SUP_IOCTL_PAGE_LOCK, pReq->u.In.pvR3 >= PAGE_SIZE);
829
830 /* execute */
831 pReq->Hdr.rc = SUPR0LockMem(pSession, pReq->u.In.pvR3, pReq->u.In.cPages, &pReq->u.Out.aPages[0]);
832 if (RT_FAILURE(pReq->Hdr.rc))
833 pReq->Hdr.cbOut = sizeof(pReq->Hdr);
834 return 0;
835 }
836
837 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_PAGE_UNLOCK):
838 {
839 /* validate */
840 PSUPPAGEUNLOCK pReq = (PSUPPAGEUNLOCK)pReqHdr;
841 REQ_CHECK_SIZES(SUP_IOCTL_PAGE_UNLOCK);
842
843 /* execute */
844 pReq->Hdr.rc = SUPR0UnlockMem(pSession, pReq->u.In.pvR3);
845 return 0;
846 }
847
848 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_CONT_ALLOC):
849 {
850 /* validate */
851 PSUPCONTALLOC pReq = (PSUPCONTALLOC)pReqHdr;
852 REQ_CHECK_SIZES(SUP_IOCTL_CONT_ALLOC);
853
854 /* execute */
855 pReq->Hdr.rc = SUPR0ContAlloc(pSession, pReq->u.In.cPages, &pReq->u.Out.pvR0, &pReq->u.Out.pvR3, &pReq->u.Out.HCPhys);
856 if (RT_FAILURE(pReq->Hdr.rc))
857 pReq->Hdr.cbOut = sizeof(pReq->Hdr);
858 return 0;
859 }
860
861 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_CONT_FREE):
862 {
863 /* validate */
864 PSUPCONTFREE pReq = (PSUPCONTFREE)pReqHdr;
865 REQ_CHECK_SIZES(SUP_IOCTL_CONT_FREE);
866
867 /* execute */
868 pReq->Hdr.rc = SUPR0ContFree(pSession, (RTHCUINTPTR)pReq->u.In.pvR3);
869 return 0;
870 }
871
872 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_LDR_OPEN):
873 {
874 /* validate */
875 PSUPLDROPEN pReq = (PSUPLDROPEN)pReqHdr;
876 REQ_CHECK_SIZES(SUP_IOCTL_LDR_OPEN);
877 REQ_CHECK_EXPR(SUP_IOCTL_LDR_OPEN, pReq->u.In.cbImage > 0);
878 REQ_CHECK_EXPR(SUP_IOCTL_LDR_OPEN, pReq->u.In.cbImage < _1M*16);
879 REQ_CHECK_EXPR(SUP_IOCTL_LDR_OPEN, pReq->u.In.szName[0]);
880 REQ_CHECK_EXPR(SUP_IOCTL_LDR_OPEN, memchr(pReq->u.In.szName, '\0', sizeof(pReq->u.In.szName)));
881 REQ_CHECK_EXPR(SUP_IOCTL_LDR_OPEN, !strpbrk(pReq->u.In.szName, ";:()[]{}/\\|&*%#@!~`\"'"));
882
883 /* execute */
884 pReq->Hdr.rc = supdrvIOCtl_LdrOpen(pDevExt, pSession, pReq);
885 return 0;
886 }
887
888 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_LDR_LOAD):
889 {
890 /* validate */
891 PSUPLDRLOAD pReq = (PSUPLDRLOAD)pReqHdr;
892 REQ_CHECK_EXPR(Name, pReq->Hdr.cbIn >= sizeof(*pReq));
893 REQ_CHECK_SIZES_EX(SUP_IOCTL_LDR_LOAD, SUP_IOCTL_LDR_LOAD_SIZE_IN(pReq->u.In.cbImage), SUP_IOCTL_LDR_LOAD_SIZE_OUT);
894 REQ_CHECK_EXPR(SUP_IOCTL_LDR_LOAD, pReq->u.In.cSymbols <= 16384);
895 REQ_CHECK_EXPR_FMT( !pReq->u.In.cSymbols
896 || ( pReq->u.In.offSymbols < pReq->u.In.cbImage
897 && pReq->u.In.offSymbols + pReq->u.In.cSymbols * sizeof(SUPLDRSYM) <= pReq->u.In.cbImage),
898 ("SUP_IOCTL_LDR_LOAD: offSymbols=%#lx cSymbols=%#lx cbImage=%#lx\n", (long)pReq->u.In.offSymbols,
899 (long)pReq->u.In.cSymbols, (long)pReq->u.In.cbImage));
900 REQ_CHECK_EXPR_FMT( !pReq->u.In.cbStrTab
901 || ( pReq->u.In.offStrTab < pReq->u.In.cbImage
902 && pReq->u.In.offStrTab + pReq->u.In.cbStrTab <= pReq->u.In.cbImage
903 && pReq->u.In.cbStrTab <= pReq->u.In.cbImage),
904 ("SUP_IOCTL_LDR_LOAD: offStrTab=%#lx cbStrTab=%#lx cbImage=%#lx\n", (long)pReq->u.In.offStrTab,
905 (long)pReq->u.In.cbStrTab, (long)pReq->u.In.cbImage));
906
907 if (pReq->u.In.cSymbols)
908 {
909 uint32_t i;
910 PSUPLDRSYM paSyms = (PSUPLDRSYM)&pReq->u.In.achImage[pReq->u.In.offSymbols];
911 for (i = 0; i < pReq->u.In.cSymbols; i++)
912 {
913 REQ_CHECK_EXPR_FMT(paSyms[i].offSymbol < pReq->u.In.cbImage,
914 ("SUP_IOCTL_LDR_LOAD: sym #%ld: symb off %#lx (max=%#lx)\n", (long)i, (long)paSyms[i].offSymbol, (long)pReq->u.In.cbImage));
915 REQ_CHECK_EXPR_FMT(paSyms[i].offName < pReq->u.In.cbStrTab,
916 ("SUP_IOCTL_LDR_LOAD: sym #%ld: name off %#lx (max=%#lx)\n", (long)i, (long)paSyms[i].offName, (long)pReq->u.In.cbImage));
917 REQ_CHECK_EXPR_FMT(memchr(&pReq->u.In.achImage[pReq->u.In.offStrTab + paSyms[i].offName], '\0', pReq->u.In.cbStrTab - paSyms[i].offName),
918 ("SUP_IOCTL_LDR_LOAD: sym #%ld: unterminated name! (%#lx / %#lx)\n", (long)i, (long)paSyms[i].offName, (long)pReq->u.In.cbImage));
919 }
920 }
921
922 /* execute */
923 pReq->Hdr.rc = supdrvIOCtl_LdrLoad(pDevExt, pSession, pReq);
924 return 0;
925 }
926
927 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_LDR_FREE):
928 {
929 /* validate */
930 PSUPLDRFREE pReq = (PSUPLDRFREE)pReqHdr;
931 REQ_CHECK_SIZES(SUP_IOCTL_LDR_FREE);
932
933 /* execute */
934 pReq->Hdr.rc = supdrvIOCtl_LdrFree(pDevExt, pSession, pReq);
935 return 0;
936 }
937
938 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_LDR_GET_SYMBOL):
939 {
940 /* validate */
941 PSUPLDRGETSYMBOL pReq = (PSUPLDRGETSYMBOL)pReqHdr;
942 REQ_CHECK_SIZES(SUP_IOCTL_LDR_GET_SYMBOL);
943 REQ_CHECK_EXPR(SUP_IOCTL_LDR_GET_SYMBOL, memchr(pReq->u.In.szSymbol, '\0', sizeof(pReq->u.In.szSymbol)));
944
945 /* execute */
946 pReq->Hdr.rc = supdrvIOCtl_LdrGetSymbol(pDevExt, pSession, pReq);
947 return 0;
948 }
949
950 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_CALL_VMMR0(0)):
951 {
952 /* validate */
953 PSUPCALLVMMR0 pReq = (PSUPCALLVMMR0)pReqHdr;
954 if (pReq->Hdr.cbIn == SUP_IOCTL_CALL_VMMR0_SIZE(0))
955 {
956 REQ_CHECK_SIZES_EX(SUP_IOCTL_CALL_VMMR0, SUP_IOCTL_CALL_VMMR0_SIZE_IN(0), SUP_IOCTL_CALL_VMMR0_SIZE_OUT(0));
957
958 /* execute */
959 if (RT_LIKELY(pDevExt->pfnVMMR0EntryEx))
960 pReq->Hdr.rc = pDevExt->pfnVMMR0EntryEx(pReq->u.In.pVMR0, pReq->u.In.uOperation, NULL, pReq->u.In.u64Arg);
961 else
962 pReq->Hdr.rc = VERR_WRONG_ORDER;
963 }
964 else
965 {
966 PSUPVMMR0REQHDR pVMMReq = (PSUPVMMR0REQHDR)&pReq->abReqPkt[0];
967 REQ_CHECK_EXPR_FMT(pReq->Hdr.cbIn >= SUP_IOCTL_CALL_VMMR0_SIZE(sizeof(SUPVMMR0REQHDR)),
968 ("SUP_IOCTL_CALL_VMMR0: cbIn=%#x < %#x\n", pReq->Hdr.cbIn, SUP_IOCTL_CALL_VMMR0_SIZE(sizeof(SUPVMMR0REQHDR))));
969 REQ_CHECK_EXPR(SUP_IOCTL_CALL_VMMR0, pVMMReq->u32Magic == SUPVMMR0REQHDR_MAGIC);
970 REQ_CHECK_SIZES_EX(SUP_IOCTL_CALL_VMMR0, SUP_IOCTL_CALL_VMMR0_SIZE_IN(pVMMReq->cbReq), SUP_IOCTL_CALL_VMMR0_SIZE_OUT(pVMMReq->cbReq));
971
972 /* execute */
973 if (RT_LIKELY(pDevExt->pfnVMMR0EntryEx))
974 pReq->Hdr.rc = pDevExt->pfnVMMR0EntryEx(pReq->u.In.pVMR0, pReq->u.In.uOperation, pVMMReq, pReq->u.In.u64Arg);
975 else
976 pReq->Hdr.rc = VERR_WRONG_ORDER;
977 }
978 return 0;
979 }
980
981 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_GET_PAGING_MODE):
982 {
983 /* validate */
984 PSUPGETPAGINGMODE pReq = (PSUPGETPAGINGMODE)pReqHdr;
985 REQ_CHECK_SIZES(SUP_IOCTL_GET_PAGING_MODE);
986
987 /* execute */
988 pReq->Hdr.rc = VINF_SUCCESS;
989 pReq->u.Out.enmMode = supdrvIOCtl_GetPagingMode();
990 return 0;
991 }
992
993 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_LOW_ALLOC):
994 {
995 /* validate */
996 PSUPLOWALLOC pReq = (PSUPLOWALLOC)pReqHdr;
997 REQ_CHECK_EXPR(SUP_IOCTL_LOW_ALLOC, pReq->Hdr.cbIn <= SUP_IOCTL_LOW_ALLOC_SIZE_IN);
998 REQ_CHECK_SIZES_EX(SUP_IOCTL_LOW_ALLOC, SUP_IOCTL_LOW_ALLOC_SIZE_IN, SUP_IOCTL_LOW_ALLOC_SIZE_OUT(pReq->u.In.cPages));
999
1000 /* execute */
1001 pReq->Hdr.rc = SUPR0LowAlloc(pSession, pReq->u.In.cPages, &pReq->u.Out.pvR0, &pReq->u.Out.pvR3, &pReq->u.Out.aPages[0]);
1002 if (RT_FAILURE(pReq->Hdr.rc))
1003 pReq->Hdr.cbOut = sizeof(pReq->Hdr);
1004 return 0;
1005 }
1006
1007 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_LOW_FREE):
1008 {
1009 /* validate */
1010 PSUPLOWFREE pReq = (PSUPLOWFREE)pReqHdr;
1011 REQ_CHECK_SIZES(SUP_IOCTL_LOW_FREE);
1012
1013 /* execute */
1014 pReq->Hdr.rc = SUPR0LowFree(pSession, (RTHCUINTPTR)pReq->u.In.pvR3);
1015 return 0;
1016 }
1017
1018 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_GIP_MAP):
1019 {
1020 /* validate */
1021 PSUPGIPMAP pReq = (PSUPGIPMAP)pReqHdr;
1022 REQ_CHECK_SIZES(SUP_IOCTL_GIP_MAP);
1023
1024 /* execute */
1025 pReq->Hdr.rc = SUPR0GipMap(pSession, &pReq->u.Out.pGipR3, &pReq->u.Out.HCPhysGip);
1026 if (RT_SUCCESS(pReq->Hdr.rc))
1027 pReq->u.Out.pGipR0 = pDevExt->pGip;
1028 return 0;
1029 }
1030
1031 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_GIP_UNMAP):
1032 {
1033 /* validate */
1034 PSUPGIPUNMAP pReq = (PSUPGIPUNMAP)pReqHdr;
1035 REQ_CHECK_SIZES(SUP_IOCTL_GIP_UNMAP);
1036
1037 /* execute */
1038 pReq->Hdr.rc = SUPR0GipUnmap(pSession);
1039 return 0;
1040 }
1041
1042 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_SET_VM_FOR_FAST):
1043 {
1044 /* validate */
1045 PSUPSETVMFORFAST pReq = (PSUPSETVMFORFAST)pReqHdr;
1046 REQ_CHECK_SIZES(SUP_IOCTL_SET_VM_FOR_FAST);
1047 REQ_CHECK_EXPR_FMT( !pReq->u.In.pVMR0
1048 || ( VALID_PTR(pReq->u.In.pVMR0)
1049 && !((uintptr_t)pReq->u.In.pVMR0 & (PAGE_SIZE - 1))),
1050 ("SUP_IOCTL_SET_VM_FOR_FAST: pVMR0=%p!\n", pReq->u.In.pVMR0));
1051 /* execute */
1052 pSession->pVM = pReq->u.In.pVMR0;
1053 pReq->Hdr.rc = VINF_SUCCESS;
1054 return 0;
1055 }
1056
1057 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_PAGE_ALLOC):
1058 {
1059 /* validate */
1060 PSUPPAGEALLOC pReq = (PSUPPAGEALLOC)pReqHdr;
1061 REQ_CHECK_EXPR(SUP_IOCTL_PAGE_ALLOC, pReq->Hdr.cbIn <= SUP_IOCTL_PAGE_ALLOC_SIZE_IN);
1062 REQ_CHECK_SIZES_EX(SUP_IOCTL_PAGE_ALLOC, SUP_IOCTL_PAGE_ALLOC_SIZE_IN, SUP_IOCTL_PAGE_ALLOC_SIZE_OUT(pReq->u.In.cPages));
1063
1064 /* execute */
1065 pReq->Hdr.rc = SUPR0PageAlloc(pSession, pReq->u.In.cPages, &pReq->u.Out.pvR3, &pReq->u.Out.aPages[0]);
1066 if (RT_FAILURE(pReq->Hdr.rc))
1067 pReq->Hdr.cbOut = sizeof(pReq->Hdr);
1068 return 0;
1069 }
1070
1071 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_PAGE_FREE):
1072 {
1073 /* validate */
1074 PSUPPAGEFREE pReq = (PSUPPAGEFREE)pReqHdr;
1075 REQ_CHECK_SIZES(SUP_IOCTL_PAGE_FREE);
1076
1077 /* execute */
1078 pReq->Hdr.rc = SUPR0PageFree(pSession, pReq->u.In.pvR3);
1079 return 0;
1080 }
1081
1082 default:
1083 dprintf(("Unknown IOCTL %#lx\n", (long)uIOCtl));
1084 break;
1085 }
1086 return SUPDRV_ERR_GENERAL_FAILURE;
1087}
1088
1089
1090/**
1091 * Register a object for reference counting.
1092 * The object is registered with one reference in the specified session.
1093 *
1094 * @returns Unique identifier on success (pointer).
1095 * All future reference must use this identifier.
1096 * @returns NULL on failure.
1097 * @param pfnDestructor The destructore function which will be called when the reference count reaches 0.
1098 * @param pvUser1 The first user argument.
1099 * @param pvUser2 The second user argument.
1100 */
1101SUPR0DECL(void *) SUPR0ObjRegister(PSUPDRVSESSION pSession, SUPDRVOBJTYPE enmType, PFNSUPDRVDESTRUCTOR pfnDestructor, void *pvUser1, void *pvUser2)
1102{
1103 RTSPINLOCKTMP SpinlockTmp = RTSPINLOCKTMP_INITIALIZER;
1104 PSUPDRVDEVEXT pDevExt = pSession->pDevExt;
1105 PSUPDRVOBJ pObj;
1106 PSUPDRVUSAGE pUsage;
1107
1108 /*
1109 * Validate the input.
1110 */
1111 AssertReturn(SUP_IS_SESSION_VALID(pSession), NULL);
1112 AssertReturn(enmType > SUPDRVOBJTYPE_INVALID && enmType < SUPDRVOBJTYPE_END, NULL);
1113 AssertPtrReturn(pfnDestructor, NULL);
1114
1115 /*
1116 * Allocate and initialize the object.
1117 */
1118 pObj = (PSUPDRVOBJ)RTMemAlloc(sizeof(*pObj));
1119 if (!pObj)
1120 return NULL;
1121 pObj->u32Magic = SUPDRVOBJ_MAGIC;
1122 pObj->enmType = enmType;
1123 pObj->pNext = NULL;
1124 pObj->cUsage = 1;
1125 pObj->pfnDestructor = pfnDestructor;
1126 pObj->pvUser1 = pvUser1;
1127 pObj->pvUser2 = pvUser2;
1128 pObj->CreatorUid = pSession->Uid;
1129 pObj->CreatorGid = pSession->Gid;
1130 pObj->CreatorProcess= pSession->Process;
1131 supdrvOSObjInitCreator(pObj, pSession);
1132
1133 /*
1134 * Allocate the usage record.
1135 * (We keep freed usage records around to simplity SUPR0ObjAddRef().)
1136 */
1137 RTSpinlockAcquire(pDevExt->Spinlock, &SpinlockTmp);
1138
1139 pUsage = pDevExt->pUsageFree;
1140 if (pUsage)
1141 pDevExt->pUsageFree = pUsage->pNext;
1142 else
1143 {
1144 RTSpinlockRelease(pDevExt->Spinlock, &SpinlockTmp);
1145 pUsage = (PSUPDRVUSAGE)RTMemAlloc(sizeof(*pUsage));
1146 if (!pUsage)
1147 {
1148 RTMemFree(pObj);
1149 return NULL;
1150 }
1151 RTSpinlockAcquire(pDevExt->Spinlock, &SpinlockTmp);
1152 }
1153
1154 /*
1155 * Insert the object and create the session usage record.
1156 */
1157 /* The object. */
1158 pObj->pNext = pDevExt->pObjs;
1159 pDevExt->pObjs = pObj;
1160
1161 /* The session record. */
1162 pUsage->cUsage = 1;
1163 pUsage->pObj = pObj;
1164 pUsage->pNext = pSession->pUsage;
1165 dprintf(("SUPR0ObjRegister: pUsage=%p:{.pObj=%p, .pNext=%p}\n", pUsage, pUsage->pObj, pUsage->pNext));
1166 pSession->pUsage = pUsage;
1167
1168 RTSpinlockRelease(pDevExt->Spinlock, &SpinlockTmp);
1169
1170 dprintf(("SUPR0ObjRegister: returns %p (pvUser1=%p, pvUser=%p)\n", pObj, pvUser1, pvUser2));
1171 return pObj;
1172}
1173
1174
1175/**
1176 * Increment the reference counter for the object associating the reference
1177 * with the specified session.
1178 *
1179 * @returns IPRT status code.
1180 * @param pvObj The identifier returned by SUPR0ObjRegister().
1181 * @param pSession The session which is referencing the object.
1182 */
1183SUPR0DECL(int) SUPR0ObjAddRef(void *pvObj, PSUPDRVSESSION pSession)
1184{
1185 RTSPINLOCKTMP SpinlockTmp = RTSPINLOCKTMP_INITIALIZER;
1186 PSUPDRVDEVEXT pDevExt = pSession->pDevExt;
1187 PSUPDRVOBJ pObj = (PSUPDRVOBJ)pvObj;
1188 PSUPDRVUSAGE pUsagePre;
1189 PSUPDRVUSAGE pUsage;
1190
1191 /*
1192 * Validate the input.
1193 */
1194 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
1195 AssertMsgReturn(VALID_PTR(pObj) && pObj->u32Magic == SUPDRVOBJ_MAGIC,
1196 ("Invalid pvObj=%p magic=%#x (exepcted %#x)\n", pvObj, pObj ? pObj->u32Magic : 0, SUPDRVOBJ_MAGIC),
1197 VERR_INVALID_PARAMETER);
1198
1199 /*
1200 * Preallocate the usage record.
1201 */
1202 RTSpinlockAcquire(pDevExt->Spinlock, &SpinlockTmp);
1203
1204 pUsagePre = pDevExt->pUsageFree;
1205 if (pUsagePre)
1206 pDevExt->pUsageFree = pUsagePre->pNext;
1207 else
1208 {
1209 RTSpinlockRelease(pDevExt->Spinlock, &SpinlockTmp);
1210 pUsagePre = (PSUPDRVUSAGE)RTMemAlloc(sizeof(*pUsagePre));
1211 if (!pUsagePre)
1212 return VERR_NO_MEMORY;
1213 RTSpinlockAcquire(pDevExt->Spinlock, &SpinlockTmp);
1214 }
1215
1216 /*
1217 * Reference the object.
1218 */
1219 pObj->cUsage++;
1220
1221 /*
1222 * Look for the session record.
1223 */
1224 for (pUsage = pSession->pUsage; pUsage; pUsage = pUsage->pNext)
1225 {
1226 dprintf(("SUPR0AddRef: pUsage=%p:{.pObj=%p, .pNext=%p}\n", pUsage, pUsage->pObj, pUsage->pNext));
1227 if (pUsage->pObj == pObj)
1228 break;
1229 }
1230 if (pUsage)
1231 pUsage->cUsage++;
1232 else
1233 {
1234 /* create a new session record. */
1235 pUsagePre->cUsage = 1;
1236 pUsagePre->pObj = pObj;
1237 pUsagePre->pNext = pSession->pUsage;
1238 pSession->pUsage = pUsagePre;
1239 dprintf(("SUPR0AddRef: pUsagePre=%p:{.pObj=%p, .pNext=%p}\n", pUsagePre, pUsagePre->pObj, pUsagePre->pNext));
1240
1241 pUsagePre = NULL;
1242 }
1243
1244 /*
1245 * Put any unused usage record into the free list..
1246 */
1247 if (pUsagePre)
1248 {
1249 pUsagePre->pNext = pDevExt->pUsageFree;
1250 pDevExt->pUsageFree = pUsagePre;
1251 }
1252
1253 RTSpinlockRelease(pDevExt->Spinlock, &SpinlockTmp);
1254
1255 return VINF_SUCCESS;
1256}
1257
1258
1259/**
1260 * Decrement / destroy a reference counter record for an object.
1261 *
1262 * The object is uniquely identified by pfnDestructor+pvUser1+pvUser2.
1263 *
1264 * @returns IPRT status code.
1265 * @param pvObj The identifier returned by SUPR0ObjRegister().
1266 * @param pSession The session which is referencing the object.
1267 */
1268SUPR0DECL(int) SUPR0ObjRelease(void *pvObj, PSUPDRVSESSION pSession)
1269{
1270 RTSPINLOCKTMP SpinlockTmp = RTSPINLOCKTMP_INITIALIZER;
1271 PSUPDRVDEVEXT pDevExt = pSession->pDevExt;
1272 PSUPDRVOBJ pObj = (PSUPDRVOBJ)pvObj;
1273 bool fDestroy = false;
1274 PSUPDRVUSAGE pUsage;
1275 PSUPDRVUSAGE pUsagePrev;
1276
1277 /*
1278 * Validate the input.
1279 */
1280 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
1281 AssertMsgReturn(VALID_PTR(pObj) && pObj->u32Magic == SUPDRVOBJ_MAGIC,
1282 ("Invalid pvObj=%p magic=%#x (exepcted %#x)\n", pvObj, pObj ? pObj->u32Magic : 0, SUPDRVOBJ_MAGIC),
1283 VERR_INVALID_PARAMETER);
1284
1285 /*
1286 * Acquire the spinlock and look for the usage record.
1287 */
1288 RTSpinlockAcquire(pDevExt->Spinlock, &SpinlockTmp);
1289
1290 for (pUsagePrev = NULL, pUsage = pSession->pUsage;
1291 pUsage;
1292 pUsagePrev = pUsage, pUsage = pUsage->pNext)
1293 {
1294 dprintf(("SUPR0ObjRelease: pUsage=%p:{.pObj=%p, .pNext=%p}\n", pUsage, pUsage->pObj, pUsage->pNext));
1295 if (pUsage->pObj == pObj)
1296 {
1297 AssertMsg(pUsage->cUsage >= 1 && pObj->cUsage >= pUsage->cUsage, ("glob %d; sess %d\n", pObj->cUsage, pUsage->cUsage));
1298 if (pUsage->cUsage > 1)
1299 {
1300 pObj->cUsage--;
1301 pUsage->cUsage--;
1302 }
1303 else
1304 {
1305 /*
1306 * Free the session record.
1307 */
1308 if (pUsagePrev)
1309 pUsagePrev->pNext = pUsage->pNext;
1310 else
1311 pSession->pUsage = pUsage->pNext;
1312 pUsage->pNext = pDevExt->pUsageFree;
1313 pDevExt->pUsageFree = pUsage;
1314
1315 /* What about the object? */
1316 if (pObj->cUsage > 1)
1317 pObj->cUsage--;
1318 else
1319 {
1320 /*
1321 * Object is to be destroyed, unlink it.
1322 */
1323 fDestroy = true;
1324 if (pDevExt->pObjs == pObj)
1325 pDevExt->pObjs = pObj->pNext;
1326 else
1327 {
1328 PSUPDRVOBJ pObjPrev;
1329 for (pObjPrev = pDevExt->pObjs; pObjPrev; pObjPrev = pObjPrev->pNext)
1330 if (pObjPrev->pNext == pObj)
1331 {
1332 pObjPrev->pNext = pObj->pNext;
1333 break;
1334 }
1335 Assert(pObjPrev);
1336 }
1337 }
1338 }
1339 break;
1340 }
1341 }
1342
1343 RTSpinlockRelease(pDevExt->Spinlock, &SpinlockTmp);
1344
1345 /*
1346 * Call the destructor and free the object if required.
1347 */
1348 if (fDestroy)
1349 {
1350 pObj->u32Magic++;
1351 if (pObj->pfnDestructor)
1352 pObj->pfnDestructor(pObj, pObj->pvUser1, pObj->pvUser2);
1353 RTMemFree(pObj);
1354 }
1355
1356 AssertMsg(pUsage, ("pvObj=%p\n", pvObj));
1357 return pUsage ? VINF_SUCCESS : VERR_INVALID_PARAMETER;
1358}
1359
1360/**
1361 * Verifies that the current process can access the specified object.
1362 *
1363 * @returns The following IPRT status code:
1364 * @retval VINF_SUCCESS if access was granted.
1365 * @retval VERR_PERMISSION_DENIED if denied access.
1366 * @retval VERR_INVALID_PARAMETER if invalid parameter.
1367 *
1368 * @param pvObj The identifier returned by SUPR0ObjRegister().
1369 * @param pSession The session which wishes to access the object.
1370 * @param pszObjName Object string name. This is optional and depends on the object type.
1371 *
1372 * @remark The caller is responsible for making sure the object isn't removed while
1373 * we're inside this function. If uncertain about this, just call AddRef before calling us.
1374 */
1375SUPR0DECL(int) SUPR0ObjVerifyAccess(void *pvObj, PSUPDRVSESSION pSession, const char *pszObjName)
1376{
1377 PSUPDRVOBJ pObj = (PSUPDRVOBJ)pvObj;
1378 int rc;
1379
1380 /*
1381 * Validate the input.
1382 */
1383 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
1384 AssertMsgReturn(VALID_PTR(pObj) && pObj->u32Magic == SUPDRVOBJ_MAGIC,
1385 ("Invalid pvObj=%p magic=%#x (exepcted %#x)\n", pvObj, pObj ? pObj->u32Magic : 0, SUPDRVOBJ_MAGIC),
1386 VERR_INVALID_PARAMETER);
1387
1388 /*
1389 * Check access. (returns true if a decision has been made.)
1390 */
1391 rc = VERR_INTERNAL_ERROR;
1392 if (supdrvOSObjCanAccess(pObj, pSession, pszObjName, &rc))
1393 return rc;
1394
1395 /*
1396 * Default policy is to allow the user to access his own
1397 * stuff but nothing else.
1398 */
1399 if (pObj->CreatorUid == pSession->Uid)
1400 return VINF_SUCCESS;
1401 return VERR_PERMISSION_DENIED;
1402}
1403
1404
1405/**
1406 * Lock pages.
1407 *
1408 * @returns IPRT status code.
1409 * @param pSession Session to which the locked memory should be associated.
1410 * @param pvR3 Start of the memory range to lock.
1411 * This must be page aligned.
1412 * @param cb Size of the memory range to lock.
1413 * This must be page aligned.
1414 */
1415SUPR0DECL(int) SUPR0LockMem(PSUPDRVSESSION pSession, RTR3PTR pvR3, uint32_t cPages, PRTHCPHYS paPages)
1416{
1417 int rc;
1418 SUPDRVMEMREF Mem = {0};
1419 const size_t cb = (size_t)cPages << PAGE_SHIFT;
1420 dprintf(("SUPR0LockMem: pSession=%p pvR3=%p cPages=%d paPages=%p\n", pSession, (void *)pvR3, cPages, paPages));
1421
1422 /*
1423 * Verify input.
1424 */
1425 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
1426 AssertPtrReturn(paPages, VERR_INVALID_PARAMETER);
1427 if ( RT_ALIGN_R3PT(pvR3, PAGE_SIZE, RTR3PTR) != pvR3
1428 || !pvR3)
1429 {
1430 dprintf(("pvR3 (%p) must be page aligned and not NULL!\n", (void *)pvR3));
1431 return VERR_INVALID_PARAMETER;
1432 }
1433
1434#ifdef RT_OS_WINDOWS /* A temporary hack for windows, will be removed once all ring-3 code has been cleaned up. */
1435 /* First check if we allocated it using SUPPageAlloc; if so then we don't need to lock it again */
1436 rc = supdrvPageGetPhys(pSession, pvR3, cPages, paPages);
1437 if (RT_SUCCESS(rc))
1438 return rc;
1439#endif
1440
1441 /*
1442 * Let IPRT do the job.
1443 */
1444 Mem.eType = MEMREF_TYPE_LOCKED;
1445 rc = RTR0MemObjLockUser(&Mem.MemObj, pvR3, cb, RTR0ProcHandleSelf());
1446 if (RT_SUCCESS(rc))
1447 {
1448 uint32_t iPage = cPages;
1449 AssertMsg(RTR0MemObjAddressR3(Mem.MemObj) == pvR3, ("%p == %p\n", RTR0MemObjAddressR3(Mem.MemObj), pvR3));
1450 AssertMsg(RTR0MemObjSize(Mem.MemObj) == cb, ("%x == %x\n", RTR0MemObjSize(Mem.MemObj), cb));
1451
1452 while (iPage-- > 0)
1453 {
1454 paPages[iPage] = RTR0MemObjGetPagePhysAddr(Mem.MemObj, iPage);
1455 if (RT_UNLIKELY(paPages[iPage] == NIL_RTCCPHYS))
1456 {
1457 AssertMsgFailed(("iPage=%d\n", iPage));
1458 rc = VERR_INTERNAL_ERROR;
1459 break;
1460 }
1461 }
1462 if (RT_SUCCESS(rc))
1463 rc = supdrvMemAdd(&Mem, pSession);
1464 if (RT_FAILURE(rc))
1465 {
1466 int rc2 = RTR0MemObjFree(Mem.MemObj, false);
1467 AssertRC(rc2);
1468 }
1469 }
1470
1471 return rc;
1472}
1473
1474
1475/**
1476 * Unlocks the memory pointed to by pv.
1477 *
1478 * @returns IPRT status code.
1479 * @param pSession Session to which the memory was locked.
1480 * @param pvR3 Memory to unlock.
1481 */
1482SUPR0DECL(int) SUPR0UnlockMem(PSUPDRVSESSION pSession, RTR3PTR pvR3)
1483{
1484 dprintf(("SUPR0UnlockMem: pSession=%p pvR3=%p\n", pSession, (void *)pvR3));
1485 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
1486#ifdef RT_OS_WINDOWS
1487 /*
1488 * Temporary hack for windows - SUPR0PageFree will unlock SUPR0PageAlloc
1489 * allocations; ignore this call.
1490 */
1491 if (supdrvPageWasLockedByPageAlloc(pSession, pvR3))
1492 {
1493 dprintf(("Page will be unlocked in SUPR0PageFree -> ignore\n"));
1494 return VINF_SUCCESS;
1495 }
1496#endif
1497 return supdrvMemRelease(pSession, (RTHCUINTPTR)pvR3, MEMREF_TYPE_LOCKED);
1498}
1499
1500
1501/**
1502 * Allocates a chunk of page aligned memory with contiguous and fixed physical
1503 * backing.
1504 *
1505 * @returns IPRT status code.
1506 * @param pSession Session data.
1507 * @param cb Number of bytes to allocate.
1508 * @param ppvR0 Where to put the address of Ring-0 mapping the allocated memory.
1509 * @param ppvR3 Where to put the address of Ring-3 mapping the allocated memory.
1510 * @param pHCPhys Where to put the physical address of allocated memory.
1511 */
1512SUPR0DECL(int) SUPR0ContAlloc(PSUPDRVSESSION pSession, uint32_t cPages, PRTR0PTR ppvR0, PRTR3PTR ppvR3, PRTHCPHYS pHCPhys)
1513{
1514 int rc;
1515 SUPDRVMEMREF Mem = {0};
1516 dprintf(("SUPR0ContAlloc: pSession=%p cPages=%d ppvR0=%p ppvR3=%p pHCPhys=%p\n", pSession, cPages, ppvR0, ppvR3, pHCPhys));
1517
1518 /*
1519 * Validate input.
1520 */
1521 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
1522 if (!ppvR3 || !ppvR0 || !pHCPhys)
1523 {
1524 dprintf(("Null pointer. All of these should be set: pSession=%p ppvR0=%p ppvR3=%p pHCPhys=%p\n",
1525 pSession, ppvR0, ppvR3, pHCPhys));
1526 return VERR_INVALID_PARAMETER;
1527
1528 }
1529 if (cPages < 1 || cPages >= 256)
1530 {
1531 dprintf(("Illegal request cPages=%d, must be greater than 0 and smaller than 256\n", cPages));
1532 return VERR_INVALID_PARAMETER;
1533 }
1534
1535 /*
1536 * Let IPRT do the job.
1537 */
1538 rc = RTR0MemObjAllocCont(&Mem.MemObj, cPages << PAGE_SHIFT, true /* executable R0 mapping */);
1539 if (RT_SUCCESS(rc))
1540 {
1541 int rc2;
1542 rc = RTR0MemObjMapUser(&Mem.MapObjR3, Mem.MemObj, (RTR3PTR)-1, 0,
1543 RTMEM_PROT_EXEC | RTMEM_PROT_WRITE | RTMEM_PROT_READ, RTR0ProcHandleSelf());
1544 if (RT_SUCCESS(rc))
1545 {
1546 Mem.eType = MEMREF_TYPE_CONT;
1547 rc = supdrvMemAdd(&Mem, pSession);
1548 if (!rc)
1549 {
1550 *ppvR0 = RTR0MemObjAddress(Mem.MemObj);
1551 *ppvR3 = RTR0MemObjAddressR3(Mem.MapObjR3);
1552 *pHCPhys = RTR0MemObjGetPagePhysAddr(Mem.MemObj, 0);
1553 return 0;
1554 }
1555
1556 rc2 = RTR0MemObjFree(Mem.MapObjR3, false);
1557 AssertRC(rc2);
1558 }
1559 rc2 = RTR0MemObjFree(Mem.MemObj, false);
1560 AssertRC(rc2);
1561 }
1562
1563 return rc;
1564}
1565
1566
1567/**
1568 * Frees memory allocated using SUPR0ContAlloc().
1569 *
1570 * @returns IPRT status code.
1571 * @param pSession The session to which the memory was allocated.
1572 * @param uPtr Pointer to the memory (ring-3 or ring-0).
1573 */
1574SUPR0DECL(int) SUPR0ContFree(PSUPDRVSESSION pSession, RTHCUINTPTR uPtr)
1575{
1576 dprintf(("SUPR0ContFree: pSession=%p uPtr=%p\n", pSession, (void *)uPtr));
1577 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
1578 return supdrvMemRelease(pSession, uPtr, MEMREF_TYPE_CONT);
1579}
1580
1581
1582/**
1583 * Allocates a chunk of page aligned memory with fixed physical backing below 4GB.
1584 *
1585 * @returns IPRT status code.
1586 * @param pSession Session data.
1587 * @param cPages Number of pages to allocate.
1588 * @param ppvR0 Where to put the address of Ring-0 mapping of the allocated memory.
1589 * @param ppvR3 Where to put the address of Ring-3 mapping of the allocated memory.
1590 * @param paPages Where to put the physical addresses of allocated memory.
1591 */
1592SUPR0DECL(int) SUPR0LowAlloc(PSUPDRVSESSION pSession, uint32_t cPages, PRTR0PTR ppvR0, PRTR3PTR ppvR3, PRTHCPHYS paPages)
1593{
1594 unsigned iPage;
1595 int rc;
1596 SUPDRVMEMREF Mem = {0};
1597 dprintf(("SUPR0LowAlloc: pSession=%p cPages=%d ppvR3=%p ppvR0=%p paPages=%p\n", pSession, cPages, ppvR3, ppvR0, paPages));
1598
1599 /*
1600 * Validate input.
1601 */
1602 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
1603 if (!ppvR3 || !ppvR0 || !paPages)
1604 {
1605 dprintf(("Null pointer. All of these should be set: pSession=%p ppvR3=%p ppvR0=%p paPages=%p\n",
1606 pSession, ppvR3, ppvR0, paPages));
1607 return VERR_INVALID_PARAMETER;
1608
1609 }
1610 if (cPages < 1 || cPages > 256)
1611 {
1612 dprintf(("Illegal request cPages=%d, must be greater than 0 and smaller than 256.\n", cPages));
1613 return VERR_INVALID_PARAMETER;
1614 }
1615
1616 /*
1617 * Let IPRT do the work.
1618 */
1619 rc = RTR0MemObjAllocLow(&Mem.MemObj, cPages << PAGE_SHIFT, true /* executable ring-0 mapping */);
1620 if (RT_SUCCESS(rc))
1621 {
1622 int rc2;
1623 rc = RTR0MemObjMapUser(&Mem.MapObjR3, Mem.MemObj, (RTR3PTR)-1, 0,
1624 RTMEM_PROT_EXEC | RTMEM_PROT_WRITE | RTMEM_PROT_READ, RTR0ProcHandleSelf());
1625 if (RT_SUCCESS(rc))
1626 {
1627 Mem.eType = MEMREF_TYPE_LOW;
1628 rc = supdrvMemAdd(&Mem, pSession);
1629 if (!rc)
1630 {
1631 for (iPage = 0; iPage < cPages; iPage++)
1632 {
1633 paPages[iPage] = RTR0MemObjGetPagePhysAddr(Mem.MemObj, iPage);
1634 AssertMsg(!(paPages[iPage] & (PAGE_SIZE - 1)), ("iPage=%d Phys=%VHp\n", paPages[iPage]));
1635 }
1636 *ppvR0 = RTR0MemObjAddress(Mem.MemObj);
1637 *ppvR3 = RTR0MemObjAddressR3(Mem.MapObjR3);
1638 return 0;
1639 }
1640
1641 rc2 = RTR0MemObjFree(Mem.MapObjR3, false);
1642 AssertRC(rc2);
1643 }
1644
1645 rc2 = RTR0MemObjFree(Mem.MemObj, false);
1646 AssertRC(rc2);
1647 }
1648
1649 return rc;
1650}
1651
1652
1653/**
1654 * Frees memory allocated using SUPR0LowAlloc().
1655 *
1656 * @returns IPRT status code.
1657 * @param pSession The session to which the memory was allocated.
1658 * @param uPtr Pointer to the memory (ring-3 or ring-0).
1659 */
1660SUPR0DECL(int) SUPR0LowFree(PSUPDRVSESSION pSession, RTHCUINTPTR uPtr)
1661{
1662 dprintf(("SUPR0LowFree: pSession=%p uPtr=%p\n", pSession, (void *)uPtr));
1663 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
1664 return supdrvMemRelease(pSession, uPtr, MEMREF_TYPE_LOW);
1665}
1666
1667
1668
1669/**
1670 * Allocates a chunk of memory with both R0 and R3 mappings.
1671 * The memory is fixed and it's possible to query the physical addresses using SUPR0MemGetPhys().
1672 *
1673 * @returns IPRT status code.
1674 * @param pSession The session to associated the allocation with.
1675 * @param cb Number of bytes to allocate.
1676 * @param ppvR0 Where to store the address of the Ring-0 mapping.
1677 * @param ppvR3 Where to store the address of the Ring-3 mapping.
1678 */
1679SUPR0DECL(int) SUPR0MemAlloc(PSUPDRVSESSION pSession, uint32_t cb, PRTR0PTR ppvR0, PRTR3PTR ppvR3)
1680{
1681 int rc;
1682 SUPDRVMEMREF Mem = {0};
1683 dprintf(("SUPR0MemAlloc: pSession=%p cb=%d ppvR0=%p ppvR3=%p\n", pSession, cb, ppvR0, ppvR3));
1684
1685 /*
1686 * Validate input.
1687 */
1688 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
1689 AssertPtrReturn(ppvR0, VERR_INVALID_POINTER);
1690 AssertPtrReturn(ppvR3, VERR_INVALID_POINTER);
1691 if (cb < 1 || cb >= _4M)
1692 {
1693 dprintf(("Illegal request cb=%u; must be greater than 0 and smaller than 4MB.\n", cb));
1694 return VERR_INVALID_PARAMETER;
1695 }
1696
1697 /*
1698 * Let IPRT do the work.
1699 */
1700 rc = RTR0MemObjAllocPage(&Mem.MemObj, cb, true /* executable ring-0 mapping */);
1701 if (RT_SUCCESS(rc))
1702 {
1703 int rc2;
1704 rc = RTR0MemObjMapUser(&Mem.MapObjR3, Mem.MemObj, (RTR3PTR)-1, 0,
1705 RTMEM_PROT_EXEC | RTMEM_PROT_WRITE | RTMEM_PROT_READ, RTR0ProcHandleSelf());
1706 if (RT_SUCCESS(rc))
1707 {
1708 Mem.eType = MEMREF_TYPE_MEM;
1709 rc = supdrvMemAdd(&Mem, pSession);
1710 if (!rc)
1711 {
1712 *ppvR0 = RTR0MemObjAddress(Mem.MemObj);
1713 *ppvR3 = RTR0MemObjAddressR3(Mem.MapObjR3);
1714 return VINF_SUCCESS;
1715 }
1716 rc2 = RTR0MemObjFree(Mem.MapObjR3, false);
1717 AssertRC(rc2);
1718 }
1719
1720 rc2 = RTR0MemObjFree(Mem.MemObj, false);
1721 AssertRC(rc2);
1722 }
1723
1724 return rc;
1725}
1726
1727
1728/**
1729 * Get the physical addresses of memory allocated using SUPR0MemAlloc().
1730 *
1731 * @returns IPRT status code.
1732 * @param pSession The session to which the memory was allocated.
1733 * @param uPtr The Ring-0 or Ring-3 address returned by SUPR0MemAlloc().
1734 * @param paPages Where to store the physical addresses.
1735 */
1736SUPR0DECL(int) SUPR0MemGetPhys(PSUPDRVSESSION pSession, RTHCUINTPTR uPtr, PSUPPAGE paPages) /** @todo switch this bugger to RTHCPHYS */
1737{
1738 PSUPDRVBUNDLE pBundle;
1739 RTSPINLOCKTMP SpinlockTmp = RTSPINLOCKTMP_INITIALIZER;
1740 dprintf(("SUPR0MemGetPhys: pSession=%p uPtr=%p paPages=%p\n", pSession, (void *)uPtr, paPages));
1741
1742 /*
1743 * Validate input.
1744 */
1745 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
1746 AssertPtrReturn(paPages, VERR_INVALID_POINTER);
1747 AssertReturn(uPtr, VERR_INVALID_PARAMETER);
1748
1749 /*
1750 * Search for the address.
1751 */
1752 RTSpinlockAcquire(pSession->Spinlock, &SpinlockTmp);
1753 for (pBundle = &pSession->Bundle; pBundle; pBundle = pBundle->pNext)
1754 {
1755 if (pBundle->cUsed > 0)
1756 {
1757 unsigned i;
1758 for (i = 0; i < RT_ELEMENTS(pBundle->aMem); i++)
1759 {
1760 if ( pBundle->aMem[i].eType == MEMREF_TYPE_MEM
1761 && pBundle->aMem[i].MemObj != NIL_RTR0MEMOBJ
1762 && ( (RTHCUINTPTR)RTR0MemObjAddress(pBundle->aMem[i].MemObj) == uPtr
1763 || ( pBundle->aMem[i].MapObjR3 != NIL_RTR0MEMOBJ
1764 && RTR0MemObjAddressR3(pBundle->aMem[i].MapObjR3) == uPtr)
1765 )
1766 )
1767 {
1768 const unsigned cPages = RTR0MemObjSize(pBundle->aMem[i].MemObj) >> PAGE_SHIFT;
1769 unsigned iPage;
1770 for (iPage = 0; iPage < cPages; iPage++)
1771 {
1772 paPages[iPage].Phys = RTR0MemObjGetPagePhysAddr(pBundle->aMem[i].MemObj, iPage);
1773 paPages[iPage].uReserved = 0;
1774 }
1775 RTSpinlockRelease(pSession->Spinlock, &SpinlockTmp);
1776 return VINF_SUCCESS;
1777 }
1778 }
1779 }
1780 }
1781 RTSpinlockRelease(pSession->Spinlock, &SpinlockTmp);
1782 dprintf(("Failed to find %p!!!\n", (void *)uPtr));
1783 return VERR_INVALID_PARAMETER;
1784}
1785
1786
1787/**
1788 * Free memory allocated by SUPR0MemAlloc().
1789 *
1790 * @returns IPRT status code.
1791 * @param pSession The session owning the allocation.
1792 * @param uPtr The Ring-0 or Ring-3 address returned by SUPR0MemAlloc().
1793 */
1794SUPR0DECL(int) SUPR0MemFree(PSUPDRVSESSION pSession, RTHCUINTPTR uPtr)
1795{
1796 dprintf(("SUPR0MemFree: pSession=%p uPtr=%p\n", pSession, (void *)uPtr));
1797 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
1798 return supdrvMemRelease(pSession, uPtr, MEMREF_TYPE_MEM);
1799}
1800
1801
1802/**
1803 * Allocates a chunk of memory with only a R3 mappings.
1804 * The memory is fixed and it's possible to query the physical addresses using SUPR0MemGetPhys().
1805 *
1806 * @returns IPRT status code.
1807 * @param pSession The session to associated the allocation with.
1808 * @param cPages The number of pages to allocate.
1809 * @param ppvR3 Where to store the address of the Ring-3 mapping.
1810 * @param paPages Where to store the addresses of the pages. Optional.
1811 */
1812SUPR0DECL(int) SUPR0PageAlloc(PSUPDRVSESSION pSession, uint32_t cPages, PRTR3PTR ppvR3, PRTHCPHYS paPages)
1813{
1814 int rc;
1815 SUPDRVMEMREF Mem = {0};
1816 dprintf(("SUPR0PageAlloc: pSession=%p cb=%d ppvR3=%p\n", pSession, cPages, ppvR3));
1817
1818 /*
1819 * Validate input. The allowed allocation size must be at least equal to the maximum guest VRAM size.
1820 */
1821 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
1822 AssertPtrReturn(ppvR3, VERR_INVALID_POINTER);
1823 if (cPages < 1 || cPages > (128 * _1M)/PAGE_SIZE)
1824 {
1825 dprintf(("SUPR0PageAlloc: Illegal request cb=%u; must be greater than 0 and smaller than 128MB.\n", cPages));
1826 return VERR_INVALID_PARAMETER;
1827 }
1828
1829 /*
1830 * Let IPRT do the work.
1831 */
1832 rc = RTR0MemObjAllocPhysNC(&Mem.MemObj, (size_t)cPages * PAGE_SIZE, NIL_RTHCPHYS);
1833 if (RT_SUCCESS(rc))
1834 {
1835 int rc2;
1836 rc = RTR0MemObjMapUser(&Mem.MapObjR3, Mem.MemObj, (RTR3PTR)-1, 0,
1837 RTMEM_PROT_EXEC | RTMEM_PROT_WRITE | RTMEM_PROT_READ, RTR0ProcHandleSelf());
1838 if (RT_SUCCESS(rc))
1839 {
1840 Mem.eType = MEMREF_TYPE_LOCKED_SUP;
1841 rc = supdrvMemAdd(&Mem, pSession);
1842 if (!rc)
1843 {
1844 *ppvR3 = RTR0MemObjAddressR3(Mem.MapObjR3);
1845 if (paPages)
1846 {
1847 uint32_t iPage = cPages;
1848 while (iPage-- > 0)
1849 {
1850 paPages[iPage] = RTR0MemObjGetPagePhysAddr(Mem.MapObjR3, iPage);
1851 Assert(paPages[iPage] != NIL_RTHCPHYS);
1852 }
1853 }
1854 return VINF_SUCCESS;
1855 }
1856 rc2 = RTR0MemObjFree(Mem.MapObjR3, false);
1857 AssertRC(rc2);
1858 }
1859
1860 rc2 = RTR0MemObjFree(Mem.MemObj, false);
1861 AssertRC(rc2);
1862 }
1863 return rc;
1864}
1865
1866
1867#ifdef RT_OS_WINDOWS
1868/**
1869 * Check if the pages were locked by SUPR0PageAlloc
1870 *
1871 * This function will be removed along with the lock/unlock hacks when
1872 * we've cleaned up the ring-3 code properly.
1873 *
1874 * @returns boolean
1875 * @param pSession The session to which the memory was allocated.
1876 * @param pvR3 The Ring-3 address returned by SUPR0PageAlloc().
1877 */
1878static bool supdrvPageWasLockedByPageAlloc(PSUPDRVSESSION pSession, RTR3PTR pvR3)
1879{
1880 PSUPDRVBUNDLE pBundle;
1881 RTSPINLOCKTMP SpinlockTmp = RTSPINLOCKTMP_INITIALIZER;
1882 dprintf(("SUPR0PageIsLockedByPageAlloc: pSession=%p pvR3=%p\n", pSession, (void *)pvR3));
1883
1884 /*
1885 * Search for the address.
1886 */
1887 RTSpinlockAcquire(pSession->Spinlock, &SpinlockTmp);
1888 for (pBundle = &pSession->Bundle; pBundle; pBundle = pBundle->pNext)
1889 {
1890 if (pBundle->cUsed > 0)
1891 {
1892 unsigned i;
1893 for (i = 0; i < RT_ELEMENTS(pBundle->aMem); i++)
1894 {
1895 if ( pBundle->aMem[i].eType == MEMREF_TYPE_LOCKED_SUP
1896 && pBundle->aMem[i].MemObj != NIL_RTR0MEMOBJ
1897 && pBundle->aMem[i].MapObjR3 != NIL_RTR0MEMOBJ
1898 && RTR0MemObjAddressR3(pBundle->aMem[i].MapObjR3) == pvR3)
1899 {
1900 RTSpinlockRelease(pSession->Spinlock, &SpinlockTmp);
1901 return true;
1902 }
1903 }
1904 }
1905 }
1906 RTSpinlockRelease(pSession->Spinlock, &SpinlockTmp);
1907 return false;
1908}
1909
1910
1911/**
1912 * Get the physical addresses of memory allocated using SUPR0PageAlloc().
1913 *
1914 * This function will be removed along with the lock/unlock hacks when
1915 * we've cleaned up the ring-3 code properly.
1916 *
1917 * @returns IPRT status code.
1918 * @param pSession The session to which the memory was allocated.
1919 * @param pvR3 The Ring-3 address returned by SUPR0PageAlloc().
1920 * @param cPages Number of pages in paPages
1921 * @param paPages Where to store the physical addresses.
1922 */
1923static int supdrvPageGetPhys(PSUPDRVSESSION pSession, RTR3PTR pvR3, uint32_t cPages, PRTHCPHYS paPages)
1924{
1925 PSUPDRVBUNDLE pBundle;
1926 RTSPINLOCKTMP SpinlockTmp = RTSPINLOCKTMP_INITIALIZER;
1927 dprintf(("supdrvPageGetPhys: pSession=%p pvR3=%p cPages=%#lx paPages=%p\n", pSession, (void *)pvR3, (long)cPages, paPages));
1928
1929 /*
1930 * Search for the address.
1931 */
1932 RTSpinlockAcquire(pSession->Spinlock, &SpinlockTmp);
1933 for (pBundle = &pSession->Bundle; pBundle; pBundle = pBundle->pNext)
1934 {
1935 if (pBundle->cUsed > 0)
1936 {
1937 unsigned i;
1938 for (i = 0; i < RT_ELEMENTS(pBundle->aMem); i++)
1939 {
1940 if ( pBundle->aMem[i].eType == MEMREF_TYPE_LOCKED_SUP
1941 && pBundle->aMem[i].MemObj != NIL_RTR0MEMOBJ
1942 && pBundle->aMem[i].MapObjR3 != NIL_RTR0MEMOBJ
1943 && RTR0MemObjAddressR3(pBundle->aMem[i].MapObjR3) == pvR3)
1944 {
1945 uint32_t iPage = RTR0MemObjSize(pBundle->aMem[i].MemObj) >> PAGE_SHIFT;
1946 cPages = RT_MIN(iPage, cPages);
1947 for (iPage = 0; iPage < cPages; iPage++)
1948 paPages[iPage] = RTR0MemObjGetPagePhysAddr(pBundle->aMem[i].MemObj, iPage);
1949 RTSpinlockRelease(pSession->Spinlock, &SpinlockTmp);
1950 return VINF_SUCCESS;
1951 }
1952 }
1953 }
1954 }
1955 RTSpinlockRelease(pSession->Spinlock, &SpinlockTmp);
1956 return VERR_INVALID_PARAMETER;
1957}
1958#endif /* RT_OS_WINDOWS */
1959
1960
1961/**
1962 * Free memory allocated by SUPR0PageAlloc().
1963 *
1964 * @returns IPRT status code.
1965 * @param pSession The session owning the allocation.
1966 * @param pvR3 The Ring-3 address returned by SUPR0PageAlloc().
1967 */
1968SUPR0DECL(int) SUPR0PageFree(PSUPDRVSESSION pSession, RTR3PTR pvR3)
1969{
1970 dprintf(("SUPR0PageFree: pSession=%p pvR3=%p\n", pSession, (void *)pvR3));
1971 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
1972 return supdrvMemRelease(pSession, (RTHCUINTPTR)pvR3, MEMREF_TYPE_LOCKED_SUP);
1973}
1974
1975
1976/**
1977 * Maps the GIP into userspace and/or get the physical address of the GIP.
1978 *
1979 * @returns IPRT status code.
1980 * @param pSession Session to which the GIP mapping should belong.
1981 * @param ppGipR3 Where to store the address of the ring-3 mapping. (optional)
1982 * @param pHCPhysGip Where to store the physical address. (optional)
1983 *
1984 * @remark There is no reference counting on the mapping, so one call to this function
1985 * count globally as one reference. One call to SUPR0GipUnmap() is will unmap GIP
1986 * and remove the session as a GIP user.
1987 */
1988SUPR0DECL(int) SUPR0GipMap(PSUPDRVSESSION pSession, PRTR3PTR ppGipR3, PRTHCPHYS pHCPhysGip)
1989{
1990 int rc = 0;
1991 PSUPDRVDEVEXT pDevExt = pSession->pDevExt;
1992 RTR3PTR pGip = NIL_RTR3PTR;
1993 RTHCPHYS HCPhys = NIL_RTHCPHYS;
1994 dprintf(("SUPR0GipMap: pSession=%p ppGipR3=%p pHCPhysGip=%p\n", pSession, ppGipR3, pHCPhysGip));
1995
1996 /*
1997 * Validate
1998 */
1999 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
2000 AssertPtrNullReturn(ppGipR3, VERR_INVALID_POINTER);
2001 AssertPtrNullReturn(pHCPhysGip, VERR_INVALID_POINTER);
2002
2003 RTSemFastMutexRequest(pDevExt->mtxGip);
2004 if (pDevExt->pGip)
2005 {
2006 /*
2007 * Map it?
2008 */
2009 if (ppGipR3)
2010 {
2011#ifdef USE_NEW_OS_INTERFACE_FOR_GIP
2012 if (pSession->GipMapObjR3 == NIL_RTR0MEMOBJ)
2013 rc = RTR0MemObjMapUser(&pSession->GipMapObjR3, pDevExt->GipMemObj, (RTR3PTR)-1, 0,
2014 RTMEM_PROT_READ, RTR0ProcHandleSelf());
2015 if (RT_SUCCESS(rc))
2016 {
2017 pGip = RTR0MemObjAddressR3(pSession->GipMapObjR3);
2018 rc = VINF_SUCCESS; /** @todo remove this and replace the !rc below with RT_SUCCESS(rc). */
2019 }
2020#else /* !USE_NEW_OS_INTERFACE_FOR_GIP */
2021 if (!pSession->pGip)
2022 rc = supdrvOSGipMap(pSession->pDevExt, &pSession->pGip);
2023 if (!rc)
2024 pGip = (RTR3PTR)pSession->pGip;
2025#endif /* !USE_NEW_OS_INTERFACE_FOR_GIP */
2026 }
2027
2028 /*
2029 * Get physical address.
2030 */
2031 if (pHCPhysGip && !rc)
2032 HCPhys = pDevExt->HCPhysGip;
2033
2034 /*
2035 * Reference globally.
2036 */
2037 if (!pSession->fGipReferenced && !rc)
2038 {
2039 pSession->fGipReferenced = 1;
2040 pDevExt->cGipUsers++;
2041 if (pDevExt->cGipUsers == 1)
2042 {
2043 PSUPGLOBALINFOPAGE pGip = pDevExt->pGip;
2044 unsigned i;
2045
2046 dprintf(("SUPR0GipMap: Resumes GIP updating\n"));
2047
2048 for (i = 0; i < RT_ELEMENTS(pGip->aCPUs); i++)
2049 ASMAtomicXchgU32(&pGip->aCPUs[i].u32TransactionId, pGip->aCPUs[i].u32TransactionId & ~(GIP_UPDATEHZ_RECALC_FREQ * 2 - 1));
2050 ASMAtomicXchgU64(&pGip->u64NanoTSLastUpdateHz, 0);
2051
2052#ifdef USE_NEW_OS_INTERFACE_FOR_GIP
2053 rc = RTTimerStart(pDevExt->pGipTimer, 0);
2054 AssertRC(rc); rc = VINF_SUCCESS;
2055#else
2056 supdrvOSGipResume(pDevExt);
2057#endif
2058 }
2059 }
2060 }
2061 else
2062 {
2063 rc = SUPDRV_ERR_GENERAL_FAILURE;
2064 dprintf(("SUPR0GipMap: GIP is not available!\n"));
2065 }
2066 RTSemFastMutexRelease(pDevExt->mtxGip);
2067
2068 /*
2069 * Write returns.
2070 */
2071 if (pHCPhysGip)
2072 *pHCPhysGip = HCPhys;
2073 if (ppGipR3)
2074 *ppGipR3 = pGip;
2075
2076#ifdef DEBUG_DARWIN_GIP
2077 OSDBGPRINT(("SUPR0GipMap: returns %d *pHCPhysGip=%lx *ppGip=%p GipMapObjR3\n", rc, (unsigned long)HCPhys, pGip, pSession->GipMapObjR3));
2078#else
2079 dprintf(("SUPR0GipMap: returns %d *pHCPhysGip=%lx *ppGipR3=%p\n", rc, (unsigned long)HCPhys, (void *)(uintptr_t)pGip));
2080#endif
2081 return rc;
2082}
2083
2084
2085/**
2086 * Unmaps any user mapping of the GIP and terminates all GIP access
2087 * from this session.
2088 *
2089 * @returns IPRT status code.
2090 * @param pSession Session to which the GIP mapping should belong.
2091 */
2092SUPR0DECL(int) SUPR0GipUnmap(PSUPDRVSESSION pSession)
2093{
2094 int rc = VINF_SUCCESS;
2095 PSUPDRVDEVEXT pDevExt = pSession->pDevExt;
2096#ifdef DEBUG_DARWIN_GIP
2097 OSDBGPRINT(("SUPR0GipUnmap: pSession=%p pGip=%p GipMapObjR3=%p\n",
2098 pSession,
2099 pSession->GipMapObjR3 != NIL_RTR0MEMOBJ ? RTR0MemObjAddress(pSession->GipMapObjR3) : NULL,
2100 pSession->GipMapObjR3));
2101#else
2102 dprintf(("SUPR0GipUnmap: pSession=%p\n", pSession));
2103#endif
2104 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
2105
2106 RTSemFastMutexRequest(pDevExt->mtxGip);
2107
2108 /*
2109 * Unmap anything?
2110 */
2111#ifdef USE_NEW_OS_INTERFACE_FOR_GIP
2112 if (pSession->GipMapObjR3 != NIL_RTR0MEMOBJ)
2113 {
2114 rc = RTR0MemObjFree(pSession->GipMapObjR3, false);
2115 AssertRC(rc);
2116 if (RT_SUCCESS(rc))
2117 pSession->GipMapObjR3 = NIL_RTR0MEMOBJ;
2118 }
2119#else
2120 if (pSession->pGip)
2121 {
2122 rc = supdrvOSGipUnmap(pDevExt, pSession->pGip);
2123 if (!rc)
2124 pSession->pGip = NULL;
2125 }
2126#endif
2127
2128 /*
2129 * Dereference global GIP.
2130 */
2131 if (pSession->fGipReferenced && !rc)
2132 {
2133 pSession->fGipReferenced = 0;
2134 if ( pDevExt->cGipUsers > 0
2135 && !--pDevExt->cGipUsers)
2136 {
2137 dprintf(("SUPR0GipUnmap: Suspends GIP updating\n"));
2138#ifdef USE_NEW_OS_INTERFACE_FOR_GIP
2139 rc = RTTimerStop(pDevExt->pGipTimer); AssertRC(rc); rc = 0;
2140#else
2141 supdrvOSGipSuspend(pDevExt);
2142#endif
2143 }
2144 }
2145
2146 RTSemFastMutexRelease(pDevExt->mtxGip);
2147
2148 return rc;
2149}
2150
2151
2152/**
2153 * Adds a memory object to the session.
2154 *
2155 * @returns IPRT status code.
2156 * @param pMem Memory tracking structure containing the
2157 * information to track.
2158 * @param pSession The session.
2159 */
2160static int supdrvMemAdd(PSUPDRVMEMREF pMem, PSUPDRVSESSION pSession)
2161{
2162 PSUPDRVBUNDLE pBundle;
2163 RTSPINLOCKTMP SpinlockTmp = RTSPINLOCKTMP_INITIALIZER;
2164
2165 /*
2166 * Find free entry and record the allocation.
2167 */
2168 RTSpinlockAcquire(pSession->Spinlock, &SpinlockTmp);
2169 for (pBundle = &pSession->Bundle; pBundle; pBundle = pBundle->pNext)
2170 {
2171 if (pBundle->cUsed < RT_ELEMENTS(pBundle->aMem))
2172 {
2173 unsigned i;
2174 for (i = 0; i < RT_ELEMENTS(pBundle->aMem); i++)
2175 {
2176 if (pBundle->aMem[i].MemObj == NIL_RTR0MEMOBJ)
2177 {
2178 pBundle->cUsed++;
2179 pBundle->aMem[i] = *pMem;
2180 RTSpinlockRelease(pSession->Spinlock, &SpinlockTmp);
2181 return VINF_SUCCESS;
2182 }
2183 }
2184 AssertFailed(); /* !!this can't be happening!!! */
2185 }
2186 }
2187 RTSpinlockRelease(pSession->Spinlock, &SpinlockTmp);
2188
2189 /*
2190 * Need to allocate a new bundle.
2191 * Insert into the last entry in the bundle.
2192 */
2193 pBundle = (PSUPDRVBUNDLE)RTMemAllocZ(sizeof(*pBundle));
2194 if (!pBundle)
2195 return VERR_NO_MEMORY;
2196
2197 /* take last entry. */
2198 pBundle->cUsed++;
2199 pBundle->aMem[RT_ELEMENTS(pBundle->aMem) - 1] = *pMem;
2200
2201 /* insert into list. */
2202 RTSpinlockAcquire(pSession->Spinlock, &SpinlockTmp);
2203 pBundle->pNext = pSession->Bundle.pNext;
2204 pSession->Bundle.pNext = pBundle;
2205 RTSpinlockRelease(pSession->Spinlock, &SpinlockTmp);
2206
2207 return VINF_SUCCESS;
2208}
2209
2210
2211/**
2212 * Releases a memory object referenced by pointer and type.
2213 *
2214 * @returns IPRT status code.
2215 * @param pSession Session data.
2216 * @param uPtr Pointer to memory. This is matched against both the R0 and R3 addresses.
2217 * @param eType Memory type.
2218 */
2219static int supdrvMemRelease(PSUPDRVSESSION pSession, RTHCUINTPTR uPtr, SUPDRVMEMREFTYPE eType)
2220{
2221 PSUPDRVBUNDLE pBundle;
2222 RTSPINLOCKTMP SpinlockTmp = RTSPINLOCKTMP_INITIALIZER;
2223
2224 /*
2225 * Validate input.
2226 */
2227 if (!uPtr)
2228 {
2229 dprintf(("Illegal address %p\n", (void *)uPtr));
2230 return VERR_INVALID_PARAMETER;
2231 }
2232
2233 /*
2234 * Search for the address.
2235 */
2236 RTSpinlockAcquire(pSession->Spinlock, &SpinlockTmp);
2237 for (pBundle = &pSession->Bundle; pBundle; pBundle = pBundle->pNext)
2238 {
2239 if (pBundle->cUsed > 0)
2240 {
2241 unsigned i;
2242 for (i = 0; i < RT_ELEMENTS(pBundle->aMem); i++)
2243 {
2244 if ( pBundle->aMem[i].eType == eType
2245 && pBundle->aMem[i].MemObj != NIL_RTR0MEMOBJ
2246 && ( (RTHCUINTPTR)RTR0MemObjAddress(pBundle->aMem[i].MemObj) == uPtr
2247 || ( pBundle->aMem[i].MapObjR3 != NIL_RTR0MEMOBJ
2248 && RTR0MemObjAddressR3(pBundle->aMem[i].MapObjR3) == uPtr))
2249 )
2250 {
2251 /* Make a copy of it and release it outside the spinlock. */
2252 SUPDRVMEMREF Mem = pBundle->aMem[i];
2253 pBundle->aMem[i].eType = MEMREF_TYPE_UNUSED;
2254 pBundle->aMem[i].MemObj = NIL_RTR0MEMOBJ;
2255 pBundle->aMem[i].MapObjR3 = NIL_RTR0MEMOBJ;
2256 RTSpinlockRelease(pSession->Spinlock, &SpinlockTmp);
2257
2258 if (Mem.MapObjR3)
2259 {
2260 int rc = RTR0MemObjFree(Mem.MapObjR3, false);
2261 AssertRC(rc); /** @todo figure out how to handle this. */
2262 }
2263 if (Mem.MemObj)
2264 {
2265 int rc = RTR0MemObjFree(Mem.MemObj, false);
2266 AssertRC(rc); /** @todo figure out how to handle this. */
2267 }
2268 return VINF_SUCCESS;
2269 }
2270 }
2271 }
2272 }
2273 RTSpinlockRelease(pSession->Spinlock, &SpinlockTmp);
2274 dprintf(("Failed to find %p!!! (eType=%d)\n", (void *)uPtr, eType));
2275 return VERR_INVALID_PARAMETER;
2276}
2277
2278
2279#ifdef VBOX_WITH_IDT_PATCHING
2280/**
2281 * Install IDT for the current CPU.
2282 *
2283 * @returns One of the following IPRT status codes:
2284 * @retval VINF_SUCCESS on success.
2285 * @retval VERR_IDT_FAILED.
2286 * @retval VERR_NO_MEMORY.
2287 * @param pDevExt The device extension.
2288 * @param pSession The session data.
2289 * @param pReq The request.
2290 */
2291static int supdrvIOCtl_IdtInstall(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPIDTINSTALL pReq)
2292{
2293 PSUPDRVPATCHUSAGE pUsagePre;
2294 PSUPDRVPATCH pPatchPre;
2295 RTIDTR Idtr;
2296 PSUPDRVPATCH pPatch;
2297 RTSPINLOCKTMP SpinlockTmp = RTSPINLOCKTMP_INITIALIZER;
2298 dprintf(("supdrvIOCtl_IdtInstall\n"));
2299
2300 /*
2301 * Preallocate entry for this CPU cause we don't wanna do
2302 * that inside the spinlock!
2303 */
2304 pUsagePre = (PSUPDRVPATCHUSAGE)RTMemAlloc(sizeof(*pUsagePre));
2305 if (!pUsagePre)
2306 return VERR_NO_MEMORY;
2307
2308 /*
2309 * Take the spinlock and see what we need to do.
2310 */
2311 RTSpinlockAcquireNoInts(pDevExt->Spinlock, &SpinlockTmp);
2312
2313 /* check if we already got a free patch. */
2314 if (!pDevExt->pIdtPatchesFree)
2315 {
2316 /*
2317 * Allocate a patch - outside the spinlock of course.
2318 */
2319 RTSpinlockReleaseNoInts(pDevExt->Spinlock, &SpinlockTmp);
2320
2321 pPatchPre = (PSUPDRVPATCH)RTMemExecAlloc(sizeof(*pPatchPre));
2322 if (!pPatchPre)
2323 return VERR_NO_MEMORY;
2324
2325 RTSpinlockAcquireNoInts(pDevExt->Spinlock, &SpinlockTmp);
2326 }
2327 else
2328 {
2329 pPatchPre = pDevExt->pIdtPatchesFree;
2330 pDevExt->pIdtPatchesFree = pPatchPre->pNext;
2331 }
2332
2333 /* look for matching patch entry */
2334 ASMGetIDTR(&Idtr);
2335 pPatch = pDevExt->pIdtPatches;
2336 while (pPatch && pPatch->pvIdt != (void *)Idtr.pIdt)
2337 pPatch = pPatch->pNext;
2338
2339 if (!pPatch)
2340 {
2341 /*
2342 * Create patch.
2343 */
2344 pPatch = supdrvIdtPatchOne(pDevExt, pPatchPre);
2345 if (pPatch)
2346 pPatchPre = NULL; /* mark as used. */
2347 }
2348 else
2349 {
2350 /*
2351 * Simply increment patch usage.
2352 */
2353 pPatch->cUsage++;
2354 }
2355
2356 if (pPatch)
2357 {
2358 /*
2359 * Increment and add if need be the session usage record for this patch.
2360 */
2361 PSUPDRVPATCHUSAGE pUsage = pSession->pPatchUsage;
2362 while (pUsage && pUsage->pPatch != pPatch)
2363 pUsage = pUsage->pNext;
2364
2365 if (!pUsage)
2366 {
2367 /*
2368 * Add usage record.
2369 */
2370 pUsagePre->cUsage = 1;
2371 pUsagePre->pPatch = pPatch;
2372 pUsagePre->pNext = pSession->pPatchUsage;
2373 pSession->pPatchUsage = pUsagePre;
2374 pUsagePre = NULL; /* mark as used. */
2375 }
2376 else
2377 {
2378 /*
2379 * Increment usage count.
2380 */
2381 pUsage->cUsage++;
2382 }
2383 }
2384
2385 /* free patch - we accumulate them for paranoid saftly reasons. */
2386 if (pPatchPre)
2387 {
2388 pPatchPre->pNext = pDevExt->pIdtPatchesFree;
2389 pDevExt->pIdtPatchesFree = pPatchPre;
2390 }
2391
2392 RTSpinlockReleaseNoInts(pDevExt->Spinlock, &SpinlockTmp);
2393
2394 /*
2395 * Free unused preallocated buffers.
2396 */
2397 if (pUsagePre)
2398 RTMemFree(pUsagePre);
2399
2400 pReq->u.Out.u8Idt = pDevExt->u8Idt;
2401
2402 return pPatch ? VINF_SUCCESS : VERR_IDT_FAILED;
2403}
2404
2405
2406/**
2407 * This creates a IDT patch entry.
2408 * If the first patch being installed it'll also determin the IDT entry
2409 * to use.
2410 *
2411 * @returns pPatch on success.
2412 * @returns NULL on failure.
2413 * @param pDevExt Pointer to globals.
2414 * @param pPatch Patch entry to use.
2415 * This will be linked into SUPDRVDEVEXT::pIdtPatches on
2416 * successful return.
2417 * @remark Call must be owning the SUPDRVDEVEXT::Spinlock!
2418 */
2419static PSUPDRVPATCH supdrvIdtPatchOne(PSUPDRVDEVEXT pDevExt, PSUPDRVPATCH pPatch)
2420{
2421 RTIDTR Idtr;
2422 PSUPDRVIDTE paIdt;
2423 dprintf(("supdrvIOCtl_IdtPatchOne: pPatch=%p\n", pPatch));
2424
2425 /*
2426 * Get IDT.
2427 */
2428 ASMGetIDTR(&Idtr);
2429 paIdt = (PSUPDRVIDTE)Idtr.pIdt;
2430 /*
2431 * Recent Linux kernels can be configured to 1G user /3G kernel.
2432 */
2433 if ((uintptr_t)paIdt < 0x40000000)
2434 {
2435 AssertMsgFailed(("bad paIdt=%p\n", paIdt));
2436 return NULL;
2437 }
2438
2439 if (!pDevExt->u8Idt)
2440 {
2441 /*
2442 * Test out the alternatives.
2443 *
2444 * At the moment we do not support chaining thus we ASSUME that one of
2445 * these 48 entries is unused (which is not a problem on Win32 and
2446 * Linux to my knowledge).
2447 */
2448 /** @todo we MUST change this detection to try grab an entry which is NOT in use. This can be
2449 * combined with gathering info about which guest system call gates we can hook up directly. */
2450 unsigned i;
2451 uint8_t u8Idt = 0;
2452 static uint8_t au8Ints[] =
2453 {
2454#ifdef RT_OS_WINDOWS /* We don't use 0xef and above because they are system stuff on linux (ef is IPI,
2455 * local apic timer, or some other frequently fireing thing). */
2456 0xef, 0xee, 0xed, 0xec,
2457#endif
2458 0xeb, 0xea, 0xe9, 0xe8,
2459 0xdf, 0xde, 0xdd, 0xdc,
2460 0x7b, 0x7a, 0x79, 0x78,
2461 0xbf, 0xbe, 0xbd, 0xbc,
2462 };
2463#if defined(RT_ARCH_AMD64) && defined(DEBUG)
2464 static int s_iWobble = 0;
2465 unsigned iMax = !(s_iWobble++ % 2) ? 0x80 : 0x100;
2466 dprintf(("IDT: Idtr=%p:%#x\n", (void *)Idtr.pIdt, (unsigned)Idtr.cbIdt));
2467 for (i = iMax - 0x80; i*16+15 < Idtr.cbIdt && i < iMax; i++)
2468 {
2469 dprintf(("%#x: %04x:%08x%04x%04x P=%d DPL=%d IST=%d Type1=%#x u32Reserved=%#x u5Reserved=%#x\n",
2470 i, paIdt[i].u16SegSel, paIdt[i].u32OffsetTop, paIdt[i].u16OffsetHigh, paIdt[i].u16OffsetLow,
2471 paIdt[i].u1Present, paIdt[i].u2DPL, paIdt[i].u3IST, paIdt[i].u5Type2,
2472 paIdt[i].u32Reserved, paIdt[i].u5Reserved));
2473 }
2474#endif
2475 /* look for entries which are not present or otherwise unused. */
2476 for (i = 0; i < sizeof(au8Ints) / sizeof(au8Ints[0]); i++)
2477 {
2478 u8Idt = au8Ints[i];
2479 if ( u8Idt * sizeof(SUPDRVIDTE) < Idtr.cbIdt
2480 && ( !paIdt[u8Idt].u1Present
2481 || paIdt[u8Idt].u5Type2 == 0))
2482 break;
2483 u8Idt = 0;
2484 }
2485 if (!u8Idt)
2486 {
2487 /* try again, look for a compatible entry .*/
2488 for (i = 0; i < sizeof(au8Ints) / sizeof(au8Ints[0]); i++)
2489 {
2490 u8Idt = au8Ints[i];
2491 if ( u8Idt * sizeof(SUPDRVIDTE) < Idtr.cbIdt
2492 && paIdt[u8Idt].u1Present
2493 && paIdt[u8Idt].u5Type2 == SUPDRV_IDTE_TYPE2_INTERRUPT_GATE
2494 && !(paIdt[u8Idt].u16SegSel & 3))
2495 break;
2496 u8Idt = 0;
2497 }
2498 if (!u8Idt)
2499 {
2500 dprintf(("Failed to find appropirate IDT entry!!\n"));
2501 return NULL;
2502 }
2503 }
2504 pDevExt->u8Idt = u8Idt;
2505 dprintf(("supdrvIOCtl_IdtPatchOne: u8Idt=%x\n", u8Idt));
2506 }
2507
2508 /*
2509 * Prepare the patch
2510 */
2511 memset(pPatch, 0, sizeof(*pPatch));
2512 pPatch->pvIdt = paIdt;
2513 pPatch->cUsage = 1;
2514 pPatch->pIdtEntry = &paIdt[pDevExt->u8Idt];
2515 pPatch->SavedIdt = paIdt[pDevExt->u8Idt];
2516 pPatch->ChangedIdt.u16OffsetLow = (uint32_t)((uintptr_t)&pPatch->auCode[0] & 0xffff);
2517 pPatch->ChangedIdt.u16OffsetHigh = (uint32_t)((uintptr_t)&pPatch->auCode[0] >> 16);
2518#ifdef RT_ARCH_AMD64
2519 pPatch->ChangedIdt.u32OffsetTop = (uint32_t)((uintptr_t)&pPatch->auCode[0] >> 32);
2520#endif
2521 pPatch->ChangedIdt.u16SegSel = ASMGetCS();
2522#ifdef RT_ARCH_AMD64
2523 pPatch->ChangedIdt.u3IST = 0;
2524 pPatch->ChangedIdt.u5Reserved = 0;
2525#else /* x86 */
2526 pPatch->ChangedIdt.u5Reserved = 0;
2527 pPatch->ChangedIdt.u3Type1 = 0;
2528#endif /* x86 */
2529 pPatch->ChangedIdt.u5Type2 = SUPDRV_IDTE_TYPE2_INTERRUPT_GATE;
2530 pPatch->ChangedIdt.u2DPL = 3;
2531 pPatch->ChangedIdt.u1Present = 1;
2532
2533 /*
2534 * Generate the patch code.
2535 */
2536 {
2537#ifdef RT_ARCH_AMD64
2538 union
2539 {
2540 uint8_t *pb;
2541 uint32_t *pu32;
2542 uint64_t *pu64;
2543 } u, uFixJmp, uFixCall, uNotNested;
2544 u.pb = &pPatch->auCode[0];
2545
2546 /* check the cookie */
2547 *u.pb++ = 0x3d; // cmp eax, GLOBALCOOKIE
2548 *u.pu32++ = pDevExt->u32Cookie;
2549
2550 *u.pb++ = 0x74; // jz @VBoxCall
2551 *u.pb++ = 2;
2552
2553 /* jump to forwarder code. */
2554 *u.pb++ = 0xeb;
2555 uFixJmp = u;
2556 *u.pb++ = 0xfe;
2557
2558 // @VBoxCall:
2559 *u.pb++ = 0x0f; // swapgs
2560 *u.pb++ = 0x01;
2561 *u.pb++ = 0xf8;
2562
2563 /*
2564 * Call VMMR0Entry
2565 * We don't have to push the arguments here, but we have top
2566 * reserve some stack space for the interrupt forwarding.
2567 */
2568# ifdef RT_OS_WINDOWS
2569 *u.pb++ = 0x50; // push rax ; alignment filler.
2570 *u.pb++ = 0x41; // push r8 ; uArg
2571 *u.pb++ = 0x50;
2572 *u.pb++ = 0x52; // push rdx ; uOperation
2573 *u.pb++ = 0x51; // push rcx ; pVM
2574# else
2575 *u.pb++ = 0x51; // push rcx ; alignment filler.
2576 *u.pb++ = 0x52; // push rdx ; uArg
2577 *u.pb++ = 0x56; // push rsi ; uOperation
2578 *u.pb++ = 0x57; // push rdi ; pVM
2579# endif
2580
2581 *u.pb++ = 0xff; // call qword [pfnVMMR0EntryInt wrt rip]
2582 *u.pb++ = 0x15;
2583 uFixCall = u;
2584 *u.pu32++ = 0;
2585
2586 *u.pb++ = 0x48; // add rsp, 20h ; remove call frame.
2587 *u.pb++ = 0x81;
2588 *u.pb++ = 0xc4;
2589 *u.pu32++ = 0x20;
2590
2591 *u.pb++ = 0x0f; // swapgs
2592 *u.pb++ = 0x01;
2593 *u.pb++ = 0xf8;
2594
2595 /* Return to R3. */
2596 uNotNested = u;
2597 *u.pb++ = 0x48; // iretq
2598 *u.pb++ = 0xcf;
2599
2600 while ((uintptr_t)u.pb & 0x7) // align 8
2601 *u.pb++ = 0xcc;
2602
2603 /* Pointer to the VMMR0Entry. */ // pfnVMMR0EntryInt dq StubVMMR0Entry
2604 *uFixCall.pu32 = (uint32_t)(u.pb - uFixCall.pb - 4); uFixCall.pb = NULL;
2605 pPatch->offVMMR0EntryFixup = (uint16_t)(u.pb - &pPatch->auCode[0]);
2606 *u.pu64++ = pDevExt->pvVMMR0 ? (uint64_t)pDevExt->pfnVMMR0EntryInt : (uint64_t)u.pb + 8;
2607
2608 /* stub entry. */ // StubVMMR0Entry:
2609 pPatch->offStub = (uint16_t)(u.pb - &pPatch->auCode[0]);
2610 *u.pb++ = 0x33; // xor eax, eax
2611 *u.pb++ = 0xc0;
2612
2613 *u.pb++ = 0x48; // dec rax
2614 *u.pb++ = 0xff;
2615 *u.pb++ = 0xc8;
2616
2617 *u.pb++ = 0xc3; // ret
2618
2619 /* forward to the original handler using a retf. */
2620 *uFixJmp.pb = (uint8_t)(u.pb - uFixJmp.pb - 1); uFixJmp.pb = NULL;
2621
2622 *u.pb++ = 0x68; // push <target cs>
2623 *u.pu32++ = !pPatch->SavedIdt.u5Type2 ? ASMGetCS() : pPatch->SavedIdt.u16SegSel;
2624
2625 *u.pb++ = 0x68; // push <low target rip>
2626 *u.pu32++ = !pPatch->SavedIdt.u5Type2
2627 ? (uint32_t)(uintptr_t)uNotNested.pb
2628 : (uint32_t)pPatch->SavedIdt.u16OffsetLow
2629 | (uint32_t)pPatch->SavedIdt.u16OffsetHigh << 16;
2630
2631 *u.pb++ = 0xc7; // mov dword [rsp + 4], <high target rip>
2632 *u.pb++ = 0x44;
2633 *u.pb++ = 0x24;
2634 *u.pb++ = 0x04;
2635 *u.pu32++ = !pPatch->SavedIdt.u5Type2
2636 ? (uint32_t)((uint64_t)uNotNested.pb >> 32)
2637 : pPatch->SavedIdt.u32OffsetTop;
2638
2639 *u.pb++ = 0x48; // retf ; does this require prefix?
2640 *u.pb++ = 0xcb;
2641
2642#else /* RT_ARCH_X86 */
2643
2644 union
2645 {
2646 uint8_t *pb;
2647 uint16_t *pu16;
2648 uint32_t *pu32;
2649 } u, uFixJmpNotNested, uFixJmp, uFixCall, uNotNested;
2650 u.pb = &pPatch->auCode[0];
2651
2652 /* check the cookie */
2653 *u.pb++ = 0x81; // cmp esi, GLOBALCOOKIE
2654 *u.pb++ = 0xfe;
2655 *u.pu32++ = pDevExt->u32Cookie;
2656
2657 *u.pb++ = 0x74; // jz VBoxCall
2658 uFixJmp = u;
2659 *u.pb++ = 0;
2660
2661 /* jump (far) to the original handler / not-nested-stub. */
2662 *u.pb++ = 0xea; // jmp far NotNested
2663 uFixJmpNotNested = u;
2664 *u.pu32++ = 0;
2665 *u.pu16++ = 0;
2666
2667 /* save selector registers. */ // VBoxCall:
2668 *uFixJmp.pb = (uint8_t)(u.pb - uFixJmp.pb - 1);
2669 *u.pb++ = 0x0f; // push fs
2670 *u.pb++ = 0xa0;
2671
2672 *u.pb++ = 0x1e; // push ds
2673
2674 *u.pb++ = 0x06; // push es
2675
2676 /* call frame */
2677 *u.pb++ = 0x51; // push ecx
2678
2679 *u.pb++ = 0x52; // push edx
2680
2681 *u.pb++ = 0x50; // push eax
2682
2683 /* load ds, es and perhaps fs before call. */
2684 *u.pb++ = 0xb8; // mov eax, KernelDS
2685 *u.pu32++ = ASMGetDS();
2686
2687 *u.pb++ = 0x8e; // mov ds, eax
2688 *u.pb++ = 0xd8;
2689
2690 *u.pb++ = 0x8e; // mov es, eax
2691 *u.pb++ = 0xc0;
2692
2693#ifdef RT_OS_WINDOWS
2694 *u.pb++ = 0xb8; // mov eax, KernelFS
2695 *u.pu32++ = ASMGetFS();
2696
2697 *u.pb++ = 0x8e; // mov fs, eax
2698 *u.pb++ = 0xe0;
2699#endif
2700
2701 /* do the call. */
2702 *u.pb++ = 0xe8; // call _VMMR0Entry / StubVMMR0Entry
2703 uFixCall = u;
2704 pPatch->offVMMR0EntryFixup = (uint16_t)(u.pb - &pPatch->auCode[0]);
2705 *u.pu32++ = 0xfffffffb;
2706
2707 *u.pb++ = 0x83; // add esp, 0ch ; cdecl
2708 *u.pb++ = 0xc4;
2709 *u.pb++ = 0x0c;
2710
2711 /* restore selector registers. */
2712 *u.pb++ = 0x07; // pop es
2713 //
2714 *u.pb++ = 0x1f; // pop ds
2715
2716 *u.pb++ = 0x0f; // pop fs
2717 *u.pb++ = 0xa1;
2718
2719 uNotNested = u; // NotNested:
2720 *u.pb++ = 0xcf; // iretd
2721
2722 /* the stub VMMR0Entry. */ // StubVMMR0Entry:
2723 pPatch->offStub = (uint16_t)(u.pb - &pPatch->auCode[0]);
2724 *u.pb++ = 0x33; // xor eax, eax
2725 *u.pb++ = 0xc0;
2726
2727 *u.pb++ = 0x48; // dec eax
2728
2729 *u.pb++ = 0xc3; // ret
2730
2731 /* Fixup the VMMR0Entry call. */
2732 if (pDevExt->pvVMMR0)
2733 *uFixCall.pu32 = (uint32_t)pDevExt->pfnVMMR0EntryInt - (uint32_t)(uFixCall.pu32 + 1);
2734 else
2735 *uFixCall.pu32 = (uint32_t)&pPatch->auCode[pPatch->offStub] - (uint32_t)(uFixCall.pu32 + 1);
2736
2737 /* Fixup the forward / nested far jump. */
2738 if (!pPatch->SavedIdt.u5Type2)
2739 {
2740 *uFixJmpNotNested.pu32++ = (uint32_t)uNotNested.pb;
2741 *uFixJmpNotNested.pu16++ = ASMGetCS();
2742 }
2743 else
2744 {
2745 *uFixJmpNotNested.pu32++ = ((uint32_t)pPatch->SavedIdt.u16OffsetHigh << 16) | pPatch->SavedIdt.u16OffsetLow;
2746 *uFixJmpNotNested.pu16++ = pPatch->SavedIdt.u16SegSel;
2747 }
2748#endif /* RT_ARCH_X86 */
2749 Assert(u.pb <= &pPatch->auCode[sizeof(pPatch->auCode)]);
2750#if 0
2751 /* dump the patch code */
2752 dprintf(("patch code: %p\n", &pPatch->auCode[0]));
2753 for (uFixCall.pb = &pPatch->auCode[0]; uFixCall.pb < u.pb; uFixCall.pb++)
2754 dprintf(("0x%02x,\n", *uFixCall.pb));
2755#endif
2756 }
2757
2758 /*
2759 * Install the patch.
2760 */
2761 supdrvIdtWrite(pPatch->pIdtEntry, &pPatch->ChangedIdt);
2762 AssertMsg(!memcmp((void *)pPatch->pIdtEntry, &pPatch->ChangedIdt, sizeof(pPatch->ChangedIdt)), ("The stupid change code didn't work!!!!!\n"));
2763
2764 /*
2765 * Link in the patch.
2766 */
2767 pPatch->pNext = pDevExt->pIdtPatches;
2768 pDevExt->pIdtPatches = pPatch;
2769
2770 return pPatch;
2771}
2772
2773
2774/**
2775 * Removes the sessions IDT references.
2776 * This will uninstall our IDT patch if we left unreferenced.
2777 *
2778 * @returns VINF_SUCCESS.
2779 * @param pDevExt Device globals.
2780 * @param pSession Session data.
2781 */
2782static int supdrvIOCtl_IdtRemoveAll(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession)
2783{
2784 PSUPDRVPATCHUSAGE pUsage;
2785 RTSPINLOCKTMP SpinlockTmp = RTSPINLOCKTMP_INITIALIZER;
2786 dprintf(("supdrvIOCtl_IdtRemoveAll: pSession=%p\n", pSession));
2787
2788 /*
2789 * Take the spinlock.
2790 */
2791 RTSpinlockAcquireNoInts(pDevExt->Spinlock, &SpinlockTmp);
2792
2793 /*
2794 * Walk usage list, removing patches as their usage count reaches zero.
2795 */
2796 pUsage = pSession->pPatchUsage;
2797 while (pUsage)
2798 {
2799 if (pUsage->pPatch->cUsage <= pUsage->cUsage)
2800 supdrvIdtRemoveOne(pDevExt, pUsage->pPatch);
2801 else
2802 pUsage->pPatch->cUsage -= pUsage->cUsage;
2803
2804 /* next */
2805 pUsage = pUsage->pNext;
2806 }
2807
2808 /*
2809 * Empty the usage chain and we're done inside the spinlock.
2810 */
2811 pUsage = pSession->pPatchUsage;
2812 pSession->pPatchUsage = NULL;
2813
2814 RTSpinlockReleaseNoInts(pDevExt->Spinlock, &SpinlockTmp);
2815
2816 /*
2817 * Free usage entries.
2818 */
2819 while (pUsage)
2820 {
2821 void *pvToFree = pUsage;
2822 pUsage->cUsage = 0;
2823 pUsage->pPatch = NULL;
2824 pUsage = pUsage->pNext;
2825 RTMemFree(pvToFree);
2826 }
2827
2828 return VINF_SUCCESS;
2829}
2830
2831
2832/**
2833 * Remove one patch.
2834 *
2835 * Worker for supdrvIOCtl_IdtRemoveAll.
2836 *
2837 * @param pDevExt Device globals.
2838 * @param pPatch Patch entry to remove.
2839 * @remark Caller must own SUPDRVDEVEXT::Spinlock!
2840 */
2841static void supdrvIdtRemoveOne(PSUPDRVDEVEXT pDevExt, PSUPDRVPATCH pPatch)
2842{
2843 dprintf(("supdrvIdtRemoveOne: pPatch=%p\n", pPatch));
2844
2845 pPatch->cUsage = 0;
2846
2847 /*
2848 * If the IDT entry was changed it have to kick around for ever!
2849 * This will be attempted freed again, perhaps next time we'll succeed :-)
2850 */
2851 if (memcmp((void *)pPatch->pIdtEntry, &pPatch->ChangedIdt, sizeof(pPatch->ChangedIdt)))
2852 {
2853 AssertMsgFailed(("The hijacked IDT entry has CHANGED!!!\n"));
2854 return;
2855 }
2856
2857 /*
2858 * Unlink it.
2859 */
2860 if (pDevExt->pIdtPatches != pPatch)
2861 {
2862 PSUPDRVPATCH pPatchPrev = pDevExt->pIdtPatches;
2863 while (pPatchPrev)
2864 {
2865 if (pPatchPrev->pNext == pPatch)
2866 {
2867 pPatchPrev->pNext = pPatch->pNext;
2868 break;
2869 }
2870 pPatchPrev = pPatchPrev->pNext;
2871 }
2872 Assert(!pPatchPrev);
2873 }
2874 else
2875 pDevExt->pIdtPatches = pPatch->pNext;
2876 pPatch->pNext = NULL;
2877
2878
2879 /*
2880 * Verify and restore the IDT.
2881 */
2882 AssertMsg(!memcmp((void *)pPatch->pIdtEntry, &pPatch->ChangedIdt, sizeof(pPatch->ChangedIdt)), ("The hijacked IDT entry has CHANGED!!!\n"));
2883 supdrvIdtWrite(pPatch->pIdtEntry, &pPatch->SavedIdt);
2884 AssertMsg(!memcmp((void *)pPatch->pIdtEntry, &pPatch->SavedIdt, sizeof(pPatch->SavedIdt)), ("The hijacked IDT entry has CHANGED!!!\n"));
2885
2886 /*
2887 * Put it in the free list.
2888 * (This free list stuff is to calm my paranoia.)
2889 */
2890 pPatch->pvIdt = NULL;
2891 pPatch->pIdtEntry = NULL;
2892
2893 pPatch->pNext = pDevExt->pIdtPatchesFree;
2894 pDevExt->pIdtPatchesFree = pPatch;
2895}
2896
2897
2898/**
2899 * Write to an IDT entry.
2900 *
2901 * @param pvIdtEntry Where to write.
2902 * @param pNewIDTEntry What to write.
2903 */
2904static void supdrvIdtWrite(volatile void *pvIdtEntry, const SUPDRVIDTE *pNewIDTEntry)
2905{
2906 RTUINTREG uCR0;
2907 RTUINTREG uFlags;
2908
2909 /*
2910 * On SMP machines (P4 hyperthreading included) we must preform a
2911 * 64-bit locked write when updating the IDT entry.
2912 *
2913 * The F00F bugfix for linux (and probably other OSes) causes
2914 * the IDT to be pointing to an readonly mapping. We get around that
2915 * by temporarily turning of WP. Since we're inside a spinlock at this
2916 * point, interrupts are disabled and there isn't any way the WP bit
2917 * flipping can cause any trouble.
2918 */
2919
2920 /* Save & Clear interrupt flag; Save & clear WP. */
2921 uFlags = ASMGetFlags();
2922 ASMSetFlags(uFlags & ~(RTUINTREG)(1 << 9)); /*X86_EFL_IF*/
2923 Assert(!(ASMGetFlags() & (1 << 9)));
2924 uCR0 = ASMGetCR0();
2925 ASMSetCR0(uCR0 & ~(RTUINTREG)(1 << 16)); /*X86_CR0_WP*/
2926
2927 /* Update IDT Entry */
2928#ifdef RT_ARCH_AMD64
2929 ASMAtomicXchgU128((volatile uint128_t *)pvIdtEntry, *(uint128_t *)(uintptr_t)pNewIDTEntry);
2930#else
2931 ASMAtomicXchgU64((volatile uint64_t *)pvIdtEntry, *(uint64_t *)(uintptr_t)pNewIDTEntry);
2932#endif
2933
2934 /* Restore CR0 & Flags */
2935 ASMSetCR0(uCR0);
2936 ASMSetFlags(uFlags);
2937}
2938#endif /* VBOX_WITH_IDT_PATCHING */
2939
2940
2941/**
2942 * Opens an image. If it's the first time it's opened the call must upload
2943 * the bits using the supdrvIOCtl_LdrLoad() / SUPDRV_IOCTL_LDR_LOAD function.
2944 *
2945 * This is the 1st step of the loading.
2946 *
2947 * @returns IPRT status code.
2948 * @param pDevExt Device globals.
2949 * @param pSession Session data.
2950 * @param pReq The open request.
2951 */
2952static int supdrvIOCtl_LdrOpen(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPLDROPEN pReq)
2953{
2954 PSUPDRVLDRIMAGE pImage;
2955 unsigned cb;
2956 void *pv;
2957 dprintf(("supdrvIOCtl_LdrOpen: szName=%s cbImage=%d\n", pReq->u.In.szName, pReq->u.In.cbImage));
2958
2959 /*
2960 * Check if we got an instance of the image already.
2961 */
2962 RTSemFastMutexRequest(pDevExt->mtxLdr);
2963 for (pImage = pDevExt->pLdrImages; pImage; pImage = pImage->pNext)
2964 {
2965 if (!strcmp(pImage->szName, pReq->u.In.szName))
2966 {
2967 pImage->cUsage++;
2968 pReq->u.Out.pvImageBase = pImage->pvImage;
2969 pReq->u.Out.fNeedsLoading = pImage->uState == SUP_IOCTL_LDR_OPEN;
2970 supdrvLdrAddUsage(pSession, pImage);
2971 RTSemFastMutexRelease(pDevExt->mtxLdr);
2972 return VINF_SUCCESS;
2973 }
2974 }
2975 /* (not found - add it!) */
2976
2977 /*
2978 * Allocate memory.
2979 */
2980 cb = pReq->u.In.cbImage + sizeof(SUPDRVLDRIMAGE) + 31;
2981 pv = RTMemExecAlloc(cb);
2982 if (!pv)
2983 {
2984 RTSemFastMutexRelease(pDevExt->mtxLdr);
2985 return VERR_NO_MEMORY;
2986 }
2987
2988 /*
2989 * Setup and link in the LDR stuff.
2990 */
2991 pImage = (PSUPDRVLDRIMAGE)pv;
2992 pImage->pvImage = RT_ALIGN_P(pImage + 1, 32);
2993 pImage->cbImage = pReq->u.In.cbImage;
2994 pImage->pfnModuleInit = NULL;
2995 pImage->pfnModuleTerm = NULL;
2996 pImage->uState = SUP_IOCTL_LDR_OPEN;
2997 pImage->cUsage = 1;
2998 strcpy(pImage->szName, pReq->u.In.szName);
2999
3000 pImage->pNext = pDevExt->pLdrImages;
3001 pDevExt->pLdrImages = pImage;
3002
3003 supdrvLdrAddUsage(pSession, pImage);
3004
3005 pReq->u.Out.pvImageBase = pImage->pvImage;
3006 pReq->u.Out.fNeedsLoading = true;
3007 RTSemFastMutexRelease(pDevExt->mtxLdr);
3008 return VINF_SUCCESS;
3009}
3010
3011
3012/**
3013 * Loads the image bits.
3014 *
3015 * This is the 2nd step of the loading.
3016 *
3017 * @returns IPRT status code.
3018 * @param pDevExt Device globals.
3019 * @param pSession Session data.
3020 * @param pReq The request.
3021 */
3022static int supdrvIOCtl_LdrLoad(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPLDRLOAD pReq)
3023{
3024 PSUPDRVLDRUSAGE pUsage;
3025 PSUPDRVLDRIMAGE pImage;
3026 int rc;
3027 dprintf(("supdrvIOCtl_LdrLoad: pvImageBase=%p cbImage=%d\n", pReq->u.In.pvImageBase, pReq->u.In.cbImage));
3028
3029 /*
3030 * Find the ldr image.
3031 */
3032 RTSemFastMutexRequest(pDevExt->mtxLdr);
3033 pUsage = pSession->pLdrUsage;
3034 while (pUsage && pUsage->pImage->pvImage != pReq->u.In.pvImageBase)
3035 pUsage = pUsage->pNext;
3036 if (!pUsage)
3037 {
3038 RTSemFastMutexRelease(pDevExt->mtxLdr);
3039 dprintf(("SUP_IOCTL_LDR_LOAD: couldn't find image!\n"));
3040 return VERR_INVALID_HANDLE;
3041 }
3042 pImage = pUsage->pImage;
3043 if (pImage->cbImage != pReq->u.In.cbImage)
3044 {
3045 RTSemFastMutexRelease(pDevExt->mtxLdr);
3046 dprintf(("SUP_IOCTL_LDR_LOAD: image size mismatch!! %d(prep) != %d(load)\n", pImage->cbImage, pReq->u.In.cbImage));
3047 return VERR_INVALID_HANDLE;
3048 }
3049 if (pImage->uState != SUP_IOCTL_LDR_OPEN)
3050 {
3051 unsigned uState = pImage->uState;
3052 RTSemFastMutexRelease(pDevExt->mtxLdr);
3053 if (uState != SUP_IOCTL_LDR_LOAD)
3054 AssertMsgFailed(("SUP_IOCTL_LDR_LOAD: invalid image state %d (%#x)!\n", uState, uState));
3055 return SUPDRV_ERR_ALREADY_LOADED;
3056 }
3057 switch (pReq->u.In.eEPType)
3058 {
3059 case SUPLDRLOADEP_NOTHING:
3060 break;
3061 case SUPLDRLOADEP_VMMR0:
3062 if ( !pReq->u.In.EP.VMMR0.pvVMMR0
3063 || !pReq->u.In.EP.VMMR0.pvVMMR0EntryInt
3064 || !pReq->u.In.EP.VMMR0.pvVMMR0EntryFast
3065 || !pReq->u.In.EP.VMMR0.pvVMMR0EntryEx)
3066 {
3067 RTSemFastMutexRelease(pDevExt->mtxLdr);
3068 dprintf(("NULL pointer: pvVMMR0=%p pvVMMR0EntryInt=%p pvVMMR0EntryFast=%p pvVMMR0EntryEx=%p!\n",
3069 pReq->u.In.EP.VMMR0.pvVMMR0, pReq->u.In.EP.VMMR0.pvVMMR0EntryInt,
3070 pReq->u.In.EP.VMMR0.pvVMMR0EntryFast, pReq->u.In.EP.VMMR0.pvVMMR0EntryEx));
3071 return VERR_INVALID_PARAMETER;
3072 }
3073 if ( (uintptr_t)pReq->u.In.EP.VMMR0.pvVMMR0EntryInt - (uintptr_t)pImage->pvImage >= pReq->u.In.cbImage
3074 || (uintptr_t)pReq->u.In.EP.VMMR0.pvVMMR0EntryFast - (uintptr_t)pImage->pvImage >= pReq->u.In.cbImage
3075 || (uintptr_t)pReq->u.In.EP.VMMR0.pvVMMR0EntryEx - (uintptr_t)pImage->pvImage >= pReq->u.In.cbImage)
3076 {
3077 RTSemFastMutexRelease(pDevExt->mtxLdr);
3078 dprintf(("Out of range (%p LB %#x): pvVMMR0EntryInt=%p, pvVMMR0EntryFast=%p or pvVMMR0EntryEx=%p is NULL!\n",
3079 pImage->pvImage, pReq->u.In.cbImage, pReq->u.In.EP.VMMR0.pvVMMR0EntryInt,
3080 pReq->u.In.EP.VMMR0.pvVMMR0EntryFast, pReq->u.In.EP.VMMR0.pvVMMR0EntryEx));
3081 return VERR_INVALID_PARAMETER;
3082 }
3083 break;
3084 default:
3085 RTSemFastMutexRelease(pDevExt->mtxLdr);
3086 dprintf(("Invalid eEPType=%d\n", pReq->u.In.eEPType));
3087 return VERR_INVALID_PARAMETER;
3088 }
3089 if ( pReq->u.In.pfnModuleInit
3090 && (uintptr_t)pReq->u.In.pfnModuleInit - (uintptr_t)pImage->pvImage >= pReq->u.In.cbImage)
3091 {
3092 RTSemFastMutexRelease(pDevExt->mtxLdr);
3093 dprintf(("SUP_IOCTL_LDR_LOAD: pfnModuleInit=%p is outside the image (%p %d bytes)\n",
3094 pReq->u.In.pfnModuleInit, pImage->pvImage, pReq->u.In.cbImage));
3095 return VERR_INVALID_PARAMETER;
3096 }
3097 if ( pReq->u.In.pfnModuleTerm
3098 && (uintptr_t)pReq->u.In.pfnModuleTerm - (uintptr_t)pImage->pvImage >= pReq->u.In.cbImage)
3099 {
3100 RTSemFastMutexRelease(pDevExt->mtxLdr);
3101 dprintf(("SUP_IOCTL_LDR_LOAD: pfnModuleTerm=%p is outside the image (%p %d bytes)\n",
3102 pReq->u.In.pfnModuleTerm, pImage->pvImage, pReq->u.In.cbImage));
3103 return VERR_INVALID_PARAMETER;
3104 }
3105
3106 /*
3107 * Copy the memory.
3108 */
3109 /* no need to do try/except as this is a buffered request. */
3110 memcpy(pImage->pvImage, &pReq->u.In.achImage[0], pImage->cbImage);
3111 pImage->uState = SUP_IOCTL_LDR_LOAD;
3112 pImage->pfnModuleInit = pReq->u.In.pfnModuleInit;
3113 pImage->pfnModuleTerm = pReq->u.In.pfnModuleTerm;
3114 pImage->offSymbols = pReq->u.In.offSymbols;
3115 pImage->cSymbols = pReq->u.In.cSymbols;
3116 pImage->offStrTab = pReq->u.In.offStrTab;
3117 pImage->cbStrTab = pReq->u.In.cbStrTab;
3118
3119 /*
3120 * Update any entry points.
3121 */
3122 switch (pReq->u.In.eEPType)
3123 {
3124 default:
3125 case SUPLDRLOADEP_NOTHING:
3126 rc = VINF_SUCCESS;
3127 break;
3128 case SUPLDRLOADEP_VMMR0:
3129 rc = supdrvLdrSetR0EP(pDevExt, pReq->u.In.EP.VMMR0.pvVMMR0, pReq->u.In.EP.VMMR0.pvVMMR0EntryInt,
3130 pReq->u.In.EP.VMMR0.pvVMMR0EntryFast, pReq->u.In.EP.VMMR0.pvVMMR0EntryEx);
3131 break;
3132 }
3133
3134 /*
3135 * On success call the module initialization.
3136 */
3137 dprintf(("supdrvIOCtl_LdrLoad: pfnModuleInit=%p\n", pImage->pfnModuleInit));
3138 if (RT_SUCCESS(rc) && pImage->pfnModuleInit)
3139 {
3140 dprintf(("supdrvIOCtl_LdrLoad: calling pfnModuleInit=%p\n", pImage->pfnModuleInit));
3141 rc = pImage->pfnModuleInit();
3142 if (rc && pDevExt->pvVMMR0 == pImage->pvImage)
3143 supdrvLdrUnsetR0EP(pDevExt);
3144 }
3145
3146 if (rc)
3147 pImage->uState = SUP_IOCTL_LDR_OPEN;
3148
3149 RTSemFastMutexRelease(pDevExt->mtxLdr);
3150 return rc;
3151}
3152
3153
3154/**
3155 * Frees a previously loaded (prep'ed) image.
3156 *
3157 * @returns IPRT status code.
3158 * @param pDevExt Device globals.
3159 * @param pSession Session data.
3160 * @param pReq The request.
3161 */
3162static int supdrvIOCtl_LdrFree(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPLDRFREE pReq)
3163{
3164 int rc;
3165 PSUPDRVLDRUSAGE pUsagePrev;
3166 PSUPDRVLDRUSAGE pUsage;
3167 PSUPDRVLDRIMAGE pImage;
3168 dprintf(("supdrvIOCtl_LdrFree: pvImageBase=%p\n", pReq->u.In.pvImageBase));
3169
3170 /*
3171 * Find the ldr image.
3172 */
3173 RTSemFastMutexRequest(pDevExt->mtxLdr);
3174 pUsagePrev = NULL;
3175 pUsage = pSession->pLdrUsage;
3176 while (pUsage && pUsage->pImage->pvImage != pReq->u.In.pvImageBase)
3177 {
3178 pUsagePrev = pUsage;
3179 pUsage = pUsage->pNext;
3180 }
3181 if (!pUsage)
3182 {
3183 RTSemFastMutexRelease(pDevExt->mtxLdr);
3184 dprintf(("SUP_IOCTL_LDR_FREE: couldn't find image!\n"));
3185 return VERR_INVALID_HANDLE;
3186 }
3187
3188 /*
3189 * Check if we can remove anything.
3190 */
3191 rc = VINF_SUCCESS;
3192 pImage = pUsage->pImage;
3193 if (pImage->cUsage <= 1 || pUsage->cUsage <= 1)
3194 {
3195 /*
3196 * Check if there are any objects with destructors in the image, if
3197 * so leave it for the session cleanup routine so we get a chance to
3198 * clean things up in the right order and not leave them all dangling.
3199 */
3200 RTSPINLOCKTMP SpinlockTmp = RTSPINLOCKTMP_INITIALIZER;
3201 RTSpinlockAcquire(pDevExt->Spinlock, &SpinlockTmp);
3202 if (pImage->cUsage <= 1)
3203 {
3204 PSUPDRVOBJ pObj;
3205 for (pObj = pDevExt->pObjs; pObj; pObj = pObj->pNext)
3206 if (RT_UNLIKELY((uintptr_t)pObj->pfnDestructor - (uintptr_t)pImage->pvImage < pImage->cbImage))
3207 {
3208 rc = VERR_SHARING_VIOLATION; /** @todo VERR_DANGLING_OBJECTS */
3209 break;
3210 }
3211 }
3212 else
3213 {
3214 PSUPDRVUSAGE pGenUsage;
3215 for (pGenUsage = pSession->pUsage; pGenUsage; pGenUsage = pGenUsage->pNext)
3216 if (RT_UNLIKELY((uintptr_t)pGenUsage->pObj->pfnDestructor - (uintptr_t)pImage->pvImage < pImage->cbImage))
3217 {
3218 rc = VERR_SHARING_VIOLATION; /** @todo VERR_DANGLING_OBJECTS */
3219 break;
3220 }
3221 }
3222 RTSpinlockRelease(pDevExt->Spinlock, &SpinlockTmp);
3223 if (rc == VINF_SUCCESS)
3224 {
3225 /* unlink it */
3226 if (pUsagePrev)
3227 pUsagePrev->pNext = pUsage->pNext;
3228 else
3229 pSession->pLdrUsage = pUsage->pNext;
3230
3231 /* free it */
3232 pUsage->pImage = NULL;
3233 pUsage->pNext = NULL;
3234 RTMemFree(pUsage);
3235
3236 /*
3237 * Derefrence the image.
3238 */
3239 if (pImage->cUsage <= 1)
3240 supdrvLdrFree(pDevExt, pImage);
3241 else
3242 pImage->cUsage--;
3243 }
3244 }
3245 else
3246 {
3247 /*
3248 * Dereference both image and usage.
3249 */
3250 pImage->cUsage--;
3251 pUsage->cUsage--;
3252 }
3253
3254 RTSemFastMutexRelease(pDevExt->mtxLdr);
3255 return VINF_SUCCESS;
3256}
3257
3258
3259/**
3260 * Gets the address of a symbol in an open image.
3261 *
3262 * @returns 0 on success.
3263 * @returns SUPDRV_ERR_* on failure.
3264 * @param pDevExt Device globals.
3265 * @param pSession Session data.
3266 * @param pReq The request buffer.
3267 */
3268static int supdrvIOCtl_LdrGetSymbol(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPLDRGETSYMBOL pReq)
3269{
3270 PSUPDRVLDRIMAGE pImage;
3271 PSUPDRVLDRUSAGE pUsage;
3272 uint32_t i;
3273 PSUPLDRSYM paSyms;
3274 const char *pchStrings;
3275 const size_t cbSymbol = strlen(pReq->u.In.szSymbol) + 1;
3276 void *pvSymbol = NULL;
3277 int rc = VERR_GENERAL_FAILURE;
3278 dprintf2(("supdrvIOCtl_LdrGetSymbol: pvImageBase=%p szSymbol=\"%s\"\n", pReq->u.In.pvImageBase, pReq->u.In.szSymbol));
3279
3280 /*
3281 * Find the ldr image.
3282 */
3283 RTSemFastMutexRequest(pDevExt->mtxLdr);
3284 pUsage = pSession->pLdrUsage;
3285 while (pUsage && pUsage->pImage->pvImage != pReq->u.In.pvImageBase)
3286 pUsage = pUsage->pNext;
3287 if (!pUsage)
3288 {
3289 RTSemFastMutexRelease(pDevExt->mtxLdr);
3290 dprintf(("SUP_IOCTL_LDR_GET_SYMBOL: couldn't find image!\n"));
3291 return VERR_INVALID_HANDLE;
3292 }
3293 pImage = pUsage->pImage;
3294 if (pImage->uState != SUP_IOCTL_LDR_LOAD)
3295 {
3296 unsigned uState = pImage->uState;
3297 RTSemFastMutexRelease(pDevExt->mtxLdr);
3298 dprintf(("SUP_IOCTL_LDR_GET_SYMBOL: invalid image state %d (%#x)!\n", uState, uState)); NOREF(uState);
3299 return VERR_ALREADY_LOADED;
3300 }
3301
3302 /*
3303 * Search the symbol string.
3304 */
3305 pchStrings = (const char *)((uint8_t *)pImage->pvImage + pImage->offStrTab);
3306 paSyms = (PSUPLDRSYM)((uint8_t *)pImage->pvImage + pImage->offSymbols);
3307 for (i = 0; i < pImage->cSymbols; i++)
3308 {
3309 if ( paSyms[i].offSymbol < pImage->cbImage /* paranoia */
3310 && paSyms[i].offName + cbSymbol <= pImage->cbStrTab
3311 && !memcmp(pchStrings + paSyms[i].offName, pReq->u.In.szSymbol, cbSymbol))
3312 {
3313 pvSymbol = (uint8_t *)pImage->pvImage + paSyms[i].offSymbol;
3314 rc = VINF_SUCCESS;
3315 break;
3316 }
3317 }
3318 RTSemFastMutexRelease(pDevExt->mtxLdr);
3319 pReq->u.Out.pvSymbol = pvSymbol;
3320 return rc;
3321}
3322
3323
3324/**
3325 * Updates the IDT patches to point to the specified VMM R0 entry
3326 * point (i.e. VMMR0Enter()).
3327 *
3328 * @returns IPRT status code.
3329 * @param pDevExt Device globals.
3330 * @param pSession Session data.
3331 * @param pVMMR0 VMMR0 image handle.
3332 * @param pvVMMR0EntryInt VMMR0EntryInt address.
3333 * @param pvVMMR0EntryFast VMMR0EntryFast address.
3334 * @param pvVMMR0EntryEx VMMR0EntryEx address.
3335 * @remark Caller must own the loader mutex.
3336 */
3337static int supdrvLdrSetR0EP(PSUPDRVDEVEXT pDevExt, void *pvVMMR0, void *pvVMMR0EntryInt, void *pvVMMR0EntryFast, void *pvVMMR0EntryEx)
3338{
3339 int rc = VINF_SUCCESS;
3340 dprintf(("supdrvLdrSetR0EP pvVMMR0=%p pvVMMR0EntryInt=%p\n", pvVMMR0, pvVMMR0EntryInt));
3341
3342
3343 /*
3344 * Check if not yet set.
3345 */
3346 if (!pDevExt->pvVMMR0)
3347 {
3348#ifdef VBOX_WITH_IDT_PATCHING
3349 PSUPDRVPATCH pPatch;
3350#endif
3351
3352 /*
3353 * Set it and update IDT patch code.
3354 */
3355 pDevExt->pvVMMR0 = pvVMMR0;
3356 pDevExt->pfnVMMR0EntryInt = pvVMMR0EntryInt;
3357 pDevExt->pfnVMMR0EntryFast = pvVMMR0EntryFast;
3358 pDevExt->pfnVMMR0EntryEx = pvVMMR0EntryEx;
3359#ifdef VBOX_WITH_IDT_PATCHING
3360 for (pPatch = pDevExt->pIdtPatches; pPatch; pPatch = pPatch->pNext)
3361 {
3362# ifdef RT_ARCH_AMD64
3363 ASMAtomicXchgU64((volatile uint64_t *)&pPatch->auCode[pPatch->offVMMR0EntryFixup], (uint64_t)pvVMMR0);
3364# else /* RT_ARCH_X86 */
3365 ASMAtomicXchgU32((volatile uint32_t *)&pPatch->auCode[pPatch->offVMMR0EntryFixup],
3366 (uint32_t)pvVMMR0 - (uint32_t)&pPatch->auCode[pPatch->offVMMR0EntryFixup + 4]);
3367# endif
3368 }
3369#endif /* VBOX_WITH_IDT_PATCHING */
3370 }
3371 else
3372 {
3373 /*
3374 * Return failure or success depending on whether the values match or not.
3375 */
3376 if ( pDevExt->pvVMMR0 != pvVMMR0
3377 || (void *)pDevExt->pfnVMMR0EntryInt != pvVMMR0EntryInt
3378 || (void *)pDevExt->pfnVMMR0EntryFast != pvVMMR0EntryFast
3379 || (void *)pDevExt->pfnVMMR0EntryEx != pvVMMR0EntryEx)
3380 {
3381 AssertMsgFailed(("SUP_IOCTL_LDR_SETR0EP: Already set pointing to a different module!\n"));
3382 rc = VERR_INVALID_PARAMETER;
3383 }
3384 }
3385 return rc;
3386}
3387
3388
3389/**
3390 * Unsets the R0 entry point installed by supdrvLdrSetR0EP.
3391 *
3392 * @param pDevExt Device globals.
3393 */
3394static void supdrvLdrUnsetR0EP(PSUPDRVDEVEXT pDevExt)
3395{
3396#ifdef VBOX_WITH_IDT_PATCHING
3397 PSUPDRVPATCH pPatch;
3398#endif
3399
3400 pDevExt->pvVMMR0 = NULL;
3401 pDevExt->pfnVMMR0EntryInt = NULL;
3402 pDevExt->pfnVMMR0EntryFast = NULL;
3403 pDevExt->pfnVMMR0EntryEx = NULL;
3404
3405#ifdef VBOX_WITH_IDT_PATCHING
3406 for (pPatch = pDevExt->pIdtPatches; pPatch; pPatch = pPatch->pNext)
3407 {
3408# ifdef RT_ARCH_AMD64
3409 ASMAtomicXchgU64((volatile uint64_t *)&pPatch->auCode[pPatch->offVMMR0EntryFixup],
3410 (uint64_t)&pPatch->auCode[pPatch->offStub]);
3411# else /* RT_ARCH_X86 */
3412 ASMAtomicXchgU32((volatile uint32_t *)&pPatch->auCode[pPatch->offVMMR0EntryFixup],
3413 (uint32_t)&pPatch->auCode[pPatch->offStub] - (uint32_t)&pPatch->auCode[pPatch->offVMMR0EntryFixup + 4]);
3414# endif
3415 }
3416#endif /* VBOX_WITH_IDT_PATCHING */
3417}
3418
3419
3420/**
3421 * Adds a usage reference in the specified session of an image.
3422 *
3423 * @param pSession Session in question.
3424 * @param pImage Image which the session is using.
3425 */
3426static void supdrvLdrAddUsage(PSUPDRVSESSION pSession, PSUPDRVLDRIMAGE pImage)
3427{
3428 PSUPDRVLDRUSAGE pUsage;
3429 dprintf(("supdrvLdrAddUsage: pImage=%p\n", pImage));
3430
3431 /*
3432 * Referenced it already?
3433 */
3434 pUsage = pSession->pLdrUsage;
3435 while (pUsage)
3436 {
3437 if (pUsage->pImage == pImage)
3438 {
3439 pUsage->cUsage++;
3440 return;
3441 }
3442 pUsage = pUsage->pNext;
3443 }
3444
3445 /*
3446 * Allocate new usage record.
3447 */
3448 pUsage = (PSUPDRVLDRUSAGE)RTMemAlloc(sizeof(*pUsage));
3449 Assert(pUsage);
3450 if (pUsage)
3451 {
3452 pUsage->cUsage = 1;
3453 pUsage->pImage = pImage;
3454 pUsage->pNext = pSession->pLdrUsage;
3455 pSession->pLdrUsage = pUsage;
3456 }
3457 /* ignore errors... */
3458}
3459
3460
3461/**
3462 * Frees a load image.
3463 *
3464 * @param pDevExt Pointer to device extension.
3465 * @param pImage Pointer to the image we're gonna free.
3466 * This image must exit!
3467 * @remark The caller MUST own SUPDRVDEVEXT::mtxLdr!
3468 */
3469static void supdrvLdrFree(PSUPDRVDEVEXT pDevExt, PSUPDRVLDRIMAGE pImage)
3470{
3471 PSUPDRVLDRIMAGE pImagePrev;
3472 dprintf(("supdrvLdrFree: pImage=%p\n", pImage));
3473
3474 /* find it - arg. should've used doubly linked list. */
3475 Assert(pDevExt->pLdrImages);
3476 pImagePrev = NULL;
3477 if (pDevExt->pLdrImages != pImage)
3478 {
3479 pImagePrev = pDevExt->pLdrImages;
3480 while (pImagePrev->pNext != pImage)
3481 pImagePrev = pImagePrev->pNext;
3482 Assert(pImagePrev->pNext == pImage);
3483 }
3484
3485 /* unlink */
3486 if (pImagePrev)
3487 pImagePrev->pNext = pImage->pNext;
3488 else
3489 pDevExt->pLdrImages = pImage->pNext;
3490
3491 /* check if this is VMMR0.r0 and fix the Idt patches if it is. */
3492 if (pDevExt->pvVMMR0 == pImage->pvImage)
3493 supdrvLdrUnsetR0EP(pDevExt);
3494
3495 /* check for objects with destructors in this image. (Shouldn't happen.) */
3496 if (pDevExt->pObjs)
3497 {
3498 unsigned cObjs = 0;
3499 PSUPDRVOBJ pObj;
3500 RTSPINLOCKTMP SpinlockTmp = RTSPINLOCKTMP_INITIALIZER;
3501 RTSpinlockAcquire(pDevExt->Spinlock, &SpinlockTmp);
3502 for (pObj = pDevExt->pObjs; pObj; pObj = pObj->pNext)
3503 if (RT_UNLIKELY((uintptr_t)pObj->pfnDestructor - (uintptr_t)pImage->pvImage < pImage->cbImage))
3504 {
3505 pObj->pfnDestructor = NULL;
3506 cObjs++;
3507 }
3508 RTSpinlockRelease(pDevExt->Spinlock, &SpinlockTmp);
3509 if (cObjs)
3510 OSDBGPRINT(("supdrvLdrFree: Image '%s' has %d dangling objects!\n", pImage->szName, cObjs));
3511 }
3512
3513 /* call termination function if fully loaded. */
3514 if ( pImage->pfnModuleTerm
3515 && pImage->uState == SUP_IOCTL_LDR_LOAD)
3516 {
3517 dprintf(("supdrvIOCtl_LdrLoad: calling pfnModuleTerm=%p\n", pImage->pfnModuleTerm));
3518 pImage->pfnModuleTerm();
3519 }
3520
3521 /* free the image */
3522 pImage->cUsage = 0;
3523 pImage->pNext = 0;
3524 pImage->uState = SUP_IOCTL_LDR_FREE;
3525 RTMemExecFree(pImage);
3526}
3527
3528
3529/**
3530 * Gets the current paging mode of the CPU and stores in in pOut.
3531 */
3532static SUPPAGINGMODE supdrvIOCtl_GetPagingMode(void)
3533{
3534 SUPPAGINGMODE enmMode;
3535
3536 RTUINTREG cr0 = ASMGetCR0();
3537 if ((cr0 & (X86_CR0_PG | X86_CR0_PE)) != (X86_CR0_PG | X86_CR0_PE))
3538 enmMode = SUPPAGINGMODE_INVALID;
3539 else
3540 {
3541 RTUINTREG cr4 = ASMGetCR4();
3542 uint32_t fNXEPlusLMA = 0;
3543 if (cr4 & X86_CR4_PAE)
3544 {
3545 uint32_t fAmdFeatures = ASMCpuId_EDX(0x80000001);
3546 if (fAmdFeatures & (X86_CPUID_AMD_FEATURE_EDX_NX | X86_CPUID_AMD_FEATURE_EDX_LONG_MODE))
3547 {
3548 uint64_t efer = ASMRdMsr(MSR_K6_EFER);
3549 if ((fAmdFeatures & X86_CPUID_AMD_FEATURE_EDX_NX) && (efer & MSR_K6_EFER_NXE))
3550 fNXEPlusLMA |= RT_BIT(0);
3551 if ((fAmdFeatures & X86_CPUID_AMD_FEATURE_EDX_LONG_MODE) && (efer & MSR_K6_EFER_LMA))
3552 fNXEPlusLMA |= RT_BIT(1);
3553 }
3554 }
3555
3556 switch ((cr4 & (X86_CR4_PAE | X86_CR4_PGE)) | fNXEPlusLMA)
3557 {
3558 case 0:
3559 enmMode = SUPPAGINGMODE_32_BIT;
3560 break;
3561
3562 case X86_CR4_PGE:
3563 enmMode = SUPPAGINGMODE_32_BIT_GLOBAL;
3564 break;
3565
3566 case X86_CR4_PAE:
3567 enmMode = SUPPAGINGMODE_PAE;
3568 break;
3569
3570 case X86_CR4_PAE | RT_BIT(0):
3571 enmMode = SUPPAGINGMODE_PAE_NX;
3572 break;
3573
3574 case X86_CR4_PAE | X86_CR4_PGE:
3575 enmMode = SUPPAGINGMODE_PAE_GLOBAL;
3576 break;
3577
3578 case X86_CR4_PAE | X86_CR4_PGE | RT_BIT(0):
3579 enmMode = SUPPAGINGMODE_PAE_GLOBAL;
3580 break;
3581
3582 case RT_BIT(1) | X86_CR4_PAE:
3583 enmMode = SUPPAGINGMODE_AMD64;
3584 break;
3585
3586 case RT_BIT(1) | X86_CR4_PAE | RT_BIT(0):
3587 enmMode = SUPPAGINGMODE_AMD64_NX;
3588 break;
3589
3590 case RT_BIT(1) | X86_CR4_PAE | X86_CR4_PGE:
3591 enmMode = SUPPAGINGMODE_AMD64_GLOBAL;
3592 break;
3593
3594 case RT_BIT(1) | X86_CR4_PAE | X86_CR4_PGE | RT_BIT(0):
3595 enmMode = SUPPAGINGMODE_AMD64_GLOBAL_NX;
3596 break;
3597
3598 default:
3599 AssertMsgFailed(("Cannot happen! cr4=%#x fNXEPlusLMA=%d\n", cr4, fNXEPlusLMA));
3600 enmMode = SUPPAGINGMODE_INVALID;
3601 break;
3602 }
3603 }
3604 return enmMode;
3605}
3606
3607
3608#ifdef USE_NEW_OS_INTERFACE_FOR_GIP
3609/**
3610 * Creates the GIP.
3611 *
3612 * @returns negative errno.
3613 * @param pDevExt Instance data. GIP stuff may be updated.
3614 */
3615static int supdrvGipCreate(PSUPDRVDEVEXT pDevExt)
3616{
3617 PSUPGLOBALINFOPAGE pGip;
3618 RTHCPHYS HCPhysGip;
3619 uint32_t u32SystemResolution;
3620 uint32_t u32Interval;
3621 int rc;
3622
3623 dprintf(("supdrvGipCreate:\n"));
3624
3625 /* assert order */
3626 Assert(pDevExt->u32SystemTimerGranularityGrant == 0);
3627 Assert(pDevExt->GipMemObj == NIL_RTR0MEMOBJ);
3628 Assert(!pDevExt->pGipTimer);
3629
3630 /*
3631 * Allocate a suitable page with a default kernel mapping.
3632 */
3633 rc = RTR0MemObjAllocLow(&pDevExt->GipMemObj, PAGE_SIZE, false);
3634 if (RT_FAILURE(rc))
3635 {
3636 OSDBGPRINT(("supdrvGipCreate: failed to allocate the GIP page. rc=%d\n", rc));
3637 return rc;
3638 }
3639 pGip = (PSUPGLOBALINFOPAGE)RTR0MemObjAddress(pDevExt->GipMemObj); AssertPtr(pGip);
3640 HCPhysGip = RTR0MemObjGetPagePhysAddr(pDevExt->GipMemObj, 0); Assert(HCPhysGip != NIL_RTHCPHYS);
3641
3642 /*
3643 * Try bump up the system timer resolution.
3644 * The more interrupts the better...
3645 */
3646 if ( RT_SUCCESS(RTTimerRequestSystemGranularity( 976563 /* 1024 HZ */, &u32SystemResolution))
3647 || RT_SUCCESS(RTTimerRequestSystemGranularity( 1000000 /* 1000 HZ */, &u32SystemResolution))
3648 || RT_SUCCESS(RTTimerRequestSystemGranularity( 3906250 /* 256 HZ */, &u32SystemResolution))
3649 || RT_SUCCESS(RTTimerRequestSystemGranularity( 4000000 /* 250 HZ */, &u32SystemResolution))
3650 || RT_SUCCESS(RTTimerRequestSystemGranularity( 7812500 /* 128 HZ */, &u32SystemResolution))
3651 || RT_SUCCESS(RTTimerRequestSystemGranularity(10000000 /* 100 HZ */, &u32SystemResolution))
3652 || RT_SUCCESS(RTTimerRequestSystemGranularity(15625000 /* 64 HZ */, &u32SystemResolution))
3653 || RT_SUCCESS(RTTimerRequestSystemGranularity(31250000 /* 32 HZ */, &u32SystemResolution))
3654 )
3655 {
3656 Assert(RTTimerGetSystemGranularity() <= u32SystemResolution);
3657 pDevExt->u32SystemTimerGranularityGrant = u32SystemResolution;
3658 }
3659
3660 /*
3661 * Find a reasonable update interval, something close to 10ms would be nice,
3662 * and create a recurring timer.
3663 */
3664 u32Interval = u32SystemResolution = RTTimerGetSystemGranularity();
3665 while (u32Interval < 10000000 /* 10 ms */)
3666 u32Interval += u32SystemResolution;
3667
3668 rc = RTTimerCreateEx(&pDevExt->pGipTimer, u32Interval, 0, supdrvGipTimer, pDevExt);
3669 if (RT_FAILURE(rc))
3670 {
3671 OSDBGPRINT(("supdrvGipCreate: failed create GIP timer at %RU32 ns interval. rc=%d\n", u32Interval, rc));
3672 Assert(!pDevExt->pGipTimer);
3673 supdrvGipDestroy(pDevExt);
3674 return rc;
3675 }
3676
3677 /*
3678 * We're good.
3679 */
3680 supdrvGipInit(pDevExt, pGip, HCPhysGip, RTTimeSystemNanoTS(), 1000000000 / u32Interval /*=Hz*/);
3681 return VINF_SUCCESS;
3682}
3683
3684
3685/**
3686 * Terminates the GIP.
3687 *
3688 * @param pDevExt Instance data. GIP stuff may be updated.
3689 */
3690static void supdrvGipDestroy(PSUPDRVDEVEXT pDevExt)
3691{
3692 int rc;
3693#ifdef DEBUG_DARWIN_GIP
3694 OSDBGPRINT(("supdrvGipDestroy: pDevExt=%p pGip=%p pGipTimer=%p GipMemObj=%p\n", pDevExt,
3695 pDevExt->GipMemObj != NIL_RTR0MEMOBJ ? RTR0MemObjAddress(pDevExt->GipMemObj) : NULL,
3696 pDevExt->pGipTimer, pDevExt->GipMemObj));
3697#endif
3698
3699 /*
3700 * Invalid the GIP data.
3701 */
3702 if (pDevExt->pGip)
3703 {
3704 supdrvGipTerm(pDevExt->pGip);
3705 pDevExt->pGip = NULL;
3706 }
3707
3708 /*
3709 * Destroy the timer and free the GIP memory object.
3710 */
3711 if (pDevExt->pGipTimer)
3712 {
3713 rc = RTTimerDestroy(pDevExt->pGipTimer); AssertRC(rc);
3714 pDevExt->pGipTimer = NULL;
3715 }
3716
3717 if (pDevExt->GipMemObj != NIL_RTR0MEMOBJ)
3718 {
3719 rc = RTR0MemObjFree(pDevExt->GipMemObj, true /* free mappings */); AssertRC(rc);
3720 pDevExt->GipMemObj = NIL_RTR0MEMOBJ;
3721 }
3722
3723 /*
3724 * Finally, release the system timer resolution request if one succeeded.
3725 */
3726 if (pDevExt->u32SystemTimerGranularityGrant)
3727 {
3728 rc = RTTimerReleaseSystemGranularity(pDevExt->u32SystemTimerGranularityGrant); AssertRC(rc);
3729 pDevExt->u32SystemTimerGranularityGrant = 0;
3730 }
3731}
3732
3733
3734/**
3735 * Timer callback function.
3736 * @param pTimer The timer.
3737 * @param pvUser The device extension.
3738 */
3739static DECLCALLBACK(void) supdrvGipTimer(PRTTIMER pTimer, void *pvUser)
3740{
3741 PSUPDRVDEVEXT pDevExt = (PSUPDRVDEVEXT)pvUser;
3742 supdrvGipUpdate(pDevExt->pGip, RTTimeSystemNanoTS());
3743}
3744#endif /* USE_NEW_OS_INTERFACE_FOR_GIP */
3745
3746
3747/**
3748 * Initializes the GIP data.
3749 *
3750 * @returns IPRT status code.
3751 * @param pDevExt Pointer to the device instance data.
3752 * @param pGip Pointer to the read-write kernel mapping of the GIP.
3753 * @param HCPhys The physical address of the GIP.
3754 * @param u64NanoTS The current nanosecond timestamp.
3755 * @param uUpdateHz The update freqence.
3756 */
3757int VBOXCALL supdrvGipInit(PSUPDRVDEVEXT pDevExt, PSUPGLOBALINFOPAGE pGip, RTHCPHYS HCPhys, uint64_t u64NanoTS, unsigned uUpdateHz)
3758{
3759 unsigned i;
3760#ifdef DEBUG_DARWIN_GIP
3761 OSDBGPRINT(("supdrvGipInit: pGip=%p HCPhys=%lx u64NanoTS=%llu uUpdateHz=%d\n", pGip, (long)HCPhys, u64NanoTS, uUpdateHz));
3762#else
3763 dprintf(("supdrvGipInit: pGip=%p HCPhys=%lx u64NanoTS=%llu uUpdateHz=%d\n", pGip, (long)HCPhys, u64NanoTS, uUpdateHz));
3764#endif
3765
3766 /*
3767 * Initialize the structure.
3768 */
3769 memset(pGip, 0, PAGE_SIZE);
3770 pGip->u32Magic = SUPGLOBALINFOPAGE_MAGIC;
3771 pGip->u32Version = SUPGLOBALINFOPAGE_VERSION;
3772 pGip->u32Mode = supdrvGipDeterminTscMode();
3773 pGip->u32UpdateHz = uUpdateHz;
3774 pGip->u32UpdateIntervalNS = 1000000000 / uUpdateHz;
3775 pGip->u64NanoTSLastUpdateHz = u64NanoTS;
3776
3777 for (i = 0; i < RT_ELEMENTS(pGip->aCPUs); i++)
3778 {
3779 pGip->aCPUs[i].u32TransactionId = 2;
3780 pGip->aCPUs[i].u64NanoTS = u64NanoTS;
3781 pGip->aCPUs[i].u64TSC = ASMReadTSC();
3782
3783 /*
3784 * We don't know the following values until we've executed updates.
3785 * So, we'll just insert very high values.
3786 */
3787 pGip->aCPUs[i].u64CpuHz = _4G + 1;
3788 pGip->aCPUs[i].u32UpdateIntervalTSC = _2G / 4;
3789 pGip->aCPUs[i].au32TSCHistory[0] = _2G / 4;
3790 pGip->aCPUs[i].au32TSCHistory[1] = _2G / 4;
3791 pGip->aCPUs[i].au32TSCHistory[2] = _2G / 4;
3792 pGip->aCPUs[i].au32TSCHistory[3] = _2G / 4;
3793 pGip->aCPUs[i].au32TSCHistory[4] = _2G / 4;
3794 pGip->aCPUs[i].au32TSCHistory[5] = _2G / 4;
3795 pGip->aCPUs[i].au32TSCHistory[6] = _2G / 4;
3796 pGip->aCPUs[i].au32TSCHistory[7] = _2G / 4;
3797 }
3798
3799 /*
3800 * Link it to the device extension.
3801 */
3802 pDevExt->pGip = pGip;
3803 pDevExt->HCPhysGip = HCPhys;
3804 pDevExt->cGipUsers = 0;
3805
3806 return VINF_SUCCESS;
3807}
3808
3809
3810/**
3811 * Determin the GIP TSC mode.
3812 *
3813 * @returns The most suitable TSC mode.
3814 */
3815static SUPGIPMODE supdrvGipDeterminTscMode(void)
3816{
3817#ifndef USE_NEW_OS_INTERFACE_FOR_GIP
3818 /*
3819 * The problem here is that AMD processors with power management features
3820 * may easily end up with different TSCs because the CPUs or even cores
3821 * on the same physical chip run at different frequencies to save power.
3822 *
3823 * It is rumoured that this will be corrected with Barcelona and it's
3824 * expected that this will be indicated by the TscInvariant bit in
3825 * cpuid(0x80000007). So, the "difficult" bit here is to correctly
3826 * identify the older CPUs which don't do different frequency and
3827 * can be relied upon to have somewhat uniform TSC between the cpus.
3828 */
3829 if (supdrvOSGetCPUCount() > 1)
3830 {
3831 uint32_t uEAX, uEBX, uECX, uEDX;
3832
3833 /* Permit user users override. */
3834 if (supdrvOSGetForcedAsyncTscMode())
3835 return SUPGIPMODE_ASYNC_TSC;
3836
3837 /* Check for "AuthenticAMD" */
3838 ASMCpuId(0, &uEAX, &uEBX, &uECX, &uEDX);
3839 if (uEAX >= 1 && uEBX == 0x68747541 && uECX == 0x444d4163 && uEDX == 0x69746e65)
3840 {
3841 /* Check for APM support and that TscInvariant is cleared. */
3842 ASMCpuId(0x80000000, &uEAX, &uEBX, &uECX, &uEDX);
3843 if (uEAX >= 0x80000007)
3844 {
3845 ASMCpuId(0x80000007, &uEAX, &uEBX, &uECX, &uEDX);
3846 if ( !(uEDX & RT_BIT(8))/* TscInvariant */
3847 && (uEDX & 0x3e)) /* STC|TM|THERMTRIP|VID|FID. Ignore TS. */
3848 return SUPGIPMODE_ASYNC_TSC;
3849 }
3850 }
3851 }
3852#endif
3853 return SUPGIPMODE_SYNC_TSC;
3854}
3855
3856
3857/**
3858 * Invalidates the GIP data upon termination.
3859 *
3860 * @param pGip Pointer to the read-write kernel mapping of the GIP.
3861 */
3862void VBOXCALL supdrvGipTerm(PSUPGLOBALINFOPAGE pGip)
3863{
3864 unsigned i;
3865 pGip->u32Magic = 0;
3866 for (i = 0; i < RT_ELEMENTS(pGip->aCPUs); i++)
3867 {
3868 pGip->aCPUs[i].u64NanoTS = 0;
3869 pGip->aCPUs[i].u64TSC = 0;
3870 pGip->aCPUs[i].iTSCHistoryHead = 0;
3871 }
3872}
3873
3874
3875/**
3876 * Worker routine for supdrvGipUpdate and supdrvGipUpdatePerCpu that
3877 * updates all the per cpu data except the transaction id.
3878 *
3879 * @param pGip The GIP.
3880 * @param pGipCpu Pointer to the per cpu data.
3881 * @param u64NanoTS The current time stamp.
3882 */
3883static void supdrvGipDoUpdateCpu(PSUPGLOBALINFOPAGE pGip, PSUPGIPCPU pGipCpu, uint64_t u64NanoTS)
3884{
3885 uint64_t u64TSC;
3886 uint64_t u64TSCDelta;
3887 uint32_t u32UpdateIntervalTSC;
3888 uint32_t u32UpdateIntervalTSCSlack;
3889 unsigned iTSCHistoryHead;
3890 uint64_t u64CpuHz;
3891
3892 /*
3893 * Update the NanoTS.
3894 */
3895 ASMAtomicXchgU64(&pGipCpu->u64NanoTS, u64NanoTS);
3896
3897 /*
3898 * Calc TSC delta.
3899 */
3900 /** @todo validate the NanoTS delta, don't trust the OS to call us when it should... */
3901 u64TSC = ASMReadTSC();
3902 u64TSCDelta = u64TSC - pGipCpu->u64TSC;
3903 ASMAtomicXchgU64(&pGipCpu->u64TSC, u64TSC);
3904
3905 if (u64TSCDelta >> 32)
3906 {
3907 u64TSCDelta = pGipCpu->u32UpdateIntervalTSC;
3908 pGipCpu->cErrors++;
3909 }
3910
3911 /*
3912 * TSC History.
3913 */
3914 Assert(ELEMENTS(pGipCpu->au32TSCHistory) == 8);
3915
3916 iTSCHistoryHead = (pGipCpu->iTSCHistoryHead + 1) & 7;
3917 ASMAtomicXchgU32(&pGipCpu->iTSCHistoryHead, iTSCHistoryHead);
3918 ASMAtomicXchgU32(&pGipCpu->au32TSCHistory[iTSCHistoryHead], (uint32_t)u64TSCDelta);
3919
3920 /*
3921 * UpdateIntervalTSC = average of last 8,2,1 intervals depending on update HZ.
3922 */
3923 if (pGip->u32UpdateHz >= 1000)
3924 {
3925 uint32_t u32;
3926 u32 = pGipCpu->au32TSCHistory[0];
3927 u32 += pGipCpu->au32TSCHistory[1];
3928 u32 += pGipCpu->au32TSCHistory[2];
3929 u32 += pGipCpu->au32TSCHistory[3];
3930 u32 >>= 2;
3931 u32UpdateIntervalTSC = pGipCpu->au32TSCHistory[4];
3932 u32UpdateIntervalTSC += pGipCpu->au32TSCHistory[5];
3933 u32UpdateIntervalTSC += pGipCpu->au32TSCHistory[6];
3934 u32UpdateIntervalTSC += pGipCpu->au32TSCHistory[7];
3935 u32UpdateIntervalTSC >>= 2;
3936 u32UpdateIntervalTSC += u32;
3937 u32UpdateIntervalTSC >>= 1;
3938
3939 /* Value choosen for a 2GHz Athlon64 running linux 2.6.10/11, . */
3940 u32UpdateIntervalTSCSlack = u32UpdateIntervalTSC >> 14;
3941 }
3942 else if (pGip->u32UpdateHz >= 90)
3943 {
3944 u32UpdateIntervalTSC = (uint32_t)u64TSCDelta;
3945 u32UpdateIntervalTSC += pGipCpu->au32TSCHistory[(iTSCHistoryHead - 1) & 7];
3946 u32UpdateIntervalTSC >>= 1;
3947
3948 /* value choosen on a 2GHz thinkpad running windows */
3949 u32UpdateIntervalTSCSlack = u32UpdateIntervalTSC >> 7;
3950 }
3951 else
3952 {
3953 u32UpdateIntervalTSC = (uint32_t)u64TSCDelta;
3954
3955 /* This value hasn't be checked yet.. waiting for OS/2 and 33Hz timers.. :-) */
3956 u32UpdateIntervalTSCSlack = u32UpdateIntervalTSC >> 6;
3957 }
3958 ASMAtomicXchgU32(&pGipCpu->u32UpdateIntervalTSC, u32UpdateIntervalTSC + u32UpdateIntervalTSCSlack);
3959
3960 /*
3961 * CpuHz.
3962 */
3963 u64CpuHz = ASMMult2xU32RetU64(u32UpdateIntervalTSC, pGip->u32UpdateHz);
3964 ASMAtomicXchgU64(&pGipCpu->u64CpuHz, u64CpuHz);
3965}
3966
3967
3968/**
3969 * Updates the GIP.
3970 *
3971 * @param pGip Pointer to the GIP.
3972 * @param u64NanoTS The current nanosecond timesamp.
3973 */
3974void VBOXCALL supdrvGipUpdate(PSUPGLOBALINFOPAGE pGip, uint64_t u64NanoTS)
3975{
3976 /*
3977 * Determin the relevant CPU data.
3978 */
3979 PSUPGIPCPU pGipCpu;
3980 if (pGip->u32Mode != SUPGIPMODE_ASYNC_TSC)
3981 pGipCpu = &pGip->aCPUs[0];
3982 else
3983 {
3984 unsigned iCpu = ASMGetApicId();
3985 if (RT_LIKELY(iCpu >= RT_ELEMENTS(pGip->aCPUs)))
3986 return;
3987 pGipCpu = &pGip->aCPUs[iCpu];
3988 }
3989
3990 /*
3991 * Start update transaction.
3992 */
3993 if (!(ASMAtomicIncU32(&pGipCpu->u32TransactionId) & 1))
3994 {
3995 /* this can happen on win32 if we're taking to long and there are more CPUs around. shouldn't happen though. */
3996 AssertMsgFailed(("Invalid transaction id, %#x, not odd!\n", pGipCpu->u32TransactionId));
3997 ASMAtomicIncU32(&pGipCpu->u32TransactionId);
3998 pGipCpu->cErrors++;
3999 return;
4000 }
4001
4002 /*
4003 * Recalc the update frequency every 0x800th time.
4004 */
4005 if (!(pGipCpu->u32TransactionId & (GIP_UPDATEHZ_RECALC_FREQ * 2 - 2)))
4006 {
4007 if (pGip->u64NanoTSLastUpdateHz)
4008 {
4009#ifdef RT_ARCH_AMD64 /** @todo fix 64-bit div here to work on x86 linux. */
4010 uint64_t u64Delta = u64NanoTS - pGip->u64NanoTSLastUpdateHz;
4011 uint32_t u32UpdateHz = (uint32_t)((UINT64_C(1000000000) * GIP_UPDATEHZ_RECALC_FREQ) / u64Delta);
4012 if (u32UpdateHz <= 2000 && u32UpdateHz >= 30)
4013 {
4014 ASMAtomicXchgU32(&pGip->u32UpdateHz, u32UpdateHz);
4015 ASMAtomicXchgU32(&pGip->u32UpdateIntervalNS, 1000000000 / u32UpdateHz);
4016 }
4017#endif
4018 }
4019 ASMAtomicXchgU64(&pGip->u64NanoTSLastUpdateHz, u64NanoTS);
4020 }
4021
4022 /*
4023 * Update the data.
4024 */
4025 supdrvGipDoUpdateCpu(pGip, pGipCpu, u64NanoTS);
4026
4027 /*
4028 * Complete transaction.
4029 */
4030 ASMAtomicIncU32(&pGipCpu->u32TransactionId);
4031}
4032
4033
4034/**
4035 * Updates the per cpu GIP data for the calling cpu.
4036 *
4037 * @param pGip Pointer to the GIP.
4038 * @param u64NanoTS The current nanosecond timesamp.
4039 * @param iCpu The CPU index.
4040 */
4041void VBOXCALL supdrvGipUpdatePerCpu(PSUPGLOBALINFOPAGE pGip, uint64_t u64NanoTS, unsigned iCpu)
4042{
4043 PSUPGIPCPU pGipCpu;
4044
4045 if (RT_LIKELY(iCpu <= RT_ELEMENTS(pGip->aCPUs)))
4046 {
4047 pGipCpu = &pGip->aCPUs[iCpu];
4048
4049 /*
4050 * Start update transaction.
4051 */
4052 if (!(ASMAtomicIncU32(&pGipCpu->u32TransactionId) & 1))
4053 {
4054 AssertMsgFailed(("Invalid transaction id, %#x, not odd!\n", pGipCpu->u32TransactionId));
4055 ASMAtomicIncU32(&pGipCpu->u32TransactionId);
4056 pGipCpu->cErrors++;
4057 return;
4058 }
4059
4060 /*
4061 * Update the data.
4062 */
4063 supdrvGipDoUpdateCpu(pGip, pGipCpu, u64NanoTS);
4064
4065 /*
4066 * Complete transaction.
4067 */
4068 ASMAtomicIncU32(&pGipCpu->u32TransactionId);
4069 }
4070}
4071
4072
4073#ifndef DEBUG /** @todo change #ifndef DEBUG -> #ifdef LOG_ENABLED */
4074/**
4075 * Stub function for non-debug builds.
4076 */
4077RTDECL(PRTLOGGER) RTLogDefaultInstance(void)
4078{
4079 return NULL;
4080}
4081
4082RTDECL(PRTLOGGER) RTLogRelDefaultInstance(void)
4083{
4084 return NULL;
4085}
4086
4087/**
4088 * Stub function for non-debug builds.
4089 */
4090RTDECL(int) RTLogSetDefaultInstanceThread(PRTLOGGER pLogger, uintptr_t uKey)
4091{
4092 return 0;
4093}
4094
4095/**
4096 * Stub function for non-debug builds.
4097 */
4098RTDECL(void) RTLogLogger(PRTLOGGER pLogger, void *pvCallerRet, const char *pszFormat, ...)
4099{
4100}
4101
4102/**
4103 * Stub function for non-debug builds.
4104 */
4105RTDECL(void) RTLogLoggerEx(PRTLOGGER pLogger, unsigned fFlags, unsigned iGroup, const char *pszFormat, ...)
4106{
4107}
4108
4109/**
4110 * Stub function for non-debug builds.
4111 */
4112RTDECL(void) RTLogLoggerExV(PRTLOGGER pLogger, unsigned fFlags, unsigned iGroup, const char *pszFormat, va_list args)
4113{
4114}
4115
4116/**
4117 * Stub function for non-debug builds.
4118 */
4119RTDECL(void) RTLogPrintf(const char *pszFormat, ...)
4120{
4121}
4122
4123/**
4124 * Stub function for non-debug builds.
4125 */
4126RTDECL(void) RTLogPrintfV(const char *pszFormat, va_list args)
4127{
4128}
4129#endif /* !DEBUG */
4130
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