VirtualBox

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

Last change on this file since 34484 was 34321, checked in by vboxsync, 14 years ago

SUPDrv.c: Set the windows timer granularity to 1024, 1000, 512 or 500 HZ (higher is prefered) while VMs are running (tied to GIP actually).

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