VirtualBox

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

Last change on this file since 32767 was 32755, checked in by vboxsync, 14 years ago

SUPDrv.c: Some timer debugging assistance.

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