VirtualBox

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

Last change on this file since 37556 was 37410, checked in by vboxsync, 13 years ago

VMM,SUPDrv: Created DBGFTrace.

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