VirtualBox

source: vbox/trunk/src/VBox/HostDrivers/Support/SUPDrv.c@ 16050

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

RTMpIsCpuWorkPending() -> RTMpIsCpuWorkPending(void), corrected source location and added the missing generic stub function.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 181.4 KB
Line 
1/* $Revision: 15843 $ */
2/** @file
3 * VBoxDrv - The VirtualBox Support Driver - Common code.
4 */
5
6/*
7 * Copyright (C) 2006-2007 Sun Microsystems, Inc.
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 *
17 * 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 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
27 * Clara, CA 95054 USA or visit http://www.sun.com if you need
28 * additional information or have any questions.
29 */
30
31/*******************************************************************************
32* Header Files *
33*******************************************************************************/
34#define LOG_GROUP LOG_GROUP_SUP_DRV
35#include "SUPDrvInternal.h"
36#ifndef PAGE_SHIFT
37# include <iprt/param.h>
38#endif
39#include <iprt/alloc.h>
40#include <iprt/semaphore.h>
41#include <iprt/spinlock.h>
42#include <iprt/thread.h>
43#include <iprt/process.h>
44#include <iprt/mp.h>
45#include <iprt/power.h>
46#include <iprt/cpuset.h>
47#include <iprt/uuid.h>
48#include <VBox/param.h>
49#include <VBox/log.h>
50#include <VBox/err.h>
51#if defined(RT_OS_DARWIN) || defined(RT_OS_SOLARIS)
52# include <iprt/crc32.h>
53# include <iprt/net.h>
54#endif
55/* VBox/x86.h not compatible with the Linux kernel sources */
56#ifdef RT_OS_LINUX
57# define X86_CPUID_VENDOR_AMD_EBX 0x68747541
58# define X86_CPUID_VENDOR_AMD_ECX 0x444d4163
59# define X86_CPUID_VENDOR_AMD_EDX 0x69746e65
60#else
61# include <VBox/x86.h>
62#endif
63
64/*
65 * Logging assignments:
66 * Log - useful stuff, like failures.
67 * LogFlow - program flow, except the really noisy bits.
68 * Log2 - Cleanup.
69 * Log3 - Loader flow noise.
70 * Log4 - Call VMMR0 flow noise.
71 * Log5 - Native yet-to-be-defined noise.
72 * Log6 - Native ioctl flow noise.
73 *
74 * Logging requires BUILD_TYPE=debug and possibly changes to the logger
75 * instanciation in log-vbox.c(pp).
76 */
77
78
79/*******************************************************************************
80* Defined Constants And Macros *
81*******************************************************************************/
82/* from x86.h - clashes with linux thus this duplication */
83#undef X86_CR0_PG
84#define X86_CR0_PG RT_BIT(31)
85#undef X86_CR0_PE
86#define X86_CR0_PE RT_BIT(0)
87#undef X86_CPUID_AMD_FEATURE_EDX_NX
88#define X86_CPUID_AMD_FEATURE_EDX_NX RT_BIT(20)
89#undef MSR_K6_EFER
90#define MSR_K6_EFER 0xc0000080
91#undef MSR_K6_EFER_NXE
92#define MSR_K6_EFER_NXE RT_BIT(11)
93#undef MSR_K6_EFER_LMA
94#define MSR_K6_EFER_LMA RT_BIT(10)
95#undef X86_CR4_PGE
96#define X86_CR4_PGE RT_BIT(7)
97#undef X86_CR4_PAE
98#define X86_CR4_PAE RT_BIT(5)
99#undef X86_CPUID_AMD_FEATURE_EDX_LONG_MODE
100#define X86_CPUID_AMD_FEATURE_EDX_LONG_MODE RT_BIT(29)
101
102
103/** The frequency by which we recalculate the u32UpdateHz and
104 * u32UpdateIntervalNS GIP members. The value must be a power of 2. */
105#define GIP_UPDATEHZ_RECALC_FREQ 0x800
106
107/**
108 * Validates a session pointer.
109 *
110 * @returns true/false accordingly.
111 * @param pSession The session.
112 */
113#define SUP_IS_SESSION_VALID(pSession) \
114 ( VALID_PTR(pSession) \
115 && pSession->u32Cookie == BIRD_INV)
116
117/** @def VBOX_SVN_REV
118 * The makefile should define this if it can. */
119#ifndef VBOX_SVN_REV
120# define VBOX_SVN_REV 0
121#endif
122
123/*******************************************************************************
124* Internal Functions *
125*******************************************************************************/
126static int supdrvMemAdd(PSUPDRVMEMREF pMem, PSUPDRVSESSION pSession);
127static int supdrvMemRelease(PSUPDRVSESSION pSession, RTHCUINTPTR uPtr, SUPDRVMEMREFTYPE eType);
128static int supdrvIOCtl_LdrOpen(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPLDROPEN pReq);
129static int supdrvIOCtl_LdrLoad(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPLDRLOAD pReq);
130static int supdrvIOCtl_LdrFree(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPLDRFREE pReq);
131static int supdrvIOCtl_LdrGetSymbol(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPLDRGETSYMBOL pReq);
132static int supdrvIDC_LdrGetSymbol(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPDRVIDCREQGETSYM pReq);
133static int supdrvLdrSetVMMR0EPs(PSUPDRVDEVEXT pDevExt, void *pvVMMR0, void *pvVMMR0EntryInt, void *pvVMMR0EntryFast, void *pvVMMR0EntryEx);
134static void supdrvLdrUnsetVMMR0EPs(PSUPDRVDEVEXT pDevExt);
135static int supdrvLdrAddUsage(PSUPDRVSESSION pSession, PSUPDRVLDRIMAGE pImage);
136static void supdrvLdrFree(PSUPDRVDEVEXT pDevExt, PSUPDRVLDRIMAGE pImage);
137static int supdrvIOCtl_CallServiceModule(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPCALLSERVICE pReq);
138static SUPGIPMODE supdrvGipDeterminTscMode(PSUPDRVDEVEXT pDevExt);
139#ifdef RT_OS_WINDOWS
140static int supdrvPageGetPhys(PSUPDRVSESSION pSession, RTR3PTR pvR3, uint32_t cPages, PRTHCPHYS paPages);
141static bool supdrvPageWasLockedByPageAlloc(PSUPDRVSESSION pSession, RTR3PTR pvR3);
142#endif /* RT_OS_WINDOWS */
143static int supdrvGipCreate(PSUPDRVDEVEXT pDevExt);
144static void supdrvGipDestroy(PSUPDRVDEVEXT pDevExt);
145static DECLCALLBACK(void) supdrvGipSyncTimer(PRTTIMER pTimer, void *pvUser, uint64_t iTick);
146static DECLCALLBACK(void) supdrvGipAsyncTimer(PRTTIMER pTimer, void *pvUser, uint64_t iTick);
147static DECLCALLBACK(void) supdrvGipMpEvent(RTMPEVENT enmEvent, RTCPUID idCpu, void *pvUser);
148
149#ifdef RT_WITH_W64_UNWIND_HACK
150DECLASM(int) supdrvNtWrapVMMR0EntryEx(PFNRT pfnVMMR0EntryEx, PVM pVM, unsigned uOperation, PSUPVMMR0REQHDR pReq, uint64_t u64Arg, PSUPDRVSESSION pSession);
151DECLASM(int) supdrvNtWrapVMMR0EntryFast(PFNRT pfnVMMR0EntryFast, PVM pVM, unsigned idCpu, unsigned uOperation);
152DECLASM(void) supdrvNtWrapObjDestructor(PFNRT pfnDestruction, void *pvObj, void *pvUser1, void *pvUser2);
153DECLASM(void *) supdrvNtWrapQueryFactoryInterface(PFNRT pfnQueryFactoryInterface, struct SUPDRVFACTORY const *pSupDrvFactory, PSUPDRVSESSION pSession, const char *pszInterfaceUuid);
154DECLASM(int) supdrvNtWrapModuleInit(PFNRT pfnModuleInit);
155DECLASM(void) supdrvNtWrapModuleTerm(PFNRT pfnModuleTerm);
156DECLASM(int) supdrvNtWrapServiceReqHandler(PFNRT pfnServiceReqHandler, PSUPDRVSESSION pSession, uint32_t uOperation, uint64_t u64Arg, PSUPR0SERVICEREQHDR pReqHdr);
157
158DECLASM(int) UNWIND_WRAP(SUPR0ComponentRegisterFactory)(PSUPDRVSESSION pSession, PCSUPDRVFACTORY pFactory);
159DECLASM(int) UNWIND_WRAP(SUPR0ComponentDeregisterFactory)(PSUPDRVSESSION pSession, PCSUPDRVFACTORY pFactory);
160DECLASM(int) UNWIND_WRAP(SUPR0ComponentQueryFactory)(PSUPDRVSESSION pSession, const char *pszName, const char *pszInterfaceUuid, void **ppvFactoryIf);
161DECLASM(void *) UNWIND_WRAP(SUPR0ObjRegister)(PSUPDRVSESSION pSession, SUPDRVOBJTYPE enmType, PFNSUPDRVDESTRUCTOR pfnDestructor, void *pvUser1, void *pvUser2);
162DECLASM(int) UNWIND_WRAP(SUPR0ObjAddRef)(void *pvObj, PSUPDRVSESSION pSession);
163DECLASM(int) UNWIND_WRAP(SUPR0ObjAddRefEx)(void *pvObj, PSUPDRVSESSION pSession, bool fNoPreempt);
164DECLASM(int) UNWIND_WRAP(SUPR0ObjRelease)(void *pvObj, PSUPDRVSESSION pSession);
165DECLASM(int) UNWIND_WRAP(SUPR0ObjVerifyAccess)(void *pvObj, PSUPDRVSESSION pSession, const char *pszObjName);
166DECLASM(int) UNWIND_WRAP(SUPR0LockMem)(PSUPDRVSESSION pSession, RTR3PTR pvR3, uint32_t cPages, PRTHCPHYS paPages);
167DECLASM(int) UNWIND_WRAP(SUPR0UnlockMem)(PSUPDRVSESSION pSession, RTR3PTR pvR3);
168DECLASM(int) UNWIND_WRAP(SUPR0ContAlloc)(PSUPDRVSESSION pSession, uint32_t cPages, PRTR0PTR ppvR0, PRTR3PTR ppvR3, PRTHCPHYS pHCPhys);
169DECLASM(int) UNWIND_WRAP(SUPR0ContFree)(PSUPDRVSESSION pSession, RTHCUINTPTR uPtr);
170DECLASM(int) UNWIND_WRAP(SUPR0LowAlloc)(PSUPDRVSESSION pSession, uint32_t cPages, PRTR0PTR ppvR0, PRTR3PTR ppvR3, PRTHCPHYS paPages);
171DECLASM(int) UNWIND_WRAP(SUPR0LowFree)(PSUPDRVSESSION pSession, RTHCUINTPTR uPtr);
172DECLASM(int) UNWIND_WRAP(SUPR0MemAlloc)(PSUPDRVSESSION pSession, uint32_t cb, PRTR0PTR ppvR0, PRTR3PTR ppvR3);
173DECLASM(int) UNWIND_WRAP(SUPR0MemGetPhys)(PSUPDRVSESSION pSession, RTHCUINTPTR uPtr, PSUPPAGE paPages);
174DECLASM(int) UNWIND_WRAP(SUPR0MemFree)(PSUPDRVSESSION pSession, RTHCUINTPTR uPtr);
175DECLASM(int) UNWIND_WRAP(SUPR0PageAlloc)(PSUPDRVSESSION pSession, uint32_t cPages, PRTR3PTR ppvR3, PRTHCPHYS paPages);
176DECLASM(int) UNWIND_WRAP(SUPR0PageFree)(PSUPDRVSESSION pSession, RTR3PTR pvR3);
177//DECLASM(int) UNWIND_WRAP(SUPR0Printf)(const char *pszFormat, ...);
178DECLASM(SUPPAGINGMODE) UNWIND_WRAP(SUPR0GetPagingMode)(void);
179DECLASM(void *) UNWIND_WRAP(RTMemAlloc)(size_t cb) RT_NO_THROW;
180DECLASM(void *) UNWIND_WRAP(RTMemAllocZ)(size_t cb) RT_NO_THROW;
181DECLASM(void) UNWIND_WRAP(RTMemFree)(void *pv) RT_NO_THROW;
182DECLASM(void *) UNWIND_WRAP(RTMemDup)(const void *pvSrc, size_t cb) RT_NO_THROW;
183DECLASM(void *) UNWIND_WRAP(RTMemDupEx)(const void *pvSrc, size_t cbSrc, size_t cbExtra) RT_NO_THROW;
184DECLASM(void *) UNWIND_WRAP(RTMemRealloc)(void *pvOld, size_t cbNew) RT_NO_THROW;
185DECLASM(int) UNWIND_WRAP(RTR0MemObjAllocLow)(PRTR0MEMOBJ pMemObj, size_t cb, bool fExecutable);
186DECLASM(int) UNWIND_WRAP(RTR0MemObjAllocPage)(PRTR0MEMOBJ pMemObj, size_t cb, bool fExecutable);
187DECLASM(int) UNWIND_WRAP(RTR0MemObjAllocPhys)(PRTR0MEMOBJ pMemObj, size_t cb, RTHCPHYS PhysHighest);
188DECLASM(int) UNWIND_WRAP(RTR0MemObjAllocPhysNC)(PRTR0MEMOBJ pMemObj, size_t cb, RTHCPHYS PhysHighest);
189DECLASM(int) UNWIND_WRAP(RTR0MemObjAllocCont)(PRTR0MEMOBJ pMemObj, size_t cb, bool fExecutable);
190DECLASM(int) UNWIND_WRAP(RTR0MemObjEnterPhys)(PRTR0MEMOBJ pMemObj, RTHCPHYS Phys, size_t cb);
191DECLASM(int) UNWIND_WRAP(RTR0MemObjLockUser)(PRTR0MEMOBJ pMemObj, RTR3PTR R3Ptr, size_t cb, RTR0PROCESS R0Process);
192DECLASM(int) UNWIND_WRAP(RTR0MemObjMapKernel)(PRTR0MEMOBJ pMemObj, RTR0MEMOBJ MemObjToMap, void *pvFixed, size_t uAlignment, unsigned fProt);
193DECLASM(int) UNWIND_WRAP(RTR0MemObjMapKernelEx)(PRTR0MEMOBJ pMemObj, RTR0MEMOBJ MemObjToMap, void *pvFixed, size_t uAlignment, unsigned fProt, size_t offSub, size_t cbSub);
194DECLASM(int) UNWIND_WRAP(RTR0MemObjMapUser)(PRTR0MEMOBJ pMemObj, RTR0MEMOBJ MemObjToMap, RTR3PTR R3PtrFixed, size_t uAlignment, unsigned fProt, RTR0PROCESS R0Process);
195/*DECLASM(void *) UNWIND_WRAP(RTR0MemObjAddress)(RTR0MEMOBJ MemObj); - not necessary */
196/*DECLASM(RTR3PTR) UNWIND_WRAP(RTR0MemObjAddressR3)(RTR0MEMOBJ MemObj); - not necessary */
197/*DECLASM(size_t) UNWIND_WRAP(RTR0MemObjSize)(RTR0MEMOBJ MemObj); - not necessary */
198/*DECLASM(bool) UNWIND_WRAP(RTR0MemObjIsMapping)(RTR0MEMOBJ MemObj); - not necessary */
199/*DECLASM(RTHCPHYS) UNWIND_WRAP(RTR0MemObjGetPagePhysAddr)(RTR0MEMOBJ MemObj, size_t iPage); - not necessary */
200DECLASM(int) UNWIND_WRAP(RTR0MemObjFree)(RTR0MEMOBJ MemObj, bool fFreeMappings);
201/* RTProcSelf - not necessary */
202/* RTR0ProcHandleSelf - not necessary */
203DECLASM(int) UNWIND_WRAP(RTSemFastMutexCreate)(PRTSEMFASTMUTEX pMutexSem);
204DECLASM(int) UNWIND_WRAP(RTSemFastMutexDestroy)(RTSEMFASTMUTEX MutexSem);
205DECLASM(int) UNWIND_WRAP(RTSemFastMutexRequest)(RTSEMFASTMUTEX MutexSem);
206DECLASM(int) UNWIND_WRAP(RTSemFastMutexRelease)(RTSEMFASTMUTEX MutexSem);
207DECLASM(int) UNWIND_WRAP(RTSemEventCreate)(PRTSEMEVENT pEventSem);
208DECLASM(int) UNWIND_WRAP(RTSemEventSignal)(RTSEMEVENT EventSem);
209DECLASM(int) UNWIND_WRAP(RTSemEventWait)(RTSEMEVENT EventSem, unsigned cMillies);
210DECLASM(int) UNWIND_WRAP(RTSemEventWaitNoResume)(RTSEMEVENT EventSem, unsigned cMillies);
211DECLASM(int) UNWIND_WRAP(RTSemEventDestroy)(RTSEMEVENT EventSem);
212DECLASM(int) UNWIND_WRAP(RTSemEventMultiCreate)(PRTSEMEVENTMULTI pEventMultiSem);
213DECLASM(int) UNWIND_WRAP(RTSemEventMultiSignal)(RTSEMEVENTMULTI EventMultiSem);
214DECLASM(int) UNWIND_WRAP(RTSemEventMultiReset)(RTSEMEVENTMULTI EventMultiSem);
215DECLASM(int) UNWIND_WRAP(RTSemEventMultiWait)(RTSEMEVENTMULTI EventMultiSem, unsigned cMillies);
216DECLASM(int) UNWIND_WRAP(RTSemEventMultiWaitNoResume)(RTSEMEVENTMULTI EventMultiSem, unsigned cMillies);
217DECLASM(int) UNWIND_WRAP(RTSemEventMultiDestroy)(RTSEMEVENTMULTI EventMultiSem);
218DECLASM(int) UNWIND_WRAP(RTSpinlockCreate)(PRTSPINLOCK pSpinlock);
219DECLASM(int) UNWIND_WRAP(RTSpinlockDestroy)(RTSPINLOCK Spinlock);
220DECLASM(void) UNWIND_WRAP(RTSpinlockAcquire)(RTSPINLOCK Spinlock, PRTSPINLOCKTMP pTmp);
221DECLASM(void) UNWIND_WRAP(RTSpinlockRelease)(RTSPINLOCK Spinlock, PRTSPINLOCKTMP pTmp);
222DECLASM(void) UNWIND_WRAP(RTSpinlockAcquireNoInts)(RTSPINLOCK Spinlock, PRTSPINLOCKTMP pTmp);
223DECLASM(void) UNWIND_WRAP(RTSpinlockReleaseNoInts)(RTSPINLOCK Spinlock, PRTSPINLOCKTMP pTmp);
224/* RTTimeNanoTS - not necessary */
225/* RTTimeMilliTS - not necessary */
226/* RTTimeSystemNanoTS - not necessary */
227/* RTTimeSystemMilliTS - not necessary */
228/* RTThreadNativeSelf - not necessary */
229DECLASM(int) UNWIND_WRAP(RTThreadSleep)(unsigned cMillies);
230DECLASM(bool) UNWIND_WRAP(RTThreadYield)(void);
231#if 0
232/* RTThreadSelf - not necessary */
233DECLASM(int) UNWIND_WRAP(RTThreadCreate)(PRTTHREAD pThread, PFNRTTHREAD pfnThread, void *pvUser, size_t cbStack,
234 RTTHREADTYPE enmType, unsigned fFlags, const char *pszName);
235DECLASM(RTNATIVETHREAD) UNWIND_WRAP(RTThreadGetNative)(RTTHREAD Thread);
236DECLASM(int) UNWIND_WRAP(RTThreadWait)(RTTHREAD Thread, unsigned cMillies, int *prc);
237DECLASM(int) UNWIND_WRAP(RTThreadWaitNoResume)(RTTHREAD Thread, unsigned cMillies, int *prc);
238DECLASM(const char *) UNWIND_WRAP(RTThreadGetName)(RTTHREAD Thread);
239DECLASM(const char *) UNWIND_WRAP(RTThreadSelfName)(void);
240DECLASM(RTTHREADTYPE) UNWIND_WRAP(RTThreadGetType)(RTTHREAD Thread);
241DECLASM(int) UNWIND_WRAP(RTThreadUserSignal)(RTTHREAD Thread);
242DECLASM(int) UNWIND_WRAP(RTThreadUserReset)(RTTHREAD Thread);
243DECLASM(int) UNWIND_WRAP(RTThreadUserWait)(RTTHREAD Thread, unsigned cMillies);
244DECLASM(int) UNWIND_WRAP(RTThreadUserWaitNoResume)(RTTHREAD Thread, unsigned cMillies);
245#endif
246/* RTLogDefaultInstance - a bit of a gamble, but we do not want the overhead! */
247/* RTMpCpuId - not necessary */
248/* RTMpCpuIdFromSetIndex - not necessary */
249/* RTMpCpuIdToSetIndex - not necessary */
250/* RTMpIsCpuPossible - not necessary */
251/* RTMpGetCount - not necessary */
252/* RTMpGetMaxCpuId - not necessary */
253/* RTMpGetOnlineCount - not necessary */
254/* RTMpGetOnlineSet - not necessary */
255/* RTMpGetSet - not necessary */
256/* RTMpIsCpuOnline - not necessary */
257DECLASM(int) UNWIND_WRAP(RTMpOnAll)(PFNRTMPWORKER pfnWorker, void *pvUser1, void *pvUser2);
258DECLASM(int) UNWIND_WRAP(RTMpOnOthers)(PFNRTMPWORKER pfnWorker, void *pvUser1, void *pvUser2);
259DECLASM(int) UNWIND_WRAP(RTMpOnSpecific)(RTCPUID idCpu, PFNRTMPWORKER pfnWorker, void *pvUser1, void *pvUser2);
260DECLASM(int) UNWIND_WRAP(RTMpIsCpuWorkPending)(void);
261/* RTLogRelDefaultInstance - not necessary. */
262DECLASM(int) UNWIND_WRAP(RTLogSetDefaultInstanceThread)(PRTLOGGER pLogger, uintptr_t uKey);
263/* RTLogLogger - can't wrap this buster. */
264/* RTLogLoggerEx - can't wrap this buster. */
265DECLASM(void) UNWIND_WRAP(RTLogLoggerExV)(PRTLOGGER pLogger, unsigned fFlags, unsigned iGroup, const char *pszFormat, va_list args);
266/* RTLogPrintf - can't wrap this buster. */ /** @todo provide va_list log wrappers in RuntimeR0. */
267DECLASM(void) UNWIND_WRAP(RTLogPrintfV)(const char *pszFormat, va_list args);
268DECLASM(void) UNWIND_WRAP(AssertMsg1)(const char *pszExpr, unsigned uLine, const char *pszFile, const char *pszFunction);
269/* AssertMsg2 - can't wrap this buster. */
270#endif /* RT_WITH_W64_UNWIND_HACK */
271
272
273/*******************************************************************************
274* Global Variables *
275*******************************************************************************/
276/**
277 * Array of the R0 SUP API.
278 */
279static SUPFUNC g_aFunctions[] =
280{
281 /* name function */
282 /* Entries with absolute addresses determined at runtime, fixup
283 code makes ugly ASSUMPTIONS about the order here: */
284 { "SUPR0AbsIs64bit", (void *)0 },
285 { "SUPR0Abs64bitKernelCS", (void *)0 },
286 { "SUPR0Abs64bitKernelSS", (void *)0 },
287 { "SUPR0Abs64bitKernelDS", (void *)0 },
288 { "SUPR0AbsKernelCS", (void *)0 },
289 { "SUPR0AbsKernelSS", (void *)0 },
290 { "SUPR0AbsKernelDS", (void *)0 },
291 { "SUPR0AbsKernelES", (void *)0 },
292 { "SUPR0AbsKernelFS", (void *)0 },
293 { "SUPR0AbsKernelGS", (void *)0 },
294 /* Normal function pointers: */
295 { "SUPR0ComponentRegisterFactory", (void *)UNWIND_WRAP(SUPR0ComponentRegisterFactory) },
296 { "SUPR0ComponentDeregisterFactory", (void *)UNWIND_WRAP(SUPR0ComponentDeregisterFactory) },
297 { "SUPR0ComponentQueryFactory", (void *)UNWIND_WRAP(SUPR0ComponentQueryFactory) },
298 { "SUPR0ObjRegister", (void *)UNWIND_WRAP(SUPR0ObjRegister) },
299 { "SUPR0ObjAddRef", (void *)UNWIND_WRAP(SUPR0ObjAddRef) },
300 { "SUPR0ObjAddRefEx", (void *)UNWIND_WRAP(SUPR0ObjAddRefEx) },
301 { "SUPR0ObjRelease", (void *)UNWIND_WRAP(SUPR0ObjRelease) },
302 { "SUPR0ObjVerifyAccess", (void *)UNWIND_WRAP(SUPR0ObjVerifyAccess) },
303 { "SUPR0LockMem", (void *)UNWIND_WRAP(SUPR0LockMem) },
304 { "SUPR0UnlockMem", (void *)UNWIND_WRAP(SUPR0UnlockMem) },
305 { "SUPR0ContAlloc", (void *)UNWIND_WRAP(SUPR0ContAlloc) },
306 { "SUPR0ContFree", (void *)UNWIND_WRAP(SUPR0ContFree) },
307 { "SUPR0LowAlloc", (void *)UNWIND_WRAP(SUPR0LowAlloc) },
308 { "SUPR0LowFree", (void *)UNWIND_WRAP(SUPR0LowFree) },
309 { "SUPR0MemAlloc", (void *)UNWIND_WRAP(SUPR0MemAlloc) },
310 { "SUPR0MemGetPhys", (void *)UNWIND_WRAP(SUPR0MemGetPhys) },
311 { "SUPR0MemFree", (void *)UNWIND_WRAP(SUPR0MemFree) },
312 { "SUPR0PageAlloc", (void *)UNWIND_WRAP(SUPR0PageAlloc) },
313 { "SUPR0PageFree", (void *)UNWIND_WRAP(SUPR0PageFree) },
314 { "SUPR0Printf", (void *)SUPR0Printf }, /** @todo needs wrapping? */
315 { "SUPR0GetPagingMode", (void *)UNWIND_WRAP(SUPR0GetPagingMode) },
316 { "SUPR0EnableVTx", (void *)SUPR0EnableVTx },
317 { "RTMemAlloc", (void *)UNWIND_WRAP(RTMemAlloc) },
318 { "RTMemAllocZ", (void *)UNWIND_WRAP(RTMemAllocZ) },
319 { "RTMemFree", (void *)UNWIND_WRAP(RTMemFree) },
320 /*{ "RTMemDup", (void *)UNWIND_WRAP(RTMemDup) },
321 { "RTMemDupEx", (void *)UNWIND_WRAP(RTMemDupEx) },*/
322 { "RTMemRealloc", (void *)UNWIND_WRAP(RTMemRealloc) },
323 { "RTR0MemObjAllocLow", (void *)UNWIND_WRAP(RTR0MemObjAllocLow) },
324 { "RTR0MemObjAllocPage", (void *)UNWIND_WRAP(RTR0MemObjAllocPage) },
325 { "RTR0MemObjAllocPhys", (void *)UNWIND_WRAP(RTR0MemObjAllocPhys) },
326 { "RTR0MemObjAllocPhysNC", (void *)UNWIND_WRAP(RTR0MemObjAllocPhysNC) },
327 { "RTR0MemObjAllocCont", (void *)UNWIND_WRAP(RTR0MemObjAllocCont) },
328 { "RTR0MemObjEnterPhys", (void *)UNWIND_WRAP(RTR0MemObjEnterPhys) },
329 { "RTR0MemObjLockUser", (void *)UNWIND_WRAP(RTR0MemObjLockUser) },
330 { "RTR0MemObjMapKernel", (void *)UNWIND_WRAP(RTR0MemObjMapKernel) },
331 { "RTR0MemObjMapKernelEx", (void *)UNWIND_WRAP(RTR0MemObjMapKernelEx) },
332 { "RTR0MemObjMapUser", (void *)UNWIND_WRAP(RTR0MemObjMapUser) },
333 { "RTR0MemObjAddress", (void *)RTR0MemObjAddress },
334 { "RTR0MemObjAddressR3", (void *)RTR0MemObjAddressR3 },
335 { "RTR0MemObjSize", (void *)RTR0MemObjSize },
336 { "RTR0MemObjIsMapping", (void *)RTR0MemObjIsMapping },
337 { "RTR0MemObjGetPagePhysAddr", (void *)RTR0MemObjGetPagePhysAddr },
338 { "RTR0MemObjFree", (void *)UNWIND_WRAP(RTR0MemObjFree) },
339/* These don't work yet on linux - use fast mutexes!
340 { "RTSemMutexCreate", (void *)RTSemMutexCreate },
341 { "RTSemMutexRequest", (void *)RTSemMutexRequest },
342 { "RTSemMutexRelease", (void *)RTSemMutexRelease },
343 { "RTSemMutexDestroy", (void *)RTSemMutexDestroy },
344*/
345 { "RTProcSelf", (void *)RTProcSelf },
346 { "RTR0ProcHandleSelf", (void *)RTR0ProcHandleSelf },
347 { "RTSemFastMutexCreate", (void *)UNWIND_WRAP(RTSemFastMutexCreate) },
348 { "RTSemFastMutexDestroy", (void *)UNWIND_WRAP(RTSemFastMutexDestroy) },
349 { "RTSemFastMutexRequest", (void *)UNWIND_WRAP(RTSemFastMutexRequest) },
350 { "RTSemFastMutexRelease", (void *)UNWIND_WRAP(RTSemFastMutexRelease) },
351 { "RTSemEventCreate", (void *)UNWIND_WRAP(RTSemEventCreate) },
352 { "RTSemEventSignal", (void *)UNWIND_WRAP(RTSemEventSignal) },
353 { "RTSemEventWait", (void *)UNWIND_WRAP(RTSemEventWait) },
354 { "RTSemEventWaitNoResume", (void *)UNWIND_WRAP(RTSemEventWaitNoResume) },
355 { "RTSemEventDestroy", (void *)UNWIND_WRAP(RTSemEventDestroy) },
356 { "RTSemEventMultiCreate", (void *)UNWIND_WRAP(RTSemEventMultiCreate) },
357 { "RTSemEventMultiSignal", (void *)UNWIND_WRAP(RTSemEventMultiSignal) },
358 { "RTSemEventMultiReset", (void *)UNWIND_WRAP(RTSemEventMultiReset) },
359 { "RTSemEventMultiWait", (void *)UNWIND_WRAP(RTSemEventMultiWait) },
360 { "RTSemEventMultiWaitNoResume", (void *)UNWIND_WRAP(RTSemEventMultiWaitNoResume) },
361 { "RTSemEventMultiDestroy", (void *)UNWIND_WRAP(RTSemEventMultiDestroy) },
362 { "RTSpinlockCreate", (void *)UNWIND_WRAP(RTSpinlockCreate) },
363 { "RTSpinlockDestroy", (void *)UNWIND_WRAP(RTSpinlockDestroy) },
364 { "RTSpinlockAcquire", (void *)UNWIND_WRAP(RTSpinlockAcquire) },
365 { "RTSpinlockRelease", (void *)UNWIND_WRAP(RTSpinlockRelease) },
366 { "RTSpinlockAcquireNoInts", (void *)UNWIND_WRAP(RTSpinlockAcquireNoInts) },
367 { "RTSpinlockReleaseNoInts", (void *)UNWIND_WRAP(RTSpinlockReleaseNoInts) },
368 { "RTTimeNanoTS", (void *)RTTimeNanoTS },
369 { "RTTimeMillieTS", (void *)RTTimeMilliTS },
370 { "RTTimeSystemNanoTS", (void *)RTTimeSystemNanoTS },
371 { "RTTimeSystemMillieTS", (void *)RTTimeSystemMilliTS },
372 { "RTThreadNativeSelf", (void *)RTThreadNativeSelf },
373 { "RTThreadSleep", (void *)UNWIND_WRAP(RTThreadSleep) },
374 { "RTThreadYield", (void *)UNWIND_WRAP(RTThreadYield) },
375#if 0 /* Thread APIs, Part 2. */
376 { "RTThreadSelf", (void *)UNWIND_WRAP(RTThreadSelf) },
377 { "RTThreadCreate", (void *)UNWIND_WRAP(RTThreadCreate) }, /** @todo need to wrap the callback */
378 { "RTThreadGetNative", (void *)UNWIND_WRAP(RTThreadGetNative) },
379 { "RTThreadWait", (void *)UNWIND_WRAP(RTThreadWait) },
380 { "RTThreadWaitNoResume", (void *)UNWIND_WRAP(RTThreadWaitNoResume) },
381 { "RTThreadGetName", (void *)UNWIND_WRAP(RTThreadGetName) },
382 { "RTThreadSelfName", (void *)UNWIND_WRAP(RTThreadSelfName) },
383 { "RTThreadGetType", (void *)UNWIND_WRAP(RTThreadGetType) },
384 { "RTThreadUserSignal", (void *)UNWIND_WRAP(RTThreadUserSignal) },
385 { "RTThreadUserReset", (void *)UNWIND_WRAP(RTThreadUserReset) },
386 { "RTThreadUserWait", (void *)UNWIND_WRAP(RTThreadUserWait) },
387 { "RTThreadUserWaitNoResume", (void *)UNWIND_WRAP(RTThreadUserWaitNoResume) },
388#endif
389 { "RTLogDefaultInstance", (void *)RTLogDefaultInstance },
390 { "RTMpCpuId", (void *)RTMpCpuId },
391 { "RTMpCpuIdFromSetIndex", (void *)RTMpCpuIdFromSetIndex },
392 { "RTMpCpuIdToSetIndex", (void *)RTMpCpuIdToSetIndex },
393 { "RTMpIsCpuPossible", (void *)RTMpIsCpuPossible },
394 { "RTMpGetCount", (void *)RTMpGetCount },
395 { "RTMpGetMaxCpuId", (void *)RTMpGetMaxCpuId },
396 { "RTMpGetOnlineCount", (void *)RTMpGetOnlineCount },
397 { "RTMpGetOnlineSet", (void *)RTMpGetOnlineSet },
398 { "RTMpGetSet", (void *)RTMpGetSet },
399 { "RTMpIsCpuOnline", (void *)RTMpIsCpuOnline },
400 { "RTMpIsCpuWorkPending", (void *)UNWIND_WRAP(RTMpIsCpuWorkPending) },
401 { "RTMpOnAll", (void *)UNWIND_WRAP(RTMpOnAll) },
402 { "RTMpOnOthers", (void *)UNWIND_WRAP(RTMpOnOthers) },
403 { "RTMpOnSpecific", (void *)UNWIND_WRAP(RTMpOnSpecific) },
404 { "RTPowerNotificationRegister", (void *)RTPowerNotificationRegister },
405 { "RTPowerNotificationDeregister", (void *)RTPowerNotificationDeregister },
406 { "RTLogRelDefaultInstance", (void *)RTLogRelDefaultInstance },
407 { "RTLogSetDefaultInstanceThread", (void *)UNWIND_WRAP(RTLogSetDefaultInstanceThread) },
408 { "RTLogLogger", (void *)RTLogLogger }, /** @todo remove this */
409 { "RTLogLoggerEx", (void *)RTLogLoggerEx }, /** @todo remove this */
410 { "RTLogLoggerExV", (void *)UNWIND_WRAP(RTLogLoggerExV) },
411 { "RTLogPrintf", (void *)RTLogPrintf }, /** @todo remove this */
412 { "RTLogPrintfV", (void *)UNWIND_WRAP(RTLogPrintfV) },
413 { "AssertMsg1", (void *)UNWIND_WRAP(AssertMsg1) },
414 { "AssertMsg2", (void *)AssertMsg2 }, /** @todo replace this by RTAssertMsg2V */
415#if defined(RT_OS_DARWIN) || defined(RT_OS_SOLARIS)
416 { "RTR0AssertPanicSystem", (void *)RTR0AssertPanicSystem },
417#endif
418#if defined(RT_OS_DARWIN)
419 { "RTAssertMsg1", (void *)RTAssertMsg1 },
420 { "RTAssertMsg2", (void *)RTAssertMsg2 },
421 { "RTAssertMsg2V", (void *)RTAssertMsg2V },
422#endif
423};
424
425#if defined(RT_OS_DARWIN) || defined(RT_OS_SOLARIS)
426/**
427 * Drag in the rest of IRPT since we share it with the
428 * rest of the kernel modules on darwin.
429 */
430PFNRT g_apfnVBoxDrvIPRTDeps[] =
431{
432 (PFNRT)RTCrc32,
433 (PFNRT)RTErrConvertFromErrno,
434 (PFNRT)RTNetIPv4IsHdrValid,
435 (PFNRT)RTNetIPv4TCPChecksum,
436 (PFNRT)RTNetIPv4UDPChecksum,
437 (PFNRT)RTUuidCompare,
438 (PFNRT)RTUuidCompareStr,
439 (PFNRT)RTUuidFromStr,
440 NULL
441};
442#endif /* RT_OS_DARWIN || RT_OS_SOLARIS */
443
444
445/**
446 * Initializes the device extentsion structure.
447 *
448 * @returns IPRT status code.
449 * @param pDevExt The device extension to initialize.
450 */
451int VBOXCALL supdrvInitDevExt(PSUPDRVDEVEXT pDevExt)
452{
453 int rc;
454
455#ifdef SUPDRV_WITH_RELEASE_LOGGER
456 /*
457 * Create the release log.
458 */
459 static const char * const s_apszGroups[] = VBOX_LOGGROUP_NAMES;
460 PRTLOGGER pRelLogger;
461 rc = RTLogCreate(&pRelLogger, 0 /* fFlags */, "all",
462 "VBOX_RELEASE_LOG", RT_ELEMENTS(s_apszGroups), s_apszGroups,
463 RTLOGDEST_STDOUT | RTLOGDEST_DEBUGGER, NULL);
464 if (RT_SUCCESS(rc))
465 RTLogRelSetDefaultInstance(pRelLogger);
466#endif
467
468 /*
469 * Initialize it.
470 */
471 memset(pDevExt, 0, sizeof(*pDevExt));
472 rc = RTSpinlockCreate(&pDevExt->Spinlock);
473 if (!rc)
474 {
475 rc = RTSemFastMutexCreate(&pDevExt->mtxLdr);
476 if (!rc)
477 {
478 rc = RTSemFastMutexCreate(&pDevExt->mtxComponentFactory);
479 if (!rc)
480 {
481 rc = RTSemFastMutexCreate(&pDevExt->mtxGip);
482 if (!rc)
483 {
484 rc = supdrvGipCreate(pDevExt);
485 if (RT_SUCCESS(rc))
486 {
487 pDevExt->u32Cookie = BIRD; /** @todo make this random? */
488
489 /*
490 * Fixup the absolute symbols.
491 *
492 * Because of the table indexing assumptions we'll do #ifdef orgy here rather
493 * than distributing this to OS specific files. At least for now.
494 */
495#ifdef RT_OS_DARWIN
496 if (SUPR0GetPagingMode() >= SUPPAGINGMODE_AMD64)
497 {
498 g_aFunctions[0].pfn = (void *)1; /* SUPR0AbsIs64bit */
499 g_aFunctions[1].pfn = (void *)0x80; /* SUPR0Abs64bitKernelCS - KERNEL64_CS, seg.h */
500 g_aFunctions[2].pfn = (void *)0x88; /* SUPR0Abs64bitKernelSS - KERNEL64_SS, seg.h */
501 g_aFunctions[3].pfn = (void *)0x88; /* SUPR0Abs64bitKernelDS - KERNEL64_SS, seg.h */
502 }
503 else
504 g_aFunctions[0].pfn = g_aFunctions[1].pfn = g_aFunctions[2].pfn = g_aFunctions[4].pfn = (void *)0;
505 g_aFunctions[4].pfn = (void *)0x08; /* SUPR0AbsKernelCS - KERNEL_CS, seg.h */
506 g_aFunctions[5].pfn = (void *)0x10; /* SUPR0AbsKernelSS - KERNEL_DS, seg.h */
507 g_aFunctions[6].pfn = (void *)0x10; /* SUPR0AbsKernelDS - KERNEL_DS, seg.h */
508 g_aFunctions[7].pfn = (void *)0x10; /* SUPR0AbsKernelES - KERNEL_DS, seg.h */
509#else
510# if ARCH_BITS == 64
511 g_aFunctions[0].pfn = (void *)1; /* SUPR0AbsIs64bit */
512 g_aFunctions[1].pfn = (void *)(uintptr_t)ASMGetCS(); /* SUPR0Abs64bitKernelCS */
513 g_aFunctions[2].pfn = (void *)(uintptr_t)ASMGetSS(); /* SUPR0Abs64bitKernelSS */
514 g_aFunctions[3].pfn = (void *)(uintptr_t)ASMGetDS(); /* SUPR0Abs64bitKernelDS */
515# elif ARCH_BITS == 32
516 g_aFunctions[0].pfn = g_aFunctions[1].pfn = g_aFunctions[2].pfn = g_aFunctions[4].pfn = (void *)0;
517# endif
518 g_aFunctions[4].pfn = (void *)(uintptr_t)ASMGetCS(); /* SUPR0AbsKernelCS */
519 g_aFunctions[5].pfn = (void *)(uintptr_t)ASMGetSS(); /* SUPR0AbsKernelSS */
520 g_aFunctions[6].pfn = (void *)(uintptr_t)ASMGetDS(); /* SUPR0AbsKernelDS */
521 g_aFunctions[7].pfn = (void *)(uintptr_t)ASMGetES(); /* SUPR0AbsKernelES */
522#endif
523 g_aFunctions[8].pfn = (void *)(uintptr_t)ASMGetFS(); /* SUPR0AbsKernelFS */
524 g_aFunctions[9].pfn = (void *)(uintptr_t)ASMGetGS(); /* SUPR0AbsKernelGS */
525 return VINF_SUCCESS;
526 }
527
528 RTSemFastMutexDestroy(pDevExt->mtxGip);
529 pDevExt->mtxGip = NIL_RTSEMFASTMUTEX;
530 }
531 RTSemFastMutexDestroy(pDevExt->mtxComponentFactory);
532 pDevExt->mtxComponentFactory = NIL_RTSEMFASTMUTEX;
533 }
534 RTSemFastMutexDestroy(pDevExt->mtxLdr);
535 pDevExt->mtxLdr = NIL_RTSEMFASTMUTEX;
536 }
537 RTSpinlockDestroy(pDevExt->Spinlock);
538 pDevExt->Spinlock = NIL_RTSPINLOCK;
539 }
540#ifdef SUPDRV_WITH_RELEASE_LOGGER
541 RTLogDestroy(RTLogRelSetDefaultInstance(NULL));
542 RTLogDestroy(RTLogSetDefaultInstance(NULL));
543#endif
544
545 return rc;
546}
547
548
549/**
550 * Delete the device extension (e.g. cleanup members).
551 *
552 * @param pDevExt The device extension to delete.
553 */
554void VBOXCALL supdrvDeleteDevExt(PSUPDRVDEVEXT pDevExt)
555{
556 PSUPDRVOBJ pObj;
557 PSUPDRVUSAGE pUsage;
558
559 /*
560 * Kill mutexes and spinlocks.
561 */
562 RTSemFastMutexDestroy(pDevExt->mtxGip);
563 pDevExt->mtxGip = NIL_RTSEMFASTMUTEX;
564 RTSemFastMutexDestroy(pDevExt->mtxLdr);
565 pDevExt->mtxLdr = NIL_RTSEMFASTMUTEX;
566 RTSpinlockDestroy(pDevExt->Spinlock);
567 pDevExt->Spinlock = NIL_RTSPINLOCK;
568 RTSemFastMutexDestroy(pDevExt->mtxComponentFactory);
569 pDevExt->mtxComponentFactory = NIL_RTSEMFASTMUTEX;
570
571 /*
572 * Free lists.
573 */
574 /* objects. */
575 pObj = pDevExt->pObjs;
576#if !defined(DEBUG_bird) || !defined(RT_OS_LINUX) /* breaks unloading, temporary, remove me! */
577 Assert(!pObj); /* (can trigger on forced unloads) */
578#endif
579 pDevExt->pObjs = NULL;
580 while (pObj)
581 {
582 void *pvFree = pObj;
583 pObj = pObj->pNext;
584 RTMemFree(pvFree);
585 }
586
587 /* usage records. */
588 pUsage = pDevExt->pUsageFree;
589 pDevExt->pUsageFree = NULL;
590 while (pUsage)
591 {
592 void *pvFree = pUsage;
593 pUsage = pUsage->pNext;
594 RTMemFree(pvFree);
595 }
596
597 /* kill the GIP. */
598 supdrvGipDestroy(pDevExt);
599
600#ifdef SUPDRV_WITH_RELEASE_LOGGER
601 /* destroy the loggers. */
602 RTLogDestroy(RTLogRelSetDefaultInstance(NULL));
603 RTLogDestroy(RTLogSetDefaultInstance(NULL));
604#endif
605}
606
607
608/**
609 * Create session.
610 *
611 * @returns IPRT status code.
612 * @param pDevExt Device extension.
613 * @param fUser Flag indicating whether this is a user or kernel session.
614 * @param ppSession Where to store the pointer to the session data.
615 */
616int VBOXCALL supdrvCreateSession(PSUPDRVDEVEXT pDevExt, bool fUser, PSUPDRVSESSION *ppSession)
617{
618 /*
619 * Allocate memory for the session data.
620 */
621 int rc = VERR_NO_MEMORY;
622 PSUPDRVSESSION pSession = *ppSession = (PSUPDRVSESSION)RTMemAllocZ(sizeof(*pSession));
623 if (pSession)
624 {
625 /* Initialize session data. */
626 rc = RTSpinlockCreate(&pSession->Spinlock);
627 if (!rc)
628 {
629 Assert(pSession->Spinlock != NIL_RTSPINLOCK);
630 pSession->pDevExt = pDevExt;
631 pSession->u32Cookie = BIRD_INV;
632 /*pSession->pLdrUsage = NULL;
633 pSession->pVM = NULL;
634 pSession->pUsage = NULL;
635 pSession->pGip = NULL;
636 pSession->fGipReferenced = false;
637 pSession->Bundle.cUsed = 0; */
638 pSession->Uid = NIL_RTUID;
639 pSession->Gid = NIL_RTGID;
640 if (fUser)
641 {
642 pSession->Process = RTProcSelf();
643 pSession->R0Process = RTR0ProcHandleSelf();
644 }
645 else
646 {
647 pSession->Process = NIL_RTPROCESS;
648 pSession->R0Process = NIL_RTR0PROCESS;
649 }
650
651 LogFlow(("Created session %p initial cookie=%#x\n", pSession, pSession->u32Cookie));
652 return VINF_SUCCESS;
653 }
654
655 RTMemFree(pSession);
656 *ppSession = NULL;
657 Log(("Failed to create spinlock, rc=%d!\n", rc));
658 }
659
660 return rc;
661}
662
663
664/**
665 * Shared code for cleaning up a session.
666 *
667 * @param pDevExt Device extension.
668 * @param pSession Session data.
669 * This data will be freed by this routine.
670 */
671void VBOXCALL supdrvCloseSession(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession)
672{
673 /*
674 * Cleanup the session first.
675 */
676 supdrvCleanupSession(pDevExt, pSession);
677
678 /*
679 * Free the rest of the session stuff.
680 */
681 RTSpinlockDestroy(pSession->Spinlock);
682 pSession->Spinlock = NIL_RTSPINLOCK;
683 pSession->pDevExt = NULL;
684 RTMemFree(pSession);
685 LogFlow(("supdrvCloseSession: returns\n"));
686}
687
688
689/**
690 * Shared code for cleaning up a session (but not quite freeing it).
691 *
692 * This is primarily intended for MAC OS X where we have to clean up the memory
693 * stuff before the file handle is closed.
694 *
695 * @param pDevExt Device extension.
696 * @param pSession Session data.
697 * This data will be freed by this routine.
698 */
699void VBOXCALL supdrvCleanupSession(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession)
700{
701 PSUPDRVBUNDLE pBundle;
702 LogFlow(("supdrvCleanupSession: pSession=%p\n", pSession));
703
704 /*
705 * Remove logger instances related to this session.
706 */
707 RTLogSetDefaultInstanceThread(NULL, (uintptr_t)pSession);
708
709 /*
710 * Release object references made in this session.
711 * In theory there should be noone racing us in this session.
712 */
713 Log2(("release objects - start\n"));
714 if (pSession->pUsage)
715 {
716 RTSPINLOCKTMP SpinlockTmp = RTSPINLOCKTMP_INITIALIZER;
717 PSUPDRVUSAGE pUsage;
718 RTSpinlockAcquire(pDevExt->Spinlock, &SpinlockTmp);
719
720 while ((pUsage = pSession->pUsage) != NULL)
721 {
722 PSUPDRVOBJ pObj = pUsage->pObj;
723 pSession->pUsage = pUsage->pNext;
724
725 AssertMsg(pUsage->cUsage >= 1 && pObj->cUsage >= pUsage->cUsage, ("glob %d; sess %d\n", pObj->cUsage, pUsage->cUsage));
726 if (pUsage->cUsage < pObj->cUsage)
727 {
728 pObj->cUsage -= pUsage->cUsage;
729 RTSpinlockRelease(pDevExt->Spinlock, &SpinlockTmp);
730 }
731 else
732 {
733 /* Destroy the object and free the record. */
734 if (pDevExt->pObjs == pObj)
735 pDevExt->pObjs = pObj->pNext;
736 else
737 {
738 PSUPDRVOBJ pObjPrev;
739 for (pObjPrev = pDevExt->pObjs; pObjPrev; pObjPrev = pObjPrev->pNext)
740 if (pObjPrev->pNext == pObj)
741 {
742 pObjPrev->pNext = pObj->pNext;
743 break;
744 }
745 Assert(pObjPrev);
746 }
747 RTSpinlockRelease(pDevExt->Spinlock, &SpinlockTmp);
748
749 Log(("supdrvCleanupSession: destroying %p/%d (%p/%p) cpid=%RTproc pid=%RTproc dtor=%p\n",
750 pObj, pObj->enmType, pObj->pvUser1, pObj->pvUser2, pObj->CreatorProcess, RTProcSelf(), pObj->pfnDestructor));
751 if (pObj->pfnDestructor)
752#ifdef RT_WITH_W64_UNWIND_HACK
753 supdrvNtWrapObjDestructor((PFNRT)pObj->pfnDestructor, pObj, pObj->pvUser1, pObj->pvUser2);
754#else
755 pObj->pfnDestructor(pObj, pObj->pvUser1, pObj->pvUser2);
756#endif
757 RTMemFree(pObj);
758 }
759
760 /* free it and continue. */
761 RTMemFree(pUsage);
762
763 RTSpinlockAcquire(pDevExt->Spinlock, &SpinlockTmp);
764 }
765
766 RTSpinlockRelease(pDevExt->Spinlock, &SpinlockTmp);
767 AssertMsg(!pSession->pUsage, ("Some buster reregistered an object during desturction!\n"));
768 }
769 Log2(("release objects - done\n"));
770
771 /*
772 * Release memory allocated in the session.
773 *
774 * We do not serialize this as we assume that the application will
775 * not allocated memory while closing the file handle object.
776 */
777 Log2(("freeing memory:\n"));
778 pBundle = &pSession->Bundle;
779 while (pBundle)
780 {
781 PSUPDRVBUNDLE pToFree;
782 unsigned i;
783
784 /*
785 * Check and unlock all entries in the bundle.
786 */
787 for (i = 0; i < RT_ELEMENTS(pBundle->aMem); i++)
788 {
789 if (pBundle->aMem[i].MemObj != NIL_RTR0MEMOBJ)
790 {
791 int rc;
792 Log2(("eType=%d pvR0=%p pvR3=%p cb=%ld\n", pBundle->aMem[i].eType, RTR0MemObjAddress(pBundle->aMem[i].MemObj),
793 (void *)RTR0MemObjAddressR3(pBundle->aMem[i].MapObjR3), (long)RTR0MemObjSize(pBundle->aMem[i].MemObj)));
794 if (pBundle->aMem[i].MapObjR3 != NIL_RTR0MEMOBJ)
795 {
796 rc = RTR0MemObjFree(pBundle->aMem[i].MapObjR3, false);
797 AssertRC(rc); /** @todo figure out how to handle this. */
798 pBundle->aMem[i].MapObjR3 = NIL_RTR0MEMOBJ;
799 }
800 rc = RTR0MemObjFree(pBundle->aMem[i].MemObj, true /* fFreeMappings */);
801 AssertRC(rc); /** @todo figure out how to handle this. */
802 pBundle->aMem[i].MemObj = NIL_RTR0MEMOBJ;
803 pBundle->aMem[i].eType = MEMREF_TYPE_UNUSED;
804 }
805 }
806
807 /*
808 * Advance and free previous bundle.
809 */
810 pToFree = pBundle;
811 pBundle = pBundle->pNext;
812
813 pToFree->pNext = NULL;
814 pToFree->cUsed = 0;
815 if (pToFree != &pSession->Bundle)
816 RTMemFree(pToFree);
817 }
818 Log2(("freeing memory - done\n"));
819
820 /*
821 * Deregister component factories.
822 */
823 RTSemFastMutexRequest(pDevExt->mtxComponentFactory);
824 Log2(("deregistering component factories:\n"));
825 if (pDevExt->pComponentFactoryHead)
826 {
827 PSUPDRVFACTORYREG pPrev = NULL;
828 PSUPDRVFACTORYREG pCur = pDevExt->pComponentFactoryHead;
829 while (pCur)
830 {
831 if (pCur->pSession == pSession)
832 {
833 /* unlink it */
834 PSUPDRVFACTORYREG pNext = pCur->pNext;
835 if (pPrev)
836 pPrev->pNext = pNext;
837 else
838 pDevExt->pComponentFactoryHead = pNext;
839
840 /* free it */
841 pCur->pNext = NULL;
842 pCur->pSession = NULL;
843 pCur->pFactory = NULL;
844 RTMemFree(pCur);
845
846 /* next */
847 pCur = pNext;
848 }
849 else
850 {
851 /* next */
852 pPrev = pCur;
853 pCur = pCur->pNext;
854 }
855 }
856 }
857 RTSemFastMutexRelease(pDevExt->mtxComponentFactory);
858 Log2(("deregistering component factories - done\n"));
859
860 /*
861 * Loaded images needs to be dereferenced and possibly freed up.
862 */
863 RTSemFastMutexRequest(pDevExt->mtxLdr);
864 Log2(("freeing images:\n"));
865 if (pSession->pLdrUsage)
866 {
867 PSUPDRVLDRUSAGE pUsage = pSession->pLdrUsage;
868 pSession->pLdrUsage = NULL;
869 while (pUsage)
870 {
871 void *pvFree = pUsage;
872 PSUPDRVLDRIMAGE pImage = pUsage->pImage;
873 if (pImage->cUsage > pUsage->cUsage)
874 pImage->cUsage -= pUsage->cUsage;
875 else
876 supdrvLdrFree(pDevExt, pImage);
877 pUsage->pImage = NULL;
878 pUsage = pUsage->pNext;
879 RTMemFree(pvFree);
880 }
881 }
882 RTSemFastMutexRelease(pDevExt->mtxLdr);
883 Log2(("freeing images - done\n"));
884
885 /*
886 * Unmap the GIP.
887 */
888 Log2(("umapping GIP:\n"));
889 if (pSession->GipMapObjR3 != NIL_RTR0MEMOBJ)
890 {
891 SUPR0GipUnmap(pSession);
892 pSession->fGipReferenced = 0;
893 }
894 Log2(("umapping GIP - done\n"));
895}
896
897
898/**
899 * Fast path I/O Control worker.
900 *
901 * @returns VBox status code that should be passed down to ring-3 unchanged.
902 * @param uIOCtl Function number.
903 * @param idCpu VMCPU id.
904 * @param pDevExt Device extention.
905 * @param pSession Session data.
906 */
907int VBOXCALL supdrvIOCtlFast(uintptr_t uIOCtl, unsigned idCpu, PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession)
908{
909 /*
910 * We check the two prereqs after doing this only to allow the compiler to optimize things better.
911 */
912 if (RT_LIKELY(pSession->pVM && pDevExt->pfnVMMR0EntryFast))
913 {
914 switch (uIOCtl)
915 {
916 case SUP_IOCTL_FAST_DO_RAW_RUN:
917#ifdef RT_WITH_W64_UNWIND_HACK
918 supdrvNtWrapVMMR0EntryFast((PFNRT)pDevExt->pfnVMMR0EntryFast, pSession->pVM, idCpu, SUP_VMMR0_DO_RAW_RUN);
919#else
920 pDevExt->pfnVMMR0EntryFast(pSession->pVM, idCpu, SUP_VMMR0_DO_RAW_RUN);
921#endif
922 break;
923 case SUP_IOCTL_FAST_DO_HWACC_RUN:
924#ifdef RT_WITH_W64_UNWIND_HACK
925 supdrvNtWrapVMMR0EntryFast((PFNRT)pDevExt->pfnVMMR0EntryFast, pSession->pVM, idCpu, SUP_VMMR0_DO_HWACC_RUN);
926#else
927 pDevExt->pfnVMMR0EntryFast(pSession->pVM, idCpu, SUP_VMMR0_DO_HWACC_RUN);
928#endif
929 break;
930 case SUP_IOCTL_FAST_DO_NOP:
931#ifdef RT_WITH_W64_UNWIND_HACK
932 supdrvNtWrapVMMR0EntryFast((PFNRT)pDevExt->pfnVMMR0EntryFast, pSession->pVM, idCpu, SUP_VMMR0_DO_NOP);
933#else
934 pDevExt->pfnVMMR0EntryFast(pSession->pVM, idCpu, SUP_VMMR0_DO_NOP);
935#endif
936 break;
937 default:
938 return VERR_INTERNAL_ERROR;
939 }
940 return VINF_SUCCESS;
941 }
942 return VERR_INTERNAL_ERROR;
943}
944
945
946/**
947 * Helper for supdrvIOCtl. Check if pszStr contains any character of pszChars.
948 * We would use strpbrk here if this function would be contained in the RedHat kABI white
949 * list, see http://www.kerneldrivers.org/RHEL5.
950 *
951 * @return 1 if pszStr does contain any character of pszChars, 0 otherwise.
952 * @param pszStr String to check
953 * @param pszChars Character set
954 */
955static int supdrvCheckInvalidChar(const char *pszStr, const char *pszChars)
956{
957 int chCur;
958 while ((chCur = *pszStr++) != '\0')
959 {
960 int ch;
961 const char *psz = pszChars;
962 while ((ch = *psz++) != '\0')
963 if (ch == chCur)
964 return 1;
965
966 }
967 return 0;
968}
969
970
971/**
972 * I/O Control worker.
973 *
974 * @returns 0 on success.
975 * @returns VERR_INVALID_PARAMETER if the request is invalid.
976 *
977 * @param uIOCtl Function number.
978 * @param pDevExt Device extention.
979 * @param pSession Session data.
980 * @param pReqHdr The request header.
981 */
982int VBOXCALL supdrvIOCtl(uintptr_t uIOCtl, PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPREQHDR pReqHdr)
983{
984 /*
985 * Validate the request.
986 */
987 /* this first check could probably be omitted as its also done by the OS specific code... */
988 if (RT_UNLIKELY( (pReqHdr->fFlags & SUPREQHDR_FLAGS_MAGIC_MASK) != SUPREQHDR_FLAGS_MAGIC
989 || pReqHdr->cbIn < sizeof(*pReqHdr)
990 || pReqHdr->cbOut < sizeof(*pReqHdr)))
991 {
992 OSDBGPRINT(("vboxdrv: Bad ioctl request header; cbIn=%#lx cbOut=%#lx fFlags=%#lx\n",
993 (long)pReqHdr->cbIn, (long)pReqHdr->cbOut, (long)pReqHdr->fFlags));
994 return VERR_INVALID_PARAMETER;
995 }
996 if (RT_UNLIKELY(uIOCtl == SUP_IOCTL_COOKIE))
997 {
998 if (pReqHdr->u32Cookie != SUPCOOKIE_INITIAL_COOKIE)
999 {
1000 OSDBGPRINT(("SUP_IOCTL_COOKIE: bad cookie %#lx\n", (long)pReqHdr->u32Cookie));
1001 return VERR_INVALID_PARAMETER;
1002 }
1003 }
1004 else if (RT_UNLIKELY( pReqHdr->u32Cookie != pDevExt->u32Cookie
1005 || pReqHdr->u32SessionCookie != pSession->u32Cookie))
1006 {
1007 OSDBGPRINT(("vboxdrv: bad cookie %#lx / %#lx.\n", (long)pReqHdr->u32Cookie, (long)pReqHdr->u32SessionCookie));
1008 return VERR_INVALID_PARAMETER;
1009 }
1010
1011/*
1012 * Validation macros
1013 */
1014#define REQ_CHECK_SIZES_EX(Name, cbInExpect, cbOutExpect) \
1015 do { \
1016 if (RT_UNLIKELY(pReqHdr->cbIn != (cbInExpect) || pReqHdr->cbOut != (cbOutExpect))) \
1017 { \
1018 OSDBGPRINT(( #Name ": Invalid input/output sizes. cbIn=%ld expected %ld. cbOut=%ld expected %ld.\n", \
1019 (long)pReq->Hdr.cbIn, (long)(cbInExpect), (long)pReq->Hdr.cbOut, (long)(cbOutExpect))); \
1020 return pReq->Hdr.rc = VERR_INVALID_PARAMETER; \
1021 } \
1022 } while (0)
1023
1024#define REQ_CHECK_SIZES(Name) REQ_CHECK_SIZES_EX(Name, Name ## _SIZE_IN, Name ## _SIZE_OUT)
1025
1026#define REQ_CHECK_SIZE_IN(Name, cbInExpect) \
1027 do { \
1028 if (RT_UNLIKELY(pReqHdr->cbIn != (cbInExpect))) \
1029 { \
1030 OSDBGPRINT(( #Name ": Invalid input/output sizes. cbIn=%ld expected %ld.\n", \
1031 (long)pReq->Hdr.cbIn, (long)(cbInExpect))); \
1032 return pReq->Hdr.rc = VERR_INVALID_PARAMETER; \
1033 } \
1034 } while (0)
1035
1036#define REQ_CHECK_SIZE_OUT(Name, cbOutExpect) \
1037 do { \
1038 if (RT_UNLIKELY(pReqHdr->cbOut != (cbOutExpect))) \
1039 { \
1040 OSDBGPRINT(( #Name ": Invalid input/output sizes. cbOut=%ld expected %ld.\n", \
1041 (long)pReq->Hdr.cbOut, (long)(cbOutExpect))); \
1042 return pReq->Hdr.rc = VERR_INVALID_PARAMETER; \
1043 } \
1044 } while (0)
1045
1046#define REQ_CHECK_EXPR(Name, expr) \
1047 do { \
1048 if (RT_UNLIKELY(!(expr))) \
1049 { \
1050 OSDBGPRINT(( #Name ": %s\n", #expr)); \
1051 return pReq->Hdr.rc = VERR_INVALID_PARAMETER; \
1052 } \
1053 } while (0)
1054
1055#define REQ_CHECK_EXPR_FMT(expr, fmt) \
1056 do { \
1057 if (RT_UNLIKELY(!(expr))) \
1058 { \
1059 OSDBGPRINT( fmt ); \
1060 return pReq->Hdr.rc = VERR_INVALID_PARAMETER; \
1061 } \
1062 } while (0)
1063
1064
1065 /*
1066 * The switch.
1067 */
1068 switch (SUP_CTL_CODE_NO_SIZE(uIOCtl))
1069 {
1070 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_COOKIE):
1071 {
1072 PSUPCOOKIE pReq = (PSUPCOOKIE)pReqHdr;
1073 REQ_CHECK_SIZES(SUP_IOCTL_COOKIE);
1074 if (strncmp(pReq->u.In.szMagic, SUPCOOKIE_MAGIC, sizeof(pReq->u.In.szMagic)))
1075 {
1076 OSDBGPRINT(("SUP_IOCTL_COOKIE: invalid magic %.16s\n", pReq->u.In.szMagic));
1077 pReq->Hdr.rc = VERR_INVALID_MAGIC;
1078 return 0;
1079 }
1080
1081#if 0
1082 /*
1083 * Call out to the OS specific code and let it do permission checks on the
1084 * client process.
1085 */
1086 if (!supdrvOSValidateClientProcess(pDevExt, pSession))
1087 {
1088 pReq->u.Out.u32Cookie = 0xffffffff;
1089 pReq->u.Out.u32SessionCookie = 0xffffffff;
1090 pReq->u.Out.u32SessionVersion = 0xffffffff;
1091 pReq->u.Out.u32DriverVersion = SUPDRV_IOC_VERSION;
1092 pReq->u.Out.pSession = NULL;
1093 pReq->u.Out.cFunctions = 0;
1094 pReq->Hdr.rc = VERR_PERMISSION_DENIED;
1095 return 0;
1096 }
1097#endif
1098
1099 /*
1100 * Match the version.
1101 * The current logic is very simple, match the major interface version.
1102 */
1103 if ( pReq->u.In.u32MinVersion > SUPDRV_IOC_VERSION
1104 || (pReq->u.In.u32MinVersion & 0xffff0000) != (SUPDRV_IOC_VERSION & 0xffff0000))
1105 {
1106 OSDBGPRINT(("SUP_IOCTL_COOKIE: Version mismatch. Requested: %#x Min: %#x Current: %#x\n",
1107 pReq->u.In.u32ReqVersion, pReq->u.In.u32MinVersion, SUPDRV_IOC_VERSION));
1108 pReq->u.Out.u32Cookie = 0xffffffff;
1109 pReq->u.Out.u32SessionCookie = 0xffffffff;
1110 pReq->u.Out.u32SessionVersion = 0xffffffff;
1111 pReq->u.Out.u32DriverVersion = SUPDRV_IOC_VERSION;
1112 pReq->u.Out.pSession = NULL;
1113 pReq->u.Out.cFunctions = 0;
1114 pReq->Hdr.rc = VERR_VERSION_MISMATCH;
1115 return 0;
1116 }
1117
1118 /*
1119 * Fill in return data and be gone.
1120 * N.B. The first one to change SUPDRV_IOC_VERSION shall makes sure that
1121 * u32SessionVersion <= u32ReqVersion!
1122 */
1123 /** @todo Somehow validate the client and negotiate a secure cookie... */
1124 pReq->u.Out.u32Cookie = pDevExt->u32Cookie;
1125 pReq->u.Out.u32SessionCookie = pSession->u32Cookie;
1126 pReq->u.Out.u32SessionVersion = SUPDRV_IOC_VERSION;
1127 pReq->u.Out.u32DriverVersion = SUPDRV_IOC_VERSION;
1128 pReq->u.Out.pSession = pSession;
1129 pReq->u.Out.cFunctions = sizeof(g_aFunctions) / sizeof(g_aFunctions[0]);
1130 pReq->Hdr.rc = VINF_SUCCESS;
1131 return 0;
1132 }
1133
1134 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_QUERY_FUNCS(0)):
1135 {
1136 /* validate */
1137 PSUPQUERYFUNCS pReq = (PSUPQUERYFUNCS)pReqHdr;
1138 REQ_CHECK_SIZES_EX(SUP_IOCTL_QUERY_FUNCS, SUP_IOCTL_QUERY_FUNCS_SIZE_IN, SUP_IOCTL_QUERY_FUNCS_SIZE_OUT(RT_ELEMENTS(g_aFunctions)));
1139
1140 /* execute */
1141 pReq->u.Out.cFunctions = RT_ELEMENTS(g_aFunctions);
1142 memcpy(&pReq->u.Out.aFunctions[0], g_aFunctions, sizeof(g_aFunctions));
1143 pReq->Hdr.rc = VINF_SUCCESS;
1144 return 0;
1145 }
1146
1147 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_IDT_INSTALL):
1148 {
1149 /* validate */
1150 PSUPIDTINSTALL pReq = (PSUPIDTINSTALL)pReqHdr;
1151 REQ_CHECK_SIZES(SUP_IOCTL_IDT_INSTALL);
1152
1153 /* execute */
1154 pReq->u.Out.u8Idt = 3;
1155 pReq->Hdr.rc = VERR_NOT_SUPPORTED;
1156 return 0;
1157 }
1158
1159 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_IDT_REMOVE):
1160 {
1161 /* validate */
1162 PSUPIDTREMOVE pReq = (PSUPIDTREMOVE)pReqHdr;
1163 REQ_CHECK_SIZES(SUP_IOCTL_IDT_REMOVE);
1164
1165 /* execute */
1166 pReq->Hdr.rc = VERR_NOT_SUPPORTED;
1167 return 0;
1168 }
1169
1170 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_PAGE_LOCK):
1171 {
1172 /* validate */
1173 PSUPPAGELOCK pReq = (PSUPPAGELOCK)pReqHdr;
1174 REQ_CHECK_SIZE_IN(SUP_IOCTL_PAGE_LOCK, SUP_IOCTL_PAGE_LOCK_SIZE_IN);
1175 REQ_CHECK_SIZE_OUT(SUP_IOCTL_PAGE_LOCK, SUP_IOCTL_PAGE_LOCK_SIZE_OUT(pReq->u.In.cPages));
1176 REQ_CHECK_EXPR(SUP_IOCTL_PAGE_LOCK, pReq->u.In.cPages > 0);
1177 REQ_CHECK_EXPR(SUP_IOCTL_PAGE_LOCK, pReq->u.In.pvR3 >= PAGE_SIZE);
1178
1179 /* execute */
1180 pReq->Hdr.rc = SUPR0LockMem(pSession, pReq->u.In.pvR3, pReq->u.In.cPages, &pReq->u.Out.aPages[0]);
1181 if (RT_FAILURE(pReq->Hdr.rc))
1182 pReq->Hdr.cbOut = sizeof(pReq->Hdr);
1183 return 0;
1184 }
1185
1186 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_PAGE_UNLOCK):
1187 {
1188 /* validate */
1189 PSUPPAGEUNLOCK pReq = (PSUPPAGEUNLOCK)pReqHdr;
1190 REQ_CHECK_SIZES(SUP_IOCTL_PAGE_UNLOCK);
1191
1192 /* execute */
1193 pReq->Hdr.rc = SUPR0UnlockMem(pSession, pReq->u.In.pvR3);
1194 return 0;
1195 }
1196
1197 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_CONT_ALLOC):
1198 {
1199 /* validate */
1200 PSUPCONTALLOC pReq = (PSUPCONTALLOC)pReqHdr;
1201 REQ_CHECK_SIZES(SUP_IOCTL_CONT_ALLOC);
1202
1203 /* execute */
1204 pReq->Hdr.rc = SUPR0ContAlloc(pSession, pReq->u.In.cPages, &pReq->u.Out.pvR0, &pReq->u.Out.pvR3, &pReq->u.Out.HCPhys);
1205 if (RT_FAILURE(pReq->Hdr.rc))
1206 pReq->Hdr.cbOut = sizeof(pReq->Hdr);
1207 return 0;
1208 }
1209
1210 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_CONT_FREE):
1211 {
1212 /* validate */
1213 PSUPCONTFREE pReq = (PSUPCONTFREE)pReqHdr;
1214 REQ_CHECK_SIZES(SUP_IOCTL_CONT_FREE);
1215
1216 /* execute */
1217 pReq->Hdr.rc = SUPR0ContFree(pSession, (RTHCUINTPTR)pReq->u.In.pvR3);
1218 return 0;
1219 }
1220
1221 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_LDR_OPEN):
1222 {
1223 /* validate */
1224 PSUPLDROPEN pReq = (PSUPLDROPEN)pReqHdr;
1225 REQ_CHECK_SIZES(SUP_IOCTL_LDR_OPEN);
1226 REQ_CHECK_EXPR(SUP_IOCTL_LDR_OPEN, pReq->u.In.cbImage > 0);
1227 REQ_CHECK_EXPR(SUP_IOCTL_LDR_OPEN, pReq->u.In.cbImage < _1M*16);
1228 REQ_CHECK_EXPR(SUP_IOCTL_LDR_OPEN, pReq->u.In.szName[0]);
1229 REQ_CHECK_EXPR(SUP_IOCTL_LDR_OPEN, memchr(pReq->u.In.szName, '\0', sizeof(pReq->u.In.szName)));
1230 REQ_CHECK_EXPR(SUP_IOCTL_LDR_OPEN, !supdrvCheckInvalidChar(pReq->u.In.szName, ";:()[]{}/\\|&*%#@!~`\"'"));
1231
1232 /* execute */
1233 pReq->Hdr.rc = supdrvIOCtl_LdrOpen(pDevExt, pSession, pReq);
1234 return 0;
1235 }
1236
1237 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_LDR_LOAD):
1238 {
1239 /* validate */
1240 PSUPLDRLOAD pReq = (PSUPLDRLOAD)pReqHdr;
1241 REQ_CHECK_EXPR(Name, pReq->Hdr.cbIn >= sizeof(*pReq));
1242 REQ_CHECK_SIZES_EX(SUP_IOCTL_LDR_LOAD, SUP_IOCTL_LDR_LOAD_SIZE_IN(pReq->u.In.cbImage), SUP_IOCTL_LDR_LOAD_SIZE_OUT);
1243 REQ_CHECK_EXPR(SUP_IOCTL_LDR_LOAD, pReq->u.In.cSymbols <= 16384);
1244 REQ_CHECK_EXPR_FMT( !pReq->u.In.cSymbols
1245 || ( pReq->u.In.offSymbols < pReq->u.In.cbImage
1246 && pReq->u.In.offSymbols + pReq->u.In.cSymbols * sizeof(SUPLDRSYM) <= pReq->u.In.cbImage),
1247 ("SUP_IOCTL_LDR_LOAD: offSymbols=%#lx cSymbols=%#lx cbImage=%#lx\n", (long)pReq->u.In.offSymbols,
1248 (long)pReq->u.In.cSymbols, (long)pReq->u.In.cbImage));
1249 REQ_CHECK_EXPR_FMT( !pReq->u.In.cbStrTab
1250 || ( pReq->u.In.offStrTab < pReq->u.In.cbImage
1251 && pReq->u.In.offStrTab + pReq->u.In.cbStrTab <= pReq->u.In.cbImage
1252 && pReq->u.In.cbStrTab <= pReq->u.In.cbImage),
1253 ("SUP_IOCTL_LDR_LOAD: offStrTab=%#lx cbStrTab=%#lx cbImage=%#lx\n", (long)pReq->u.In.offStrTab,
1254 (long)pReq->u.In.cbStrTab, (long)pReq->u.In.cbImage));
1255
1256 if (pReq->u.In.cSymbols)
1257 {
1258 uint32_t i;
1259 PSUPLDRSYM paSyms = (PSUPLDRSYM)&pReq->u.In.achImage[pReq->u.In.offSymbols];
1260 for (i = 0; i < pReq->u.In.cSymbols; i++)
1261 {
1262 REQ_CHECK_EXPR_FMT(paSyms[i].offSymbol < pReq->u.In.cbImage,
1263 ("SUP_IOCTL_LDR_LOAD: sym #%ld: symb off %#lx (max=%#lx)\n", (long)i, (long)paSyms[i].offSymbol, (long)pReq->u.In.cbImage));
1264 REQ_CHECK_EXPR_FMT(paSyms[i].offName < pReq->u.In.cbStrTab,
1265 ("SUP_IOCTL_LDR_LOAD: sym #%ld: name off %#lx (max=%#lx)\n", (long)i, (long)paSyms[i].offName, (long)pReq->u.In.cbImage));
1266 REQ_CHECK_EXPR_FMT(memchr(&pReq->u.In.achImage[pReq->u.In.offStrTab + paSyms[i].offName], '\0', pReq->u.In.cbStrTab - paSyms[i].offName),
1267 ("SUP_IOCTL_LDR_LOAD: sym #%ld: unterminated name! (%#lx / %#lx)\n", (long)i, (long)paSyms[i].offName, (long)pReq->u.In.cbImage));
1268 }
1269 }
1270
1271 /* execute */
1272 pReq->Hdr.rc = supdrvIOCtl_LdrLoad(pDevExt, pSession, pReq);
1273 return 0;
1274 }
1275
1276 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_LDR_FREE):
1277 {
1278 /* validate */
1279 PSUPLDRFREE pReq = (PSUPLDRFREE)pReqHdr;
1280 REQ_CHECK_SIZES(SUP_IOCTL_LDR_FREE);
1281
1282 /* execute */
1283 pReq->Hdr.rc = supdrvIOCtl_LdrFree(pDevExt, pSession, pReq);
1284 return 0;
1285 }
1286
1287 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_LDR_GET_SYMBOL):
1288 {
1289 /* validate */
1290 PSUPLDRGETSYMBOL pReq = (PSUPLDRGETSYMBOL)pReqHdr;
1291 REQ_CHECK_SIZES(SUP_IOCTL_LDR_GET_SYMBOL);
1292 REQ_CHECK_EXPR(SUP_IOCTL_LDR_GET_SYMBOL, memchr(pReq->u.In.szSymbol, '\0', sizeof(pReq->u.In.szSymbol)));
1293
1294 /* execute */
1295 pReq->Hdr.rc = supdrvIOCtl_LdrGetSymbol(pDevExt, pSession, pReq);
1296 return 0;
1297 }
1298
1299 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_CALL_VMMR0(0)):
1300 {
1301 /* validate */
1302 PSUPCALLVMMR0 pReq = (PSUPCALLVMMR0)pReqHdr;
1303 Log4(("SUP_IOCTL_CALL_VMMR0: op=%u in=%u arg=%RX64 p/t=%RTproc/%RTthrd\n",
1304 pReq->u.In.uOperation, pReq->Hdr.cbIn, pReq->u.In.u64Arg, RTProcSelf(), RTThreadNativeSelf()));
1305
1306 if (pReq->Hdr.cbIn == SUP_IOCTL_CALL_VMMR0_SIZE(0))
1307 {
1308 REQ_CHECK_SIZES_EX(SUP_IOCTL_CALL_VMMR0, SUP_IOCTL_CALL_VMMR0_SIZE_IN(0), SUP_IOCTL_CALL_VMMR0_SIZE_OUT(0));
1309
1310 /* execute */
1311 if (RT_LIKELY(pDevExt->pfnVMMR0EntryEx))
1312#ifdef RT_WITH_W64_UNWIND_HACK
1313 pReq->Hdr.rc = supdrvNtWrapVMMR0EntryEx((PFNRT)pDevExt->pfnVMMR0EntryEx, pReq->u.In.pVMR0, pReq->u.In.uOperation, NULL, pReq->u.In.u64Arg, pSession);
1314#else
1315 pReq->Hdr.rc = pDevExt->pfnVMMR0EntryEx(pReq->u.In.pVMR0, pReq->u.In.uOperation, NULL, pReq->u.In.u64Arg, pSession);
1316#endif
1317 else
1318 pReq->Hdr.rc = VERR_WRONG_ORDER;
1319 }
1320 else
1321 {
1322 PSUPVMMR0REQHDR pVMMReq = (PSUPVMMR0REQHDR)&pReq->abReqPkt[0];
1323 REQ_CHECK_EXPR_FMT(pReq->Hdr.cbIn >= SUP_IOCTL_CALL_VMMR0_SIZE(sizeof(SUPVMMR0REQHDR)),
1324 ("SUP_IOCTL_CALL_VMMR0: cbIn=%#x < %#lx\n", pReq->Hdr.cbIn, SUP_IOCTL_CALL_VMMR0_SIZE(sizeof(SUPVMMR0REQHDR))));
1325 REQ_CHECK_EXPR(SUP_IOCTL_CALL_VMMR0, pVMMReq->u32Magic == SUPVMMR0REQHDR_MAGIC);
1326 REQ_CHECK_SIZES_EX(SUP_IOCTL_CALL_VMMR0, SUP_IOCTL_CALL_VMMR0_SIZE_IN(pVMMReq->cbReq), SUP_IOCTL_CALL_VMMR0_SIZE_OUT(pVMMReq->cbReq));
1327
1328 /* execute */
1329 if (RT_LIKELY(pDevExt->pfnVMMR0EntryEx))
1330#ifdef RT_WITH_W64_UNWIND_HACK
1331 pReq->Hdr.rc = supdrvNtWrapVMMR0EntryEx((PFNRT)pDevExt->pfnVMMR0EntryEx, pReq->u.In.pVMR0, pReq->u.In.uOperation, pVMMReq, pReq->u.In.u64Arg, pSession);
1332#else
1333 pReq->Hdr.rc = pDevExt->pfnVMMR0EntryEx(pReq->u.In.pVMR0, pReq->u.In.uOperation, pVMMReq, pReq->u.In.u64Arg, pSession);
1334#endif
1335 else
1336 pReq->Hdr.rc = VERR_WRONG_ORDER;
1337 }
1338
1339 if ( RT_FAILURE(pReq->Hdr.rc)
1340 && pReq->Hdr.rc != VERR_INTERRUPTED
1341 && pReq->Hdr.rc != VERR_TIMEOUT)
1342 Log(("SUP_IOCTL_CALL_VMMR0: rc=%Rrc op=%u out=%u arg=%RX64 p/t=%RTproc/%RTthrd\n",
1343 pReq->Hdr.rc, pReq->u.In.uOperation, pReq->Hdr.cbOut, pReq->u.In.u64Arg, RTProcSelf(), RTThreadNativeSelf()));
1344 else
1345 Log4(("SUP_IOCTL_CALL_VMMR0: rc=%Rrc op=%u out=%u arg=%RX64 p/t=%RTproc/%RTthrd\n",
1346 pReq->Hdr.rc, pReq->u.In.uOperation, pReq->Hdr.cbOut, pReq->u.In.u64Arg, RTProcSelf(), RTThreadNativeSelf()));
1347 return 0;
1348 }
1349
1350 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_GET_PAGING_MODE):
1351 {
1352 /* validate */
1353 PSUPGETPAGINGMODE pReq = (PSUPGETPAGINGMODE)pReqHdr;
1354 REQ_CHECK_SIZES(SUP_IOCTL_GET_PAGING_MODE);
1355
1356 /* execute */
1357 pReq->Hdr.rc = VINF_SUCCESS;
1358 pReq->u.Out.enmMode = SUPR0GetPagingMode();
1359 return 0;
1360 }
1361
1362 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_LOW_ALLOC):
1363 {
1364 /* validate */
1365 PSUPLOWALLOC pReq = (PSUPLOWALLOC)pReqHdr;
1366 REQ_CHECK_EXPR(SUP_IOCTL_LOW_ALLOC, pReq->Hdr.cbIn <= SUP_IOCTL_LOW_ALLOC_SIZE_IN);
1367 REQ_CHECK_SIZES_EX(SUP_IOCTL_LOW_ALLOC, SUP_IOCTL_LOW_ALLOC_SIZE_IN, SUP_IOCTL_LOW_ALLOC_SIZE_OUT(pReq->u.In.cPages));
1368
1369 /* execute */
1370 pReq->Hdr.rc = SUPR0LowAlloc(pSession, pReq->u.In.cPages, &pReq->u.Out.pvR0, &pReq->u.Out.pvR3, &pReq->u.Out.aPages[0]);
1371 if (RT_FAILURE(pReq->Hdr.rc))
1372 pReq->Hdr.cbOut = sizeof(pReq->Hdr);
1373 return 0;
1374 }
1375
1376 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_LOW_FREE):
1377 {
1378 /* validate */
1379 PSUPLOWFREE pReq = (PSUPLOWFREE)pReqHdr;
1380 REQ_CHECK_SIZES(SUP_IOCTL_LOW_FREE);
1381
1382 /* execute */
1383 pReq->Hdr.rc = SUPR0LowFree(pSession, (RTHCUINTPTR)pReq->u.In.pvR3);
1384 return 0;
1385 }
1386
1387 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_GIP_MAP):
1388 {
1389 /* validate */
1390 PSUPGIPMAP pReq = (PSUPGIPMAP)pReqHdr;
1391 REQ_CHECK_SIZES(SUP_IOCTL_GIP_MAP);
1392
1393 /* execute */
1394 pReq->Hdr.rc = SUPR0GipMap(pSession, &pReq->u.Out.pGipR3, &pReq->u.Out.HCPhysGip);
1395 if (RT_SUCCESS(pReq->Hdr.rc))
1396 pReq->u.Out.pGipR0 = pDevExt->pGip;
1397 return 0;
1398 }
1399
1400 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_GIP_UNMAP):
1401 {
1402 /* validate */
1403 PSUPGIPUNMAP pReq = (PSUPGIPUNMAP)pReqHdr;
1404 REQ_CHECK_SIZES(SUP_IOCTL_GIP_UNMAP);
1405
1406 /* execute */
1407 pReq->Hdr.rc = SUPR0GipUnmap(pSession);
1408 return 0;
1409 }
1410
1411 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_SET_VM_FOR_FAST):
1412 {
1413 /* validate */
1414 PSUPSETVMFORFAST pReq = (PSUPSETVMFORFAST)pReqHdr;
1415 REQ_CHECK_SIZES(SUP_IOCTL_SET_VM_FOR_FAST);
1416 REQ_CHECK_EXPR_FMT( !pReq->u.In.pVMR0
1417 || ( VALID_PTR(pReq->u.In.pVMR0)
1418 && !((uintptr_t)pReq->u.In.pVMR0 & (PAGE_SIZE - 1))),
1419 ("SUP_IOCTL_SET_VM_FOR_FAST: pVMR0=%p!\n", pReq->u.In.pVMR0));
1420 /* execute */
1421 pSession->pVM = pReq->u.In.pVMR0;
1422 pReq->Hdr.rc = VINF_SUCCESS;
1423 return 0;
1424 }
1425
1426 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_PAGE_ALLOC):
1427 {
1428 /* validate */
1429 PSUPPAGEALLOC pReq = (PSUPPAGEALLOC)pReqHdr;
1430 REQ_CHECK_EXPR(SUP_IOCTL_PAGE_ALLOC, pReq->Hdr.cbIn <= SUP_IOCTL_PAGE_ALLOC_SIZE_IN);
1431 REQ_CHECK_SIZES_EX(SUP_IOCTL_PAGE_ALLOC, SUP_IOCTL_PAGE_ALLOC_SIZE_IN, SUP_IOCTL_PAGE_ALLOC_SIZE_OUT(pReq->u.In.cPages));
1432
1433 /* execute */
1434 pReq->Hdr.rc = SUPR0PageAlloc(pSession, pReq->u.In.cPages, &pReq->u.Out.pvR3, &pReq->u.Out.aPages[0]);
1435 if (RT_FAILURE(pReq->Hdr.rc))
1436 pReq->Hdr.cbOut = sizeof(pReq->Hdr);
1437 return 0;
1438 }
1439
1440 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_PAGE_ALLOC_EX):
1441 {
1442 /* validate */
1443 PSUPPAGEALLOCEX pReq = (PSUPPAGEALLOCEX)pReqHdr;
1444 REQ_CHECK_EXPR(SUP_IOCTL_PAGE_ALLOC_EX, pReq->Hdr.cbIn <= SUP_IOCTL_PAGE_ALLOC_EX_SIZE_IN);
1445 REQ_CHECK_SIZES_EX(SUP_IOCTL_PAGE_ALLOC_EX, SUP_IOCTL_PAGE_ALLOC_EX_SIZE_IN, SUP_IOCTL_PAGE_ALLOC_EX_SIZE_OUT(pReq->u.In.cPages));
1446 REQ_CHECK_EXPR_FMT(pReq->u.In.fKernelMapping || pReq->u.In.fUserMapping,
1447 ("SUP_IOCTL_PAGE_ALLOC_EX: No mapping requested!\n"));
1448 REQ_CHECK_EXPR_FMT(pReq->u.In.fUserMapping,
1449 ("SUP_IOCTL_PAGE_ALLOC_EX: Must have user mapping!\n"));
1450 REQ_CHECK_EXPR_FMT(!pReq->u.In.fReserved0 && !pReq->u.In.fReserved1,
1451 ("SUP_IOCTL_PAGE_ALLOC_EX: fReserved0=%d fReserved1=%d\n", pReq->u.In.fReserved0, pReq->u.In.fReserved1));
1452
1453 /* execute */
1454 pReq->Hdr.rc = SUPR0PageAllocEx(pSession, pReq->u.In.cPages, 0 /* fFlags */,
1455 pReq->u.In.fUserMapping ? &pReq->u.Out.pvR3 : NULL,
1456 pReq->u.In.fKernelMapping ? &pReq->u.Out.pvR0 : NULL,
1457 &pReq->u.Out.aPages[0]);
1458 if (RT_FAILURE(pReq->Hdr.rc))
1459 pReq->Hdr.cbOut = sizeof(pReq->Hdr);
1460 return 0;
1461 }
1462
1463 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_PAGE_MAP_KERNEL):
1464 {
1465 /* validate */
1466 PSUPPAGEMAPKERNEL pReq = (PSUPPAGEMAPKERNEL)pReqHdr;
1467 REQ_CHECK_SIZES(SUP_IOCTL_PAGE_MAP_KERNEL);
1468 REQ_CHECK_EXPR_FMT(!pReq->u.In.fFlags, ("SUP_IOCTL_PAGE_MAP_KERNEL: fFlags=%#x! MBZ\n", pReq->u.In.fFlags));
1469 REQ_CHECK_EXPR_FMT(!(pReq->u.In.offSub & PAGE_OFFSET_MASK), ("SUP_IOCTL_PAGE_MAP_KERNEL: offSub=%#x\n", pReq->u.In.offSub));
1470 REQ_CHECK_EXPR_FMT(pReq->u.In.cbSub && !(pReq->u.In.cbSub & PAGE_OFFSET_MASK),
1471 ("SUP_IOCTL_PAGE_MAP_KERNEL: cbSub=%#x\n", pReq->u.In.cbSub));
1472
1473 /* execute */
1474 pReq->Hdr.rc = SUPR0PageMapKernel(pSession, pReq->u.In.pvR3, pReq->u.In.offSub, pReq->u.In.cbSub,
1475 pReq->u.In.fFlags, &pReq->u.Out.pvR0);
1476 if (RT_FAILURE(pReq->Hdr.rc))
1477 pReq->Hdr.cbOut = sizeof(pReq->Hdr);
1478 return 0;
1479 }
1480
1481 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_PAGE_FREE):
1482 {
1483 /* validate */
1484 PSUPPAGEFREE pReq = (PSUPPAGEFREE)pReqHdr;
1485 REQ_CHECK_SIZES(SUP_IOCTL_PAGE_FREE);
1486
1487 /* execute */
1488 pReq->Hdr.rc = SUPR0PageFree(pSession, pReq->u.In.pvR3);
1489 return 0;
1490 }
1491
1492 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_CALL_SERVICE(0)):
1493 {
1494 /* validate */
1495 PSUPCALLSERVICE pReq = (PSUPCALLSERVICE)pReqHdr;
1496 Log4(("SUP_IOCTL_CALL_SERVICE: op=%u in=%u arg=%RX64 p/t=%RTproc/%RTthrd\n",
1497 pReq->u.In.uOperation, pReq->Hdr.cbIn, pReq->u.In.u64Arg, RTProcSelf(), RTThreadNativeSelf()));
1498
1499 if (pReq->Hdr.cbIn == SUP_IOCTL_CALL_SERVICE_SIZE(0))
1500 REQ_CHECK_SIZES_EX(SUP_IOCTL_CALL_SERVICE, SUP_IOCTL_CALL_SERVICE_SIZE_IN(0), SUP_IOCTL_CALL_SERVICE_SIZE_OUT(0));
1501 else
1502 {
1503 PSUPR0SERVICEREQHDR pSrvReq = (PSUPR0SERVICEREQHDR)&pReq->abReqPkt[0];
1504 REQ_CHECK_EXPR_FMT(pReq->Hdr.cbIn >= SUP_IOCTL_CALL_SERVICE_SIZE(sizeof(SUPR0SERVICEREQHDR)),
1505 ("SUP_IOCTL_CALL_SERVICE: cbIn=%#x < %#lx\n", pReq->Hdr.cbIn, SUP_IOCTL_CALL_SERVICE_SIZE(sizeof(SUPR0SERVICEREQHDR))));
1506 REQ_CHECK_EXPR(SUP_IOCTL_CALL_SERVICE, pSrvReq->u32Magic == SUPR0SERVICEREQHDR_MAGIC);
1507 REQ_CHECK_SIZES_EX(SUP_IOCTL_CALL_SERVICE, SUP_IOCTL_CALL_SERVICE_SIZE_IN(pSrvReq->cbReq), SUP_IOCTL_CALL_SERVICE_SIZE_OUT(pSrvReq->cbReq));
1508 }
1509 REQ_CHECK_EXPR(SUP_IOCTL_CALL_SERVICE, memchr(pReq->u.In.szName, '\0', sizeof(pReq->u.In.szName)));
1510
1511 /* execute */
1512 pReq->Hdr.rc = supdrvIOCtl_CallServiceModule(pDevExt, pSession, pReq);
1513 return 0;
1514 }
1515
1516 default:
1517 Log(("Unknown IOCTL %#lx\n", (long)uIOCtl));
1518 break;
1519 }
1520 return SUPDRV_ERR_GENERAL_FAILURE;
1521}
1522
1523
1524/**
1525 * Inter-Driver Communcation (IDC) worker.
1526 *
1527 * @returns VBox status code.
1528 * @retval VINF_SUCCESS on success.
1529 * @retval VERR_INVALID_PARAMETER if the request is invalid.
1530 * @retval VERR_NOT_SUPPORTED if the request isn't supported.
1531 *
1532 * @param uReq The request (function) code.
1533 * @param pDevExt Device extention.
1534 * @param pSession Session data.
1535 * @param pReqHdr The request header.
1536 */
1537int VBOXCALL supdrvIDC(uintptr_t uReq, PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPDRVIDCREQHDR pReqHdr)
1538{
1539 /*
1540 * The OS specific code has already validated the pSession
1541 * pointer, and the request size being greater or equal to
1542 * size of the header.
1543 *
1544 * So, just check that pSession is a kernel context session.
1545 */
1546 if (RT_UNLIKELY( pSession
1547 && pSession->R0Process != NIL_RTR0PROCESS))
1548 return VERR_INVALID_PARAMETER;
1549
1550/*
1551 * Validation macro.
1552 */
1553#define REQ_CHECK_IDC_SIZE(Name, cbExpect) \
1554 do { \
1555 if (RT_UNLIKELY(pReqHdr->cb != (cbExpect))) \
1556 { \
1557 OSDBGPRINT(( #Name ": Invalid input/output sizes. cb=%ld expected %ld.\n", \
1558 (long)pReqHdr->cb, (long)(cbExpect))); \
1559 return pReqHdr->rc = VERR_INVALID_PARAMETER; \
1560 } \
1561 } while (0)
1562
1563 switch (uReq)
1564 {
1565 case SUPDRV_IDC_REQ_CONNECT:
1566 {
1567 PSUPDRVIDCREQCONNECT pReq = (PSUPDRVIDCREQCONNECT)pReqHdr;
1568 REQ_CHECK_IDC_SIZE(SUPDRV_IDC_REQ_CONNECT, sizeof(*pReq));
1569
1570 /*
1571 * Validate the cookie and other input.
1572 */
1573 if (pReq->Hdr.pSession != NULL)
1574 {
1575 OSDBGPRINT(("SUPDRV_IDC_REQ_CONNECT: pSession=%p expected NULL!\n", pReq->Hdr.pSession));
1576 return pReqHdr->rc = VERR_INVALID_PARAMETER;
1577 }
1578 if (pReq->u.In.u32MagicCookie != SUPDRVIDCREQ_CONNECT_MAGIC_COOKIE)
1579 {
1580 OSDBGPRINT(("SUPDRV_IDC_REQ_CONNECT: u32MagicCookie=%#x expected %#x!\n",
1581 pReq->u.In.u32MagicCookie, SUPDRVIDCREQ_CONNECT_MAGIC_COOKIE));
1582 return pReqHdr->rc = VERR_INVALID_PARAMETER;
1583 }
1584 if ( pReq->u.In.uMinVersion > pReq->u.In.uReqVersion
1585 || (pReq->u.In.uMinVersion & UINT32_C(0xffff0000)) != (pReq->u.In.uReqVersion & UINT32_C(0xffff0000)))
1586 {
1587 OSDBGPRINT(("SUPDRV_IDC_REQ_CONNECT: uMinVersion=%#x uMaxVersion=%#x doesn't match!\n",
1588 pReq->u.In.uMinVersion, pReq->u.In.uReqVersion));
1589 return pReqHdr->rc = VERR_INVALID_PARAMETER;
1590 }
1591
1592 /*
1593 * Match the version.
1594 * The current logic is very simple, match the major interface version.
1595 */
1596 if ( pReq->u.In.uMinVersion > SUPDRV_IDC_VERSION
1597 || (pReq->u.In.uMinVersion & 0xffff0000) != (SUPDRV_IDC_VERSION & 0xffff0000))
1598 {
1599 OSDBGPRINT(("SUPDRV_IDC_REQ_CONNECT: Version mismatch. Requested: %#x Min: %#x Current: %#x\n",
1600 pReq->u.In.uReqVersion, pReq->u.In.uMinVersion, SUPDRV_IDC_VERSION));
1601 pReq->u.Out.pSession = NULL;
1602 pReq->u.Out.uSessionVersion = 0xffffffff;
1603 pReq->u.Out.uDriverVersion = SUPDRV_IDC_VERSION;
1604 pReq->u.Out.uDriverRevision = VBOX_SVN_REV;
1605 pReq->Hdr.rc = VERR_VERSION_MISMATCH;
1606 return VINF_SUCCESS;
1607 }
1608
1609 pReq->u.Out.pSession = NULL;
1610 pReq->u.Out.uSessionVersion = SUPDRV_IDC_VERSION;
1611 pReq->u.Out.uDriverVersion = SUPDRV_IDC_VERSION;
1612 pReq->u.Out.uDriverRevision = VBOX_SVN_REV;
1613
1614 /*
1615 * On NT we will already have a session associated with the
1616 * client, just like with the SUP_IOCTL_COOKIE request, while
1617 * the other doesn't.
1618 */
1619#ifdef RT_OS_WINDOWS
1620 pReq->Hdr.rc = VINF_SUCCESS;
1621#else
1622 AssertReturn(!pSession, VERR_INTERNAL_ERROR);
1623 pReq->Hdr.rc = supdrvCreateSession(pDevExt, false /* fUser */, &pSession);
1624 if (RT_FAILURE(pReq->Hdr.rc))
1625 {
1626 OSDBGPRINT(("SUPDRV_IDC_REQ_CONNECT: failed to create session, rc=%d\n", pReq->Hdr.rc));
1627 return VINF_SUCCESS;
1628 }
1629#endif
1630
1631 pReq->u.Out.pSession = pSession;
1632 pReq->Hdr.pSession = pSession;
1633
1634 return VINF_SUCCESS;
1635 }
1636
1637 case SUPDRV_IDC_REQ_DISCONNECT:
1638 {
1639 REQ_CHECK_IDC_SIZE(SUPDRV_IDC_REQ_DISCONNECT, sizeof(*pReqHdr));
1640
1641#ifdef RT_OS_WINDOWS
1642 /* Windows will destroy the session when the file object is destroyed. */
1643#else
1644 supdrvCloseSession(pDevExt, pSession);
1645#endif
1646 return pReqHdr->rc = VINF_SUCCESS;
1647 }
1648
1649 case SUPDRV_IDC_REQ_GET_SYMBOL:
1650 {
1651 PSUPDRVIDCREQGETSYM pReq = (PSUPDRVIDCREQGETSYM)pReqHdr;
1652 REQ_CHECK_IDC_SIZE(SUPDRV_IDC_REQ_GET_SYMBOL, sizeof(*pReq));
1653
1654 pReq->Hdr.rc = supdrvIDC_LdrGetSymbol(pDevExt, pSession, pReq);
1655 return VINF_SUCCESS;
1656 }
1657
1658 case SUPDRV_IDC_REQ_COMPONENT_REGISTER_FACTORY:
1659 {
1660 PSUPDRVIDCREQCOMPREGFACTORY pReq = (PSUPDRVIDCREQCOMPREGFACTORY)pReqHdr;
1661 REQ_CHECK_IDC_SIZE(SUPDRV_IDC_REQ_COMPONENT_REGISTER_FACTORY, sizeof(*pReq));
1662
1663 pReq->Hdr.rc = SUPR0ComponentRegisterFactory(pSession, pReq->u.In.pFactory);
1664 return VINF_SUCCESS;
1665 }
1666
1667 case SUPDRV_IDC_REQ_COMPONENT_DEREGISTER_FACTORY:
1668 {
1669 PSUPDRVIDCREQCOMPDEREGFACTORY pReq = (PSUPDRVIDCREQCOMPDEREGFACTORY)pReqHdr;
1670 REQ_CHECK_IDC_SIZE(SUPDRV_IDC_REQ_COMPONENT_DEREGISTER_FACTORY, sizeof(*pReq));
1671
1672 pReq->Hdr.rc = SUPR0ComponentDeregisterFactory(pSession, pReq->u.In.pFactory);
1673 return VINF_SUCCESS;
1674 }
1675
1676 default:
1677 Log(("Unknown IDC %#lx\n", (long)uReq));
1678 break;
1679 }
1680
1681#undef REQ_CHECK_IDC_SIZE
1682 return VERR_NOT_SUPPORTED;
1683}
1684
1685
1686/**
1687 * Register a object for reference counting.
1688 * The object is registered with one reference in the specified session.
1689 *
1690 * @returns Unique identifier on success (pointer).
1691 * All future reference must use this identifier.
1692 * @returns NULL on failure.
1693 * @param pfnDestructor The destructore function which will be called when the reference count reaches 0.
1694 * @param pvUser1 The first user argument.
1695 * @param pvUser2 The second user argument.
1696 */
1697SUPR0DECL(void *) SUPR0ObjRegister(PSUPDRVSESSION pSession, SUPDRVOBJTYPE enmType, PFNSUPDRVDESTRUCTOR pfnDestructor, void *pvUser1, void *pvUser2)
1698{
1699 RTSPINLOCKTMP SpinlockTmp = RTSPINLOCKTMP_INITIALIZER;
1700 PSUPDRVDEVEXT pDevExt = pSession->pDevExt;
1701 PSUPDRVOBJ pObj;
1702 PSUPDRVUSAGE pUsage;
1703
1704 /*
1705 * Validate the input.
1706 */
1707 AssertReturn(SUP_IS_SESSION_VALID(pSession), NULL);
1708 AssertReturn(enmType > SUPDRVOBJTYPE_INVALID && enmType < SUPDRVOBJTYPE_END, NULL);
1709 AssertPtrReturn(pfnDestructor, NULL);
1710
1711 /*
1712 * Allocate and initialize the object.
1713 */
1714 pObj = (PSUPDRVOBJ)RTMemAlloc(sizeof(*pObj));
1715 if (!pObj)
1716 return NULL;
1717 pObj->u32Magic = SUPDRVOBJ_MAGIC;
1718 pObj->enmType = enmType;
1719 pObj->pNext = NULL;
1720 pObj->cUsage = 1;
1721 pObj->pfnDestructor = pfnDestructor;
1722 pObj->pvUser1 = pvUser1;
1723 pObj->pvUser2 = pvUser2;
1724 pObj->CreatorUid = pSession->Uid;
1725 pObj->CreatorGid = pSession->Gid;
1726 pObj->CreatorProcess= pSession->Process;
1727 supdrvOSObjInitCreator(pObj, pSession);
1728
1729 /*
1730 * Allocate the usage record.
1731 * (We keep freed usage records around to simplify SUPR0ObjAddRefEx().)
1732 */
1733 RTSpinlockAcquire(pDevExt->Spinlock, &SpinlockTmp);
1734
1735 pUsage = pDevExt->pUsageFree;
1736 if (pUsage)
1737 pDevExt->pUsageFree = pUsage->pNext;
1738 else
1739 {
1740 RTSpinlockRelease(pDevExt->Spinlock, &SpinlockTmp);
1741 pUsage = (PSUPDRVUSAGE)RTMemAlloc(sizeof(*pUsage));
1742 if (!pUsage)
1743 {
1744 RTMemFree(pObj);
1745 return NULL;
1746 }
1747 RTSpinlockAcquire(pDevExt->Spinlock, &SpinlockTmp);
1748 }
1749
1750 /*
1751 * Insert the object and create the session usage record.
1752 */
1753 /* The object. */
1754 pObj->pNext = pDevExt->pObjs;
1755 pDevExt->pObjs = pObj;
1756
1757 /* The session record. */
1758 pUsage->cUsage = 1;
1759 pUsage->pObj = pObj;
1760 pUsage->pNext = pSession->pUsage;
1761 /* Log2(("SUPR0ObjRegister: pUsage=%p:{.pObj=%p, .pNext=%p}\n", pUsage, pUsage->pObj, pUsage->pNext)); */
1762 pSession->pUsage = pUsage;
1763
1764 RTSpinlockRelease(pDevExt->Spinlock, &SpinlockTmp);
1765
1766 Log(("SUPR0ObjRegister: returns %p (pvUser1=%p, pvUser=%p)\n", pObj, pvUser1, pvUser2));
1767 return pObj;
1768}
1769
1770
1771/**
1772 * Increment the reference counter for the object associating the reference
1773 * with the specified session.
1774 *
1775 * @returns IPRT status code.
1776 * @param pvObj The identifier returned by SUPR0ObjRegister().
1777 * @param pSession The session which is referencing the object.
1778 *
1779 * @remarks The caller should not own any spinlocks and must carefully protect
1780 * itself against potential race with the destructor so freed memory
1781 * isn't accessed here.
1782 */
1783SUPR0DECL(int) SUPR0ObjAddRef(void *pvObj, PSUPDRVSESSION pSession)
1784{
1785 return SUPR0ObjAddRefEx(pvObj, pSession, false /* fNoBlocking */);
1786}
1787
1788
1789/**
1790 * Increment the reference counter for the object associating the reference
1791 * with the specified session.
1792 *
1793 * @returns IPRT status code.
1794 * @retval VERR_TRY_AGAIN if fNoBlocking was set and a new usage record
1795 * couldn't be allocated. (If you see this you're not doing the right
1796 * thing and it won't ever work reliably.)
1797 *
1798 * @param pvObj The identifier returned by SUPR0ObjRegister().
1799 * @param pSession The session which is referencing the object.
1800 * @param fNoBlocking Set if it's not OK to block. Never try to make the
1801 * first reference to an object in a session with this
1802 * argument set.
1803 *
1804 * @remarks The caller should not own any spinlocks and must carefully protect
1805 * itself against potential race with the destructor so freed memory
1806 * isn't accessed here.
1807 */
1808SUPR0DECL(int) SUPR0ObjAddRefEx(void *pvObj, PSUPDRVSESSION pSession, bool fNoBlocking)
1809{
1810 RTSPINLOCKTMP SpinlockTmp = RTSPINLOCKTMP_INITIALIZER;
1811 PSUPDRVDEVEXT pDevExt = pSession->pDevExt;
1812 PSUPDRVOBJ pObj = (PSUPDRVOBJ)pvObj;
1813 int rc = VINF_SUCCESS;
1814 PSUPDRVUSAGE pUsagePre;
1815 PSUPDRVUSAGE pUsage;
1816
1817 /*
1818 * Validate the input.
1819 * Be ready for the destruction race (someone might be stuck in the
1820 * destructor waiting a lock we own).
1821 */
1822 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
1823 AssertPtrReturn(pObj, VERR_INVALID_POINTER);
1824 AssertMsgReturn(pObj->u32Magic == SUPDRVOBJ_MAGIC || pObj->u32Magic == SUPDRVOBJ_MAGIC_DEAD,
1825 ("Invalid pvObj=%p magic=%#x (expected %#x or %#x)\n", pvObj, pObj->u32Magic, SUPDRVOBJ_MAGIC, SUPDRVOBJ_MAGIC_DEAD),
1826 VERR_INVALID_PARAMETER);
1827
1828 RTSpinlockAcquire(pDevExt->Spinlock, &SpinlockTmp);
1829
1830 if (RT_UNLIKELY(pObj->u32Magic != SUPDRVOBJ_MAGIC))
1831 {
1832 RTSpinlockRelease(pDevExt->Spinlock, &SpinlockTmp);
1833
1834 AssertMsgFailed(("pvObj=%p magic=%#x\n", pvObj, pObj->u32Magic));
1835 return VERR_WRONG_ORDER;
1836 }
1837
1838 /*
1839 * Preallocate the usage record if we can.
1840 */
1841 pUsagePre = pDevExt->pUsageFree;
1842 if (pUsagePre)
1843 pDevExt->pUsageFree = pUsagePre->pNext;
1844 else if (!fNoBlocking)
1845 {
1846 RTSpinlockRelease(pDevExt->Spinlock, &SpinlockTmp);
1847 pUsagePre = (PSUPDRVUSAGE)RTMemAlloc(sizeof(*pUsagePre));
1848 if (!pUsagePre)
1849 return VERR_NO_MEMORY;
1850
1851 RTSpinlockAcquire(pDevExt->Spinlock, &SpinlockTmp);
1852 if (RT_UNLIKELY(pObj->u32Magic != SUPDRVOBJ_MAGIC))
1853 {
1854 RTSpinlockRelease(pDevExt->Spinlock, &SpinlockTmp);
1855
1856 AssertMsgFailed(("pvObj=%p magic=%#x\n", pvObj, pObj->u32Magic));
1857 return VERR_WRONG_ORDER;
1858 }
1859 }
1860
1861 /*
1862 * Reference the object.
1863 */
1864 pObj->cUsage++;
1865
1866 /*
1867 * Look for the session record.
1868 */
1869 for (pUsage = pSession->pUsage; pUsage; pUsage = pUsage->pNext)
1870 {
1871 /*Log(("SUPR0AddRef: pUsage=%p:{.pObj=%p, .pNext=%p}\n", pUsage, pUsage->pObj, pUsage->pNext));*/
1872 if (pUsage->pObj == pObj)
1873 break;
1874 }
1875 if (pUsage)
1876 pUsage->cUsage++;
1877 else if (pUsagePre)
1878 {
1879 /* create a new session record. */
1880 pUsagePre->cUsage = 1;
1881 pUsagePre->pObj = pObj;
1882 pUsagePre->pNext = pSession->pUsage;
1883 pSession->pUsage = pUsagePre;
1884 /*Log(("SUPR0AddRef: pUsagePre=%p:{.pObj=%p, .pNext=%p}\n", pUsagePre, pUsagePre->pObj, pUsagePre->pNext));*/
1885
1886 pUsagePre = NULL;
1887 }
1888 else
1889 {
1890 pObj->cUsage--;
1891 rc = VERR_TRY_AGAIN;
1892 }
1893
1894 /*
1895 * Put any unused usage record into the free list..
1896 */
1897 if (pUsagePre)
1898 {
1899 pUsagePre->pNext = pDevExt->pUsageFree;
1900 pDevExt->pUsageFree = pUsagePre;
1901 }
1902
1903 RTSpinlockRelease(pDevExt->Spinlock, &SpinlockTmp);
1904
1905 return rc;
1906}
1907
1908
1909/**
1910 * Decrement / destroy a reference counter record for an object.
1911 *
1912 * The object is uniquely identified by pfnDestructor+pvUser1+pvUser2.
1913 *
1914 * @returns IPRT status code.
1915 * @retval VINF_SUCCESS if not destroyed.
1916 * @retval VINF_OBJECT_DESTROYED if it's destroyed by this release call.
1917 * @retval VERR_INVALID_PARAMETER if the object isn't valid. Will assert in
1918 * string builds.
1919 *
1920 * @param pvObj The identifier returned by SUPR0ObjRegister().
1921 * @param pSession The session which is referencing the object.
1922 */
1923SUPR0DECL(int) SUPR0ObjRelease(void *pvObj, PSUPDRVSESSION pSession)
1924{
1925 RTSPINLOCKTMP SpinlockTmp = RTSPINLOCKTMP_INITIALIZER;
1926 PSUPDRVDEVEXT pDevExt = pSession->pDevExt;
1927 PSUPDRVOBJ pObj = (PSUPDRVOBJ)pvObj;
1928 int rc = VERR_INVALID_PARAMETER;
1929 PSUPDRVUSAGE pUsage;
1930 PSUPDRVUSAGE pUsagePrev;
1931
1932 /*
1933 * Validate the input.
1934 */
1935 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
1936 AssertMsgReturn(VALID_PTR(pObj) && pObj->u32Magic == SUPDRVOBJ_MAGIC,
1937 ("Invalid pvObj=%p magic=%#x (exepcted %#x)\n", pvObj, pObj ? pObj->u32Magic : 0, SUPDRVOBJ_MAGIC),
1938 VERR_INVALID_PARAMETER);
1939
1940 /*
1941 * Acquire the spinlock and look for the usage record.
1942 */
1943 RTSpinlockAcquire(pDevExt->Spinlock, &SpinlockTmp);
1944
1945 for (pUsagePrev = NULL, pUsage = pSession->pUsage;
1946 pUsage;
1947 pUsagePrev = pUsage, pUsage = pUsage->pNext)
1948 {
1949 /*Log2(("SUPR0ObjRelease: pUsage=%p:{.pObj=%p, .pNext=%p}\n", pUsage, pUsage->pObj, pUsage->pNext));*/
1950 if (pUsage->pObj == pObj)
1951 {
1952 rc = VINF_SUCCESS;
1953 AssertMsg(pUsage->cUsage >= 1 && pObj->cUsage >= pUsage->cUsage, ("glob %d; sess %d\n", pObj->cUsage, pUsage->cUsage));
1954 if (pUsage->cUsage > 1)
1955 {
1956 pObj->cUsage--;
1957 pUsage->cUsage--;
1958 }
1959 else
1960 {
1961 /*
1962 * Free the session record.
1963 */
1964 if (pUsagePrev)
1965 pUsagePrev->pNext = pUsage->pNext;
1966 else
1967 pSession->pUsage = pUsage->pNext;
1968 pUsage->pNext = pDevExt->pUsageFree;
1969 pDevExt->pUsageFree = pUsage;
1970
1971 /* What about the object? */
1972 if (pObj->cUsage > 1)
1973 pObj->cUsage--;
1974 else
1975 {
1976 /*
1977 * Object is to be destroyed, unlink it.
1978 */
1979 pObj->u32Magic = SUPDRVOBJ_MAGIC_DEAD;
1980 rc = VINF_OBJECT_DESTROYED;
1981 if (pDevExt->pObjs == pObj)
1982 pDevExt->pObjs = pObj->pNext;
1983 else
1984 {
1985 PSUPDRVOBJ pObjPrev;
1986 for (pObjPrev = pDevExt->pObjs; pObjPrev; pObjPrev = pObjPrev->pNext)
1987 if (pObjPrev->pNext == pObj)
1988 {
1989 pObjPrev->pNext = pObj->pNext;
1990 break;
1991 }
1992 Assert(pObjPrev);
1993 }
1994 }
1995 }
1996 break;
1997 }
1998 }
1999
2000 RTSpinlockRelease(pDevExt->Spinlock, &SpinlockTmp);
2001
2002 /*
2003 * Call the destructor and free the object if required.
2004 */
2005 if (rc == VINF_OBJECT_DESTROYED)
2006 {
2007 Log(("SUPR0ObjRelease: destroying %p/%d (%p/%p) cpid=%RTproc pid=%RTproc dtor=%p\n",
2008 pObj, pObj->enmType, pObj->pvUser1, pObj->pvUser2, pObj->CreatorProcess, RTProcSelf(), pObj->pfnDestructor));
2009 if (pObj->pfnDestructor)
2010#ifdef RT_WITH_W64_UNWIND_HACK
2011 supdrvNtWrapObjDestructor((PFNRT)pObj->pfnDestructor, pObj, pObj->pvUser1, pObj->pvUser2);
2012#else
2013 pObj->pfnDestructor(pObj, pObj->pvUser1, pObj->pvUser2);
2014#endif
2015 RTMemFree(pObj);
2016 }
2017
2018 AssertMsg(pUsage, ("pvObj=%p\n", pvObj));
2019 return rc;
2020}
2021
2022
2023/**
2024 * Verifies that the current process can access the specified object.
2025 *
2026 * @returns The following IPRT status code:
2027 * @retval VINF_SUCCESS if access was granted.
2028 * @retval VERR_PERMISSION_DENIED if denied access.
2029 * @retval VERR_INVALID_PARAMETER if invalid parameter.
2030 *
2031 * @param pvObj The identifier returned by SUPR0ObjRegister().
2032 * @param pSession The session which wishes to access the object.
2033 * @param pszObjName Object string name. This is optional and depends on the object type.
2034 *
2035 * @remark The caller is responsible for making sure the object isn't removed while
2036 * we're inside this function. If uncertain about this, just call AddRef before calling us.
2037 */
2038SUPR0DECL(int) SUPR0ObjVerifyAccess(void *pvObj, PSUPDRVSESSION pSession, const char *pszObjName)
2039{
2040 PSUPDRVOBJ pObj = (PSUPDRVOBJ)pvObj;
2041 int rc;
2042
2043 /*
2044 * Validate the input.
2045 */
2046 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
2047 AssertMsgReturn(VALID_PTR(pObj) && pObj->u32Magic == SUPDRVOBJ_MAGIC,
2048 ("Invalid pvObj=%p magic=%#x (exepcted %#x)\n", pvObj, pObj ? pObj->u32Magic : 0, SUPDRVOBJ_MAGIC),
2049 VERR_INVALID_PARAMETER);
2050
2051 /*
2052 * Check access. (returns true if a decision has been made.)
2053 */
2054 rc = VERR_INTERNAL_ERROR;
2055 if (supdrvOSObjCanAccess(pObj, pSession, pszObjName, &rc))
2056 return rc;
2057
2058 /*
2059 * Default policy is to allow the user to access his own
2060 * stuff but nothing else.
2061 */
2062 if (pObj->CreatorUid == pSession->Uid)
2063 return VINF_SUCCESS;
2064 return VERR_PERMISSION_DENIED;
2065}
2066
2067
2068/**
2069 * Lock pages.
2070 *
2071 * @returns IPRT status code.
2072 * @param pSession Session to which the locked memory should be associated.
2073 * @param pvR3 Start of the memory range to lock.
2074 * This must be page aligned.
2075 * @param cb Size of the memory range to lock.
2076 * This must be page aligned.
2077 */
2078SUPR0DECL(int) SUPR0LockMem(PSUPDRVSESSION pSession, RTR3PTR pvR3, uint32_t cPages, PRTHCPHYS paPages)
2079{
2080 int rc;
2081 SUPDRVMEMREF Mem = { NIL_RTR0MEMOBJ, NIL_RTR0MEMOBJ, MEMREF_TYPE_UNUSED };
2082 const size_t cb = (size_t)cPages << PAGE_SHIFT;
2083 LogFlow(("SUPR0LockMem: pSession=%p pvR3=%p cPages=%d paPages=%p\n", pSession, (void *)pvR3, cPages, paPages));
2084
2085 /*
2086 * Verify input.
2087 */
2088 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
2089 AssertPtrReturn(paPages, VERR_INVALID_PARAMETER);
2090 if ( RT_ALIGN_R3PT(pvR3, PAGE_SIZE, RTR3PTR) != pvR3
2091 || !pvR3)
2092 {
2093 Log(("pvR3 (%p) must be page aligned and not NULL!\n", (void *)pvR3));
2094 return VERR_INVALID_PARAMETER;
2095 }
2096
2097#ifdef RT_OS_WINDOWS /* A temporary hack for windows, will be removed once all ring-3 code has been cleaned up. */
2098 /* First check if we allocated it using SUPPageAlloc; if so then we don't need to lock it again */
2099 rc = supdrvPageGetPhys(pSession, pvR3, cPages, paPages);
2100 if (RT_SUCCESS(rc))
2101 return rc;
2102#endif
2103
2104 /*
2105 * Let IPRT do the job.
2106 */
2107 Mem.eType = MEMREF_TYPE_LOCKED;
2108 rc = RTR0MemObjLockUser(&Mem.MemObj, pvR3, cb, RTR0ProcHandleSelf());
2109 if (RT_SUCCESS(rc))
2110 {
2111 uint32_t iPage = cPages;
2112 AssertMsg(RTR0MemObjAddressR3(Mem.MemObj) == pvR3, ("%p == %p\n", RTR0MemObjAddressR3(Mem.MemObj), pvR3));
2113 AssertMsg(RTR0MemObjSize(Mem.MemObj) == cb, ("%x == %x\n", RTR0MemObjSize(Mem.MemObj), cb));
2114
2115 while (iPage-- > 0)
2116 {
2117 paPages[iPage] = RTR0MemObjGetPagePhysAddr(Mem.MemObj, iPage);
2118 if (RT_UNLIKELY(paPages[iPage] == NIL_RTCCPHYS))
2119 {
2120 AssertMsgFailed(("iPage=%d\n", iPage));
2121 rc = VERR_INTERNAL_ERROR;
2122 break;
2123 }
2124 }
2125 if (RT_SUCCESS(rc))
2126 rc = supdrvMemAdd(&Mem, pSession);
2127 if (RT_FAILURE(rc))
2128 {
2129 int rc2 = RTR0MemObjFree(Mem.MemObj, false);
2130 AssertRC(rc2);
2131 }
2132 }
2133
2134 return rc;
2135}
2136
2137
2138/**
2139 * Unlocks the memory pointed to by pv.
2140 *
2141 * @returns IPRT status code.
2142 * @param pSession Session to which the memory was locked.
2143 * @param pvR3 Memory to unlock.
2144 */
2145SUPR0DECL(int) SUPR0UnlockMem(PSUPDRVSESSION pSession, RTR3PTR pvR3)
2146{
2147 LogFlow(("SUPR0UnlockMem: pSession=%p pvR3=%p\n", pSession, (void *)pvR3));
2148 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
2149#ifdef RT_OS_WINDOWS
2150 /*
2151 * Temporary hack for windows - SUPR0PageFree will unlock SUPR0PageAlloc
2152 * allocations; ignore this call.
2153 */
2154 if (supdrvPageWasLockedByPageAlloc(pSession, pvR3))
2155 {
2156 LogFlow(("Page will be unlocked in SUPR0PageFree -> ignore\n"));
2157 return VINF_SUCCESS;
2158 }
2159#endif
2160 return supdrvMemRelease(pSession, (RTHCUINTPTR)pvR3, MEMREF_TYPE_LOCKED);
2161}
2162
2163
2164/**
2165 * Allocates a chunk of page aligned memory with contiguous and fixed physical
2166 * backing.
2167 *
2168 * @returns IPRT status code.
2169 * @param pSession Session data.
2170 * @param cb Number of bytes to allocate.
2171 * @param ppvR0 Where to put the address of Ring-0 mapping the allocated memory.
2172 * @param ppvR3 Where to put the address of Ring-3 mapping the allocated memory.
2173 * @param pHCPhys Where to put the physical address of allocated memory.
2174 */
2175SUPR0DECL(int) SUPR0ContAlloc(PSUPDRVSESSION pSession, uint32_t cPages, PRTR0PTR ppvR0, PRTR3PTR ppvR3, PRTHCPHYS pHCPhys)
2176{
2177 int rc;
2178 SUPDRVMEMREF Mem = { NIL_RTR0MEMOBJ, NIL_RTR0MEMOBJ, MEMREF_TYPE_UNUSED };
2179 LogFlow(("SUPR0ContAlloc: pSession=%p cPages=%d ppvR0=%p ppvR3=%p pHCPhys=%p\n", pSession, cPages, ppvR0, ppvR3, pHCPhys));
2180
2181 /*
2182 * Validate input.
2183 */
2184 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
2185 if (!ppvR3 || !ppvR0 || !pHCPhys)
2186 {
2187 Log(("Null pointer. All of these should be set: pSession=%p ppvR0=%p ppvR3=%p pHCPhys=%p\n",
2188 pSession, ppvR0, ppvR3, pHCPhys));
2189 return VERR_INVALID_PARAMETER;
2190
2191 }
2192 if (cPages < 1 || cPages >= 256)
2193 {
2194 Log(("Illegal request cPages=%d, must be greater than 0 and smaller than 256.\n", cPages));
2195 return VERR_PAGE_COUNT_OUT_OF_RANGE;
2196 }
2197
2198 /*
2199 * Let IPRT do the job.
2200 */
2201 rc = RTR0MemObjAllocCont(&Mem.MemObj, cPages << PAGE_SHIFT, true /* executable R0 mapping */);
2202 if (RT_SUCCESS(rc))
2203 {
2204 int rc2;
2205 rc = RTR0MemObjMapUser(&Mem.MapObjR3, Mem.MemObj, (RTR3PTR)-1, 0,
2206 RTMEM_PROT_EXEC | RTMEM_PROT_WRITE | RTMEM_PROT_READ, RTR0ProcHandleSelf());
2207 if (RT_SUCCESS(rc))
2208 {
2209 Mem.eType = MEMREF_TYPE_CONT;
2210 rc = supdrvMemAdd(&Mem, pSession);
2211 if (!rc)
2212 {
2213 *ppvR0 = RTR0MemObjAddress(Mem.MemObj);
2214 *ppvR3 = RTR0MemObjAddressR3(Mem.MapObjR3);
2215 *pHCPhys = RTR0MemObjGetPagePhysAddr(Mem.MemObj, 0);
2216 return 0;
2217 }
2218
2219 rc2 = RTR0MemObjFree(Mem.MapObjR3, false);
2220 AssertRC(rc2);
2221 }
2222 rc2 = RTR0MemObjFree(Mem.MemObj, false);
2223 AssertRC(rc2);
2224 }
2225
2226 return rc;
2227}
2228
2229
2230/**
2231 * Frees memory allocated using SUPR0ContAlloc().
2232 *
2233 * @returns IPRT status code.
2234 * @param pSession The session to which the memory was allocated.
2235 * @param uPtr Pointer to the memory (ring-3 or ring-0).
2236 */
2237SUPR0DECL(int) SUPR0ContFree(PSUPDRVSESSION pSession, RTHCUINTPTR uPtr)
2238{
2239 LogFlow(("SUPR0ContFree: pSession=%p uPtr=%p\n", pSession, (void *)uPtr));
2240 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
2241 return supdrvMemRelease(pSession, uPtr, MEMREF_TYPE_CONT);
2242}
2243
2244
2245/**
2246 * Allocates a chunk of page aligned memory with fixed physical backing below 4GB.
2247 *
2248 * The memory isn't zeroed.
2249 *
2250 * @returns IPRT status code.
2251 * @param pSession Session data.
2252 * @param cPages Number of pages to allocate.
2253 * @param ppvR0 Where to put the address of Ring-0 mapping of the allocated memory.
2254 * @param ppvR3 Where to put the address of Ring-3 mapping of the allocated memory.
2255 * @param paPages Where to put the physical addresses of allocated memory.
2256 */
2257SUPR0DECL(int) SUPR0LowAlloc(PSUPDRVSESSION pSession, uint32_t cPages, PRTR0PTR ppvR0, PRTR3PTR ppvR3, PRTHCPHYS paPages)
2258{
2259 unsigned iPage;
2260 int rc;
2261 SUPDRVMEMREF Mem = { NIL_RTR0MEMOBJ, NIL_RTR0MEMOBJ, MEMREF_TYPE_UNUSED };
2262 LogFlow(("SUPR0LowAlloc: pSession=%p cPages=%d ppvR3=%p ppvR0=%p paPages=%p\n", pSession, cPages, ppvR3, ppvR0, paPages));
2263
2264 /*
2265 * Validate input.
2266 */
2267 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
2268 if (!ppvR3 || !ppvR0 || !paPages)
2269 {
2270 Log(("Null pointer. All of these should be set: pSession=%p ppvR3=%p ppvR0=%p paPages=%p\n",
2271 pSession, ppvR3, ppvR0, paPages));
2272 return VERR_INVALID_PARAMETER;
2273
2274 }
2275 if (cPages < 1 || cPages >= 256)
2276 {
2277 Log(("Illegal request cPages=%d, must be greater than 0 and smaller than 256.\n", cPages));
2278 return VERR_PAGE_COUNT_OUT_OF_RANGE;
2279 }
2280
2281 /*
2282 * Let IPRT do the work.
2283 */
2284 rc = RTR0MemObjAllocLow(&Mem.MemObj, cPages << PAGE_SHIFT, true /* executable ring-0 mapping */);
2285 if (RT_SUCCESS(rc))
2286 {
2287 int rc2;
2288 rc = RTR0MemObjMapUser(&Mem.MapObjR3, Mem.MemObj, (RTR3PTR)-1, 0,
2289 RTMEM_PROT_EXEC | RTMEM_PROT_WRITE | RTMEM_PROT_READ, RTR0ProcHandleSelf());
2290 if (RT_SUCCESS(rc))
2291 {
2292 Mem.eType = MEMREF_TYPE_LOW;
2293 rc = supdrvMemAdd(&Mem, pSession);
2294 if (!rc)
2295 {
2296 for (iPage = 0; iPage < cPages; iPage++)
2297 {
2298 paPages[iPage] = RTR0MemObjGetPagePhysAddr(Mem.MemObj, iPage);
2299 AssertMsg(!(paPages[iPage] & (PAGE_SIZE - 1)), ("iPage=%d Phys=%RHp\n", paPages[iPage]));
2300 }
2301 *ppvR0 = RTR0MemObjAddress(Mem.MemObj);
2302 *ppvR3 = RTR0MemObjAddressR3(Mem.MapObjR3);
2303 return 0;
2304 }
2305
2306 rc2 = RTR0MemObjFree(Mem.MapObjR3, false);
2307 AssertRC(rc2);
2308 }
2309
2310 rc2 = RTR0MemObjFree(Mem.MemObj, false);
2311 AssertRC(rc2);
2312 }
2313
2314 return rc;
2315}
2316
2317
2318/**
2319 * Frees memory allocated using SUPR0LowAlloc().
2320 *
2321 * @returns IPRT status code.
2322 * @param pSession The session to which the memory was allocated.
2323 * @param uPtr Pointer to the memory (ring-3 or ring-0).
2324 */
2325SUPR0DECL(int) SUPR0LowFree(PSUPDRVSESSION pSession, RTHCUINTPTR uPtr)
2326{
2327 LogFlow(("SUPR0LowFree: pSession=%p uPtr=%p\n", pSession, (void *)uPtr));
2328 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
2329 return supdrvMemRelease(pSession, uPtr, MEMREF_TYPE_LOW);
2330}
2331
2332
2333
2334/**
2335 * Allocates a chunk of memory with both R0 and R3 mappings.
2336 * The memory is fixed and it's possible to query the physical addresses using SUPR0MemGetPhys().
2337 *
2338 * @returns IPRT status code.
2339 * @param pSession The session to associated the allocation with.
2340 * @param cb Number of bytes to allocate.
2341 * @param ppvR0 Where to store the address of the Ring-0 mapping.
2342 * @param ppvR3 Where to store the address of the Ring-3 mapping.
2343 */
2344SUPR0DECL(int) SUPR0MemAlloc(PSUPDRVSESSION pSession, uint32_t cb, PRTR0PTR ppvR0, PRTR3PTR ppvR3)
2345{
2346 int rc;
2347 SUPDRVMEMREF Mem = { NIL_RTR0MEMOBJ, NIL_RTR0MEMOBJ, MEMREF_TYPE_UNUSED };
2348 LogFlow(("SUPR0MemAlloc: pSession=%p cb=%d ppvR0=%p ppvR3=%p\n", pSession, cb, ppvR0, ppvR3));
2349
2350 /*
2351 * Validate input.
2352 */
2353 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
2354 AssertPtrReturn(ppvR0, VERR_INVALID_POINTER);
2355 AssertPtrReturn(ppvR3, VERR_INVALID_POINTER);
2356 if (cb < 1 || cb >= _4M)
2357 {
2358 Log(("Illegal request cb=%u; must be greater than 0 and smaller than 4MB.\n", cb));
2359 return VERR_INVALID_PARAMETER;
2360 }
2361
2362 /*
2363 * Let IPRT do the work.
2364 */
2365 rc = RTR0MemObjAllocPage(&Mem.MemObj, cb, true /* executable ring-0 mapping */);
2366 if (RT_SUCCESS(rc))
2367 {
2368 int rc2;
2369 rc = RTR0MemObjMapUser(&Mem.MapObjR3, Mem.MemObj, (RTR3PTR)-1, 0,
2370 RTMEM_PROT_EXEC | RTMEM_PROT_WRITE | RTMEM_PROT_READ, RTR0ProcHandleSelf());
2371 if (RT_SUCCESS(rc))
2372 {
2373 Mem.eType = MEMREF_TYPE_MEM;
2374 rc = supdrvMemAdd(&Mem, pSession);
2375 if (!rc)
2376 {
2377 *ppvR0 = RTR0MemObjAddress(Mem.MemObj);
2378 *ppvR3 = RTR0MemObjAddressR3(Mem.MapObjR3);
2379 return VINF_SUCCESS;
2380 }
2381
2382 rc2 = RTR0MemObjFree(Mem.MapObjR3, false);
2383 AssertRC(rc2);
2384 }
2385
2386 rc2 = RTR0MemObjFree(Mem.MemObj, false);
2387 AssertRC(rc2);
2388 }
2389
2390 return rc;
2391}
2392
2393
2394/**
2395 * Get the physical addresses of memory allocated using SUPR0MemAlloc().
2396 *
2397 * @returns IPRT status code.
2398 * @param pSession The session to which the memory was allocated.
2399 * @param uPtr The Ring-0 or Ring-3 address returned by SUPR0MemAlloc().
2400 * @param paPages Where to store the physical addresses.
2401 */
2402SUPR0DECL(int) SUPR0MemGetPhys(PSUPDRVSESSION pSession, RTHCUINTPTR uPtr, PSUPPAGE paPages) /** @todo switch this bugger to RTHCPHYS */
2403{
2404 PSUPDRVBUNDLE pBundle;
2405 RTSPINLOCKTMP SpinlockTmp = RTSPINLOCKTMP_INITIALIZER;
2406 LogFlow(("SUPR0MemGetPhys: pSession=%p uPtr=%p paPages=%p\n", pSession, (void *)uPtr, paPages));
2407
2408 /*
2409 * Validate input.
2410 */
2411 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
2412 AssertPtrReturn(paPages, VERR_INVALID_POINTER);
2413 AssertReturn(uPtr, VERR_INVALID_PARAMETER);
2414
2415 /*
2416 * Search for the address.
2417 */
2418 RTSpinlockAcquire(pSession->Spinlock, &SpinlockTmp);
2419 for (pBundle = &pSession->Bundle; pBundle; pBundle = pBundle->pNext)
2420 {
2421 if (pBundle->cUsed > 0)
2422 {
2423 unsigned i;
2424 for (i = 0; i < RT_ELEMENTS(pBundle->aMem); i++)
2425 {
2426 if ( pBundle->aMem[i].eType == MEMREF_TYPE_MEM
2427 && pBundle->aMem[i].MemObj != NIL_RTR0MEMOBJ
2428 && ( (RTHCUINTPTR)RTR0MemObjAddress(pBundle->aMem[i].MemObj) == uPtr
2429 || ( pBundle->aMem[i].MapObjR3 != NIL_RTR0MEMOBJ
2430 && RTR0MemObjAddressR3(pBundle->aMem[i].MapObjR3) == uPtr)
2431 )
2432 )
2433 {
2434 const size_t cPages = RTR0MemObjSize(pBundle->aMem[i].MemObj) >> PAGE_SHIFT;
2435 size_t iPage;
2436 for (iPage = 0; iPage < cPages; iPage++)
2437 {
2438 paPages[iPage].Phys = RTR0MemObjGetPagePhysAddr(pBundle->aMem[i].MemObj, iPage);
2439 paPages[iPage].uReserved = 0;
2440 }
2441 RTSpinlockRelease(pSession->Spinlock, &SpinlockTmp);
2442 return VINF_SUCCESS;
2443 }
2444 }
2445 }
2446 }
2447 RTSpinlockRelease(pSession->Spinlock, &SpinlockTmp);
2448 Log(("Failed to find %p!!!\n", (void *)uPtr));
2449 return VERR_INVALID_PARAMETER;
2450}
2451
2452
2453/**
2454 * Free memory allocated by SUPR0MemAlloc().
2455 *
2456 * @returns IPRT status code.
2457 * @param pSession The session owning the allocation.
2458 * @param uPtr The Ring-0 or Ring-3 address returned by SUPR0MemAlloc().
2459 */
2460SUPR0DECL(int) SUPR0MemFree(PSUPDRVSESSION pSession, RTHCUINTPTR uPtr)
2461{
2462 LogFlow(("SUPR0MemFree: pSession=%p uPtr=%p\n", pSession, (void *)uPtr));
2463 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
2464 return supdrvMemRelease(pSession, uPtr, MEMREF_TYPE_MEM);
2465}
2466
2467
2468/**
2469 * Allocates a chunk of memory with only a R3 mappings.
2470 *
2471 * The memory is fixed and it's possible to query the physical addresses using
2472 * SUPR0MemGetPhys().
2473 *
2474 * @returns IPRT status code.
2475 * @param pSession The session to associated the allocation with.
2476 * @param cPages The number of pages to allocate.
2477 * @param ppvR3 Where to store the address of the Ring-3 mapping.
2478 * @param paPages Where to store the addresses of the pages. Optional.
2479 */
2480SUPR0DECL(int) SUPR0PageAlloc(PSUPDRVSESSION pSession, uint32_t cPages, PRTR3PTR ppvR3, PRTHCPHYS paPages)
2481{
2482 AssertPtrReturn(ppvR3, VERR_INVALID_POINTER);
2483 return SUPR0PageAllocEx(pSession, cPages, 0 /*fFlags*/, ppvR3, NULL, paPages);
2484}
2485
2486
2487/**
2488 * Allocates a chunk of memory with a kernel or/and a user mode mapping.
2489 *
2490 * The memory is fixed and it's possible to query the physical addresses using
2491 * SUPR0MemGetPhys().
2492 *
2493 * @returns IPRT status code.
2494 * @param pSession The session to associated the allocation with.
2495 * @param cPages The number of pages to allocate.
2496 * @param fFlags Flags, reserved for the future. Must be zero.
2497 * @param ppvR3 Where to store the address of the Ring-3 mapping.
2498 * NULL if no ring-3 mapping.
2499 * @param ppvR3 Where to store the address of the Ring-0 mapping.
2500 * NULL if no ring-0 mapping.
2501 * @param paPages Where to store the addresses of the pages. Optional.
2502 */
2503SUPR0DECL(int) SUPR0PageAllocEx(PSUPDRVSESSION pSession, uint32_t cPages, uint32_t fFlags, PRTR3PTR ppvR3, PRTR0PTR ppvR0, PRTHCPHYS paPages)
2504{
2505 int rc;
2506 SUPDRVMEMREF Mem = { NIL_RTR0MEMOBJ, NIL_RTR0MEMOBJ, MEMREF_TYPE_UNUSED };
2507 LogFlow(("SUPR0PageAlloc: pSession=%p cb=%d ppvR3=%p\n", pSession, cPages, ppvR3));
2508
2509 /*
2510 * Validate input. The allowed allocation size must be at least equal to the maximum guest VRAM size.
2511 */
2512 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
2513 AssertPtrNullReturn(ppvR3, VERR_INVALID_POINTER);
2514 AssertPtrNullReturn(ppvR0, VERR_INVALID_POINTER);
2515 AssertReturn(ppvR3 || ppvR0, VERR_INVALID_PARAMETER);
2516 AssertReturn(!fFlags, VERR_INVALID_PARAMETER);
2517 if (cPages < 1 || cPages > VBOX_MAX_ALLOC_PAGE_COUNT)
2518 {
2519 Log(("SUPR0PageAlloc: Illegal request cb=%u; must be greater than 0 and smaller than 128MB.\n", cPages));
2520 return VERR_PAGE_COUNT_OUT_OF_RANGE;
2521 }
2522
2523 /*
2524 * Let IPRT do the work.
2525 */
2526 if (ppvR0)
2527 rc = RTR0MemObjAllocPage(&Mem.MemObj, (size_t)cPages * PAGE_SIZE, true /* fExecutable */);
2528 else
2529 rc = RTR0MemObjAllocPhysNC(&Mem.MemObj, (size_t)cPages * PAGE_SIZE, NIL_RTHCPHYS);
2530 if (RT_SUCCESS(rc))
2531 {
2532 int rc2;
2533 if (ppvR3)
2534 rc = RTR0MemObjMapUser(&Mem.MapObjR3, Mem.MemObj, (RTR3PTR)-1, 0,
2535 RTMEM_PROT_EXEC | RTMEM_PROT_WRITE | RTMEM_PROT_READ, RTR0ProcHandleSelf());
2536 else
2537 Mem.MapObjR3 = NIL_RTR0MEMOBJ;
2538 if (RT_SUCCESS(rc))
2539 {
2540 Mem.eType = MEMREF_TYPE_PAGE;
2541 rc = supdrvMemAdd(&Mem, pSession);
2542 if (!rc)
2543 {
2544 if (ppvR3)
2545 *ppvR3 = RTR0MemObjAddressR3(Mem.MapObjR3);
2546 if (ppvR0)
2547 *ppvR0 = RTR0MemObjAddress(Mem.MemObj);
2548 if (paPages)
2549 {
2550 uint32_t iPage = cPages;
2551 while (iPage-- > 0)
2552 {
2553 paPages[iPage] = RTR0MemObjGetPagePhysAddr(Mem.MapObjR3, iPage);
2554 Assert(paPages[iPage] != NIL_RTHCPHYS);
2555 }
2556 }
2557 return VINF_SUCCESS;
2558 }
2559
2560 rc2 = RTR0MemObjFree(Mem.MapObjR3, false);
2561 AssertRC(rc2);
2562 }
2563
2564 rc2 = RTR0MemObjFree(Mem.MemObj, false);
2565 AssertRC(rc2);
2566 }
2567 return rc;
2568}
2569
2570
2571/**
2572 * Allocates a chunk of memory with a kernel or/and a user mode mapping.
2573 *
2574 * The memory is fixed and it's possible to query the physical addresses using
2575 * SUPR0MemGetPhys().
2576 *
2577 * @returns IPRT status code.
2578 * @param pSession The session to associated the allocation with.
2579 * @param cPages The number of pages to allocate.
2580 * @param fFlags Flags, reserved for the future. Must be zero.
2581 * @param ppvR3 Where to store the address of the Ring-3 mapping.
2582 * NULL if no ring-3 mapping.
2583 * @param ppvR3 Where to store the address of the Ring-0 mapping.
2584 * NULL if no ring-0 mapping.
2585 * @param paPages Where to store the addresses of the pages. Optional.
2586 */
2587SUPR0DECL(int) SUPR0PageMapKernel(PSUPDRVSESSION pSession, RTR3PTR pvR3, uint32_t offSub, uint32_t cbSub,
2588 uint32_t fFlags, PRTR0PTR ppvR0)
2589{
2590 int rc;
2591 PSUPDRVBUNDLE pBundle;
2592 RTSPINLOCKTMP SpinlockTmp = RTSPINLOCKTMP_INITIALIZER;
2593 RTR0MEMOBJ hMemObj = NIL_RTR0MEMOBJ;
2594 LogFlow(("SUPR0PageMapKernel: pSession=%p pvR3=%p offSub=%#x cbSub=%#x\n", pSession, pvR3, offSub, cbSub));
2595
2596 /*
2597 * Validate input. The allowed allocation size must be at least equal to the maximum guest VRAM size.
2598 */
2599 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
2600 AssertPtrNullReturn(ppvR0, VERR_INVALID_POINTER);
2601 AssertReturn(!fFlags, VERR_INVALID_PARAMETER);
2602 AssertReturn(!(offSub & PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
2603 AssertReturn(!(cbSub & PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
2604 AssertReturn(cbSub, VERR_INVALID_PARAMETER);
2605
2606 /*
2607 * Find the memory object.
2608 */
2609 RTSpinlockAcquire(pSession->Spinlock, &SpinlockTmp);
2610 for (pBundle = &pSession->Bundle; pBundle; pBundle = pBundle->pNext)
2611 {
2612 if (pBundle->cUsed > 0)
2613 {
2614 unsigned i;
2615 for (i = 0; i < RT_ELEMENTS(pBundle->aMem); i++)
2616 {
2617 if ( ( pBundle->aMem[i].eType == MEMREF_TYPE_PAGE
2618 && pBundle->aMem[i].MemObj != NIL_RTR0MEMOBJ
2619 && pBundle->aMem[i].MapObjR3 != NIL_RTR0MEMOBJ
2620 && RTR0MemObjAddressR3(pBundle->aMem[i].MapObjR3) == pvR3)
2621 || ( pBundle->aMem[i].eType == MEMREF_TYPE_LOCKED
2622 && pBundle->aMem[i].MemObj != NIL_RTR0MEMOBJ
2623 && pBundle->aMem[i].MapObjR3 == NIL_RTR0MEMOBJ
2624 && RTR0MemObjAddressR3(pBundle->aMem[i].MemObj) == pvR3))
2625 {
2626 hMemObj = pBundle->aMem[i].MemObj;
2627 break;
2628 }
2629 }
2630 }
2631 }
2632 RTSpinlockRelease(pSession->Spinlock, &SpinlockTmp);
2633
2634 rc = VERR_INVALID_PARAMETER;
2635 if (hMemObj != NIL_RTR0MEMOBJ)
2636 {
2637 /*
2638 * Do some furter input validations before calling IPRT.
2639 * (Cleanup is done indirectly by telling RTR0MemObjFree to include mappings.)
2640 */
2641 size_t cbMemObj = RTR0MemObjSize(hMemObj);
2642 if ( offSub < cbMemObj
2643 && cbSub <= cbMemObj
2644 && offSub + cbSub <= cbMemObj)
2645 {
2646 RTR0MEMOBJ hMapObj;
2647 rc = RTR0MemObjMapKernelEx(&hMapObj, hMemObj, (void *)-1, 0,
2648 RTMEM_PROT_READ | RTMEM_PROT_WRITE, offSub, cbSub);
2649 if (RT_SUCCESS(rc))
2650 *ppvR0 = RTR0MemObjAddress(hMapObj);
2651 }
2652 else
2653 SUPR0Printf("SUPR0PageMapKernel: cbMemObj=%#x offSub=%#x cbSub=%#x\n", cbMemObj, offSub, cbSub);
2654
2655 }
2656 return rc;
2657}
2658
2659
2660
2661#ifdef RT_OS_WINDOWS
2662/**
2663 * Check if the pages were locked by SUPR0PageAlloc
2664 *
2665 * This function will be removed along with the lock/unlock hacks when
2666 * we've cleaned up the ring-3 code properly.
2667 *
2668 * @returns boolean
2669 * @param pSession The session to which the memory was allocated.
2670 * @param pvR3 The Ring-3 address returned by SUPR0PageAlloc().
2671 */
2672static bool supdrvPageWasLockedByPageAlloc(PSUPDRVSESSION pSession, RTR3PTR pvR3)
2673{
2674 PSUPDRVBUNDLE pBundle;
2675 RTSPINLOCKTMP SpinlockTmp = RTSPINLOCKTMP_INITIALIZER;
2676 LogFlow(("SUPR0PageIsLockedByPageAlloc: pSession=%p pvR3=%p\n", pSession, (void *)pvR3));
2677
2678 /*
2679 * Search for the address.
2680 */
2681 RTSpinlockAcquire(pSession->Spinlock, &SpinlockTmp);
2682 for (pBundle = &pSession->Bundle; pBundle; pBundle = pBundle->pNext)
2683 {
2684 if (pBundle->cUsed > 0)
2685 {
2686 unsigned i;
2687 for (i = 0; i < RT_ELEMENTS(pBundle->aMem); i++)
2688 {
2689 if ( pBundle->aMem[i].eType == MEMREF_TYPE_PAGE
2690 && pBundle->aMem[i].MemObj != NIL_RTR0MEMOBJ
2691 && pBundle->aMem[i].MapObjR3 != NIL_RTR0MEMOBJ
2692 && RTR0MemObjAddressR3(pBundle->aMem[i].MapObjR3) == pvR3)
2693 {
2694 RTSpinlockRelease(pSession->Spinlock, &SpinlockTmp);
2695 return true;
2696 }
2697 }
2698 }
2699 }
2700 RTSpinlockRelease(pSession->Spinlock, &SpinlockTmp);
2701 return false;
2702}
2703
2704
2705/**
2706 * Get the physical addresses of memory allocated using SUPR0PageAllocEx().
2707 *
2708 * This function will be removed along with the lock/unlock hacks when
2709 * we've cleaned up the ring-3 code properly.
2710 *
2711 * @returns IPRT status code.
2712 * @param pSession The session to which the memory was allocated.
2713 * @param pvR3 The Ring-3 address returned by SUPR0PageAlloc().
2714 * @param cPages Number of pages in paPages
2715 * @param paPages Where to store the physical addresses.
2716 */
2717static int supdrvPageGetPhys(PSUPDRVSESSION pSession, RTR3PTR pvR3, uint32_t cPages, PRTHCPHYS paPages)
2718{
2719 PSUPDRVBUNDLE pBundle;
2720 RTSPINLOCKTMP SpinlockTmp = RTSPINLOCKTMP_INITIALIZER;
2721 LogFlow(("supdrvPageGetPhys: pSession=%p pvR3=%p cPages=%#lx paPages=%p\n", pSession, (void *)pvR3, (long)cPages, paPages));
2722
2723 /*
2724 * Search for the address.
2725 */
2726 RTSpinlockAcquire(pSession->Spinlock, &SpinlockTmp);
2727 for (pBundle = &pSession->Bundle; pBundle; pBundle = pBundle->pNext)
2728 {
2729 if (pBundle->cUsed > 0)
2730 {
2731 unsigned i;
2732 for (i = 0; i < RT_ELEMENTS(pBundle->aMem); i++)
2733 {
2734 if ( pBundle->aMem[i].eType == MEMREF_TYPE_PAGE
2735 && pBundle->aMem[i].MemObj != NIL_RTR0MEMOBJ
2736 && pBundle->aMem[i].MapObjR3 != NIL_RTR0MEMOBJ
2737 && RTR0MemObjAddressR3(pBundle->aMem[i].MapObjR3) == pvR3)
2738 {
2739 uint32_t iPage;
2740 size_t cMaxPages = RTR0MemObjSize(pBundle->aMem[i].MemObj) >> PAGE_SHIFT;
2741 cPages = (uint32_t)RT_MIN(cMaxPages, cPages);
2742 for (iPage = 0; iPage < cPages; iPage++)
2743 paPages[iPage] = RTR0MemObjGetPagePhysAddr(pBundle->aMem[i].MemObj, iPage);
2744 RTSpinlockRelease(pSession->Spinlock, &SpinlockTmp);
2745 return VINF_SUCCESS;
2746 }
2747 }
2748 }
2749 }
2750 RTSpinlockRelease(pSession->Spinlock, &SpinlockTmp);
2751 return VERR_INVALID_PARAMETER;
2752}
2753#endif /* RT_OS_WINDOWS */
2754
2755
2756/**
2757 * Free memory allocated by SUPR0PageAlloc() and SUPR0PageAllocEx().
2758 *
2759 * @returns IPRT status code.
2760 * @param pSession The session owning the allocation.
2761 * @param pvR3 The Ring-3 address returned by SUPR0PageAlloc() or
2762 * SUPR0PageAllocEx().
2763 */
2764SUPR0DECL(int) SUPR0PageFree(PSUPDRVSESSION pSession, RTR3PTR pvR3)
2765{
2766 LogFlow(("SUPR0PageFree: pSession=%p pvR3=%p\n", pSession, (void *)pvR3));
2767 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
2768 return supdrvMemRelease(pSession, (RTHCUINTPTR)pvR3, MEMREF_TYPE_PAGE);
2769}
2770
2771
2772/**
2773 * Maps the GIP into userspace and/or get the physical address of the GIP.
2774 *
2775 * @returns IPRT status code.
2776 * @param pSession Session to which the GIP mapping should belong.
2777 * @param ppGipR3 Where to store the address of the ring-3 mapping. (optional)
2778 * @param pHCPhysGip Where to store the physical address. (optional)
2779 *
2780 * @remark There is no reference counting on the mapping, so one call to this function
2781 * count globally as one reference. One call to SUPR0GipUnmap() is will unmap GIP
2782 * and remove the session as a GIP user.
2783 */
2784SUPR0DECL(int) SUPR0GipMap(PSUPDRVSESSION pSession, PRTR3PTR ppGipR3, PRTHCPHYS pHCPhysGip)
2785{
2786 int rc = 0;
2787 PSUPDRVDEVEXT pDevExt = pSession->pDevExt;
2788 RTR3PTR pGip = NIL_RTR3PTR;
2789 RTHCPHYS HCPhys = NIL_RTHCPHYS;
2790 LogFlow(("SUPR0GipMap: pSession=%p ppGipR3=%p pHCPhysGip=%p\n", pSession, ppGipR3, pHCPhysGip));
2791
2792 /*
2793 * Validate
2794 */
2795 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
2796 AssertPtrNullReturn(ppGipR3, VERR_INVALID_POINTER);
2797 AssertPtrNullReturn(pHCPhysGip, VERR_INVALID_POINTER);
2798
2799 RTSemFastMutexRequest(pDevExt->mtxGip);
2800 if (pDevExt->pGip)
2801 {
2802 /*
2803 * Map it?
2804 */
2805 if (ppGipR3)
2806 {
2807 if (pSession->GipMapObjR3 == NIL_RTR0MEMOBJ)
2808 rc = RTR0MemObjMapUser(&pSession->GipMapObjR3, pDevExt->GipMemObj, (RTR3PTR)-1, 0,
2809 RTMEM_PROT_READ, RTR0ProcHandleSelf());
2810 if (RT_SUCCESS(rc))
2811 {
2812 pGip = RTR0MemObjAddressR3(pSession->GipMapObjR3);
2813 rc = VINF_SUCCESS; /** @todo remove this and replace the !rc below with RT_SUCCESS(rc). */
2814 }
2815 }
2816
2817 /*
2818 * Get physical address.
2819 */
2820 if (pHCPhysGip && !rc)
2821 HCPhys = pDevExt->HCPhysGip;
2822
2823 /*
2824 * Reference globally.
2825 */
2826 if (!pSession->fGipReferenced && !rc)
2827 {
2828 pSession->fGipReferenced = 1;
2829 pDevExt->cGipUsers++;
2830 if (pDevExt->cGipUsers == 1)
2831 {
2832 PSUPGLOBALINFOPAGE pGip = pDevExt->pGip;
2833 unsigned i;
2834
2835 LogFlow(("SUPR0GipMap: Resumes GIP updating\n"));
2836
2837 for (i = 0; i < RT_ELEMENTS(pGip->aCPUs); i++)
2838 ASMAtomicXchgU32(&pGip->aCPUs[i].u32TransactionId, pGip->aCPUs[i].u32TransactionId & ~(GIP_UPDATEHZ_RECALC_FREQ * 2 - 1));
2839 ASMAtomicXchgU64(&pGip->u64NanoTSLastUpdateHz, 0);
2840
2841 rc = RTTimerStart(pDevExt->pGipTimer, 0);
2842 AssertRC(rc); rc = VINF_SUCCESS;
2843 }
2844 }
2845 }
2846 else
2847 {
2848 rc = SUPDRV_ERR_GENERAL_FAILURE;
2849 Log(("SUPR0GipMap: GIP is not available!\n"));
2850 }
2851 RTSemFastMutexRelease(pDevExt->mtxGip);
2852
2853 /*
2854 * Write returns.
2855 */
2856 if (pHCPhysGip)
2857 *pHCPhysGip = HCPhys;
2858 if (ppGipR3)
2859 *ppGipR3 = pGip;
2860
2861#ifdef DEBUG_DARWIN_GIP
2862 OSDBGPRINT(("SUPR0GipMap: returns %d *pHCPhysGip=%lx *ppGip=%p GipMapObjR3\n", rc, (unsigned long)HCPhys, pGip, pSession->GipMapObjR3));
2863#else
2864 LogFlow(("SUPR0GipMap: returns %d *pHCPhysGip=%lx *ppGipR3=%p\n", rc, (unsigned long)HCPhys, (void *)(uintptr_t)pGip));
2865#endif
2866 return rc;
2867}
2868
2869
2870/**
2871 * Unmaps any user mapping of the GIP and terminates all GIP access
2872 * from this session.
2873 *
2874 * @returns IPRT status code.
2875 * @param pSession Session to which the GIP mapping should belong.
2876 */
2877SUPR0DECL(int) SUPR0GipUnmap(PSUPDRVSESSION pSession)
2878{
2879 int rc = VINF_SUCCESS;
2880 PSUPDRVDEVEXT pDevExt = pSession->pDevExt;
2881#ifdef DEBUG_DARWIN_GIP
2882 OSDBGPRINT(("SUPR0GipUnmap: pSession=%p pGip=%p GipMapObjR3=%p\n",
2883 pSession,
2884 pSession->GipMapObjR3 != NIL_RTR0MEMOBJ ? RTR0MemObjAddress(pSession->GipMapObjR3) : NULL,
2885 pSession->GipMapObjR3));
2886#else
2887 LogFlow(("SUPR0GipUnmap: pSession=%p\n", pSession));
2888#endif
2889 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
2890
2891 RTSemFastMutexRequest(pDevExt->mtxGip);
2892
2893 /*
2894 * Unmap anything?
2895 */
2896 if (pSession->GipMapObjR3 != NIL_RTR0MEMOBJ)
2897 {
2898 rc = RTR0MemObjFree(pSession->GipMapObjR3, false);
2899 AssertRC(rc);
2900 if (RT_SUCCESS(rc))
2901 pSession->GipMapObjR3 = NIL_RTR0MEMOBJ;
2902 }
2903
2904 /*
2905 * Dereference global GIP.
2906 */
2907 if (pSession->fGipReferenced && !rc)
2908 {
2909 pSession->fGipReferenced = 0;
2910 if ( pDevExt->cGipUsers > 0
2911 && !--pDevExt->cGipUsers)
2912 {
2913 LogFlow(("SUPR0GipUnmap: Suspends GIP updating\n"));
2914 rc = RTTimerStop(pDevExt->pGipTimer); AssertRC(rc); rc = 0;
2915 }
2916 }
2917
2918 RTSemFastMutexRelease(pDevExt->mtxGip);
2919
2920 return rc;
2921}
2922
2923
2924/**
2925 * Register a component factory with the support driver.
2926 *
2927 * This is currently restricted to kernel sessions only.
2928 *
2929 * @returns VBox status code.
2930 * @retval VINF_SUCCESS on success.
2931 * @retval VERR_NO_MEMORY if we're out of memory.
2932 * @retval VERR_ALREADY_EXISTS if the factory has already been registered.
2933 * @retval VERR_ACCESS_DENIED if it isn't a kernel session.
2934 * @retval VERR_INVALID_PARAMETER on invalid parameter.
2935 * @retval VERR_INVALID_POINTER on invalid pointer parameter.
2936 *
2937 * @param pSession The SUPDRV session (must be a ring-0 session).
2938 * @param pFactory Pointer to the component factory registration structure.
2939 *
2940 * @remarks This interface is also available via SUPR0IdcComponentRegisterFactory.
2941 */
2942SUPR0DECL(int) SUPR0ComponentRegisterFactory(PSUPDRVSESSION pSession, PCSUPDRVFACTORY pFactory)
2943{
2944 PSUPDRVFACTORYREG pNewReg;
2945 const char *psz;
2946 int rc;
2947
2948 /*
2949 * Validate parameters.
2950 */
2951 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
2952 AssertReturn(pSession->R0Process == NIL_RTR0PROCESS, VERR_ACCESS_DENIED);
2953 AssertPtrReturn(pFactory, VERR_INVALID_POINTER);
2954 AssertPtrReturn(pFactory->pfnQueryFactoryInterface, VERR_INVALID_POINTER);
2955 psz = (const char *)memchr(pFactory->szName, '\0', sizeof(pFactory->szName));
2956 AssertReturn(psz, VERR_INVALID_PARAMETER);
2957
2958 /*
2959 * Allocate and initialize a new registration structure.
2960 */
2961 pNewReg = (PSUPDRVFACTORYREG)RTMemAlloc(sizeof(SUPDRVFACTORYREG));
2962 if (pNewReg)
2963 {
2964 pNewReg->pNext = NULL;
2965 pNewReg->pFactory = pFactory;
2966 pNewReg->pSession = pSession;
2967 pNewReg->cchName = psz - &pFactory->szName[0];
2968
2969 /*
2970 * Add it to the tail of the list after checking for prior registration.
2971 */
2972 rc = RTSemFastMutexRequest(pSession->pDevExt->mtxComponentFactory);
2973 if (RT_SUCCESS(rc))
2974 {
2975 PSUPDRVFACTORYREG pPrev = NULL;
2976 PSUPDRVFACTORYREG pCur = pSession->pDevExt->pComponentFactoryHead;
2977 while (pCur && pCur->pFactory != pFactory)
2978 {
2979 pPrev = pCur;
2980 pCur = pCur->pNext;
2981 }
2982 if (!pCur)
2983 {
2984 if (pPrev)
2985 pPrev->pNext = pNewReg;
2986 else
2987 pSession->pDevExt->pComponentFactoryHead = pNewReg;
2988 rc = VINF_SUCCESS;
2989 }
2990 else
2991 rc = VERR_ALREADY_EXISTS;
2992
2993 RTSemFastMutexRelease(pSession->pDevExt->mtxComponentFactory);
2994 }
2995
2996 if (RT_FAILURE(rc))
2997 RTMemFree(pNewReg);
2998 }
2999 else
3000 rc = VERR_NO_MEMORY;
3001 return rc;
3002}
3003
3004
3005/**
3006 * Deregister a component factory.
3007 *
3008 * @returns VBox status code.
3009 * @retval VINF_SUCCESS on success.
3010 * @retval VERR_NOT_FOUND if the factory wasn't registered.
3011 * @retval VERR_ACCESS_DENIED if it isn't a kernel session.
3012 * @retval VERR_INVALID_PARAMETER on invalid parameter.
3013 * @retval VERR_INVALID_POINTER on invalid pointer parameter.
3014 *
3015 * @param pSession The SUPDRV session (must be a ring-0 session).
3016 * @param pFactory Pointer to the component factory registration structure
3017 * previously passed SUPR0ComponentRegisterFactory().
3018 *
3019 * @remarks This interface is also available via SUPR0IdcComponentDeregisterFactory.
3020 */
3021SUPR0DECL(int) SUPR0ComponentDeregisterFactory(PSUPDRVSESSION pSession, PCSUPDRVFACTORY pFactory)
3022{
3023 int rc;
3024
3025 /*
3026 * Validate parameters.
3027 */
3028 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
3029 AssertReturn(pSession->R0Process == NIL_RTR0PROCESS, VERR_ACCESS_DENIED);
3030 AssertPtrReturn(pFactory, VERR_INVALID_POINTER);
3031
3032 /*
3033 * Take the lock and look for the registration record.
3034 */
3035 rc = RTSemFastMutexRequest(pSession->pDevExt->mtxComponentFactory);
3036 if (RT_SUCCESS(rc))
3037 {
3038 PSUPDRVFACTORYREG pPrev = NULL;
3039 PSUPDRVFACTORYREG pCur = pSession->pDevExt->pComponentFactoryHead;
3040 while (pCur && pCur->pFactory != pFactory)
3041 {
3042 pPrev = pCur;
3043 pCur = pCur->pNext;
3044 }
3045 if (pCur)
3046 {
3047 if (!pPrev)
3048 pSession->pDevExt->pComponentFactoryHead = pCur->pNext;
3049 else
3050 pPrev->pNext = pCur->pNext;
3051
3052 pCur->pNext = NULL;
3053 pCur->pFactory = NULL;
3054 pCur->pSession = NULL;
3055 rc = VINF_SUCCESS;
3056 }
3057 else
3058 rc = VERR_NOT_FOUND;
3059
3060 RTSemFastMutexRelease(pSession->pDevExt->mtxComponentFactory);
3061
3062 RTMemFree(pCur);
3063 }
3064 return rc;
3065}
3066
3067
3068/**
3069 * Queries a component factory.
3070 *
3071 * @returns VBox status code.
3072 * @retval VERR_INVALID_PARAMETER on invalid parameter.
3073 * @retval VERR_INVALID_POINTER on invalid pointer parameter.
3074 * @retval VERR_SUPDRV_COMPONENT_NOT_FOUND if the component factory wasn't found.
3075 * @retval VERR_SUPDRV_INTERFACE_NOT_SUPPORTED if the interface wasn't supported.
3076 *
3077 * @param pSession The SUPDRV session.
3078 * @param pszName The name of the component factory.
3079 * @param pszInterfaceUuid The UUID of the factory interface (stringified).
3080 * @param ppvFactoryIf Where to store the factory interface.
3081 */
3082SUPR0DECL(int) SUPR0ComponentQueryFactory(PSUPDRVSESSION pSession, const char *pszName, const char *pszInterfaceUuid, void **ppvFactoryIf)
3083{
3084 const char *pszEnd;
3085 size_t cchName;
3086 int rc;
3087
3088 /*
3089 * Validate parameters.
3090 */
3091 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
3092
3093 AssertPtrReturn(pszName, VERR_INVALID_POINTER);
3094 pszEnd = memchr(pszName, '\0', RT_SIZEOFMEMB(SUPDRVFACTORY, szName));
3095 AssertReturn(pszEnd, VERR_INVALID_PARAMETER);
3096 cchName = pszEnd - pszName;
3097
3098 AssertPtrReturn(pszInterfaceUuid, VERR_INVALID_POINTER);
3099 pszEnd = memchr(pszInterfaceUuid, '\0', RTUUID_STR_LENGTH);
3100 AssertReturn(pszEnd, VERR_INVALID_PARAMETER);
3101
3102 AssertPtrReturn(ppvFactoryIf, VERR_INVALID_POINTER);
3103 *ppvFactoryIf = NULL;
3104
3105 /*
3106 * Take the lock and try all factories by this name.
3107 */
3108 rc = RTSemFastMutexRequest(pSession->pDevExt->mtxComponentFactory);
3109 if (RT_SUCCESS(rc))
3110 {
3111 PSUPDRVFACTORYREG pCur = pSession->pDevExt->pComponentFactoryHead;
3112 rc = VERR_SUPDRV_COMPONENT_NOT_FOUND;
3113 while (pCur)
3114 {
3115 if ( pCur->cchName == cchName
3116 && !memcmp(pCur->pFactory->szName, pszName, cchName))
3117 {
3118#ifdef RT_WITH_W64_UNWIND_HACK
3119 void *pvFactory = supdrvNtWrapQueryFactoryInterface((PFNRT)pCur->pFactory->pfnQueryFactoryInterface, pCur->pFactory, pSession, pszInterfaceUuid);
3120#else
3121 void *pvFactory = pCur->pFactory->pfnQueryFactoryInterface(pCur->pFactory, pSession, pszInterfaceUuid);
3122#endif
3123 if (pvFactory)
3124 {
3125 *ppvFactoryIf = pvFactory;
3126 rc = VINF_SUCCESS;
3127 break;
3128 }
3129 rc = VERR_SUPDRV_INTERFACE_NOT_SUPPORTED;
3130 }
3131
3132 /* next */
3133 pCur = pCur->pNext;
3134 }
3135
3136 RTSemFastMutexRelease(pSession->pDevExt->mtxComponentFactory);
3137 }
3138 return rc;
3139}
3140
3141
3142/**
3143 * Adds a memory object to the session.
3144 *
3145 * @returns IPRT status code.
3146 * @param pMem Memory tracking structure containing the
3147 * information to track.
3148 * @param pSession The session.
3149 */
3150static int supdrvMemAdd(PSUPDRVMEMREF pMem, PSUPDRVSESSION pSession)
3151{
3152 PSUPDRVBUNDLE pBundle;
3153 RTSPINLOCKTMP SpinlockTmp = RTSPINLOCKTMP_INITIALIZER;
3154
3155 /*
3156 * Find free entry and record the allocation.
3157 */
3158 RTSpinlockAcquire(pSession->Spinlock, &SpinlockTmp);
3159 for (pBundle = &pSession->Bundle; pBundle; pBundle = pBundle->pNext)
3160 {
3161 if (pBundle->cUsed < RT_ELEMENTS(pBundle->aMem))
3162 {
3163 unsigned i;
3164 for (i = 0; i < RT_ELEMENTS(pBundle->aMem); i++)
3165 {
3166 if (pBundle->aMem[i].MemObj == NIL_RTR0MEMOBJ)
3167 {
3168 pBundle->cUsed++;
3169 pBundle->aMem[i] = *pMem;
3170 RTSpinlockRelease(pSession->Spinlock, &SpinlockTmp);
3171 return VINF_SUCCESS;
3172 }
3173 }
3174 AssertFailed(); /* !!this can't be happening!!! */
3175 }
3176 }
3177 RTSpinlockRelease(pSession->Spinlock, &SpinlockTmp);
3178
3179 /*
3180 * Need to allocate a new bundle.
3181 * Insert into the last entry in the bundle.
3182 */
3183 pBundle = (PSUPDRVBUNDLE)RTMemAllocZ(sizeof(*pBundle));
3184 if (!pBundle)
3185 return VERR_NO_MEMORY;
3186
3187 /* take last entry. */
3188 pBundle->cUsed++;
3189 pBundle->aMem[RT_ELEMENTS(pBundle->aMem) - 1] = *pMem;
3190
3191 /* insert into list. */
3192 RTSpinlockAcquire(pSession->Spinlock, &SpinlockTmp);
3193 pBundle->pNext = pSession->Bundle.pNext;
3194 pSession->Bundle.pNext = pBundle;
3195 RTSpinlockRelease(pSession->Spinlock, &SpinlockTmp);
3196
3197 return VINF_SUCCESS;
3198}
3199
3200
3201/**
3202 * Releases a memory object referenced by pointer and type.
3203 *
3204 * @returns IPRT status code.
3205 * @param pSession Session data.
3206 * @param uPtr Pointer to memory. This is matched against both the R0 and R3 addresses.
3207 * @param eType Memory type.
3208 */
3209static int supdrvMemRelease(PSUPDRVSESSION pSession, RTHCUINTPTR uPtr, SUPDRVMEMREFTYPE eType)
3210{
3211 PSUPDRVBUNDLE pBundle;
3212 RTSPINLOCKTMP SpinlockTmp = RTSPINLOCKTMP_INITIALIZER;
3213
3214 /*
3215 * Validate input.
3216 */
3217 if (!uPtr)
3218 {
3219 Log(("Illegal address %p\n", (void *)uPtr));
3220 return VERR_INVALID_PARAMETER;
3221 }
3222
3223 /*
3224 * Search for the address.
3225 */
3226 RTSpinlockAcquire(pSession->Spinlock, &SpinlockTmp);
3227 for (pBundle = &pSession->Bundle; pBundle; pBundle = pBundle->pNext)
3228 {
3229 if (pBundle->cUsed > 0)
3230 {
3231 unsigned i;
3232 for (i = 0; i < RT_ELEMENTS(pBundle->aMem); i++)
3233 {
3234 if ( pBundle->aMem[i].eType == eType
3235 && pBundle->aMem[i].MemObj != NIL_RTR0MEMOBJ
3236 && ( (RTHCUINTPTR)RTR0MemObjAddress(pBundle->aMem[i].MemObj) == uPtr
3237 || ( pBundle->aMem[i].MapObjR3 != NIL_RTR0MEMOBJ
3238 && RTR0MemObjAddressR3(pBundle->aMem[i].MapObjR3) == uPtr))
3239 )
3240 {
3241 /* Make a copy of it and release it outside the spinlock. */
3242 SUPDRVMEMREF Mem = pBundle->aMem[i];
3243 pBundle->aMem[i].eType = MEMREF_TYPE_UNUSED;
3244 pBundle->aMem[i].MemObj = NIL_RTR0MEMOBJ;
3245 pBundle->aMem[i].MapObjR3 = NIL_RTR0MEMOBJ;
3246 RTSpinlockRelease(pSession->Spinlock, &SpinlockTmp);
3247
3248 if (Mem.MapObjR3 != NIL_RTR0MEMOBJ)
3249 {
3250 int rc = RTR0MemObjFree(Mem.MapObjR3, false);
3251 AssertRC(rc); /** @todo figure out how to handle this. */
3252 }
3253 if (Mem.MemObj != NIL_RTR0MEMOBJ)
3254 {
3255 int rc = RTR0MemObjFree(Mem.MemObj, true /* fFreeMappings */);
3256 AssertRC(rc); /** @todo figure out how to handle this. */
3257 }
3258 return VINF_SUCCESS;
3259 }
3260 }
3261 }
3262 }
3263 RTSpinlockRelease(pSession->Spinlock, &SpinlockTmp);
3264 Log(("Failed to find %p!!! (eType=%d)\n", (void *)uPtr, eType));
3265 return VERR_INVALID_PARAMETER;
3266}
3267
3268
3269/**
3270 * Opens an image. If it's the first time it's opened the call must upload
3271 * the bits using the supdrvIOCtl_LdrLoad() / SUPDRV_IOCTL_LDR_LOAD function.
3272 *
3273 * This is the 1st step of the loading.
3274 *
3275 * @returns IPRT status code.
3276 * @param pDevExt Device globals.
3277 * @param pSession Session data.
3278 * @param pReq The open request.
3279 */
3280static int supdrvIOCtl_LdrOpen(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPLDROPEN pReq)
3281{
3282 PSUPDRVLDRIMAGE pImage;
3283 unsigned cb;
3284 void *pv;
3285 LogFlow(("supdrvIOCtl_LdrOpen: szName=%s cbImage=%d\n", pReq->u.In.szName, pReq->u.In.cbImage));
3286
3287 /*
3288 * Check if we got an instance of the image already.
3289 */
3290 RTSemFastMutexRequest(pDevExt->mtxLdr);
3291 for (pImage = pDevExt->pLdrImages; pImage; pImage = pImage->pNext)
3292 {
3293 if (!strcmp(pImage->szName, pReq->u.In.szName))
3294 {
3295 pImage->cUsage++;
3296 pReq->u.Out.pvImageBase = pImage->pvImage;
3297 pReq->u.Out.fNeedsLoading = pImage->uState == SUP_IOCTL_LDR_OPEN;
3298 supdrvLdrAddUsage(pSession, pImage);
3299 RTSemFastMutexRelease(pDevExt->mtxLdr);
3300 return VINF_SUCCESS;
3301 }
3302 }
3303 /* (not found - add it!) */
3304
3305 /*
3306 * Allocate memory.
3307 */
3308 cb = pReq->u.In.cbImage + sizeof(SUPDRVLDRIMAGE) + 31;
3309 pv = RTMemExecAlloc(cb);
3310 if (!pv)
3311 {
3312 RTSemFastMutexRelease(pDevExt->mtxLdr);
3313 Log(("supdrvIOCtl_LdrOpen: RTMemExecAlloc(%u) failed\n", cb));
3314 return VERR_NO_MEMORY;
3315 }
3316
3317 /*
3318 * Setup and link in the LDR stuff.
3319 */
3320 pImage = (PSUPDRVLDRIMAGE)pv;
3321 pImage->pvImage = RT_ALIGN_P(pImage + 1, 32);
3322 pImage->cbImage = pReq->u.In.cbImage;
3323 pImage->pfnModuleInit = NULL;
3324 pImage->pfnModuleTerm = NULL;
3325 pImage->pfnServiceReqHandler = NULL;
3326 pImage->uState = SUP_IOCTL_LDR_OPEN;
3327 pImage->cUsage = 1;
3328 strcpy(pImage->szName, pReq->u.In.szName);
3329
3330 pImage->pNext = pDevExt->pLdrImages;
3331 pDevExt->pLdrImages = pImage;
3332
3333 supdrvLdrAddUsage(pSession, pImage);
3334
3335 pReq->u.Out.pvImageBase = pImage->pvImage;
3336 pReq->u.Out.fNeedsLoading = true;
3337 RTSemFastMutexRelease(pDevExt->mtxLdr);
3338
3339#if defined(RT_OS_WINDOWS) && defined(DEBUG)
3340 SUPR0Printf("VBoxDrv: windbg> .reload /f %s=%#p\n", pImage->szName, pImage->pvImage);
3341#endif
3342 return VINF_SUCCESS;
3343}
3344
3345
3346/**
3347 * Loads the image bits.
3348 *
3349 * This is the 2nd step of the loading.
3350 *
3351 * @returns IPRT status code.
3352 * @param pDevExt Device globals.
3353 * @param pSession Session data.
3354 * @param pReq The request.
3355 */
3356static int supdrvIOCtl_LdrLoad(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPLDRLOAD pReq)
3357{
3358 PSUPDRVLDRUSAGE pUsage;
3359 PSUPDRVLDRIMAGE pImage;
3360 int rc;
3361 LogFlow(("supdrvIOCtl_LdrLoad: pvImageBase=%p cbImage=%d\n", pReq->u.In.pvImageBase, pReq->u.In.cbImage));
3362
3363 /*
3364 * Find the ldr image.
3365 */
3366 RTSemFastMutexRequest(pDevExt->mtxLdr);
3367 pUsage = pSession->pLdrUsage;
3368 while (pUsage && pUsage->pImage->pvImage != pReq->u.In.pvImageBase)
3369 pUsage = pUsage->pNext;
3370 if (!pUsage)
3371 {
3372 RTSemFastMutexRelease(pDevExt->mtxLdr);
3373 Log(("SUP_IOCTL_LDR_LOAD: couldn't find image!\n"));
3374 return VERR_INVALID_HANDLE;
3375 }
3376 pImage = pUsage->pImage;
3377 if (pImage->cbImage != pReq->u.In.cbImage)
3378 {
3379 RTSemFastMutexRelease(pDevExt->mtxLdr);
3380 Log(("SUP_IOCTL_LDR_LOAD: image size mismatch!! %d(prep) != %d(load)\n", pImage->cbImage, pReq->u.In.cbImage));
3381 return VERR_INVALID_HANDLE;
3382 }
3383 if (pImage->uState != SUP_IOCTL_LDR_OPEN)
3384 {
3385 unsigned uState = pImage->uState;
3386 RTSemFastMutexRelease(pDevExt->mtxLdr);
3387 if (uState != SUP_IOCTL_LDR_LOAD)
3388 AssertMsgFailed(("SUP_IOCTL_LDR_LOAD: invalid image state %d (%#x)!\n", uState, uState));
3389 return SUPDRV_ERR_ALREADY_LOADED;
3390 }
3391 switch (pReq->u.In.eEPType)
3392 {
3393 case SUPLDRLOADEP_NOTHING:
3394 break;
3395
3396 case SUPLDRLOADEP_VMMR0:
3397 if ( !pReq->u.In.EP.VMMR0.pvVMMR0
3398 || !pReq->u.In.EP.VMMR0.pvVMMR0EntryInt
3399 || !pReq->u.In.EP.VMMR0.pvVMMR0EntryFast
3400 || !pReq->u.In.EP.VMMR0.pvVMMR0EntryEx)
3401 {
3402 RTSemFastMutexRelease(pDevExt->mtxLdr);
3403 Log(("NULL pointer: pvVMMR0=%p pvVMMR0EntryInt=%p pvVMMR0EntryFast=%p pvVMMR0EntryEx=%p!\n",
3404 pReq->u.In.EP.VMMR0.pvVMMR0, pReq->u.In.EP.VMMR0.pvVMMR0EntryInt,
3405 pReq->u.In.EP.VMMR0.pvVMMR0EntryFast, pReq->u.In.EP.VMMR0.pvVMMR0EntryEx));
3406 return VERR_INVALID_PARAMETER;
3407 }
3408 /** @todo validate pReq->u.In.EP.VMMR0.pvVMMR0 against pvImage! */
3409 if ( (uintptr_t)pReq->u.In.EP.VMMR0.pvVMMR0EntryInt - (uintptr_t)pImage->pvImage >= pReq->u.In.cbImage
3410 || (uintptr_t)pReq->u.In.EP.VMMR0.pvVMMR0EntryFast - (uintptr_t)pImage->pvImage >= pReq->u.In.cbImage
3411 || (uintptr_t)pReq->u.In.EP.VMMR0.pvVMMR0EntryEx - (uintptr_t)pImage->pvImage >= pReq->u.In.cbImage)
3412 {
3413 RTSemFastMutexRelease(pDevExt->mtxLdr);
3414 Log(("Out of range (%p LB %#x): pvVMMR0EntryInt=%p, pvVMMR0EntryFast=%p or pvVMMR0EntryEx=%p is NULL!\n",
3415 pImage->pvImage, pReq->u.In.cbImage, pReq->u.In.EP.VMMR0.pvVMMR0EntryInt,
3416 pReq->u.In.EP.VMMR0.pvVMMR0EntryFast, pReq->u.In.EP.VMMR0.pvVMMR0EntryEx));
3417 return VERR_INVALID_PARAMETER;
3418 }
3419 break;
3420
3421 case SUPLDRLOADEP_SERVICE:
3422 if (!pReq->u.In.EP.Service.pfnServiceReq)
3423 {
3424 RTSemFastMutexRelease(pDevExt->mtxLdr);
3425 Log(("NULL pointer: pfnServiceReq=%p!\n", pReq->u.In.EP.Service.pfnServiceReq));
3426 return VERR_INVALID_PARAMETER;
3427 }
3428 if ((uintptr_t)pReq->u.In.EP.Service.pfnServiceReq - (uintptr_t)pImage->pvImage >= pReq->u.In.cbImage)
3429 {
3430 RTSemFastMutexRelease(pDevExt->mtxLdr);
3431 Log(("Out of range (%p LB %#x): pfnServiceReq=%p, pvVMMR0EntryFast=%p or pvVMMR0EntryEx=%p is NULL!\n",
3432 pImage->pvImage, pReq->u.In.cbImage, pReq->u.In.EP.Service.pfnServiceReq));
3433 return VERR_INVALID_PARAMETER;
3434 }
3435 if ( pReq->u.In.EP.Service.apvReserved[0] != NIL_RTR0PTR
3436 || pReq->u.In.EP.Service.apvReserved[1] != NIL_RTR0PTR
3437 || pReq->u.In.EP.Service.apvReserved[2] != NIL_RTR0PTR)
3438 {
3439 RTSemFastMutexRelease(pDevExt->mtxLdr);
3440 Log(("Out of range (%p LB %#x): apvReserved={%p,%p,%p} MBZ!\n",
3441 pImage->pvImage, pReq->u.In.cbImage,
3442 pReq->u.In.EP.Service.apvReserved[0],
3443 pReq->u.In.EP.Service.apvReserved[1],
3444 pReq->u.In.EP.Service.apvReserved[2]));
3445 return VERR_INVALID_PARAMETER;
3446 }
3447 break;
3448
3449 default:
3450 RTSemFastMutexRelease(pDevExt->mtxLdr);
3451 Log(("Invalid eEPType=%d\n", pReq->u.In.eEPType));
3452 return VERR_INVALID_PARAMETER;
3453 }
3454 if ( pReq->u.In.pfnModuleInit
3455 && (uintptr_t)pReq->u.In.pfnModuleInit - (uintptr_t)pImage->pvImage >= pReq->u.In.cbImage)
3456 {
3457 RTSemFastMutexRelease(pDevExt->mtxLdr);
3458 Log(("SUP_IOCTL_LDR_LOAD: pfnModuleInit=%p is outside the image (%p %d bytes)\n",
3459 pReq->u.In.pfnModuleInit, pImage->pvImage, pReq->u.In.cbImage));
3460 return VERR_INVALID_PARAMETER;
3461 }
3462 if ( pReq->u.In.pfnModuleTerm
3463 && (uintptr_t)pReq->u.In.pfnModuleTerm - (uintptr_t)pImage->pvImage >= pReq->u.In.cbImage)
3464 {
3465 RTSemFastMutexRelease(pDevExt->mtxLdr);
3466 Log(("SUP_IOCTL_LDR_LOAD: pfnModuleTerm=%p is outside the image (%p %d bytes)\n",
3467 pReq->u.In.pfnModuleTerm, pImage->pvImage, pReq->u.In.cbImage));
3468 return VERR_INVALID_PARAMETER;
3469 }
3470
3471 /*
3472 * Copy the memory.
3473 */
3474 /* no need to do try/except as this is a buffered request. */
3475 memcpy(pImage->pvImage, &pReq->u.In.achImage[0], pImage->cbImage);
3476 pImage->uState = SUP_IOCTL_LDR_LOAD;
3477 pImage->pfnModuleInit = pReq->u.In.pfnModuleInit;
3478 pImage->pfnModuleTerm = pReq->u.In.pfnModuleTerm;
3479 pImage->offSymbols = pReq->u.In.offSymbols;
3480 pImage->cSymbols = pReq->u.In.cSymbols;
3481 pImage->offStrTab = pReq->u.In.offStrTab;
3482 pImage->cbStrTab = pReq->u.In.cbStrTab;
3483
3484 /*
3485 * Update any entry points.
3486 */
3487 switch (pReq->u.In.eEPType)
3488 {
3489 default:
3490 case SUPLDRLOADEP_NOTHING:
3491 rc = VINF_SUCCESS;
3492 break;
3493 case SUPLDRLOADEP_VMMR0:
3494 rc = supdrvLdrSetVMMR0EPs(pDevExt, pReq->u.In.EP.VMMR0.pvVMMR0, pReq->u.In.EP.VMMR0.pvVMMR0EntryInt,
3495 pReq->u.In.EP.VMMR0.pvVMMR0EntryFast, pReq->u.In.EP.VMMR0.pvVMMR0EntryEx);
3496 break;
3497 case SUPLDRLOADEP_SERVICE:
3498 pImage->pfnServiceReqHandler = pReq->u.In.EP.Service.pfnServiceReq;
3499 rc = VINF_SUCCESS;
3500 break;
3501 }
3502
3503 /*
3504 * On success call the module initialization.
3505 */
3506 LogFlow(("supdrvIOCtl_LdrLoad: pfnModuleInit=%p\n", pImage->pfnModuleInit));
3507 if (RT_SUCCESS(rc) && pImage->pfnModuleInit)
3508 {
3509 Log(("supdrvIOCtl_LdrLoad: calling pfnModuleInit=%p\n", pImage->pfnModuleInit));
3510#ifdef RT_WITH_W64_UNWIND_HACK
3511 rc = supdrvNtWrapModuleInit((PFNRT)pImage->pfnModuleInit);
3512#else
3513 rc = pImage->pfnModuleInit();
3514#endif
3515 if (rc && pDevExt->pvVMMR0 == pImage->pvImage)
3516 supdrvLdrUnsetVMMR0EPs(pDevExt);
3517 }
3518
3519 if (rc)
3520 pImage->uState = SUP_IOCTL_LDR_OPEN;
3521
3522 RTSemFastMutexRelease(pDevExt->mtxLdr);
3523 return rc;
3524}
3525
3526
3527/**
3528 * Frees a previously loaded (prep'ed) image.
3529 *
3530 * @returns IPRT status code.
3531 * @param pDevExt Device globals.
3532 * @param pSession Session data.
3533 * @param pReq The request.
3534 */
3535static int supdrvIOCtl_LdrFree(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPLDRFREE pReq)
3536{
3537 int rc;
3538 PSUPDRVLDRUSAGE pUsagePrev;
3539 PSUPDRVLDRUSAGE pUsage;
3540 PSUPDRVLDRIMAGE pImage;
3541 LogFlow(("supdrvIOCtl_LdrFree: pvImageBase=%p\n", pReq->u.In.pvImageBase));
3542
3543 /*
3544 * Find the ldr image.
3545 */
3546 RTSemFastMutexRequest(pDevExt->mtxLdr);
3547 pUsagePrev = NULL;
3548 pUsage = pSession->pLdrUsage;
3549 while (pUsage && pUsage->pImage->pvImage != pReq->u.In.pvImageBase)
3550 {
3551 pUsagePrev = pUsage;
3552 pUsage = pUsage->pNext;
3553 }
3554 if (!pUsage)
3555 {
3556 RTSemFastMutexRelease(pDevExt->mtxLdr);
3557 Log(("SUP_IOCTL_LDR_FREE: couldn't find image!\n"));
3558 return VERR_INVALID_HANDLE;
3559 }
3560
3561 /*
3562 * Check if we can remove anything.
3563 */
3564 rc = VINF_SUCCESS;
3565 pImage = pUsage->pImage;
3566 if (pImage->cUsage <= 1 || pUsage->cUsage <= 1)
3567 {
3568 /*
3569 * Check if there are any objects with destructors in the image, if
3570 * so leave it for the session cleanup routine so we get a chance to
3571 * clean things up in the right order and not leave them all dangling.
3572 */
3573 RTSPINLOCKTMP SpinlockTmp = RTSPINLOCKTMP_INITIALIZER;
3574 RTSpinlockAcquire(pDevExt->Spinlock, &SpinlockTmp);
3575 if (pImage->cUsage <= 1)
3576 {
3577 PSUPDRVOBJ pObj;
3578 for (pObj = pDevExt->pObjs; pObj; pObj = pObj->pNext)
3579 if (RT_UNLIKELY((uintptr_t)pObj->pfnDestructor - (uintptr_t)pImage->pvImage < pImage->cbImage))
3580 {
3581 rc = VERR_DANGLING_OBJECTS;
3582 break;
3583 }
3584 }
3585 else
3586 {
3587 PSUPDRVUSAGE pGenUsage;
3588 for (pGenUsage = pSession->pUsage; pGenUsage; pGenUsage = pGenUsage->pNext)
3589 if (RT_UNLIKELY((uintptr_t)pGenUsage->pObj->pfnDestructor - (uintptr_t)pImage->pvImage < pImage->cbImage))
3590 {
3591 rc = VERR_DANGLING_OBJECTS;
3592 break;
3593 }
3594 }
3595 RTSpinlockRelease(pDevExt->Spinlock, &SpinlockTmp);
3596 if (rc == VINF_SUCCESS)
3597 {
3598 /* unlink it */
3599 if (pUsagePrev)
3600 pUsagePrev->pNext = pUsage->pNext;
3601 else
3602 pSession->pLdrUsage = pUsage->pNext;
3603
3604 /* free it */
3605 pUsage->pImage = NULL;
3606 pUsage->pNext = NULL;
3607 RTMemFree(pUsage);
3608
3609 /*
3610 * Derefrence the image.
3611 */
3612 if (pImage->cUsage <= 1)
3613 supdrvLdrFree(pDevExt, pImage);
3614 else
3615 pImage->cUsage--;
3616 }
3617 else
3618 {
3619 Log(("supdrvIOCtl_LdrFree: Dangling objects in %p/%s!\n", pImage->pvImage, pImage->szName));
3620 rc = VINF_SUCCESS; /** @todo BRANCH-2.1: remove this after branching. */
3621 }
3622 }
3623 else
3624 {
3625 /*
3626 * Dereference both image and usage.
3627 */
3628 pImage->cUsage--;
3629 pUsage->cUsage--;
3630 }
3631
3632 RTSemFastMutexRelease(pDevExt->mtxLdr);
3633 return rc;
3634}
3635
3636
3637/**
3638 * Gets the address of a symbol in an open image.
3639 *
3640 * @returns 0 on success.
3641 * @returns SUPDRV_ERR_* on failure.
3642 * @param pDevExt Device globals.
3643 * @param pSession Session data.
3644 * @param pReq The request buffer.
3645 */
3646static int supdrvIOCtl_LdrGetSymbol(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPLDRGETSYMBOL pReq)
3647{
3648 PSUPDRVLDRIMAGE pImage;
3649 PSUPDRVLDRUSAGE pUsage;
3650 uint32_t i;
3651 PSUPLDRSYM paSyms;
3652 const char *pchStrings;
3653 const size_t cbSymbol = strlen(pReq->u.In.szSymbol) + 1;
3654 void *pvSymbol = NULL;
3655 int rc = VERR_GENERAL_FAILURE;
3656 Log3(("supdrvIOCtl_LdrGetSymbol: pvImageBase=%p szSymbol=\"%s\"\n", pReq->u.In.pvImageBase, pReq->u.In.szSymbol));
3657
3658 /*
3659 * Find the ldr image.
3660 */
3661 RTSemFastMutexRequest(pDevExt->mtxLdr);
3662 pUsage = pSession->pLdrUsage;
3663 while (pUsage && pUsage->pImage->pvImage != pReq->u.In.pvImageBase)
3664 pUsage = pUsage->pNext;
3665 if (!pUsage)
3666 {
3667 RTSemFastMutexRelease(pDevExt->mtxLdr);
3668 Log(("SUP_IOCTL_LDR_GET_SYMBOL: couldn't find image!\n"));
3669 return VERR_INVALID_HANDLE;
3670 }
3671 pImage = pUsage->pImage;
3672 if (pImage->uState != SUP_IOCTL_LDR_LOAD)
3673 {
3674 unsigned uState = pImage->uState;
3675 RTSemFastMutexRelease(pDevExt->mtxLdr);
3676 Log(("SUP_IOCTL_LDR_GET_SYMBOL: invalid image state %d (%#x)!\n", uState, uState)); NOREF(uState);
3677 return VERR_ALREADY_LOADED;
3678 }
3679
3680 /*
3681 * Search the symbol strings.
3682 */
3683 pchStrings = (const char *)((uint8_t *)pImage->pvImage + pImage->offStrTab);
3684 paSyms = (PSUPLDRSYM)((uint8_t *)pImage->pvImage + pImage->offSymbols);
3685 for (i = 0; i < pImage->cSymbols; i++)
3686 {
3687 if ( paSyms[i].offSymbol < pImage->cbImage /* paranoia */
3688 && paSyms[i].offName + cbSymbol <= pImage->cbStrTab
3689 && !memcmp(pchStrings + paSyms[i].offName, pReq->u.In.szSymbol, cbSymbol))
3690 {
3691 pvSymbol = (uint8_t *)pImage->pvImage + paSyms[i].offSymbol;
3692 rc = VINF_SUCCESS;
3693 break;
3694 }
3695 }
3696 RTSemFastMutexRelease(pDevExt->mtxLdr);
3697 pReq->u.Out.pvSymbol = pvSymbol;
3698 return rc;
3699}
3700
3701
3702/**
3703 * Gets the address of a symbol in an open image or the support driver.
3704 *
3705 * @returns VINF_SUCCESS on success.
3706 * @returns
3707 * @param pDevExt Device globals.
3708 * @param pSession Session data.
3709 * @param pReq The request buffer.
3710 */
3711static int supdrvIDC_LdrGetSymbol(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPDRVIDCREQGETSYM pReq)
3712{
3713 int rc = VINF_SUCCESS;
3714 const char *pszSymbol = pReq->u.In.pszSymbol;
3715 const char *pszModule = pReq->u.In.pszModule;
3716 size_t cbSymbol;
3717 char const *pszEnd;
3718 uint32_t i;
3719
3720 /*
3721 * Input validation.
3722 */
3723 AssertPtrReturn(pszSymbol, VERR_INVALID_POINTER);
3724 pszEnd = (char *)memchr(pszSymbol, '\0', 512);
3725 AssertReturn(pszEnd, VERR_INVALID_PARAMETER);
3726 cbSymbol = pszEnd - pszSymbol + 1;
3727
3728 if (pszModule)
3729 {
3730 AssertPtrReturn(pszModule, VERR_INVALID_POINTER);
3731 pszEnd = (char *)memchr(pszModule, '\0', 64);
3732 AssertReturn(pszEnd, VERR_INVALID_PARAMETER);
3733 }
3734 Log3(("supdrvIDC_LdrGetSymbol: pszModule=%p:{%s} pszSymbol=%p:{%s}\n", pszModule, pszModule, pszSymbol, pszSymbol));
3735
3736
3737 if ( !pszModule
3738 || !strcmp(pszModule, "SupDrv"))
3739 {
3740 /*
3741 * Search the support driver export table.
3742 */
3743 for (i = 0; i < RT_ELEMENTS(g_aFunctions); i++)
3744 if (!strcmp(g_aFunctions[i].szName, pszSymbol))
3745 {
3746 pReq->u.Out.pfnSymbol = g_aFunctions[i].pfn;
3747 break;
3748 }
3749 }
3750 else
3751 {
3752 /*
3753 * Find the loader image.
3754 */
3755 PSUPDRVLDRIMAGE pImage;
3756
3757 RTSemFastMutexRequest(pDevExt->mtxLdr);
3758
3759 for (pImage = pDevExt->pLdrImages; pImage; pImage = pImage->pNext)
3760 if (!strcmp(pImage->szName, pszModule))
3761 break;
3762 if (pImage && pImage->uState == SUP_IOCTL_LDR_LOAD)
3763 {
3764 /*
3765 * Search the symbol strings.
3766 */
3767 const char *pchStrings = (const char *)((uint8_t *)pImage->pvImage + pImage->offStrTab);
3768 PCSUPLDRSYM paSyms = (PCSUPLDRSYM)((uint8_t *)pImage->pvImage + pImage->offSymbols);
3769 for (i = 0; i < pImage->cSymbols; i++)
3770 {
3771 if ( paSyms[i].offSymbol < pImage->cbImage /* paranoia */
3772 && paSyms[i].offName + cbSymbol <= pImage->cbStrTab
3773 && !memcmp(pchStrings + paSyms[i].offName, pszSymbol, cbSymbol))
3774 {
3775 /*
3776 * Found it! Calc the symbol address and add a reference to the module.
3777 */
3778 pReq->u.Out.pfnSymbol = (PFNRT)((uint8_t *)pImage->pvImage + paSyms[i].offSymbol);
3779 rc = supdrvLdrAddUsage(pSession, pImage);
3780 break;
3781 }
3782 }
3783 }
3784 else
3785 rc = pImage ? VERR_WRONG_ORDER : VERR_MODULE_NOT_FOUND;
3786
3787 RTSemFastMutexRelease(pDevExt->mtxLdr);
3788 }
3789 return rc;
3790}
3791
3792
3793/**
3794 * Updates the VMMR0 entry point pointers.
3795 *
3796 * @returns IPRT status code.
3797 * @param pDevExt Device globals.
3798 * @param pSession Session data.
3799 * @param pVMMR0 VMMR0 image handle.
3800 * @param pvVMMR0EntryInt VMMR0EntryInt address.
3801 * @param pvVMMR0EntryFast VMMR0EntryFast address.
3802 * @param pvVMMR0EntryEx VMMR0EntryEx address.
3803 * @remark Caller must own the loader mutex.
3804 */
3805static int supdrvLdrSetVMMR0EPs(PSUPDRVDEVEXT pDevExt, void *pvVMMR0, void *pvVMMR0EntryInt, void *pvVMMR0EntryFast, void *pvVMMR0EntryEx)
3806{
3807 int rc = VINF_SUCCESS;
3808 LogFlow(("supdrvLdrSetR0EP pvVMMR0=%p pvVMMR0EntryInt=%p\n", pvVMMR0, pvVMMR0EntryInt));
3809
3810
3811 /*
3812 * Check if not yet set.
3813 */
3814 if (!pDevExt->pvVMMR0)
3815 {
3816 pDevExt->pvVMMR0 = pvVMMR0;
3817 pDevExt->pfnVMMR0EntryInt = pvVMMR0EntryInt;
3818 pDevExt->pfnVMMR0EntryFast = pvVMMR0EntryFast;
3819 pDevExt->pfnVMMR0EntryEx = pvVMMR0EntryEx;
3820 }
3821 else
3822 {
3823 /*
3824 * Return failure or success depending on whether the values match or not.
3825 */
3826 if ( pDevExt->pvVMMR0 != pvVMMR0
3827 || (void *)pDevExt->pfnVMMR0EntryInt != pvVMMR0EntryInt
3828 || (void *)pDevExt->pfnVMMR0EntryFast != pvVMMR0EntryFast
3829 || (void *)pDevExt->pfnVMMR0EntryEx != pvVMMR0EntryEx)
3830 {
3831 AssertMsgFailed(("SUP_IOCTL_LDR_SETR0EP: Already set pointing to a different module!\n"));
3832 rc = VERR_INVALID_PARAMETER;
3833 }
3834 }
3835 return rc;
3836}
3837
3838
3839/**
3840 * Unsets the VMMR0 entry point installed by supdrvLdrSetR0EP.
3841 *
3842 * @param pDevExt Device globals.
3843 */
3844static void supdrvLdrUnsetVMMR0EPs(PSUPDRVDEVEXT pDevExt)
3845{
3846 pDevExt->pvVMMR0 = NULL;
3847 pDevExt->pfnVMMR0EntryInt = NULL;
3848 pDevExt->pfnVMMR0EntryFast = NULL;
3849 pDevExt->pfnVMMR0EntryEx = NULL;
3850}
3851
3852
3853/**
3854 * Adds a usage reference in the specified session of an image.
3855 *
3856 * Called while owning the loader semaphore.
3857 *
3858 * @returns VINF_SUCCESS on success and VERR_NO_MEMORY on failure.
3859 * @param pSession Session in question.
3860 * @param pImage Image which the session is using.
3861 */
3862static int supdrvLdrAddUsage(PSUPDRVSESSION pSession, PSUPDRVLDRIMAGE pImage)
3863{
3864 PSUPDRVLDRUSAGE pUsage;
3865 LogFlow(("supdrvLdrAddUsage: pImage=%p\n", pImage));
3866
3867 /*
3868 * Referenced it already?
3869 */
3870 pUsage = pSession->pLdrUsage;
3871 while (pUsage)
3872 {
3873 if (pUsage->pImage == pImage)
3874 {
3875 pUsage->cUsage++;
3876 return VINF_SUCCESS;
3877 }
3878 pUsage = pUsage->pNext;
3879 }
3880
3881 /*
3882 * Allocate new usage record.
3883 */
3884 pUsage = (PSUPDRVLDRUSAGE)RTMemAlloc(sizeof(*pUsage));
3885 AssertReturn(pUsage, VERR_NO_MEMORY);
3886 pUsage->cUsage = 1;
3887 pUsage->pImage = pImage;
3888 pUsage->pNext = pSession->pLdrUsage;
3889 pSession->pLdrUsage = pUsage;
3890 return VINF_SUCCESS;
3891}
3892
3893
3894/**
3895 * Frees a load image.
3896 *
3897 * @param pDevExt Pointer to device extension.
3898 * @param pImage Pointer to the image we're gonna free.
3899 * This image must exit!
3900 * @remark The caller MUST own SUPDRVDEVEXT::mtxLdr!
3901 */
3902static void supdrvLdrFree(PSUPDRVDEVEXT pDevExt, PSUPDRVLDRIMAGE pImage)
3903{
3904 PSUPDRVLDRIMAGE pImagePrev;
3905 LogFlow(("supdrvLdrFree: pImage=%p\n", pImage));
3906
3907 /* find it - arg. should've used doubly linked list. */
3908 Assert(pDevExt->pLdrImages);
3909 pImagePrev = NULL;
3910 if (pDevExt->pLdrImages != pImage)
3911 {
3912 pImagePrev = pDevExt->pLdrImages;
3913 while (pImagePrev->pNext != pImage)
3914 pImagePrev = pImagePrev->pNext;
3915 Assert(pImagePrev->pNext == pImage);
3916 }
3917
3918 /* unlink */
3919 if (pImagePrev)
3920 pImagePrev->pNext = pImage->pNext;
3921 else
3922 pDevExt->pLdrImages = pImage->pNext;
3923
3924 /* check if this is VMMR0.r0 unset its entry point pointers. */
3925 if (pDevExt->pvVMMR0 == pImage->pvImage)
3926 supdrvLdrUnsetVMMR0EPs(pDevExt);
3927
3928 /* check for objects with destructors in this image. (Shouldn't happen.) */
3929 if (pDevExt->pObjs)
3930 {
3931 unsigned cObjs = 0;
3932 PSUPDRVOBJ pObj;
3933 RTSPINLOCKTMP SpinlockTmp = RTSPINLOCKTMP_INITIALIZER;
3934 RTSpinlockAcquire(pDevExt->Spinlock, &SpinlockTmp);
3935 for (pObj = pDevExt->pObjs; pObj; pObj = pObj->pNext)
3936 if (RT_UNLIKELY((uintptr_t)pObj->pfnDestructor - (uintptr_t)pImage->pvImage < pImage->cbImage))
3937 {
3938 pObj->pfnDestructor = NULL;
3939 cObjs++;
3940 }
3941 RTSpinlockRelease(pDevExt->Spinlock, &SpinlockTmp);
3942 if (cObjs)
3943 OSDBGPRINT(("supdrvLdrFree: Image '%s' has %d dangling objects!\n", pImage->szName, cObjs));
3944 }
3945
3946 /* call termination function if fully loaded. */
3947 if ( pImage->pfnModuleTerm
3948 && pImage->uState == SUP_IOCTL_LDR_LOAD)
3949 {
3950 LogFlow(("supdrvIOCtl_LdrLoad: calling pfnModuleTerm=%p\n", pImage->pfnModuleTerm));
3951#ifdef RT_WITH_W64_UNWIND_HACK
3952 supdrvNtWrapModuleTerm(pImage->pfnModuleTerm);
3953#else
3954 pImage->pfnModuleTerm();
3955#endif
3956 }
3957
3958 /* free the image */
3959 pImage->cUsage = 0;
3960 pImage->pNext = 0;
3961 pImage->uState = SUP_IOCTL_LDR_FREE;
3962 RTMemExecFree(pImage);
3963}
3964
3965
3966/**
3967 * Implements the service call request.
3968 *
3969 * @returns VBox status code.
3970 * @param pDevExt The device extension.
3971 * @param pSession The calling session.
3972 * @param pReq The request packet, valid.
3973 */
3974static int supdrvIOCtl_CallServiceModule(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPCALLSERVICE pReq)
3975{
3976#if !defined(RT_OS_WINDOWS) || defined(DEBUG)
3977 int rc;
3978
3979 /*
3980 * Find the module first in the module referenced by the calling session.
3981 */
3982 rc = RTSemFastMutexRequest(pDevExt->mtxLdr);
3983 if (RT_SUCCESS(rc))
3984 {
3985 PFNSUPR0SERVICEREQHANDLER pfnServiceReqHandler = NULL;
3986 PSUPDRVLDRUSAGE pUsage;
3987
3988 for (pUsage = pSession->pLdrUsage; pUsage; pUsage = pUsage->pNext)
3989 if ( pUsage->pImage->pfnServiceReqHandler
3990 && !strcmp(pUsage->pImage->szName, pReq->u.In.szName))
3991 {
3992 pfnServiceReqHandler = pUsage->pImage->pfnServiceReqHandler;
3993 break;
3994 }
3995 RTSemFastMutexRelease(pDevExt->mtxLdr);
3996
3997 if (pfnServiceReqHandler)
3998 {
3999 /*
4000 * Call it.
4001 */
4002 if (pReq->Hdr.cbIn == SUP_IOCTL_CALL_SERVICE_SIZE(0))
4003#ifdef RT_WITH_W64_UNWIND_HACK
4004 rc = supdrvNtWrapServiceReqHandler((PFNRT)pfnServiceReqHandler, pSession, pReq->u.In.uOperation, pReq->u.In.u64Arg, NULL);
4005#else
4006 rc = pfnServiceReqHandler(pSession, pReq->u.In.uOperation, pReq->u.In.u64Arg, NULL);
4007#endif
4008 else
4009#ifdef RT_WITH_W64_UNWIND_HACK
4010 rc = supdrvNtWrapServiceReqHandler((PFNRT)pfnServiceReqHandler, pSession, pReq->u.In.uOperation,
4011 pReq->u.In.u64Arg, (PSUPR0SERVICEREQHDR)&pReq->abReqPkt[0]);
4012#else
4013 rc = pfnServiceReqHandler(pSession, pReq->u.In.uOperation, pReq->u.In.u64Arg, (PSUPR0SERVICEREQHDR)&pReq->abReqPkt[0]);
4014#endif
4015 }
4016 else
4017 rc = VERR_SUPDRV_SERVICE_NOT_FOUND;
4018 }
4019
4020 /* log it */
4021 if ( RT_FAILURE(rc)
4022 && rc != VERR_INTERRUPTED
4023 && rc != VERR_TIMEOUT)
4024 Log(("SUP_IOCTL_CALL_SERVICE: rc=%Rrc op=%u out=%u arg=%RX64 p/t=%RTproc/%RTthrd\n",
4025 rc, pReq->u.In.uOperation, pReq->Hdr.cbOut, pReq->u.In.u64Arg, RTProcSelf(), RTThreadNativeSelf()));
4026 else
4027 Log4(("SUP_IOCTL_CALL_SERVICE: rc=%Rrc op=%u out=%u arg=%RX64 p/t=%RTproc/%RTthrd\n",
4028 rc, pReq->u.In.uOperation, pReq->Hdr.cbOut, pReq->u.In.u64Arg, RTProcSelf(), RTThreadNativeSelf()));
4029 return rc;
4030#else /* RT_OS_WINDOWS && !DEBUG */
4031 return VERR_NOT_IMPLEMENTED;
4032#endif /* RT_OS_WINDOWS && !DEBUG */
4033}
4034
4035
4036/**
4037 * Gets the paging mode of the current CPU.
4038 *
4039 * @returns Paging mode, SUPPAGEINGMODE_INVALID on error.
4040 */
4041SUPR0DECL(SUPPAGINGMODE) SUPR0GetPagingMode(void)
4042{
4043 SUPPAGINGMODE enmMode;
4044
4045 RTR0UINTREG cr0 = ASMGetCR0();
4046 if ((cr0 & (X86_CR0_PG | X86_CR0_PE)) != (X86_CR0_PG | X86_CR0_PE))
4047 enmMode = SUPPAGINGMODE_INVALID;
4048 else
4049 {
4050 RTR0UINTREG cr4 = ASMGetCR4();
4051 uint32_t fNXEPlusLMA = 0;
4052 if (cr4 & X86_CR4_PAE)
4053 {
4054 uint32_t fAmdFeatures = ASMCpuId_EDX(0x80000001);
4055 if (fAmdFeatures & (X86_CPUID_AMD_FEATURE_EDX_NX | X86_CPUID_AMD_FEATURE_EDX_LONG_MODE))
4056 {
4057 uint64_t efer = ASMRdMsr(MSR_K6_EFER);
4058 if ((fAmdFeatures & X86_CPUID_AMD_FEATURE_EDX_NX) && (efer & MSR_K6_EFER_NXE))
4059 fNXEPlusLMA |= RT_BIT(0);
4060 if ((fAmdFeatures & X86_CPUID_AMD_FEATURE_EDX_LONG_MODE) && (efer & MSR_K6_EFER_LMA))
4061 fNXEPlusLMA |= RT_BIT(1);
4062 }
4063 }
4064
4065 switch ((cr4 & (X86_CR4_PAE | X86_CR4_PGE)) | fNXEPlusLMA)
4066 {
4067 case 0:
4068 enmMode = SUPPAGINGMODE_32_BIT;
4069 break;
4070
4071 case X86_CR4_PGE:
4072 enmMode = SUPPAGINGMODE_32_BIT_GLOBAL;
4073 break;
4074
4075 case X86_CR4_PAE:
4076 enmMode = SUPPAGINGMODE_PAE;
4077 break;
4078
4079 case X86_CR4_PAE | RT_BIT(0):
4080 enmMode = SUPPAGINGMODE_PAE_NX;
4081 break;
4082
4083 case X86_CR4_PAE | X86_CR4_PGE:
4084 enmMode = SUPPAGINGMODE_PAE_GLOBAL;
4085 break;
4086
4087 case X86_CR4_PAE | X86_CR4_PGE | RT_BIT(0):
4088 enmMode = SUPPAGINGMODE_PAE_GLOBAL;
4089 break;
4090
4091 case RT_BIT(1) | X86_CR4_PAE:
4092 enmMode = SUPPAGINGMODE_AMD64;
4093 break;
4094
4095 case RT_BIT(1) | X86_CR4_PAE | RT_BIT(0):
4096 enmMode = SUPPAGINGMODE_AMD64_NX;
4097 break;
4098
4099 case RT_BIT(1) | X86_CR4_PAE | X86_CR4_PGE:
4100 enmMode = SUPPAGINGMODE_AMD64_GLOBAL;
4101 break;
4102
4103 case RT_BIT(1) | X86_CR4_PAE | X86_CR4_PGE | RT_BIT(0):
4104 enmMode = SUPPAGINGMODE_AMD64_GLOBAL_NX;
4105 break;
4106
4107 default:
4108 AssertMsgFailed(("Cannot happen! cr4=%#x fNXEPlusLMA=%d\n", cr4, fNXEPlusLMA));
4109 enmMode = SUPPAGINGMODE_INVALID;
4110 break;
4111 }
4112 }
4113 return enmMode;
4114}
4115
4116
4117/**
4118 * Enables or disabled hardware virtualization extensions using native OS APIs.
4119 *
4120 * @returns VBox status code.
4121 * @retval VINF_SUCCESS on success.
4122 * @retval VERR_NOT_SUPPORTED if not supported by the native OS.
4123 *
4124 * @param fEnable Whether to enable or disable.
4125 */
4126SUPR0DECL(int) SUPR0EnableVTx(bool fEnable)
4127{
4128#ifdef RT_OS_DARWIN
4129 return supdrvOSEnableVTx(fEnable);
4130#else
4131 return VERR_NOT_SUPPORTED;
4132#endif
4133}
4134
4135
4136/**
4137 * Creates the GIP.
4138 *
4139 * @returns VBox status code.
4140 * @param pDevExt Instance data. GIP stuff may be updated.
4141 */
4142static int supdrvGipCreate(PSUPDRVDEVEXT pDevExt)
4143{
4144 PSUPGLOBALINFOPAGE pGip;
4145 RTHCPHYS HCPhysGip;
4146 uint32_t u32SystemResolution;
4147 uint32_t u32Interval;
4148 int rc;
4149
4150 LogFlow(("supdrvGipCreate:\n"));
4151
4152 /* assert order */
4153 Assert(pDevExt->u32SystemTimerGranularityGrant == 0);
4154 Assert(pDevExt->GipMemObj == NIL_RTR0MEMOBJ);
4155 Assert(!pDevExt->pGipTimer);
4156
4157 /*
4158 * Allocate a suitable page with a default kernel mapping.
4159 */
4160 rc = RTR0MemObjAllocLow(&pDevExt->GipMemObj, PAGE_SIZE, false);
4161 if (RT_FAILURE(rc))
4162 {
4163 OSDBGPRINT(("supdrvGipCreate: failed to allocate the GIP page. rc=%d\n", rc));
4164 return rc;
4165 }
4166 pGip = (PSUPGLOBALINFOPAGE)RTR0MemObjAddress(pDevExt->GipMemObj); AssertPtr(pGip);
4167 HCPhysGip = RTR0MemObjGetPagePhysAddr(pDevExt->GipMemObj, 0); Assert(HCPhysGip != NIL_RTHCPHYS);
4168
4169#if 0 /** @todo Disabled this as we didn't used to do it before and causes unnecessary stress on laptops.
4170 * It only applies to Windows and should probably revisited later, if possible made part of the
4171 * timer code (return min granularity in RTTimerGetSystemGranularity and set it in RTTimerStart). */
4172 /*
4173 * Try bump up the system timer resolution.
4174 * The more interrupts the better...
4175 */
4176 if ( RT_SUCCESS(RTTimerRequestSystemGranularity( 488281 /* 2048 HZ */, &u32SystemResolution))
4177 || RT_SUCCESS(RTTimerRequestSystemGranularity( 500000 /* 2000 HZ */, &u32SystemResolution))
4178 || RT_SUCCESS(RTTimerRequestSystemGranularity( 976563 /* 1024 HZ */, &u32SystemResolution))
4179 || RT_SUCCESS(RTTimerRequestSystemGranularity( 1000000 /* 1000 HZ */, &u32SystemResolution))
4180 || RT_SUCCESS(RTTimerRequestSystemGranularity( 1953125 /* 512 HZ */, &u32SystemResolution))
4181 || RT_SUCCESS(RTTimerRequestSystemGranularity( 2000000 /* 500 HZ */, &u32SystemResolution))
4182 || RT_SUCCESS(RTTimerRequestSystemGranularity( 3906250 /* 256 HZ */, &u32SystemResolution))
4183 || RT_SUCCESS(RTTimerRequestSystemGranularity( 4000000 /* 250 HZ */, &u32SystemResolution))
4184 || RT_SUCCESS(RTTimerRequestSystemGranularity( 7812500 /* 128 HZ */, &u32SystemResolution))
4185 || RT_SUCCESS(RTTimerRequestSystemGranularity(10000000 /* 100 HZ */, &u32SystemResolution))
4186 || RT_SUCCESS(RTTimerRequestSystemGranularity(15625000 /* 64 HZ */, &u32SystemResolution))
4187 || RT_SUCCESS(RTTimerRequestSystemGranularity(31250000 /* 32 HZ */, &u32SystemResolution))
4188 )
4189 {
4190 Assert(RTTimerGetSystemGranularity() <= u32SystemResolution);
4191 pDevExt->u32SystemTimerGranularityGrant = u32SystemResolution;
4192 }
4193#endif
4194
4195 /*
4196 * Find a reasonable update interval and initialize the structure.
4197 */
4198 u32Interval = u32SystemResolution = RTTimerGetSystemGranularity();
4199 while (u32Interval < 10000000 /* 10 ms */)
4200 u32Interval += u32SystemResolution;
4201
4202 supdrvGipInit(pDevExt, pGip, HCPhysGip, RTTimeSystemNanoTS(), 1000000000 / u32Interval /*=Hz*/);
4203
4204 /*
4205 * Create the timer.
4206 * If CPU_ALL isn't supported we'll have to fall back to synchronous mode.
4207 */
4208 if (pGip->u32Mode == SUPGIPMODE_ASYNC_TSC)
4209 {
4210 rc = RTTimerCreateEx(&pDevExt->pGipTimer, u32Interval, RTTIMER_FLAGS_CPU_ALL, supdrvGipAsyncTimer, pDevExt);
4211 if (rc == VERR_NOT_SUPPORTED)
4212 {
4213 OSDBGPRINT(("supdrvGipCreate: omni timer not supported, falling back to synchronous mode\n"));
4214 pGip->u32Mode = SUPGIPMODE_SYNC_TSC;
4215 }
4216 }
4217 if (pGip->u32Mode != SUPGIPMODE_ASYNC_TSC)
4218 rc = RTTimerCreateEx(&pDevExt->pGipTimer, u32Interval, 0, supdrvGipSyncTimer, pDevExt);
4219 if (RT_SUCCESS(rc))
4220 {
4221 if (pGip->u32Mode == SUPGIPMODE_ASYNC_TSC)
4222 rc = RTMpNotificationRegister(supdrvGipMpEvent, pDevExt);
4223 if (RT_SUCCESS(rc))
4224 {
4225 /*
4226 * We're good.
4227 */
4228 dprintf(("supdrvGipCreate: %ld ns interval.\n", (long)u32Interval));
4229 return VINF_SUCCESS;
4230 }
4231
4232 OSDBGPRINT(("supdrvGipCreate: failed register MP event notfication. rc=%d\n", rc));
4233 }
4234 else
4235 {
4236 OSDBGPRINT(("supdrvGipCreate: failed create GIP timer at %ld ns interval. rc=%d\n", (long)u32Interval, rc));
4237 Assert(!pDevExt->pGipTimer);
4238 }
4239 supdrvGipDestroy(pDevExt);
4240 return rc;
4241}
4242
4243
4244/**
4245 * Terminates the GIP.
4246 *
4247 * @param pDevExt Instance data. GIP stuff may be updated.
4248 */
4249static void supdrvGipDestroy(PSUPDRVDEVEXT pDevExt)
4250{
4251 int rc;
4252#ifdef DEBUG_DARWIN_GIP
4253 OSDBGPRINT(("supdrvGipDestroy: pDevExt=%p pGip=%p pGipTimer=%p GipMemObj=%p\n", pDevExt,
4254 pDevExt->GipMemObj != NIL_RTR0MEMOBJ ? RTR0MemObjAddress(pDevExt->GipMemObj) : NULL,
4255 pDevExt->pGipTimer, pDevExt->GipMemObj));
4256#endif
4257
4258 /*
4259 * Invalid the GIP data.
4260 */
4261 if (pDevExt->pGip)
4262 {
4263 supdrvGipTerm(pDevExt->pGip);
4264 pDevExt->pGip = NULL;
4265 }
4266
4267 /*
4268 * Destroy the timer and free the GIP memory object.
4269 */
4270 if (pDevExt->pGipTimer)
4271 {
4272 rc = RTTimerDestroy(pDevExt->pGipTimer); AssertRC(rc);
4273 pDevExt->pGipTimer = NULL;
4274 }
4275
4276 if (pDevExt->GipMemObj != NIL_RTR0MEMOBJ)
4277 {
4278 rc = RTR0MemObjFree(pDevExt->GipMemObj, true /* free mappings */); AssertRC(rc);
4279 pDevExt->GipMemObj = NIL_RTR0MEMOBJ;
4280 }
4281
4282 /*
4283 * Finally, release the system timer resolution request if one succeeded.
4284 */
4285 if (pDevExt->u32SystemTimerGranularityGrant)
4286 {
4287 rc = RTTimerReleaseSystemGranularity(pDevExt->u32SystemTimerGranularityGrant); AssertRC(rc);
4288 pDevExt->u32SystemTimerGranularityGrant = 0;
4289 }
4290}
4291
4292
4293/**
4294 * Timer callback function sync GIP mode.
4295 * @param pTimer The timer.
4296 * @param pvUser The device extension.
4297 */
4298static DECLCALLBACK(void) supdrvGipSyncTimer(PRTTIMER pTimer, void *pvUser, uint64_t iTick)
4299{
4300 RTCCUINTREG fOldFlags = ASMIntDisableFlags(); /* No interruptions please (real problem on S10). */
4301 PSUPDRVDEVEXT pDevExt = (PSUPDRVDEVEXT)pvUser;
4302
4303 supdrvGipUpdate(pDevExt->pGip, RTTimeSystemNanoTS());
4304
4305 ASMSetFlags(fOldFlags);
4306}
4307
4308
4309/**
4310 * Timer callback function for async GIP mode.
4311 * @param pTimer The timer.
4312 * @param pvUser The device extension.
4313 */
4314static DECLCALLBACK(void) supdrvGipAsyncTimer(PRTTIMER pTimer, void *pvUser, uint64_t iTick)
4315{
4316 RTCCUINTREG fOldFlags = ASMIntDisableFlags(); /* No interruptions please (real problem on S10). */
4317 PSUPDRVDEVEXT pDevExt = (PSUPDRVDEVEXT)pvUser;
4318 RTCPUID idCpu = RTMpCpuId();
4319 uint64_t NanoTS = RTTimeSystemNanoTS();
4320
4321 /** @todo reset the transaction number and whatnot when iTick == 1. */
4322 if (pDevExt->idGipMaster == idCpu)
4323 supdrvGipUpdate(pDevExt->pGip, NanoTS);
4324 else
4325 supdrvGipUpdatePerCpu(pDevExt->pGip, NanoTS, ASMGetApicId());
4326
4327 ASMSetFlags(fOldFlags);
4328}
4329
4330
4331/**
4332 * Multiprocessor event notification callback.
4333 *
4334 * This is used to make sue that the GIP master gets passed on to
4335 * another CPU.
4336 *
4337 * @param enmEvent The event.
4338 * @param idCpu The cpu it applies to.
4339 * @param pvUser Pointer to the device extension.
4340 */
4341static DECLCALLBACK(void) supdrvGipMpEvent(RTMPEVENT enmEvent, RTCPUID idCpu, void *pvUser)
4342{
4343 PSUPDRVDEVEXT pDevExt = (PSUPDRVDEVEXT)pvUser;
4344 if (enmEvent == RTMPEVENT_OFFLINE)
4345 {
4346 RTCPUID idGipMaster;
4347 ASMAtomicReadSize(&pDevExt->idGipMaster, &idGipMaster);
4348 if (idGipMaster == idCpu)
4349 {
4350 /*
4351 * Find a new GIP master.
4352 */
4353 bool fIgnored;
4354 unsigned i;
4355 RTCPUID idNewGipMaster = NIL_RTCPUID;
4356 RTCPUSET OnlineCpus;
4357 RTMpGetOnlineSet(&OnlineCpus);
4358
4359 for (i = 0; i < RTCPUSET_MAX_CPUS; i++)
4360 {
4361 RTCPUID idCurCpu = RTMpCpuIdFromSetIndex(i);
4362 if ( RTCpuSetIsMember(&OnlineCpus, idCurCpu)
4363 && idCurCpu != idGipMaster)
4364 {
4365 idNewGipMaster = idCurCpu;
4366 break;
4367 }
4368 }
4369
4370 dprintf(("supdrvGipMpEvent: Gip master %#lx -> %#lx\n", (long)idGipMaster, (long)idNewGipMaster));
4371 ASMAtomicCmpXchgSize(&pDevExt->idGipMaster, idNewGipMaster, idGipMaster, fIgnored);
4372 NOREF(fIgnored);
4373 }
4374 }
4375}
4376
4377
4378/**
4379 * Initializes the GIP data.
4380 *
4381 * @returns IPRT status code.
4382 * @param pDevExt Pointer to the device instance data.
4383 * @param pGip Pointer to the read-write kernel mapping of the GIP.
4384 * @param HCPhys The physical address of the GIP.
4385 * @param u64NanoTS The current nanosecond timestamp.
4386 * @param uUpdateHz The update freqence.
4387 */
4388int VBOXCALL supdrvGipInit(PSUPDRVDEVEXT pDevExt, PSUPGLOBALINFOPAGE pGip, RTHCPHYS HCPhys, uint64_t u64NanoTS, unsigned uUpdateHz)
4389{
4390 unsigned i;
4391#ifdef DEBUG_DARWIN_GIP
4392 OSDBGPRINT(("supdrvGipInit: pGip=%p HCPhys=%lx u64NanoTS=%llu uUpdateHz=%d\n", pGip, (long)HCPhys, u64NanoTS, uUpdateHz));
4393#else
4394 LogFlow(("supdrvGipInit: pGip=%p HCPhys=%lx u64NanoTS=%llu uUpdateHz=%d\n", pGip, (long)HCPhys, u64NanoTS, uUpdateHz));
4395#endif
4396
4397 /*
4398 * Initialize the structure.
4399 */
4400 memset(pGip, 0, PAGE_SIZE);
4401 pGip->u32Magic = SUPGLOBALINFOPAGE_MAGIC;
4402 pGip->u32Version = SUPGLOBALINFOPAGE_VERSION;
4403 pGip->u32Mode = supdrvGipDeterminTscMode(pDevExt);
4404 pGip->u32UpdateHz = uUpdateHz;
4405 pGip->u32UpdateIntervalNS = 1000000000 / uUpdateHz;
4406 pGip->u64NanoTSLastUpdateHz = u64NanoTS;
4407
4408 for (i = 0; i < RT_ELEMENTS(pGip->aCPUs); i++)
4409 {
4410 pGip->aCPUs[i].u32TransactionId = 2;
4411 pGip->aCPUs[i].u64NanoTS = u64NanoTS;
4412 pGip->aCPUs[i].u64TSC = ASMReadTSC();
4413
4414 /*
4415 * We don't know the following values until we've executed updates.
4416 * So, we'll just insert very high values.
4417 */
4418 pGip->aCPUs[i].u64CpuHz = _4G + 1;
4419 pGip->aCPUs[i].u32UpdateIntervalTSC = _2G / 4;
4420 pGip->aCPUs[i].au32TSCHistory[0] = _2G / 4;
4421 pGip->aCPUs[i].au32TSCHistory[1] = _2G / 4;
4422 pGip->aCPUs[i].au32TSCHistory[2] = _2G / 4;
4423 pGip->aCPUs[i].au32TSCHistory[3] = _2G / 4;
4424 pGip->aCPUs[i].au32TSCHistory[4] = _2G / 4;
4425 pGip->aCPUs[i].au32TSCHistory[5] = _2G / 4;
4426 pGip->aCPUs[i].au32TSCHistory[6] = _2G / 4;
4427 pGip->aCPUs[i].au32TSCHistory[7] = _2G / 4;
4428 }
4429
4430 /*
4431 * Link it to the device extension.
4432 */
4433 pDevExt->pGip = pGip;
4434 pDevExt->HCPhysGip = HCPhys;
4435 pDevExt->cGipUsers = 0;
4436
4437 return VINF_SUCCESS;
4438}
4439
4440
4441/**
4442 * Callback used by supdrvDetermineAsyncTSC to read the TSC on a CPU.
4443 *
4444 * @param idCpu Ignored.
4445 * @param pvUser1 Where to put the TSC.
4446 * @param pvUser2 Ignored.
4447 */
4448static DECLCALLBACK(void) supdrvDetermineAsyncTscWorker(RTCPUID idCpu, void *pvUser1, void *pvUser2)
4449{
4450#if 1
4451 ASMAtomicWriteU64((uint64_t volatile *)pvUser1, ASMReadTSC());
4452#else
4453 *(uint64_t *)pvUser1 = ASMReadTSC();
4454#endif
4455}
4456
4457
4458/**
4459 * Determine if Async GIP mode is required because of TSC drift.
4460 *
4461 * When using the default/normal timer code it is essential that the time stamp counter
4462 * (TSC) runs never backwards, that is, a read operation to the counter should return
4463 * a bigger value than any previous read operation. This is guaranteed by the latest
4464 * AMD CPUs and by newer Intel CPUs which never enter the C2 state (P4). In any other
4465 * case we have to choose the asynchronous timer mode.
4466 *
4467 * @param poffMin Pointer to the determined difference between different cores.
4468 * @return false if the time stamp counters appear to be synchron, true otherwise.
4469 */
4470bool VBOXCALL supdrvDetermineAsyncTsc(uint64_t *poffMin)
4471{
4472 /*
4473 * Just iterate all the cpus 8 times and make sure that the TSC is
4474 * ever increasing. We don't bother taking TSC rollover into account.
4475 */
4476 RTCPUSET CpuSet;
4477 int iLastCpu = RTCpuLastIndex(RTMpGetSet(&CpuSet));
4478 int iCpu;
4479 int cLoops = 8;
4480 bool fAsync = false;
4481 int rc = VINF_SUCCESS;
4482 uint64_t offMax = 0;
4483 uint64_t offMin = ~(uint64_t)0;
4484 uint64_t PrevTsc = ASMReadTSC();
4485
4486 while (cLoops-- > 0)
4487 {
4488 for (iCpu = 0; iCpu <= iLastCpu; iCpu++)
4489 {
4490 uint64_t CurTsc;
4491 rc = RTMpOnSpecific(RTMpCpuIdFromSetIndex(iCpu), supdrvDetermineAsyncTscWorker, &CurTsc, NULL);
4492 if (RT_SUCCESS(rc))
4493 {
4494 if (CurTsc <= PrevTsc)
4495 {
4496 fAsync = true;
4497 offMin = offMax = PrevTsc - CurTsc;
4498 dprintf(("supdrvDetermineAsyncTsc: iCpu=%d cLoops=%d CurTsc=%llx PrevTsc=%llx\n",
4499 iCpu, cLoops, CurTsc, PrevTsc));
4500 break;
4501 }
4502
4503 /* Gather statistics (except the first time). */
4504 if (iCpu != 0 || cLoops != 7)
4505 {
4506 uint64_t off = CurTsc - PrevTsc;
4507 if (off < offMin)
4508 offMin = off;
4509 if (off > offMax)
4510 offMax = off;
4511 dprintf2(("%d/%d: off=%llx\n", cLoops, iCpu, off));
4512 }
4513
4514 /* Next */
4515 PrevTsc = CurTsc;
4516 }
4517 else if (rc == VERR_NOT_SUPPORTED)
4518 break;
4519 else
4520 AssertMsg(rc == VERR_CPU_NOT_FOUND || rc == VERR_CPU_OFFLINE, ("%d\n", rc));
4521 }
4522
4523 /* broke out of the loop. */
4524 if (iCpu <= iLastCpu)
4525 break;
4526 }
4527
4528 *poffMin = offMin; /* Almost RTMpOnSpecific profiling. */
4529 dprintf(("supdrvDetermineAsyncTsc: returns %d; iLastCpu=%d rc=%d offMin=%llx offMax=%llx\n",
4530 fAsync, iLastCpu, rc, offMin, offMax));
4531#if !defined(RT_OS_SOLARIS) && !defined(RT_OS_OS2) && !defined(RT_OS_WINDOWS)
4532 OSDBGPRINT(("vboxdrv: fAsync=%d offMin=%#lx offMax=%#lx\n", fAsync, (long)offMin, (long)offMax));
4533#endif
4534 return fAsync;
4535}
4536
4537
4538/**
4539 * Determin the GIP TSC mode.
4540 *
4541 * @returns The most suitable TSC mode.
4542 * @param pDevExt Pointer to the device instance data.
4543 */
4544static SUPGIPMODE supdrvGipDeterminTscMode(PSUPDRVDEVEXT pDevExt)
4545{
4546 /*
4547 * On SMP we're faced with two problems:
4548 * (1) There might be a skew between the CPU, so that cpu0
4549 * returns a TSC that is sligtly different from cpu1.
4550 * (2) Power management (and other things) may cause the TSC
4551 * to run at a non-constant speed, and cause the speed
4552 * to be different on the cpus. This will result in (1).
4553 *
4554 * So, on SMP systems we'll have to select the ASYNC update method
4555 * if there are symphoms of these problems.
4556 */
4557 if (RTMpGetCount() > 1)
4558 {
4559 uint32_t uEAX, uEBX, uECX, uEDX;
4560 uint64_t u64DiffCoresIgnored;
4561
4562 /* Permit the user and/or the OS specfic bits to force async mode. */
4563 if (supdrvOSGetForcedAsyncTscMode(pDevExt))
4564 return SUPGIPMODE_ASYNC_TSC;
4565
4566 /* Try check for current differences between the cpus. */
4567 if (supdrvDetermineAsyncTsc(&u64DiffCoresIgnored))
4568 return SUPGIPMODE_ASYNC_TSC;
4569
4570 /*
4571 * If the CPU supports power management and is an AMD one we
4572 * won't trust it unless it has the TscInvariant bit is set.
4573 */
4574 /* Check for "AuthenticAMD" */
4575 ASMCpuId(0, &uEAX, &uEBX, &uECX, &uEDX);
4576 if ( uEAX >= 1
4577 && uEBX == X86_CPUID_VENDOR_AMD_EBX
4578 && uECX == X86_CPUID_VENDOR_AMD_ECX
4579 && uEDX == X86_CPUID_VENDOR_AMD_EDX)
4580 {
4581 /* Check for APM support and that TscInvariant is cleared. */
4582 ASMCpuId(0x80000000, &uEAX, &uEBX, &uECX, &uEDX);
4583 if (uEAX >= 0x80000007)
4584 {
4585 ASMCpuId(0x80000007, &uEAX, &uEBX, &uECX, &uEDX);
4586 if ( !(uEDX & RT_BIT(8))/* TscInvariant */
4587 && (uEDX & 0x3e)) /* STC|TM|THERMTRIP|VID|FID. Ignore TS. */
4588 return SUPGIPMODE_ASYNC_TSC;
4589 }
4590 }
4591 }
4592 return SUPGIPMODE_SYNC_TSC;
4593}
4594
4595
4596/**
4597 * Invalidates the GIP data upon termination.
4598 *
4599 * @param pGip Pointer to the read-write kernel mapping of the GIP.
4600 */
4601void VBOXCALL supdrvGipTerm(PSUPGLOBALINFOPAGE pGip)
4602{
4603 unsigned i;
4604 pGip->u32Magic = 0;
4605 for (i = 0; i < RT_ELEMENTS(pGip->aCPUs); i++)
4606 {
4607 pGip->aCPUs[i].u64NanoTS = 0;
4608 pGip->aCPUs[i].u64TSC = 0;
4609 pGip->aCPUs[i].iTSCHistoryHead = 0;
4610 }
4611}
4612
4613
4614/**
4615 * Worker routine for supdrvGipUpdate and supdrvGipUpdatePerCpu that
4616 * updates all the per cpu data except the transaction id.
4617 *
4618 * @param pGip The GIP.
4619 * @param pGipCpu Pointer to the per cpu data.
4620 * @param u64NanoTS The current time stamp.
4621 */
4622static void supdrvGipDoUpdateCpu(PSUPGLOBALINFOPAGE pGip, PSUPGIPCPU pGipCpu, uint64_t u64NanoTS)
4623{
4624 uint64_t u64TSC;
4625 uint64_t u64TSCDelta;
4626 uint32_t u32UpdateIntervalTSC;
4627 uint32_t u32UpdateIntervalTSCSlack;
4628 unsigned iTSCHistoryHead;
4629 uint64_t u64CpuHz;
4630
4631 /*
4632 * Update the NanoTS.
4633 */
4634 ASMAtomicXchgU64(&pGipCpu->u64NanoTS, u64NanoTS);
4635
4636 /*
4637 * Calc TSC delta.
4638 */
4639 /** @todo validate the NanoTS delta, don't trust the OS to call us when it should... */
4640 u64TSC = ASMReadTSC();
4641 u64TSCDelta = u64TSC - pGipCpu->u64TSC;
4642 ASMAtomicXchgU64(&pGipCpu->u64TSC, u64TSC);
4643
4644 if (u64TSCDelta >> 32)
4645 {
4646 u64TSCDelta = pGipCpu->u32UpdateIntervalTSC;
4647 pGipCpu->cErrors++;
4648 }
4649
4650 /*
4651 * TSC History.
4652 */
4653 Assert(RT_ELEMENTS(pGipCpu->au32TSCHistory) == 8);
4654
4655 iTSCHistoryHead = (pGipCpu->iTSCHistoryHead + 1) & 7;
4656 ASMAtomicXchgU32(&pGipCpu->iTSCHistoryHead, iTSCHistoryHead);
4657 ASMAtomicXchgU32(&pGipCpu->au32TSCHistory[iTSCHistoryHead], (uint32_t)u64TSCDelta);
4658
4659 /*
4660 * UpdateIntervalTSC = average of last 8,2,1 intervals depending on update HZ.
4661 */
4662 if (pGip->u32UpdateHz >= 1000)
4663 {
4664 uint32_t u32;
4665 u32 = pGipCpu->au32TSCHistory[0];
4666 u32 += pGipCpu->au32TSCHistory[1];
4667 u32 += pGipCpu->au32TSCHistory[2];
4668 u32 += pGipCpu->au32TSCHistory[3];
4669 u32 >>= 2;
4670 u32UpdateIntervalTSC = pGipCpu->au32TSCHistory[4];
4671 u32UpdateIntervalTSC += pGipCpu->au32TSCHistory[5];
4672 u32UpdateIntervalTSC += pGipCpu->au32TSCHistory[6];
4673 u32UpdateIntervalTSC += pGipCpu->au32TSCHistory[7];
4674 u32UpdateIntervalTSC >>= 2;
4675 u32UpdateIntervalTSC += u32;
4676 u32UpdateIntervalTSC >>= 1;
4677
4678 /* Value choosen for a 2GHz Athlon64 running linux 2.6.10/11, . */
4679 u32UpdateIntervalTSCSlack = u32UpdateIntervalTSC >> 14;
4680 }
4681 else if (pGip->u32UpdateHz >= 90)
4682 {
4683 u32UpdateIntervalTSC = (uint32_t)u64TSCDelta;
4684 u32UpdateIntervalTSC += pGipCpu->au32TSCHistory[(iTSCHistoryHead - 1) & 7];
4685 u32UpdateIntervalTSC >>= 1;
4686
4687 /* value choosen on a 2GHz thinkpad running windows */
4688 u32UpdateIntervalTSCSlack = u32UpdateIntervalTSC >> 7;
4689 }
4690 else
4691 {
4692 u32UpdateIntervalTSC = (uint32_t)u64TSCDelta;
4693
4694 /* This value hasn't be checked yet.. waiting for OS/2 and 33Hz timers.. :-) */
4695 u32UpdateIntervalTSCSlack = u32UpdateIntervalTSC >> 6;
4696 }
4697 ASMAtomicXchgU32(&pGipCpu->u32UpdateIntervalTSC, u32UpdateIntervalTSC + u32UpdateIntervalTSCSlack);
4698
4699 /*
4700 * CpuHz.
4701 */
4702 u64CpuHz = ASMMult2xU32RetU64(u32UpdateIntervalTSC, pGip->u32UpdateHz);
4703 ASMAtomicXchgU64(&pGipCpu->u64CpuHz, u64CpuHz);
4704}
4705
4706
4707/**
4708 * Updates the GIP.
4709 *
4710 * @param pGip Pointer to the GIP.
4711 * @param u64NanoTS The current nanosecond timesamp.
4712 */
4713void VBOXCALL supdrvGipUpdate(PSUPGLOBALINFOPAGE pGip, uint64_t u64NanoTS)
4714{
4715 /*
4716 * Determin the relevant CPU data.
4717 */
4718 PSUPGIPCPU pGipCpu;
4719 if (pGip->u32Mode != SUPGIPMODE_ASYNC_TSC)
4720 pGipCpu = &pGip->aCPUs[0];
4721 else
4722 {
4723 unsigned iCpu = ASMGetApicId();
4724 if (RT_LIKELY(iCpu >= RT_ELEMENTS(pGip->aCPUs)))
4725 return;
4726 pGipCpu = &pGip->aCPUs[iCpu];
4727 }
4728
4729 /*
4730 * Start update transaction.
4731 */
4732 if (!(ASMAtomicIncU32(&pGipCpu->u32TransactionId) & 1))
4733 {
4734 /* this can happen on win32 if we're taking to long and there are more CPUs around. shouldn't happen though. */
4735 AssertMsgFailed(("Invalid transaction id, %#x, not odd!\n", pGipCpu->u32TransactionId));
4736 ASMAtomicIncU32(&pGipCpu->u32TransactionId);
4737 pGipCpu->cErrors++;
4738 return;
4739 }
4740
4741 /*
4742 * Recalc the update frequency every 0x800th time.
4743 */
4744 if (!(pGipCpu->u32TransactionId & (GIP_UPDATEHZ_RECALC_FREQ * 2 - 2)))
4745 {
4746 if (pGip->u64NanoTSLastUpdateHz)
4747 {
4748#ifdef RT_ARCH_AMD64 /** @todo fix 64-bit div here to work on x86 linux. */
4749 uint64_t u64Delta = u64NanoTS - pGip->u64NanoTSLastUpdateHz;
4750 uint32_t u32UpdateHz = (uint32_t)((UINT64_C(1000000000) * GIP_UPDATEHZ_RECALC_FREQ) / u64Delta);
4751 if (u32UpdateHz <= 2000 && u32UpdateHz >= 30)
4752 {
4753 ASMAtomicXchgU32(&pGip->u32UpdateHz, u32UpdateHz);
4754 ASMAtomicXchgU32(&pGip->u32UpdateIntervalNS, 1000000000 / u32UpdateHz);
4755 }
4756#endif
4757 }
4758 ASMAtomicXchgU64(&pGip->u64NanoTSLastUpdateHz, u64NanoTS);
4759 }
4760
4761 /*
4762 * Update the data.
4763 */
4764 supdrvGipDoUpdateCpu(pGip, pGipCpu, u64NanoTS);
4765
4766 /*
4767 * Complete transaction.
4768 */
4769 ASMAtomicIncU32(&pGipCpu->u32TransactionId);
4770}
4771
4772
4773/**
4774 * Updates the per cpu GIP data for the calling cpu.
4775 *
4776 * @param pGip Pointer to the GIP.
4777 * @param u64NanoTS The current nanosecond timesamp.
4778 * @param iCpu The CPU index.
4779 */
4780void VBOXCALL supdrvGipUpdatePerCpu(PSUPGLOBALINFOPAGE pGip, uint64_t u64NanoTS, unsigned iCpu)
4781{
4782 PSUPGIPCPU pGipCpu;
4783
4784 if (RT_LIKELY(iCpu < RT_ELEMENTS(pGip->aCPUs)))
4785 {
4786 pGipCpu = &pGip->aCPUs[iCpu];
4787
4788 /*
4789 * Start update transaction.
4790 */
4791 if (!(ASMAtomicIncU32(&pGipCpu->u32TransactionId) & 1))
4792 {
4793 AssertMsgFailed(("Invalid transaction id, %#x, not odd!\n", pGipCpu->u32TransactionId));
4794 ASMAtomicIncU32(&pGipCpu->u32TransactionId);
4795 pGipCpu->cErrors++;
4796 return;
4797 }
4798
4799 /*
4800 * Update the data.
4801 */
4802 supdrvGipDoUpdateCpu(pGip, pGipCpu, u64NanoTS);
4803
4804 /*
4805 * Complete transaction.
4806 */
4807 ASMAtomicIncU32(&pGipCpu->u32TransactionId);
4808 }
4809}
4810
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