VirtualBox

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

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

hrmpf

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