VirtualBox

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

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

GIP,++: Lots of CPUs (disabled).

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