VirtualBox

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

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

VMM: Assert, doxygen, todo question.

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