VirtualBox

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

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

supdrvIOCtl: Reduce the number of return probes.

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