VirtualBox

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

Last change on this file since 52478 was 52192, checked in by vboxsync, 11 years ago

HostDrivers/Support, VMM: support CONFIG_PAX_KERNEXEC Linux kernels

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