VirtualBox

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

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

SUPR0VtgFireProbe -> SUPR0TracerFireProbe and other SUPDrv-tracer.cpp changes.

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