VirtualBox

source: vbox/trunk/src/VBox/HostDrivers/Support/SUPDrv.cpp@ 54464

Last change on this file since 54464 was 54375, checked in by vboxsync, 10 years ago

SUPDrvGip.cpp: Replaced idTscDeltaInitiator+RTThreadSleep(1) with a mutex semaphore. Allocate the SUPDRVGIPTSCDELTARGS structure (stack might be swappable, also don't waste it). Remove old sync code.

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