VirtualBox

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

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

HostDrivers/Support: Moved spinlock to DevExt for Mp event race updating the GIP.

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