VirtualBox

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

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

SUPDrv: Fix VT-x capability querying for BIOSes that don't set the LOCK bit in the feature control MSR.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 226.2 KB
Line 
1/* $Id: SUPDrv.c 49178 2013-10-18 12:17:21Z 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 /** @todo Unify code with hmR0InitIntelCpu(). */
3416 uint64_t u64FeatMsr = ASMRdMsr(MSR_IA32_FEATURE_CONTROL);
3417 bool const fInSmxMode = RT_BOOL(ASMGetCR4() & X86_CR4_SMXE);
3418 bool fMsrLocked = RT_BOOL(u64FeatMsr & MSR_IA32_FEATURE_CONTROL_LOCK);
3419 bool fSmxVmxAllowed = RT_BOOL(u64FeatMsr & MSR_IA32_FEATURE_CONTROL_SMX_VMXON);
3420 bool fVmxAllowed = RT_BOOL(u64FeatMsr & MSR_IA32_FEATURE_CONTROL_VMXON);
3421
3422 /* Check if the LOCK bit is set but excludes the required VMXON bit. */
3423 int rc = VERR_HM_IPE_1;
3424 if (fMsrLocked)
3425 {
3426 if (fInSmxMode && !fSmxVmxAllowed)
3427 rc = VERR_VMX_MSR_SMX_VMXON_DISABLED;
3428 else if (!fVmxAllowed)
3429 rc = VERR_VMX_MSR_VMXON_DISABLED;
3430 else
3431 rc = VINF_SUCCESS;
3432 }
3433 else
3434 {
3435 /*
3436 * MSR is not yet locked; we can change it ourselves here.
3437 * Once the lock bit is set, this MSR can no longer be modified.
3438 */
3439 bool fAllowed;
3440 u64FeatMsr |= MSR_IA32_FEATURE_CONTROL_LOCK;
3441 if (fInSmxMode)
3442 u64FeatMsr |= MSR_IA32_FEATURE_CONTROL_SMX_VMXON;
3443 else
3444 u64FeatMsr |= MSR_IA32_FEATURE_CONTROL_VMXON;
3445
3446 ASMWrMsr(MSR_IA32_FEATURE_CONTROL, u64FeatMsr);
3447
3448 /* Verify. */
3449 u64FeatMsr = ASMRdMsr(MSR_IA32_FEATURE_CONTROL);
3450 fMsrLocked = RT_BOOL(u64FeatMsr & MSR_IA32_FEATURE_CONTROL_LOCK);
3451 fSmxVmxAllowed = fMsrLocked && RT_BOOL(u64FeatMsr & MSR_IA32_FEATURE_CONTROL_SMX_VMXON);
3452 fVmxAllowed = fMsrLocked && RT_BOOL(u64FeatMsr & MSR_IA32_FEATURE_CONTROL_VMXON);
3453 fAllowed = fInSmxMode ? fSmxVmxAllowed : fVmxAllowed;
3454 if (fAllowed)
3455 rc = VINF_SUCCESS;
3456 else
3457 rc = VERR_VMX_MSR_LOCKING_FAILED;
3458 }
3459
3460 if (rc == VINF_SUCCESS)
3461 {
3462 VMX_CAPABILITY vtCaps;
3463
3464 *pfCaps |= SUPVTCAPS_VT_X;
3465
3466 vtCaps.u = ASMRdMsr(MSR_IA32_VMX_PROCBASED_CTLS);
3467 if (vtCaps.n.allowed1 & VMX_VMCS_CTRL_PROC_EXEC_USE_SECONDARY_EXEC_CTRL)
3468 {
3469 vtCaps.u = ASMRdMsr(MSR_IA32_VMX_PROCBASED_CTLS2);
3470 if (vtCaps.n.allowed1 & VMX_VMCS_CTRL_PROC_EXEC2_EPT)
3471 *pfCaps |= SUPVTCAPS_NESTED_PAGING;
3472 }
3473 return VINF_SUCCESS;
3474 }
3475 return rc;
3476 }
3477 return VERR_VMX_NO_VMX;
3478 }
3479
3480 if ( ASMIsAmdCpuEx(uVendorEBX, uVendorECX, uVendorEDX)
3481 && ASMIsValidStdRange(uMaxId))
3482 {
3483 uint32_t fExtFeaturesEcx, uExtMaxId;
3484 ASMCpuId(0x80000000, &uExtMaxId, &uDummy, &uDummy, &uDummy);
3485 ASMCpuId(0x80000001, &uDummy, &uDummy, &fExtFeaturesEcx, &uDummy);
3486 if ( ASMIsValidExtRange(uExtMaxId)
3487 && uExtMaxId >= 0x8000000a
3488 && (fExtFeaturesEcx & X86_CPUID_AMD_FEATURE_ECX_SVM)
3489 && (fFeaturesEDX & X86_CPUID_FEATURE_EDX_MSR)
3490 && (fFeaturesEDX & X86_CPUID_FEATURE_EDX_FXSR)
3491 )
3492 {
3493 /* Check if SVM is disabled */
3494 u64FeatMsr = ASMRdMsr(MSR_K8_VM_CR);
3495 if (!(u64FeatMsr & MSR_K8_VM_CR_SVM_DISABLE))
3496 {
3497 uint32_t fSvmFeatures;
3498 *pfCaps |= SUPVTCAPS_AMD_V;
3499
3500 /* Query AMD-V features. */
3501 ASMCpuId(0x8000000a, &uDummy, &uDummy, &uDummy, &fSvmFeatures);
3502 if (fSvmFeatures & AMD_CPUID_SVM_FEATURE_EDX_NESTED_PAGING)
3503 *pfCaps |= SUPVTCAPS_NESTED_PAGING;
3504
3505 return VINF_SUCCESS;
3506 }
3507 return VERR_SVM_DISABLED;
3508 }
3509 return VERR_SVM_NO_SVM;
3510 }
3511 }
3512
3513 return VERR_UNSUPPORTED_CPU;
3514}
3515
3516
3517/**
3518 * (Re-)initializes the per-cpu structure prior to starting or resuming the GIP
3519 * updating.
3520 *
3521 * @param pGipCpu The per CPU structure for this CPU.
3522 * @param u64NanoTS The current time.
3523 */
3524static void supdrvGipReInitCpu(PSUPGIPCPU pGipCpu, uint64_t u64NanoTS)
3525{
3526 pGipCpu->u64TSC = ASMReadTSC() - pGipCpu->u32UpdateIntervalTSC;
3527 pGipCpu->u64NanoTS = u64NanoTS;
3528}
3529
3530
3531/**
3532 * Set the current TSC and NanoTS value for the CPU.
3533 *
3534 * @param idCpu The CPU ID. Unused - we have to use the APIC ID.
3535 * @param pvUser1 Pointer to the ring-0 GIP mapping.
3536 * @param pvUser2 Pointer to the variable holding the current time.
3537 */
3538static DECLCALLBACK(void) supdrvGipReInitCpuCallback(RTCPUID idCpu, void *pvUser1, void *pvUser2)
3539{
3540 PSUPGLOBALINFOPAGE pGip = (PSUPGLOBALINFOPAGE)pvUser1;
3541 unsigned iCpu = pGip->aiCpuFromApicId[ASMGetApicId()];
3542
3543 if (RT_LIKELY(iCpu < pGip->cCpus && pGip->aCPUs[iCpu].idCpu == idCpu))
3544 supdrvGipReInitCpu(&pGip->aCPUs[iCpu], *(uint64_t *)pvUser2);
3545
3546 NOREF(pvUser2);
3547 NOREF(idCpu);
3548}
3549
3550
3551/**
3552 * Maps the GIP into userspace and/or get the physical address of the GIP.
3553 *
3554 * @returns IPRT status code.
3555 * @param pSession Session to which the GIP mapping should belong.
3556 * @param ppGipR3 Where to store the address of the ring-3 mapping. (optional)
3557 * @param pHCPhysGip Where to store the physical address. (optional)
3558 *
3559 * @remark There is no reference counting on the mapping, so one call to this function
3560 * count globally as one reference. One call to SUPR0GipUnmap() is will unmap GIP
3561 * and remove the session as a GIP user.
3562 */
3563SUPR0DECL(int) SUPR0GipMap(PSUPDRVSESSION pSession, PRTR3PTR ppGipR3, PRTHCPHYS pHCPhysGip)
3564{
3565 int rc;
3566 PSUPDRVDEVEXT pDevExt = pSession->pDevExt;
3567 RTR3PTR pGipR3 = NIL_RTR3PTR;
3568 RTHCPHYS HCPhys = NIL_RTHCPHYS;
3569 LogFlow(("SUPR0GipMap: pSession=%p ppGipR3=%p pHCPhysGip=%p\n", pSession, ppGipR3, pHCPhysGip));
3570
3571 /*
3572 * Validate
3573 */
3574 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
3575 AssertPtrNullReturn(ppGipR3, VERR_INVALID_POINTER);
3576 AssertPtrNullReturn(pHCPhysGip, VERR_INVALID_POINTER);
3577
3578#ifdef SUPDRV_USE_MUTEX_FOR_GIP
3579 RTSemMutexRequest(pDevExt->mtxGip, RT_INDEFINITE_WAIT);
3580#else
3581 RTSemFastMutexRequest(pDevExt->mtxGip);
3582#endif
3583 if (pDevExt->pGip)
3584 {
3585 /*
3586 * Map it?
3587 */
3588 rc = VINF_SUCCESS;
3589 if (ppGipR3)
3590 {
3591 if (pSession->GipMapObjR3 == NIL_RTR0MEMOBJ)
3592 rc = RTR0MemObjMapUser(&pSession->GipMapObjR3, pDevExt->GipMemObj, (RTR3PTR)-1, 0,
3593 RTMEM_PROT_READ, RTR0ProcHandleSelf());
3594 if (RT_SUCCESS(rc))
3595 pGipR3 = RTR0MemObjAddressR3(pSession->GipMapObjR3);
3596 }
3597
3598 /*
3599 * Get physical address.
3600 */
3601 if (pHCPhysGip && RT_SUCCESS(rc))
3602 HCPhys = pDevExt->HCPhysGip;
3603
3604 /*
3605 * Reference globally.
3606 */
3607 if (!pSession->fGipReferenced && RT_SUCCESS(rc))
3608 {
3609 pSession->fGipReferenced = 1;
3610 pDevExt->cGipUsers++;
3611 if (pDevExt->cGipUsers == 1)
3612 {
3613 PSUPGLOBALINFOPAGE pGipR0 = pDevExt->pGip;
3614 uint64_t u64NanoTS;
3615 uint32_t u32SystemResolution;
3616 unsigned i;
3617
3618 LogFlow(("SUPR0GipMap: Resumes GIP updating\n"));
3619
3620 /*
3621 * Try bump up the system timer resolution.
3622 * The more interrupts the better...
3623 */
3624 if ( RT_SUCCESS_NP(RTTimerRequestSystemGranularity( 976563 /* 1024 HZ */, &u32SystemResolution))
3625 || RT_SUCCESS_NP(RTTimerRequestSystemGranularity( 1000000 /* 1000 HZ */, &u32SystemResolution))
3626 || RT_SUCCESS_NP(RTTimerRequestSystemGranularity( 1953125 /* 512 HZ */, &u32SystemResolution))
3627 || RT_SUCCESS_NP(RTTimerRequestSystemGranularity( 2000000 /* 500 HZ */, &u32SystemResolution))
3628 )
3629 {
3630 Assert(RTTimerGetSystemGranularity() <= u32SystemResolution);
3631 pDevExt->u32SystemTimerGranularityGrant = u32SystemResolution;
3632 }
3633
3634 if (pGipR0->aCPUs[0].u32TransactionId != 2 /* not the first time */)
3635 {
3636 for (i = 0; i < RT_ELEMENTS(pGipR0->aCPUs); i++)
3637 ASMAtomicUoWriteU32(&pGipR0->aCPUs[i].u32TransactionId,
3638 (pGipR0->aCPUs[i].u32TransactionId + GIP_UPDATEHZ_RECALC_FREQ * 2)
3639 & ~(GIP_UPDATEHZ_RECALC_FREQ * 2 - 1));
3640 ASMAtomicWriteU64(&pGipR0->u64NanoTSLastUpdateHz, 0);
3641 }
3642
3643 u64NanoTS = RTTimeSystemNanoTS() - pGipR0->u32UpdateIntervalNS;
3644 if ( pGipR0->u32Mode == SUPGIPMODE_SYNC_TSC
3645 || RTMpGetOnlineCount() == 1)
3646 supdrvGipReInitCpu(&pGipR0->aCPUs[0], u64NanoTS);
3647 else
3648 RTMpOnAll(supdrvGipReInitCpuCallback, pGipR0, &u64NanoTS);
3649
3650#ifndef DO_NOT_START_GIP
3651 rc = RTTimerStart(pDevExt->pGipTimer, 0); AssertRC(rc);
3652#endif
3653 rc = VINF_SUCCESS;
3654 }
3655 }
3656 }
3657 else
3658 {
3659 rc = VERR_GENERAL_FAILURE;
3660 Log(("SUPR0GipMap: GIP is not available!\n"));
3661 }
3662#ifdef SUPDRV_USE_MUTEX_FOR_GIP
3663 RTSemMutexRelease(pDevExt->mtxGip);
3664#else
3665 RTSemFastMutexRelease(pDevExt->mtxGip);
3666#endif
3667
3668 /*
3669 * Write returns.
3670 */
3671 if (pHCPhysGip)
3672 *pHCPhysGip = HCPhys;
3673 if (ppGipR3)
3674 *ppGipR3 = pGipR3;
3675
3676#ifdef DEBUG_DARWIN_GIP
3677 OSDBGPRINT(("SUPR0GipMap: returns %d *pHCPhysGip=%lx pGipR3=%p\n", rc, (unsigned long)HCPhys, (void *)pGipR3));
3678#else
3679 LogFlow(( "SUPR0GipMap: returns %d *pHCPhysGip=%lx pGipR3=%p\n", rc, (unsigned long)HCPhys, (void *)pGipR3));
3680#endif
3681 return rc;
3682}
3683
3684
3685/**
3686 * Unmaps any user mapping of the GIP and terminates all GIP access
3687 * from this session.
3688 *
3689 * @returns IPRT status code.
3690 * @param pSession Session to which the GIP mapping should belong.
3691 */
3692SUPR0DECL(int) SUPR0GipUnmap(PSUPDRVSESSION pSession)
3693{
3694 int rc = VINF_SUCCESS;
3695 PSUPDRVDEVEXT pDevExt = pSession->pDevExt;
3696#ifdef DEBUG_DARWIN_GIP
3697 OSDBGPRINT(("SUPR0GipUnmap: pSession=%p pGip=%p GipMapObjR3=%p\n",
3698 pSession,
3699 pSession->GipMapObjR3 != NIL_RTR0MEMOBJ ? RTR0MemObjAddress(pSession->GipMapObjR3) : NULL,
3700 pSession->GipMapObjR3));
3701#else
3702 LogFlow(("SUPR0GipUnmap: pSession=%p\n", pSession));
3703#endif
3704 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
3705
3706#ifdef SUPDRV_USE_MUTEX_FOR_GIP
3707 RTSemMutexRequest(pDevExt->mtxGip, RT_INDEFINITE_WAIT);
3708#else
3709 RTSemFastMutexRequest(pDevExt->mtxGip);
3710#endif
3711
3712 /*
3713 * Unmap anything?
3714 */
3715 if (pSession->GipMapObjR3 != NIL_RTR0MEMOBJ)
3716 {
3717 rc = RTR0MemObjFree(pSession->GipMapObjR3, false);
3718 AssertRC(rc);
3719 if (RT_SUCCESS(rc))
3720 pSession->GipMapObjR3 = NIL_RTR0MEMOBJ;
3721 }
3722
3723 /*
3724 * Dereference global GIP.
3725 */
3726 if (pSession->fGipReferenced && !rc)
3727 {
3728 pSession->fGipReferenced = 0;
3729 if ( pDevExt->cGipUsers > 0
3730 && !--pDevExt->cGipUsers)
3731 {
3732 LogFlow(("SUPR0GipUnmap: Suspends GIP updating\n"));
3733#ifndef DO_NOT_START_GIP
3734 rc = RTTimerStop(pDevExt->pGipTimer); AssertRC(rc); rc = VINF_SUCCESS;
3735#endif
3736
3737 if (pDevExt->u32SystemTimerGranularityGrant)
3738 {
3739 int rc2 = RTTimerReleaseSystemGranularity(pDevExt->u32SystemTimerGranularityGrant);
3740 AssertRC(rc2);
3741 pDevExt->u32SystemTimerGranularityGrant = 0;
3742 }
3743 }
3744 }
3745
3746#ifdef SUPDRV_USE_MUTEX_FOR_GIP
3747 RTSemMutexRelease(pDevExt->mtxGip);
3748#else
3749 RTSemFastMutexRelease(pDevExt->mtxGip);
3750#endif
3751
3752 return rc;
3753}
3754
3755
3756/**
3757 * Gets the GIP pointer.
3758 *
3759 * @returns Pointer to the GIP or NULL.
3760 */
3761SUPDECL(PSUPGLOBALINFOPAGE) SUPGetGIP(void)
3762{
3763 return g_pSUPGlobalInfoPage;
3764}
3765
3766
3767/**
3768 * Register a component factory with the support driver.
3769 *
3770 * This is currently restricted to kernel sessions only.
3771 *
3772 * @returns VBox status code.
3773 * @retval VINF_SUCCESS on success.
3774 * @retval VERR_NO_MEMORY if we're out of memory.
3775 * @retval VERR_ALREADY_EXISTS if the factory has already been registered.
3776 * @retval VERR_ACCESS_DENIED if it isn't a kernel session.
3777 * @retval VERR_INVALID_PARAMETER on invalid parameter.
3778 * @retval VERR_INVALID_POINTER on invalid pointer parameter.
3779 *
3780 * @param pSession The SUPDRV session (must be a ring-0 session).
3781 * @param pFactory Pointer to the component factory registration structure.
3782 *
3783 * @remarks This interface is also available via SUPR0IdcComponentRegisterFactory.
3784 */
3785SUPR0DECL(int) SUPR0ComponentRegisterFactory(PSUPDRVSESSION pSession, PCSUPDRVFACTORY pFactory)
3786{
3787 PSUPDRVFACTORYREG pNewReg;
3788 const char *psz;
3789 int rc;
3790
3791 /*
3792 * Validate parameters.
3793 */
3794 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
3795 AssertReturn(pSession->R0Process == NIL_RTR0PROCESS, VERR_ACCESS_DENIED);
3796 AssertPtrReturn(pFactory, VERR_INVALID_POINTER);
3797 AssertPtrReturn(pFactory->pfnQueryFactoryInterface, VERR_INVALID_POINTER);
3798 psz = RTStrEnd(pFactory->szName, sizeof(pFactory->szName));
3799 AssertReturn(psz, VERR_INVALID_PARAMETER);
3800
3801 /*
3802 * Allocate and initialize a new registration structure.
3803 */
3804 pNewReg = (PSUPDRVFACTORYREG)RTMemAlloc(sizeof(SUPDRVFACTORYREG));
3805 if (pNewReg)
3806 {
3807 pNewReg->pNext = NULL;
3808 pNewReg->pFactory = pFactory;
3809 pNewReg->pSession = pSession;
3810 pNewReg->cchName = psz - &pFactory->szName[0];
3811
3812 /*
3813 * Add it to the tail of the list after checking for prior registration.
3814 */
3815 rc = RTSemFastMutexRequest(pSession->pDevExt->mtxComponentFactory);
3816 if (RT_SUCCESS(rc))
3817 {
3818 PSUPDRVFACTORYREG pPrev = NULL;
3819 PSUPDRVFACTORYREG pCur = pSession->pDevExt->pComponentFactoryHead;
3820 while (pCur && pCur->pFactory != pFactory)
3821 {
3822 pPrev = pCur;
3823 pCur = pCur->pNext;
3824 }
3825 if (!pCur)
3826 {
3827 if (pPrev)
3828 pPrev->pNext = pNewReg;
3829 else
3830 pSession->pDevExt->pComponentFactoryHead = pNewReg;
3831 rc = VINF_SUCCESS;
3832 }
3833 else
3834 rc = VERR_ALREADY_EXISTS;
3835
3836 RTSemFastMutexRelease(pSession->pDevExt->mtxComponentFactory);
3837 }
3838
3839 if (RT_FAILURE(rc))
3840 RTMemFree(pNewReg);
3841 }
3842 else
3843 rc = VERR_NO_MEMORY;
3844 return rc;
3845}
3846
3847
3848/**
3849 * Deregister a component factory.
3850 *
3851 * @returns VBox status code.
3852 * @retval VINF_SUCCESS on success.
3853 * @retval VERR_NOT_FOUND if the factory wasn't registered.
3854 * @retval VERR_ACCESS_DENIED if it isn't a kernel session.
3855 * @retval VERR_INVALID_PARAMETER on invalid parameter.
3856 * @retval VERR_INVALID_POINTER on invalid pointer parameter.
3857 *
3858 * @param pSession The SUPDRV session (must be a ring-0 session).
3859 * @param pFactory Pointer to the component factory registration structure
3860 * previously passed SUPR0ComponentRegisterFactory().
3861 *
3862 * @remarks This interface is also available via SUPR0IdcComponentDeregisterFactory.
3863 */
3864SUPR0DECL(int) SUPR0ComponentDeregisterFactory(PSUPDRVSESSION pSession, PCSUPDRVFACTORY pFactory)
3865{
3866 int rc;
3867
3868 /*
3869 * Validate parameters.
3870 */
3871 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
3872 AssertReturn(pSession->R0Process == NIL_RTR0PROCESS, VERR_ACCESS_DENIED);
3873 AssertPtrReturn(pFactory, VERR_INVALID_POINTER);
3874
3875 /*
3876 * Take the lock and look for the registration record.
3877 */
3878 rc = RTSemFastMutexRequest(pSession->pDevExt->mtxComponentFactory);
3879 if (RT_SUCCESS(rc))
3880 {
3881 PSUPDRVFACTORYREG pPrev = NULL;
3882 PSUPDRVFACTORYREG pCur = pSession->pDevExt->pComponentFactoryHead;
3883 while (pCur && pCur->pFactory != pFactory)
3884 {
3885 pPrev = pCur;
3886 pCur = pCur->pNext;
3887 }
3888 if (pCur)
3889 {
3890 if (!pPrev)
3891 pSession->pDevExt->pComponentFactoryHead = pCur->pNext;
3892 else
3893 pPrev->pNext = pCur->pNext;
3894
3895 pCur->pNext = NULL;
3896 pCur->pFactory = NULL;
3897 pCur->pSession = NULL;
3898 rc = VINF_SUCCESS;
3899 }
3900 else
3901 rc = VERR_NOT_FOUND;
3902
3903 RTSemFastMutexRelease(pSession->pDevExt->mtxComponentFactory);
3904
3905 RTMemFree(pCur);
3906 }
3907 return rc;
3908}
3909
3910
3911/**
3912 * Queries a component factory.
3913 *
3914 * @returns VBox status code.
3915 * @retval VERR_INVALID_PARAMETER on invalid parameter.
3916 * @retval VERR_INVALID_POINTER on invalid pointer parameter.
3917 * @retval VERR_SUPDRV_COMPONENT_NOT_FOUND if the component factory wasn't found.
3918 * @retval VERR_SUPDRV_INTERFACE_NOT_SUPPORTED if the interface wasn't supported.
3919 *
3920 * @param pSession The SUPDRV session.
3921 * @param pszName The name of the component factory.
3922 * @param pszInterfaceUuid The UUID of the factory interface (stringified).
3923 * @param ppvFactoryIf Where to store the factory interface.
3924 */
3925SUPR0DECL(int) SUPR0ComponentQueryFactory(PSUPDRVSESSION pSession, const char *pszName, const char *pszInterfaceUuid, void **ppvFactoryIf)
3926{
3927 const char *pszEnd;
3928 size_t cchName;
3929 int rc;
3930
3931 /*
3932 * Validate parameters.
3933 */
3934 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
3935
3936 AssertPtrReturn(pszName, VERR_INVALID_POINTER);
3937 pszEnd = RTStrEnd(pszName, RT_SIZEOFMEMB(SUPDRVFACTORY, szName));
3938 AssertReturn(pszEnd, VERR_INVALID_PARAMETER);
3939 cchName = pszEnd - pszName;
3940
3941 AssertPtrReturn(pszInterfaceUuid, VERR_INVALID_POINTER);
3942 pszEnd = RTStrEnd(pszInterfaceUuid, RTUUID_STR_LENGTH);
3943 AssertReturn(pszEnd, VERR_INVALID_PARAMETER);
3944
3945 AssertPtrReturn(ppvFactoryIf, VERR_INVALID_POINTER);
3946 *ppvFactoryIf = NULL;
3947
3948 /*
3949 * Take the lock and try all factories by this name.
3950 */
3951 rc = RTSemFastMutexRequest(pSession->pDevExt->mtxComponentFactory);
3952 if (RT_SUCCESS(rc))
3953 {
3954 PSUPDRVFACTORYREG pCur = pSession->pDevExt->pComponentFactoryHead;
3955 rc = VERR_SUPDRV_COMPONENT_NOT_FOUND;
3956 while (pCur)
3957 {
3958 if ( pCur->cchName == cchName
3959 && !memcmp(pCur->pFactory->szName, pszName, cchName))
3960 {
3961 void *pvFactory = pCur->pFactory->pfnQueryFactoryInterface(pCur->pFactory, pSession, pszInterfaceUuid);
3962 if (pvFactory)
3963 {
3964 *ppvFactoryIf = pvFactory;
3965 rc = VINF_SUCCESS;
3966 break;
3967 }
3968 rc = VERR_SUPDRV_INTERFACE_NOT_SUPPORTED;
3969 }
3970
3971 /* next */
3972 pCur = pCur->pNext;
3973 }
3974
3975 RTSemFastMutexRelease(pSession->pDevExt->mtxComponentFactory);
3976 }
3977 return rc;
3978}
3979
3980
3981/**
3982 * Adds a memory object to the session.
3983 *
3984 * @returns IPRT status code.
3985 * @param pMem Memory tracking structure containing the
3986 * information to track.
3987 * @param pSession The session.
3988 */
3989static int supdrvMemAdd(PSUPDRVMEMREF pMem, PSUPDRVSESSION pSession)
3990{
3991 PSUPDRVBUNDLE pBundle;
3992
3993 /*
3994 * Find free entry and record the allocation.
3995 */
3996 RTSpinlockAcquire(pSession->Spinlock);
3997 for (pBundle = &pSession->Bundle; pBundle; pBundle = pBundle->pNext)
3998 {
3999 if (pBundle->cUsed < RT_ELEMENTS(pBundle->aMem))
4000 {
4001 unsigned i;
4002 for (i = 0; i < RT_ELEMENTS(pBundle->aMem); i++)
4003 {
4004 if (pBundle->aMem[i].MemObj == NIL_RTR0MEMOBJ)
4005 {
4006 pBundle->cUsed++;
4007 pBundle->aMem[i] = *pMem;
4008 RTSpinlockRelease(pSession->Spinlock);
4009 return VINF_SUCCESS;
4010 }
4011 }
4012 AssertFailed(); /* !!this can't be happening!!! */
4013 }
4014 }
4015 RTSpinlockRelease(pSession->Spinlock);
4016
4017 /*
4018 * Need to allocate a new bundle.
4019 * Insert into the last entry in the bundle.
4020 */
4021 pBundle = (PSUPDRVBUNDLE)RTMemAllocZ(sizeof(*pBundle));
4022 if (!pBundle)
4023 return VERR_NO_MEMORY;
4024
4025 /* take last entry. */
4026 pBundle->cUsed++;
4027 pBundle->aMem[RT_ELEMENTS(pBundle->aMem) - 1] = *pMem;
4028
4029 /* insert into list. */
4030 RTSpinlockAcquire(pSession->Spinlock);
4031 pBundle->pNext = pSession->Bundle.pNext;
4032 pSession->Bundle.pNext = pBundle;
4033 RTSpinlockRelease(pSession->Spinlock);
4034
4035 return VINF_SUCCESS;
4036}
4037
4038
4039/**
4040 * Releases a memory object referenced by pointer and type.
4041 *
4042 * @returns IPRT status code.
4043 * @param pSession Session data.
4044 * @param uPtr Pointer to memory. This is matched against both the R0 and R3 addresses.
4045 * @param eType Memory type.
4046 */
4047static int supdrvMemRelease(PSUPDRVSESSION pSession, RTHCUINTPTR uPtr, SUPDRVMEMREFTYPE eType)
4048{
4049 PSUPDRVBUNDLE pBundle;
4050
4051 /*
4052 * Validate input.
4053 */
4054 if (!uPtr)
4055 {
4056 Log(("Illegal address %p\n", (void *)uPtr));
4057 return VERR_INVALID_PARAMETER;
4058 }
4059
4060 /*
4061 * Search for the address.
4062 */
4063 RTSpinlockAcquire(pSession->Spinlock);
4064 for (pBundle = &pSession->Bundle; pBundle; pBundle = pBundle->pNext)
4065 {
4066 if (pBundle->cUsed > 0)
4067 {
4068 unsigned i;
4069 for (i = 0; i < RT_ELEMENTS(pBundle->aMem); i++)
4070 {
4071 if ( pBundle->aMem[i].eType == eType
4072 && pBundle->aMem[i].MemObj != NIL_RTR0MEMOBJ
4073 && ( (RTHCUINTPTR)RTR0MemObjAddress(pBundle->aMem[i].MemObj) == uPtr
4074 || ( pBundle->aMem[i].MapObjR3 != NIL_RTR0MEMOBJ
4075 && RTR0MemObjAddressR3(pBundle->aMem[i].MapObjR3) == uPtr))
4076 )
4077 {
4078 /* Make a copy of it and release it outside the spinlock. */
4079 SUPDRVMEMREF Mem = pBundle->aMem[i];
4080 pBundle->aMem[i].eType = MEMREF_TYPE_UNUSED;
4081 pBundle->aMem[i].MemObj = NIL_RTR0MEMOBJ;
4082 pBundle->aMem[i].MapObjR3 = NIL_RTR0MEMOBJ;
4083 RTSpinlockRelease(pSession->Spinlock);
4084
4085 if (Mem.MapObjR3 != NIL_RTR0MEMOBJ)
4086 {
4087 int rc = RTR0MemObjFree(Mem.MapObjR3, false);
4088 AssertRC(rc); /** @todo figure out how to handle this. */
4089 }
4090 if (Mem.MemObj != NIL_RTR0MEMOBJ)
4091 {
4092 int rc = RTR0MemObjFree(Mem.MemObj, true /* fFreeMappings */);
4093 AssertRC(rc); /** @todo figure out how to handle this. */
4094 }
4095 return VINF_SUCCESS;
4096 }
4097 }
4098 }
4099 }
4100 RTSpinlockRelease(pSession->Spinlock);
4101 Log(("Failed to find %p!!! (eType=%d)\n", (void *)uPtr, eType));
4102 return VERR_INVALID_PARAMETER;
4103}
4104
4105
4106/**
4107 * Opens an image. If it's the first time it's opened the call must upload
4108 * the bits using the supdrvIOCtl_LdrLoad() / SUPDRV_IOCTL_LDR_LOAD function.
4109 *
4110 * This is the 1st step of the loading.
4111 *
4112 * @returns IPRT status code.
4113 * @param pDevExt Device globals.
4114 * @param pSession Session data.
4115 * @param pReq The open request.
4116 */
4117static int supdrvIOCtl_LdrOpen(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPLDROPEN pReq)
4118{
4119 int rc;
4120 PSUPDRVLDRIMAGE pImage;
4121 void *pv;
4122 size_t cchName = strlen(pReq->u.In.szName); /* (caller checked < 32). */
4123 LogFlow(("supdrvIOCtl_LdrOpen: szName=%s cbImageWithTabs=%d\n", pReq->u.In.szName, pReq->u.In.cbImageWithTabs));
4124
4125 /*
4126 * Check if we got an instance of the image already.
4127 */
4128 supdrvLdrLock(pDevExt);
4129 for (pImage = pDevExt->pLdrImages; pImage; pImage = pImage->pNext)
4130 {
4131 if ( pImage->szName[cchName] == '\0'
4132 && !memcmp(pImage->szName, pReq->u.In.szName, cchName))
4133 {
4134 /** @todo check cbImageBits and cbImageWithTabs here, if they differs that indicates that the images are different. */
4135 pImage->cUsage++;
4136 pReq->u.Out.pvImageBase = pImage->pvImage;
4137 pReq->u.Out.fNeedsLoading = pImage->uState == SUP_IOCTL_LDR_OPEN;
4138 pReq->u.Out.fNativeLoader = pImage->fNative;
4139 supdrvLdrAddUsage(pSession, pImage);
4140 supdrvLdrUnlock(pDevExt);
4141 return VINF_SUCCESS;
4142 }
4143 }
4144 /* (not found - add it!) */
4145
4146 /*
4147 * Allocate memory.
4148 */
4149 Assert(cchName < sizeof(pImage->szName));
4150 pv = RTMemAlloc(sizeof(SUPDRVLDRIMAGE));
4151 if (!pv)
4152 {
4153 supdrvLdrUnlock(pDevExt);
4154 Log(("supdrvIOCtl_LdrOpen: RTMemAlloc() failed\n"));
4155 return /*VERR_NO_MEMORY*/ VERR_INTERNAL_ERROR_2;
4156 }
4157
4158 /*
4159 * Setup and link in the LDR stuff.
4160 */
4161 pImage = (PSUPDRVLDRIMAGE)pv;
4162 pImage->pvImage = NULL;
4163 pImage->pvImageAlloc = NULL;
4164 pImage->cbImageWithTabs = pReq->u.In.cbImageWithTabs;
4165 pImage->cbImageBits = pReq->u.In.cbImageBits;
4166 pImage->cSymbols = 0;
4167 pImage->paSymbols = NULL;
4168 pImage->pachStrTab = NULL;
4169 pImage->cbStrTab = 0;
4170 pImage->pfnModuleInit = NULL;
4171 pImage->pfnModuleTerm = NULL;
4172 pImage->pfnServiceReqHandler = NULL;
4173 pImage->uState = SUP_IOCTL_LDR_OPEN;
4174 pImage->cUsage = 1;
4175 pImage->pDevExt = pDevExt;
4176 memcpy(pImage->szName, pReq->u.In.szName, cchName + 1);
4177
4178 /*
4179 * Try load it using the native loader, if that isn't supported, fall back
4180 * on the older method.
4181 */
4182 pImage->fNative = true;
4183 rc = supdrvOSLdrOpen(pDevExt, pImage, pReq->u.In.szFilename);
4184 if (rc == VERR_NOT_SUPPORTED)
4185 {
4186 pImage->pvImageAlloc = RTMemExecAlloc(pImage->cbImageBits + 31);
4187 pImage->pvImage = RT_ALIGN_P(pImage->pvImageAlloc, 32);
4188 pImage->fNative = false;
4189 rc = pImage->pvImageAlloc ? VINF_SUCCESS : VERR_NO_EXEC_MEMORY;
4190 }
4191 if (RT_FAILURE(rc))
4192 {
4193 supdrvLdrUnlock(pDevExt);
4194 RTMemFree(pImage);
4195 Log(("supdrvIOCtl_LdrOpen(%s): failed - %Rrc\n", pReq->u.In.szName, rc));
4196 return rc;
4197 }
4198 Assert(VALID_PTR(pImage->pvImage) || RT_FAILURE(rc));
4199
4200 /*
4201 * Link it.
4202 */
4203 pImage->pNext = pDevExt->pLdrImages;
4204 pDevExt->pLdrImages = pImage;
4205
4206 supdrvLdrAddUsage(pSession, pImage);
4207
4208 pReq->u.Out.pvImageBase = pImage->pvImage;
4209 pReq->u.Out.fNeedsLoading = true;
4210 pReq->u.Out.fNativeLoader = pImage->fNative;
4211 supdrvOSLdrNotifyOpened(pDevExt, pImage);
4212
4213 supdrvLdrUnlock(pDevExt);
4214 return VINF_SUCCESS;
4215}
4216
4217
4218/**
4219 * Worker that validates a pointer to an image entrypoint.
4220 *
4221 * @returns IPRT status code.
4222 * @param pDevExt The device globals.
4223 * @param pImage The loader image.
4224 * @param pv The pointer into the image.
4225 * @param fMayBeNull Whether it may be NULL.
4226 * @param pszWhat What is this entrypoint? (for logging)
4227 * @param pbImageBits The image bits prepared by ring-3.
4228 *
4229 * @remarks Will leave the lock on failure.
4230 */
4231static int supdrvLdrValidatePointer(PSUPDRVDEVEXT pDevExt, PSUPDRVLDRIMAGE pImage, void *pv,
4232 bool fMayBeNull, const uint8_t *pbImageBits, const char *pszWhat)
4233{
4234 if (!fMayBeNull || pv)
4235 {
4236 if ((uintptr_t)pv - (uintptr_t)pImage->pvImage >= pImage->cbImageBits)
4237 {
4238 supdrvLdrUnlock(pDevExt);
4239 Log(("Out of range (%p LB %#x): %s=%p\n", pImage->pvImage, pImage->cbImageBits, pszWhat, pv));
4240 return VERR_INVALID_PARAMETER;
4241 }
4242
4243 if (pImage->fNative)
4244 {
4245 int rc = supdrvOSLdrValidatePointer(pDevExt, pImage, pv, pbImageBits);
4246 if (RT_FAILURE(rc))
4247 {
4248 supdrvLdrUnlock(pDevExt);
4249 Log(("Bad entry point address: %s=%p (rc=%Rrc)\n", pszWhat, pv, rc));
4250 return rc;
4251 }
4252 }
4253 }
4254 return VINF_SUCCESS;
4255}
4256
4257
4258/**
4259 * Loads the image bits.
4260 *
4261 * This is the 2nd step of the loading.
4262 *
4263 * @returns IPRT status code.
4264 * @param pDevExt Device globals.
4265 * @param pSession Session data.
4266 * @param pReq The request.
4267 */
4268static int supdrvIOCtl_LdrLoad(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPLDRLOAD pReq)
4269{
4270 PSUPDRVLDRUSAGE pUsage;
4271 PSUPDRVLDRIMAGE pImage;
4272 int rc;
4273 LogFlow(("supdrvIOCtl_LdrLoad: pvImageBase=%p cbImageWithBits=%d\n", pReq->u.In.pvImageBase, pReq->u.In.cbImageWithTabs));
4274
4275 /*
4276 * Find the ldr image.
4277 */
4278 supdrvLdrLock(pDevExt);
4279 pUsage = pSession->pLdrUsage;
4280 while (pUsage && pUsage->pImage->pvImage != pReq->u.In.pvImageBase)
4281 pUsage = pUsage->pNext;
4282 if (!pUsage)
4283 {
4284 supdrvLdrUnlock(pDevExt);
4285 Log(("SUP_IOCTL_LDR_LOAD: couldn't find image!\n"));
4286 return VERR_INVALID_HANDLE;
4287 }
4288 pImage = pUsage->pImage;
4289
4290 /*
4291 * Validate input.
4292 */
4293 if ( pImage->cbImageWithTabs != pReq->u.In.cbImageWithTabs
4294 || pImage->cbImageBits != pReq->u.In.cbImageBits)
4295 {
4296 supdrvLdrUnlock(pDevExt);
4297 Log(("SUP_IOCTL_LDR_LOAD: image size mismatch!! %d(prep) != %d(load) or %d != %d\n",
4298 pImage->cbImageWithTabs, pReq->u.In.cbImageWithTabs, pImage->cbImageBits, pReq->u.In.cbImageBits));
4299 return VERR_INVALID_HANDLE;
4300 }
4301
4302 if (pImage->uState != SUP_IOCTL_LDR_OPEN)
4303 {
4304 unsigned uState = pImage->uState;
4305 supdrvLdrUnlock(pDevExt);
4306 if (uState != SUP_IOCTL_LDR_LOAD)
4307 AssertMsgFailed(("SUP_IOCTL_LDR_LOAD: invalid image state %d (%#x)!\n", uState, uState));
4308 return VERR_ALREADY_LOADED;
4309 }
4310
4311 switch (pReq->u.In.eEPType)
4312 {
4313 case SUPLDRLOADEP_NOTHING:
4314 break;
4315
4316 case SUPLDRLOADEP_VMMR0:
4317 rc = supdrvLdrValidatePointer( pDevExt, pImage, pReq->u.In.EP.VMMR0.pvVMMR0, false, pReq->u.In.abImage, "pvVMMR0");
4318 if (RT_SUCCESS(rc))
4319 rc = supdrvLdrValidatePointer(pDevExt, pImage, pReq->u.In.EP.VMMR0.pvVMMR0EntryInt, false, pReq->u.In.abImage, "pvVMMR0EntryInt");
4320 if (RT_SUCCESS(rc))
4321 rc = supdrvLdrValidatePointer(pDevExt, pImage, pReq->u.In.EP.VMMR0.pvVMMR0EntryFast, false, pReq->u.In.abImage, "pvVMMR0EntryFast");
4322 if (RT_SUCCESS(rc))
4323 rc = supdrvLdrValidatePointer(pDevExt, pImage, pReq->u.In.EP.VMMR0.pvVMMR0EntryEx, false, pReq->u.In.abImage, "pvVMMR0EntryEx");
4324 if (RT_FAILURE(rc))
4325 return rc;
4326 break;
4327
4328 case SUPLDRLOADEP_SERVICE:
4329 rc = supdrvLdrValidatePointer(pDevExt, pImage, pReq->u.In.EP.Service.pfnServiceReq, false, pReq->u.In.abImage, "pfnServiceReq");
4330 if (RT_FAILURE(rc))
4331 return rc;
4332 if ( pReq->u.In.EP.Service.apvReserved[0] != NIL_RTR0PTR
4333 || pReq->u.In.EP.Service.apvReserved[1] != NIL_RTR0PTR
4334 || pReq->u.In.EP.Service.apvReserved[2] != NIL_RTR0PTR)
4335 {
4336 supdrvLdrUnlock(pDevExt);
4337 Log(("Out of range (%p LB %#x): apvReserved={%p,%p,%p} MBZ!\n",
4338 pImage->pvImage, pReq->u.In.cbImageWithTabs,
4339 pReq->u.In.EP.Service.apvReserved[0],
4340 pReq->u.In.EP.Service.apvReserved[1],
4341 pReq->u.In.EP.Service.apvReserved[2]));
4342 return VERR_INVALID_PARAMETER;
4343 }
4344 break;
4345
4346 default:
4347 supdrvLdrUnlock(pDevExt);
4348 Log(("Invalid eEPType=%d\n", pReq->u.In.eEPType));
4349 return VERR_INVALID_PARAMETER;
4350 }
4351
4352 rc = supdrvLdrValidatePointer(pDevExt, pImage, pReq->u.In.pfnModuleInit, true, pReq->u.In.abImage, "pfnModuleInit");
4353 if (RT_FAILURE(rc))
4354 return rc;
4355 rc = supdrvLdrValidatePointer(pDevExt, pImage, pReq->u.In.pfnModuleTerm, true, pReq->u.In.abImage, "pfnModuleTerm");
4356 if (RT_FAILURE(rc))
4357 return rc;
4358
4359 /*
4360 * Allocate and copy the tables.
4361 * (No need to do try/except as this is a buffered request.)
4362 */
4363 pImage->cbStrTab = pReq->u.In.cbStrTab;
4364 if (pImage->cbStrTab)
4365 {
4366 pImage->pachStrTab = (char *)RTMemAlloc(pImage->cbStrTab);
4367 if (pImage->pachStrTab)
4368 memcpy(pImage->pachStrTab, &pReq->u.In.abImage[pReq->u.In.offStrTab], pImage->cbStrTab);
4369 else
4370 rc = /*VERR_NO_MEMORY*/ VERR_INTERNAL_ERROR_3;
4371 }
4372
4373 pImage->cSymbols = pReq->u.In.cSymbols;
4374 if (RT_SUCCESS(rc) && pImage->cSymbols)
4375 {
4376 size_t cbSymbols = pImage->cSymbols * sizeof(SUPLDRSYM);
4377 pImage->paSymbols = (PSUPLDRSYM)RTMemAlloc(cbSymbols);
4378 if (pImage->paSymbols)
4379 memcpy(pImage->paSymbols, &pReq->u.In.abImage[pReq->u.In.offSymbols], cbSymbols);
4380 else
4381 rc = /*VERR_NO_MEMORY*/ VERR_INTERNAL_ERROR_4;
4382 }
4383
4384 /*
4385 * Copy the bits / complete native loading.
4386 */
4387 if (RT_SUCCESS(rc))
4388 {
4389 pImage->uState = SUP_IOCTL_LDR_LOAD;
4390 pImage->pfnModuleInit = pReq->u.In.pfnModuleInit;
4391 pImage->pfnModuleTerm = pReq->u.In.pfnModuleTerm;
4392
4393 if (pImage->fNative)
4394 rc = supdrvOSLdrLoad(pDevExt, pImage, pReq->u.In.abImage, pReq);
4395 else
4396 {
4397 memcpy(pImage->pvImage, &pReq->u.In.abImage[0], pImage->cbImageBits);
4398 Log(("vboxdrv: Loaded '%s' at %p\n", pImage->szName, pImage->pvImage));
4399 }
4400 }
4401
4402 /*
4403 * Update any entry points.
4404 */
4405 if (RT_SUCCESS(rc))
4406 {
4407 switch (pReq->u.In.eEPType)
4408 {
4409 default:
4410 case SUPLDRLOADEP_NOTHING:
4411 rc = VINF_SUCCESS;
4412 break;
4413 case SUPLDRLOADEP_VMMR0:
4414 rc = supdrvLdrSetVMMR0EPs(pDevExt, pReq->u.In.EP.VMMR0.pvVMMR0, pReq->u.In.EP.VMMR0.pvVMMR0EntryInt,
4415 pReq->u.In.EP.VMMR0.pvVMMR0EntryFast, pReq->u.In.EP.VMMR0.pvVMMR0EntryEx);
4416 break;
4417 case SUPLDRLOADEP_SERVICE:
4418 pImage->pfnServiceReqHandler = pReq->u.In.EP.Service.pfnServiceReq;
4419 rc = VINF_SUCCESS;
4420 break;
4421 }
4422 }
4423
4424 /*
4425 * On success call the module initialization.
4426 */
4427 LogFlow(("supdrvIOCtl_LdrLoad: pfnModuleInit=%p\n", pImage->pfnModuleInit));
4428 if (RT_SUCCESS(rc) && pImage->pfnModuleInit)
4429 {
4430 Log(("supdrvIOCtl_LdrLoad: calling pfnModuleInit=%p\n", pImage->pfnModuleInit));
4431 pDevExt->pLdrInitImage = pImage;
4432 pDevExt->hLdrInitThread = RTThreadNativeSelf();
4433 rc = pImage->pfnModuleInit(pImage);
4434 pDevExt->pLdrInitImage = NULL;
4435 pDevExt->hLdrInitThread = NIL_RTNATIVETHREAD;
4436 if (RT_FAILURE(rc) && pDevExt->pvVMMR0 == pImage->pvImage)
4437 supdrvLdrUnsetVMMR0EPs(pDevExt);
4438 }
4439
4440 if (RT_FAILURE(rc))
4441 {
4442 /* Inform the tracing component in case ModuleInit registered TPs. */
4443 supdrvTracerModuleUnloading(pDevExt, pImage);
4444
4445 pImage->uState = SUP_IOCTL_LDR_OPEN;
4446 pImage->pfnModuleInit = NULL;
4447 pImage->pfnModuleTerm = NULL;
4448 pImage->pfnServiceReqHandler= NULL;
4449 pImage->cbStrTab = 0;
4450 RTMemFree(pImage->pachStrTab);
4451 pImage->pachStrTab = NULL;
4452 RTMemFree(pImage->paSymbols);
4453 pImage->paSymbols = NULL;
4454 pImage->cSymbols = 0;
4455 }
4456
4457 supdrvLdrUnlock(pDevExt);
4458 return rc;
4459}
4460
4461
4462/**
4463 * Frees a previously loaded (prep'ed) image.
4464 *
4465 * @returns IPRT status code.
4466 * @param pDevExt Device globals.
4467 * @param pSession Session data.
4468 * @param pReq The request.
4469 */
4470static int supdrvIOCtl_LdrFree(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPLDRFREE pReq)
4471{
4472 int rc;
4473 PSUPDRVLDRUSAGE pUsagePrev;
4474 PSUPDRVLDRUSAGE pUsage;
4475 PSUPDRVLDRIMAGE pImage;
4476 LogFlow(("supdrvIOCtl_LdrFree: pvImageBase=%p\n", pReq->u.In.pvImageBase));
4477
4478 /*
4479 * Find the ldr image.
4480 */
4481 supdrvLdrLock(pDevExt);
4482 pUsagePrev = NULL;
4483 pUsage = pSession->pLdrUsage;
4484 while (pUsage && pUsage->pImage->pvImage != pReq->u.In.pvImageBase)
4485 {
4486 pUsagePrev = pUsage;
4487 pUsage = pUsage->pNext;
4488 }
4489 if (!pUsage)
4490 {
4491 supdrvLdrUnlock(pDevExt);
4492 Log(("SUP_IOCTL_LDR_FREE: couldn't find image!\n"));
4493 return VERR_INVALID_HANDLE;
4494 }
4495
4496 /*
4497 * Check if we can remove anything.
4498 */
4499 rc = VINF_SUCCESS;
4500 pImage = pUsage->pImage;
4501 if (pImage->cUsage <= 1 || pUsage->cUsage <= 1)
4502 {
4503 /*
4504 * Check if there are any objects with destructors in the image, if
4505 * so leave it for the session cleanup routine so we get a chance to
4506 * clean things up in the right order and not leave them all dangling.
4507 */
4508 RTSpinlockAcquire(pDevExt->Spinlock);
4509 if (pImage->cUsage <= 1)
4510 {
4511 PSUPDRVOBJ pObj;
4512 for (pObj = pDevExt->pObjs; pObj; pObj = pObj->pNext)
4513 if (RT_UNLIKELY((uintptr_t)pObj->pfnDestructor - (uintptr_t)pImage->pvImage < pImage->cbImageBits))
4514 {
4515 rc = VERR_DANGLING_OBJECTS;
4516 break;
4517 }
4518 }
4519 else
4520 {
4521 PSUPDRVUSAGE pGenUsage;
4522 for (pGenUsage = pSession->pUsage; pGenUsage; pGenUsage = pGenUsage->pNext)
4523 if (RT_UNLIKELY((uintptr_t)pGenUsage->pObj->pfnDestructor - (uintptr_t)pImage->pvImage < pImage->cbImageBits))
4524 {
4525 rc = VERR_DANGLING_OBJECTS;
4526 break;
4527 }
4528 }
4529 RTSpinlockRelease(pDevExt->Spinlock);
4530 if (rc == VINF_SUCCESS)
4531 {
4532 /* unlink it */
4533 if (pUsagePrev)
4534 pUsagePrev->pNext = pUsage->pNext;
4535 else
4536 pSession->pLdrUsage = pUsage->pNext;
4537
4538 /* free it */
4539 pUsage->pImage = NULL;
4540 pUsage->pNext = NULL;
4541 RTMemFree(pUsage);
4542
4543 /*
4544 * Dereference the image.
4545 */
4546 if (pImage->cUsage <= 1)
4547 supdrvLdrFree(pDevExt, pImage);
4548 else
4549 pImage->cUsage--;
4550 }
4551 else
4552 {
4553 Log(("supdrvIOCtl_LdrFree: Dangling objects in %p/%s!\n", pImage->pvImage, pImage->szName));
4554 rc = VINF_SUCCESS; /** @todo BRANCH-2.1: remove this after branching. */
4555 }
4556 }
4557 else
4558 {
4559 /*
4560 * Dereference both image and usage.
4561 */
4562 pImage->cUsage--;
4563 pUsage->cUsage--;
4564 }
4565
4566 supdrvLdrUnlock(pDevExt);
4567 return rc;
4568}
4569
4570
4571/**
4572 * Gets the address of a symbol in an open image.
4573 *
4574 * @returns IPRT status code.
4575 * @param pDevExt Device globals.
4576 * @param pSession Session data.
4577 * @param pReq The request buffer.
4578 */
4579static int supdrvIOCtl_LdrGetSymbol(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPLDRGETSYMBOL pReq)
4580{
4581 PSUPDRVLDRIMAGE pImage;
4582 PSUPDRVLDRUSAGE pUsage;
4583 uint32_t i;
4584 PSUPLDRSYM paSyms;
4585 const char *pchStrings;
4586 const size_t cbSymbol = strlen(pReq->u.In.szSymbol) + 1;
4587 void *pvSymbol = NULL;
4588 int rc = VERR_GENERAL_FAILURE;
4589 Log3(("supdrvIOCtl_LdrGetSymbol: pvImageBase=%p szSymbol=\"%s\"\n", pReq->u.In.pvImageBase, pReq->u.In.szSymbol));
4590
4591 /*
4592 * Find the ldr image.
4593 */
4594 supdrvLdrLock(pDevExt);
4595 pUsage = pSession->pLdrUsage;
4596 while (pUsage && pUsage->pImage->pvImage != pReq->u.In.pvImageBase)
4597 pUsage = pUsage->pNext;
4598 if (!pUsage)
4599 {
4600 supdrvLdrUnlock(pDevExt);
4601 Log(("SUP_IOCTL_LDR_GET_SYMBOL: couldn't find image!\n"));
4602 return VERR_INVALID_HANDLE;
4603 }
4604 pImage = pUsage->pImage;
4605 if (pImage->uState != SUP_IOCTL_LDR_LOAD)
4606 {
4607 unsigned uState = pImage->uState;
4608 supdrvLdrUnlock(pDevExt);
4609 Log(("SUP_IOCTL_LDR_GET_SYMBOL: invalid image state %d (%#x)!\n", uState, uState)); NOREF(uState);
4610 return VERR_ALREADY_LOADED;
4611 }
4612
4613 /*
4614 * Search the symbol strings.
4615 *
4616 * Note! The int32_t is for native loading on solaris where the data
4617 * and text segments are in very different places.
4618 */
4619 pchStrings = pImage->pachStrTab;
4620 paSyms = pImage->paSymbols;
4621 for (i = 0; i < pImage->cSymbols; i++)
4622 {
4623 if ( paSyms[i].offName + cbSymbol <= pImage->cbStrTab
4624 && !memcmp(pchStrings + paSyms[i].offName, pReq->u.In.szSymbol, cbSymbol))
4625 {
4626 pvSymbol = (uint8_t *)pImage->pvImage + (int32_t)paSyms[i].offSymbol;
4627 rc = VINF_SUCCESS;
4628 break;
4629 }
4630 }
4631 supdrvLdrUnlock(pDevExt);
4632 pReq->u.Out.pvSymbol = pvSymbol;
4633 return rc;
4634}
4635
4636
4637/**
4638 * Gets the address of a symbol in an open image or the support driver.
4639 *
4640 * @returns VINF_SUCCESS on success.
4641 * @returns
4642 * @param pDevExt Device globals.
4643 * @param pSession Session data.
4644 * @param pReq The request buffer.
4645 */
4646static int supdrvIDC_LdrGetSymbol(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPDRVIDCREQGETSYM pReq)
4647{
4648 int rc = VINF_SUCCESS;
4649 const char *pszSymbol = pReq->u.In.pszSymbol;
4650 const char *pszModule = pReq->u.In.pszModule;
4651 size_t cbSymbol;
4652 char const *pszEnd;
4653 uint32_t i;
4654
4655 /*
4656 * Input validation.
4657 */
4658 AssertPtrReturn(pszSymbol, VERR_INVALID_POINTER);
4659 pszEnd = RTStrEnd(pszSymbol, 512);
4660 AssertReturn(pszEnd, VERR_INVALID_PARAMETER);
4661 cbSymbol = pszEnd - pszSymbol + 1;
4662
4663 if (pszModule)
4664 {
4665 AssertPtrReturn(pszModule, VERR_INVALID_POINTER);
4666 pszEnd = RTStrEnd(pszModule, 64);
4667 AssertReturn(pszEnd, VERR_INVALID_PARAMETER);
4668 }
4669 Log3(("supdrvIDC_LdrGetSymbol: pszModule=%p:{%s} pszSymbol=%p:{%s}\n", pszModule, pszModule, pszSymbol, pszSymbol));
4670
4671
4672 if ( !pszModule
4673 || !strcmp(pszModule, "SupDrv"))
4674 {
4675 /*
4676 * Search the support driver export table.
4677 */
4678 for (i = 0; i < RT_ELEMENTS(g_aFunctions); i++)
4679 if (!strcmp(g_aFunctions[i].szName, pszSymbol))
4680 {
4681 pReq->u.Out.pfnSymbol = g_aFunctions[i].pfn;
4682 break;
4683 }
4684 }
4685 else
4686 {
4687 /*
4688 * Find the loader image.
4689 */
4690 PSUPDRVLDRIMAGE pImage;
4691
4692 supdrvLdrLock(pDevExt);
4693
4694 for (pImage = pDevExt->pLdrImages; pImage; pImage = pImage->pNext)
4695 if (!strcmp(pImage->szName, pszModule))
4696 break;
4697 if (pImage && pImage->uState == SUP_IOCTL_LDR_LOAD)
4698 {
4699 /*
4700 * Search the symbol strings.
4701 */
4702 const char *pchStrings = pImage->pachStrTab;
4703 PCSUPLDRSYM paSyms = pImage->paSymbols;
4704 for (i = 0; i < pImage->cSymbols; i++)
4705 {
4706 if ( paSyms[i].offName + cbSymbol <= pImage->cbStrTab
4707 && !memcmp(pchStrings + paSyms[i].offName, pszSymbol, cbSymbol))
4708 {
4709 /*
4710 * Found it! Calc the symbol address and add a reference to the module.
4711 */
4712 pReq->u.Out.pfnSymbol = (PFNRT)((uint8_t *)pImage->pvImage + (int32_t)paSyms[i].offSymbol);
4713 rc = supdrvLdrAddUsage(pSession, pImage);
4714 break;
4715 }
4716 }
4717 }
4718 else
4719 rc = pImage ? VERR_WRONG_ORDER : VERR_MODULE_NOT_FOUND;
4720
4721 supdrvLdrUnlock(pDevExt);
4722 }
4723 return rc;
4724}
4725
4726
4727/**
4728 * Updates the VMMR0 entry point pointers.
4729 *
4730 * @returns IPRT status code.
4731 * @param pDevExt Device globals.
4732 * @param pSession Session data.
4733 * @param pVMMR0 VMMR0 image handle.
4734 * @param pvVMMR0EntryInt VMMR0EntryInt address.
4735 * @param pvVMMR0EntryFast VMMR0EntryFast address.
4736 * @param pvVMMR0EntryEx VMMR0EntryEx address.
4737 * @remark Caller must own the loader mutex.
4738 */
4739static int supdrvLdrSetVMMR0EPs(PSUPDRVDEVEXT pDevExt, void *pvVMMR0, void *pvVMMR0EntryInt, void *pvVMMR0EntryFast, void *pvVMMR0EntryEx)
4740{
4741 int rc = VINF_SUCCESS;
4742 LogFlow(("supdrvLdrSetR0EP pvVMMR0=%p pvVMMR0EntryInt=%p\n", pvVMMR0, pvVMMR0EntryInt));
4743
4744
4745 /*
4746 * Check if not yet set.
4747 */
4748 if (!pDevExt->pvVMMR0)
4749 {
4750 pDevExt->pvVMMR0 = pvVMMR0;
4751 pDevExt->pfnVMMR0EntryInt = pvVMMR0EntryInt;
4752 pDevExt->pfnVMMR0EntryFast = pvVMMR0EntryFast;
4753 pDevExt->pfnVMMR0EntryEx = pvVMMR0EntryEx;
4754 }
4755 else
4756 {
4757 /*
4758 * Return failure or success depending on whether the values match or not.
4759 */
4760 if ( pDevExt->pvVMMR0 != pvVMMR0
4761 || (void *)pDevExt->pfnVMMR0EntryInt != pvVMMR0EntryInt
4762 || (void *)pDevExt->pfnVMMR0EntryFast != pvVMMR0EntryFast
4763 || (void *)pDevExt->pfnVMMR0EntryEx != pvVMMR0EntryEx)
4764 {
4765 AssertMsgFailed(("SUP_IOCTL_LDR_SETR0EP: Already set pointing to a different module!\n"));
4766 rc = VERR_INVALID_PARAMETER;
4767 }
4768 }
4769 return rc;
4770}
4771
4772
4773/**
4774 * Unsets the VMMR0 entry point installed by supdrvLdrSetR0EP.
4775 *
4776 * @param pDevExt Device globals.
4777 */
4778static void supdrvLdrUnsetVMMR0EPs(PSUPDRVDEVEXT pDevExt)
4779{
4780 pDevExt->pvVMMR0 = NULL;
4781 pDevExt->pfnVMMR0EntryInt = NULL;
4782 pDevExt->pfnVMMR0EntryFast = NULL;
4783 pDevExt->pfnVMMR0EntryEx = NULL;
4784}
4785
4786
4787/**
4788 * Adds a usage reference in the specified session of an image.
4789 *
4790 * Called while owning the loader semaphore.
4791 *
4792 * @returns VINF_SUCCESS on success and VERR_NO_MEMORY on failure.
4793 * @param pSession Session in question.
4794 * @param pImage Image which the session is using.
4795 */
4796static int supdrvLdrAddUsage(PSUPDRVSESSION pSession, PSUPDRVLDRIMAGE pImage)
4797{
4798 PSUPDRVLDRUSAGE pUsage;
4799 LogFlow(("supdrvLdrAddUsage: pImage=%p\n", pImage));
4800
4801 /*
4802 * Referenced it already?
4803 */
4804 pUsage = pSession->pLdrUsage;
4805 while (pUsage)
4806 {
4807 if (pUsage->pImage == pImage)
4808 {
4809 pUsage->cUsage++;
4810 return VINF_SUCCESS;
4811 }
4812 pUsage = pUsage->pNext;
4813 }
4814
4815 /*
4816 * Allocate new usage record.
4817 */
4818 pUsage = (PSUPDRVLDRUSAGE)RTMemAlloc(sizeof(*pUsage));
4819 AssertReturn(pUsage, /*VERR_NO_MEMORY*/ VERR_INTERNAL_ERROR_5);
4820 pUsage->cUsage = 1;
4821 pUsage->pImage = pImage;
4822 pUsage->pNext = pSession->pLdrUsage;
4823 pSession->pLdrUsage = pUsage;
4824 return VINF_SUCCESS;
4825}
4826
4827
4828/**
4829 * Frees a load image.
4830 *
4831 * @param pDevExt Pointer to device extension.
4832 * @param pImage Pointer to the image we're gonna free.
4833 * This image must exit!
4834 * @remark The caller MUST own SUPDRVDEVEXT::mtxLdr!
4835 */
4836static void supdrvLdrFree(PSUPDRVDEVEXT pDevExt, PSUPDRVLDRIMAGE pImage)
4837{
4838 PSUPDRVLDRIMAGE pImagePrev;
4839 LogFlow(("supdrvLdrFree: pImage=%p\n", pImage));
4840
4841 /* find it - arg. should've used doubly linked list. */
4842 Assert(pDevExt->pLdrImages);
4843 pImagePrev = NULL;
4844 if (pDevExt->pLdrImages != pImage)
4845 {
4846 pImagePrev = pDevExt->pLdrImages;
4847 while (pImagePrev->pNext != pImage)
4848 pImagePrev = pImagePrev->pNext;
4849 Assert(pImagePrev->pNext == pImage);
4850 }
4851
4852 /* unlink */
4853 if (pImagePrev)
4854 pImagePrev->pNext = pImage->pNext;
4855 else
4856 pDevExt->pLdrImages = pImage->pNext;
4857
4858 /* check if this is VMMR0.r0 unset its entry point pointers. */
4859 if (pDevExt->pvVMMR0 == pImage->pvImage)
4860 supdrvLdrUnsetVMMR0EPs(pDevExt);
4861
4862 /* check for objects with destructors in this image. (Shouldn't happen.) */
4863 if (pDevExt->pObjs)
4864 {
4865 unsigned cObjs = 0;
4866 PSUPDRVOBJ pObj;
4867 RTSpinlockAcquire(pDevExt->Spinlock);
4868 for (pObj = pDevExt->pObjs; pObj; pObj = pObj->pNext)
4869 if (RT_UNLIKELY((uintptr_t)pObj->pfnDestructor - (uintptr_t)pImage->pvImage < pImage->cbImageBits))
4870 {
4871 pObj->pfnDestructor = NULL;
4872 cObjs++;
4873 }
4874 RTSpinlockRelease(pDevExt->Spinlock);
4875 if (cObjs)
4876 OSDBGPRINT(("supdrvLdrFree: Image '%s' has %d dangling objects!\n", pImage->szName, cObjs));
4877 }
4878
4879 /* call termination function if fully loaded. */
4880 if ( pImage->pfnModuleTerm
4881 && pImage->uState == SUP_IOCTL_LDR_LOAD)
4882 {
4883 LogFlow(("supdrvIOCtl_LdrLoad: calling pfnModuleTerm=%p\n", pImage->pfnModuleTerm));
4884 pImage->pfnModuleTerm(pImage);
4885 }
4886
4887 /* Inform the tracing component. */
4888 supdrvTracerModuleUnloading(pDevExt, pImage);
4889
4890 /* do native unload if appropriate. */
4891 if (pImage->fNative)
4892 supdrvOSLdrUnload(pDevExt, pImage);
4893
4894 /* free the image */
4895 pImage->cUsage = 0;
4896 pImage->pDevExt = NULL;
4897 pImage->pNext = NULL;
4898 pImage->uState = SUP_IOCTL_LDR_FREE;
4899 RTMemExecFree(pImage->pvImageAlloc, pImage->cbImageBits + 31);
4900 pImage->pvImageAlloc = NULL;
4901 RTMemFree(pImage->pachStrTab);
4902 pImage->pachStrTab = NULL;
4903 RTMemFree(pImage->paSymbols);
4904 pImage->paSymbols = NULL;
4905 RTMemFree(pImage);
4906}
4907
4908
4909/**
4910 * Acquires the loader lock.
4911 *
4912 * @returns IPRT status code.
4913 * @param pDevExt The device extension.
4914 */
4915DECLINLINE(int) supdrvLdrLock(PSUPDRVDEVEXT pDevExt)
4916{
4917#ifdef SUPDRV_USE_MUTEX_FOR_LDR
4918 int rc = RTSemMutexRequest(pDevExt->mtxLdr, RT_INDEFINITE_WAIT);
4919#else
4920 int rc = RTSemFastMutexRequest(pDevExt->mtxLdr);
4921#endif
4922 AssertRC(rc);
4923 return rc;
4924}
4925
4926
4927/**
4928 * Releases the loader lock.
4929 *
4930 * @returns IPRT status code.
4931 * @param pDevExt The device extension.
4932 */
4933DECLINLINE(int) supdrvLdrUnlock(PSUPDRVDEVEXT pDevExt)
4934{
4935#ifdef SUPDRV_USE_MUTEX_FOR_LDR
4936 return RTSemMutexRelease(pDevExt->mtxLdr);
4937#else
4938 return RTSemFastMutexRelease(pDevExt->mtxLdr);
4939#endif
4940}
4941
4942
4943/**
4944 * Implements the service call request.
4945 *
4946 * @returns VBox status code.
4947 * @param pDevExt The device extension.
4948 * @param pSession The calling session.
4949 * @param pReq The request packet, valid.
4950 */
4951static int supdrvIOCtl_CallServiceModule(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPCALLSERVICE pReq)
4952{
4953#if !defined(RT_OS_WINDOWS) || defined(RT_ARCH_AMD64) || defined(DEBUG)
4954 int rc;
4955
4956 /*
4957 * Find the module first in the module referenced by the calling session.
4958 */
4959 rc = supdrvLdrLock(pDevExt);
4960 if (RT_SUCCESS(rc))
4961 {
4962 PFNSUPR0SERVICEREQHANDLER pfnServiceReqHandler = NULL;
4963 PSUPDRVLDRUSAGE pUsage;
4964
4965 for (pUsage = pSession->pLdrUsage; pUsage; pUsage = pUsage->pNext)
4966 if ( pUsage->pImage->pfnServiceReqHandler
4967 && !strcmp(pUsage->pImage->szName, pReq->u.In.szName))
4968 {
4969 pfnServiceReqHandler = pUsage->pImage->pfnServiceReqHandler;
4970 break;
4971 }
4972 supdrvLdrUnlock(pDevExt);
4973
4974 if (pfnServiceReqHandler)
4975 {
4976 /*
4977 * Call it.
4978 */
4979 if (pReq->Hdr.cbIn == SUP_IOCTL_CALL_SERVICE_SIZE(0))
4980 rc = pfnServiceReqHandler(pSession, pReq->u.In.uOperation, pReq->u.In.u64Arg, NULL);
4981 else
4982 rc = pfnServiceReqHandler(pSession, pReq->u.In.uOperation, pReq->u.In.u64Arg, (PSUPR0SERVICEREQHDR)&pReq->abReqPkt[0]);
4983 }
4984 else
4985 rc = VERR_SUPDRV_SERVICE_NOT_FOUND;
4986 }
4987
4988 /* log it */
4989 if ( RT_FAILURE(rc)
4990 && rc != VERR_INTERRUPTED
4991 && rc != VERR_TIMEOUT)
4992 Log(("SUP_IOCTL_CALL_SERVICE: rc=%Rrc op=%u out=%u arg=%RX64 p/t=%RTproc/%RTthrd\n",
4993 rc, pReq->u.In.uOperation, pReq->Hdr.cbOut, pReq->u.In.u64Arg, RTProcSelf(), RTThreadNativeSelf()));
4994 else
4995 Log4(("SUP_IOCTL_CALL_SERVICE: rc=%Rrc op=%u out=%u arg=%RX64 p/t=%RTproc/%RTthrd\n",
4996 rc, pReq->u.In.uOperation, pReq->Hdr.cbOut, pReq->u.In.u64Arg, RTProcSelf(), RTThreadNativeSelf()));
4997 return rc;
4998#else /* RT_OS_WINDOWS && !RT_ARCH_AMD64 && !DEBUG */
4999 return VERR_NOT_IMPLEMENTED;
5000#endif /* RT_OS_WINDOWS && !RT_ARCH_AMD64 && !DEBUG */
5001}
5002
5003
5004/**
5005 * Implements the logger settings request.
5006 *
5007 * @returns VBox status code.
5008 * @param pDevExt The device extension.
5009 * @param pSession The caller's session.
5010 * @param pReq The request.
5011 */
5012static int supdrvIOCtl_LoggerSettings(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPLOGGERSETTINGS pReq)
5013{
5014 const char *pszGroup = &pReq->u.In.szStrings[pReq->u.In.offGroups];
5015 const char *pszFlags = &pReq->u.In.szStrings[pReq->u.In.offFlags];
5016 const char *pszDest = &pReq->u.In.szStrings[pReq->u.In.offDestination];
5017 PRTLOGGER pLogger = NULL;
5018 int rc;
5019
5020 /*
5021 * Some further validation.
5022 */
5023 switch (pReq->u.In.fWhat)
5024 {
5025 case SUPLOGGERSETTINGS_WHAT_SETTINGS:
5026 case SUPLOGGERSETTINGS_WHAT_CREATE:
5027 break;
5028
5029 case SUPLOGGERSETTINGS_WHAT_DESTROY:
5030 if (*pszGroup || *pszFlags || *pszDest)
5031 return VERR_INVALID_PARAMETER;
5032 if (pReq->u.In.fWhich == SUPLOGGERSETTINGS_WHICH_RELEASE)
5033 return VERR_ACCESS_DENIED;
5034 break;
5035
5036 default:
5037 return VERR_INTERNAL_ERROR;
5038 }
5039
5040 /*
5041 * Get the logger.
5042 */
5043 switch (pReq->u.In.fWhich)
5044 {
5045 case SUPLOGGERSETTINGS_WHICH_DEBUG:
5046 pLogger = RTLogGetDefaultInstance();
5047 break;
5048
5049 case SUPLOGGERSETTINGS_WHICH_RELEASE:
5050 pLogger = RTLogRelDefaultInstance();
5051 break;
5052
5053 default:
5054 return VERR_INTERNAL_ERROR;
5055 }
5056
5057 /*
5058 * Do the job.
5059 */
5060 switch (pReq->u.In.fWhat)
5061 {
5062 case SUPLOGGERSETTINGS_WHAT_SETTINGS:
5063 if (pLogger)
5064 {
5065 rc = RTLogFlags(pLogger, pszFlags);
5066 if (RT_SUCCESS(rc))
5067 rc = RTLogGroupSettings(pLogger, pszGroup);
5068 NOREF(pszDest);
5069 }
5070 else
5071 rc = VERR_NOT_FOUND;
5072 break;
5073
5074 case SUPLOGGERSETTINGS_WHAT_CREATE:
5075 {
5076 if (pLogger)
5077 rc = VERR_ALREADY_EXISTS;
5078 else
5079 {
5080 static const char * const s_apszGroups[] = VBOX_LOGGROUP_NAMES;
5081
5082 rc = RTLogCreate(&pLogger,
5083 0 /* fFlags */,
5084 pszGroup,
5085 pReq->u.In.fWhich == SUPLOGGERSETTINGS_WHICH_DEBUG
5086 ? "VBOX_LOG"
5087 : "VBOX_RELEASE_LOG",
5088 RT_ELEMENTS(s_apszGroups),
5089 s_apszGroups,
5090 RTLOGDEST_STDOUT | RTLOGDEST_DEBUGGER,
5091 NULL);
5092 if (RT_SUCCESS(rc))
5093 {
5094 rc = RTLogFlags(pLogger, pszFlags);
5095 NOREF(pszDest);
5096 if (RT_SUCCESS(rc))
5097 {
5098 switch (pReq->u.In.fWhich)
5099 {
5100 case SUPLOGGERSETTINGS_WHICH_DEBUG:
5101 pLogger = RTLogSetDefaultInstance(pLogger);
5102 break;
5103 case SUPLOGGERSETTINGS_WHICH_RELEASE:
5104 pLogger = RTLogRelSetDefaultInstance(pLogger);
5105 break;
5106 }
5107 }
5108 RTLogDestroy(pLogger);
5109 }
5110 }
5111 break;
5112 }
5113
5114 case SUPLOGGERSETTINGS_WHAT_DESTROY:
5115 switch (pReq->u.In.fWhich)
5116 {
5117 case SUPLOGGERSETTINGS_WHICH_DEBUG:
5118 pLogger = RTLogSetDefaultInstance(NULL);
5119 break;
5120 case SUPLOGGERSETTINGS_WHICH_RELEASE:
5121 pLogger = RTLogRelSetDefaultInstance(NULL);
5122 break;
5123 }
5124 rc = RTLogDestroy(pLogger);
5125 break;
5126
5127 default:
5128 {
5129 rc = VERR_INTERNAL_ERROR;
5130 break;
5131 }
5132 }
5133
5134 return rc;
5135}
5136
5137
5138/**
5139 * Creates the GIP.
5140 *
5141 * @returns VBox status code.
5142 * @param pDevExt Instance data. GIP stuff may be updated.
5143 */
5144static int supdrvGipCreate(PSUPDRVDEVEXT pDevExt)
5145{
5146 PSUPGLOBALINFOPAGE pGip;
5147 RTHCPHYS HCPhysGip;
5148 uint32_t u32SystemResolution;
5149 uint32_t u32Interval;
5150 unsigned cCpus;
5151 int rc;
5152
5153
5154 LogFlow(("supdrvGipCreate:\n"));
5155
5156 /* assert order */
5157 Assert(pDevExt->u32SystemTimerGranularityGrant == 0);
5158 Assert(pDevExt->GipMemObj == NIL_RTR0MEMOBJ);
5159 Assert(!pDevExt->pGipTimer);
5160
5161 /*
5162 * Check the CPU count.
5163 */
5164 cCpus = RTMpGetArraySize();
5165 if ( cCpus > RTCPUSET_MAX_CPUS
5166 || cCpus > 256 /*ApicId is used for the mappings*/)
5167 {
5168 SUPR0Printf("VBoxDrv: Too many CPUs (%u) for the GIP (max %u)\n", cCpus, RT_MIN(RTCPUSET_MAX_CPUS, 256));
5169 return VERR_TOO_MANY_CPUS;
5170 }
5171
5172 /*
5173 * Allocate a contiguous set of pages with a default kernel mapping.
5174 */
5175 rc = RTR0MemObjAllocCont(&pDevExt->GipMemObj, RT_UOFFSETOF(SUPGLOBALINFOPAGE, aCPUs[cCpus]), false /*fExecutable*/);
5176 if (RT_FAILURE(rc))
5177 {
5178 OSDBGPRINT(("supdrvGipCreate: failed to allocate the GIP page. rc=%d\n", rc));
5179 return rc;
5180 }
5181 pGip = (PSUPGLOBALINFOPAGE)RTR0MemObjAddress(pDevExt->GipMemObj); AssertPtr(pGip);
5182 HCPhysGip = RTR0MemObjGetPagePhysAddr(pDevExt->GipMemObj, 0); Assert(HCPhysGip != NIL_RTHCPHYS);
5183
5184 /*
5185 * Find a reasonable update interval and initialize the structure.
5186 */
5187 u32Interval = u32SystemResolution = RTTimerGetSystemGranularity();
5188 while (u32Interval < 10000000 /* 10 ms */)
5189 u32Interval += u32SystemResolution;
5190
5191 supdrvGipInit(pDevExt, pGip, HCPhysGip, RTTimeSystemNanoTS(), 1000000000 / u32Interval /*=Hz*/, cCpus);
5192
5193 /*
5194 * Create the timer.
5195 * If CPU_ALL isn't supported we'll have to fall back to synchronous mode.
5196 */
5197 if (pGip->u32Mode == SUPGIPMODE_ASYNC_TSC)
5198 {
5199 rc = RTTimerCreateEx(&pDevExt->pGipTimer, u32Interval, RTTIMER_FLAGS_CPU_ALL, supdrvGipAsyncTimer, pDevExt);
5200 if (rc == VERR_NOT_SUPPORTED)
5201 {
5202 OSDBGPRINT(("supdrvGipCreate: omni timer not supported, falling back to synchronous mode\n"));
5203 pGip->u32Mode = SUPGIPMODE_SYNC_TSC;
5204 }
5205 }
5206 if (pGip->u32Mode != SUPGIPMODE_ASYNC_TSC)
5207 rc = RTTimerCreateEx(&pDevExt->pGipTimer, u32Interval, 0 /* fFlags */, supdrvGipSyncTimer, pDevExt);
5208 if (RT_SUCCESS(rc))
5209 {
5210 rc = RTMpNotificationRegister(supdrvGipMpEvent, pDevExt);
5211 if (RT_SUCCESS(rc))
5212 {
5213 rc = RTMpOnAll(supdrvGipInitOnCpu, pDevExt, pGip);
5214 if (RT_SUCCESS(rc))
5215 {
5216 /*
5217 * We're good.
5218 */
5219 Log(("supdrvGipCreate: %u ns interval.\n", u32Interval));
5220 g_pSUPGlobalInfoPage = pGip;
5221 return VINF_SUCCESS;
5222 }
5223
5224 OSDBGPRINT(("supdrvGipCreate: RTMpOnAll failed with rc=%Rrc\n", rc));
5225 RTMpNotificationDeregister(supdrvGipMpEvent, pDevExt);
5226
5227 }
5228 else
5229 OSDBGPRINT(("supdrvGipCreate: failed to register MP event notfication. rc=%Rrc\n", rc));
5230 }
5231 else
5232 {
5233 OSDBGPRINT(("supdrvGipCreate: failed create GIP timer at %u ns interval. rc=%Rrc\n", u32Interval, rc));
5234 Assert(!pDevExt->pGipTimer);
5235 }
5236 supdrvGipDestroy(pDevExt);
5237 return rc;
5238}
5239
5240
5241/**
5242 * Terminates the GIP.
5243 *
5244 * @param pDevExt Instance data. GIP stuff may be updated.
5245 */
5246static void supdrvGipDestroy(PSUPDRVDEVEXT pDevExt)
5247{
5248 int rc;
5249#ifdef DEBUG_DARWIN_GIP
5250 OSDBGPRINT(("supdrvGipDestroy: pDevExt=%p pGip=%p pGipTimer=%p GipMemObj=%p\n", pDevExt,
5251 pDevExt->GipMemObj != NIL_RTR0MEMOBJ ? RTR0MemObjAddress(pDevExt->GipMemObj) : NULL,
5252 pDevExt->pGipTimer, pDevExt->GipMemObj));
5253#endif
5254
5255 /*
5256 * Invalid the GIP data.
5257 */
5258 if (pDevExt->pGip)
5259 {
5260 supdrvGipTerm(pDevExt->pGip);
5261 pDevExt->pGip = NULL;
5262 }
5263 g_pSUPGlobalInfoPage = NULL;
5264
5265 /*
5266 * Destroy the timer and free the GIP memory object.
5267 */
5268 if (pDevExt->pGipTimer)
5269 {
5270 rc = RTTimerDestroy(pDevExt->pGipTimer); AssertRC(rc);
5271 pDevExt->pGipTimer = NULL;
5272 }
5273
5274 if (pDevExt->GipMemObj != NIL_RTR0MEMOBJ)
5275 {
5276 rc = RTR0MemObjFree(pDevExt->GipMemObj, true /* free mappings */); AssertRC(rc);
5277 pDevExt->GipMemObj = NIL_RTR0MEMOBJ;
5278 }
5279
5280 /*
5281 * Finally, make sure we've release the system timer resolution request
5282 * if one actually succeeded and is still pending.
5283 */
5284 if (pDevExt->u32SystemTimerGranularityGrant)
5285 {
5286 rc = RTTimerReleaseSystemGranularity(pDevExt->u32SystemTimerGranularityGrant); AssertRC(rc);
5287 pDevExt->u32SystemTimerGranularityGrant = 0;
5288 }
5289}
5290
5291
5292/**
5293 * Timer callback function sync GIP mode.
5294 * @param pTimer The timer.
5295 * @param pvUser The device extension.
5296 */
5297static DECLCALLBACK(void) supdrvGipSyncTimer(PRTTIMER pTimer, void *pvUser, uint64_t iTick)
5298{
5299 RTCCUINTREG fOldFlags = ASMIntDisableFlags(); /* No interruptions please (real problem on S10). */
5300 PSUPDRVDEVEXT pDevExt = (PSUPDRVDEVEXT)pvUser;
5301 uint64_t u64TSC = ASMReadTSC();
5302 uint64_t NanoTS = RTTimeSystemNanoTS();
5303
5304 supdrvGipUpdate(pDevExt, NanoTS, u64TSC, NIL_RTCPUID, iTick);
5305
5306 ASMSetFlags(fOldFlags);
5307}
5308
5309
5310/**
5311 * Timer callback function for async GIP mode.
5312 * @param pTimer The timer.
5313 * @param pvUser The device extension.
5314 */
5315static DECLCALLBACK(void) supdrvGipAsyncTimer(PRTTIMER pTimer, void *pvUser, uint64_t iTick)
5316{
5317 RTCCUINTREG fOldFlags = ASMIntDisableFlags(); /* No interruptions please (real problem on S10). */
5318 PSUPDRVDEVEXT pDevExt = (PSUPDRVDEVEXT)pvUser;
5319 RTCPUID idCpu = RTMpCpuId();
5320 uint64_t u64TSC = ASMReadTSC();
5321 uint64_t NanoTS = RTTimeSystemNanoTS();
5322
5323 /** @todo reset the transaction number and whatnot when iTick == 1. */
5324 if (pDevExt->idGipMaster == idCpu)
5325 supdrvGipUpdate(pDevExt, NanoTS, u64TSC, idCpu, iTick);
5326 else
5327 supdrvGipUpdatePerCpu(pDevExt, NanoTS, u64TSC, idCpu, ASMGetApicId(), iTick);
5328
5329 ASMSetFlags(fOldFlags);
5330}
5331
5332
5333/**
5334 * Finds our (@a idCpu) entry, or allocates a new one if not found.
5335 *
5336 * @returns Index of the CPU in the cache set.
5337 * @param pGip The GIP.
5338 * @param idCpu The CPU ID.
5339 */
5340static uint32_t supdrvGipCpuIndexFromCpuId(PSUPGLOBALINFOPAGE pGip, RTCPUID idCpu)
5341{
5342 uint32_t i, cTries;
5343
5344 /*
5345 * ASSUMES that CPU IDs are constant.
5346 */
5347 for (i = 0; i < pGip->cCpus; i++)
5348 if (pGip->aCPUs[i].idCpu == idCpu)
5349 return i;
5350
5351 cTries = 0;
5352 do
5353 {
5354 for (i = 0; i < pGip->cCpus; i++)
5355 {
5356 bool fRc;
5357 ASMAtomicCmpXchgSize(&pGip->aCPUs[i].idCpu, idCpu, NIL_RTCPUID, fRc);
5358 if (fRc)
5359 return i;
5360 }
5361 } while (cTries++ < 32);
5362 AssertReleaseFailed();
5363 return i - 1;
5364}
5365
5366
5367/**
5368 * The calling CPU should be accounted as online, update GIP accordingly.
5369 *
5370 * This is used by supdrvGipMpEvent as well as the supdrvGipCreate.
5371 *
5372 * @param pDevExt The device extension.
5373 * @param idCpu The CPU ID.
5374 */
5375static void supdrvGipMpEventOnline(PSUPDRVDEVEXT pDevExt, RTCPUID idCpu)
5376{
5377 int iCpuSet = 0;
5378 uint16_t idApic = UINT16_MAX;
5379 uint32_t i = 0;
5380 uint64_t u64NanoTS = 0;
5381 PSUPGLOBALINFOPAGE pGip = pDevExt->pGip;
5382
5383 AssertPtrReturnVoid(pGip);
5384 AssertRelease(idCpu == RTMpCpuId());
5385 Assert(pGip->cPossibleCpus == RTMpGetCount());
5386
5387 /*
5388 * Do this behind a spinlock with interrupts disabled as this can fire
5389 * on all CPUs simultaneously, see @bugref{6110}.
5390 */
5391 RTSpinlockAcquire(pDevExt->hGipSpinlock);
5392
5393 /*
5394 * Update the globals.
5395 */
5396 ASMAtomicWriteU16(&pGip->cPresentCpus, RTMpGetPresentCount());
5397 ASMAtomicWriteU16(&pGip->cOnlineCpus, RTMpGetOnlineCount());
5398 iCpuSet = RTMpCpuIdToSetIndex(idCpu);
5399 if (iCpuSet >= 0)
5400 {
5401 Assert(RTCpuSetIsMemberByIndex(&pGip->PossibleCpuSet, iCpuSet));
5402 RTCpuSetAddByIndex(&pGip->OnlineCpuSet, iCpuSet);
5403 RTCpuSetAddByIndex(&pGip->PresentCpuSet, iCpuSet);
5404 }
5405
5406 /*
5407 * Update the entry.
5408 */
5409 u64NanoTS = RTTimeSystemNanoTS() - pGip->u32UpdateIntervalNS;
5410 i = supdrvGipCpuIndexFromCpuId(pGip, idCpu);
5411 supdrvGipInitCpu(pGip, &pGip->aCPUs[i], u64NanoTS);
5412 idApic = ASMGetApicId();
5413 ASMAtomicWriteU16(&pGip->aCPUs[i].idApic, idApic);
5414 ASMAtomicWriteS16(&pGip->aCPUs[i].iCpuSet, (int16_t)iCpuSet);
5415 ASMAtomicWriteSize(&pGip->aCPUs[i].idCpu, idCpu);
5416
5417 /*
5418 * Update the APIC ID and CPU set index mappings.
5419 */
5420 ASMAtomicWriteU16(&pGip->aiCpuFromApicId[idApic], i);
5421 ASMAtomicWriteU16(&pGip->aiCpuFromCpuSetIdx[iCpuSet], i);
5422
5423 /* commit it */
5424 ASMAtomicWriteSize(&pGip->aCPUs[i].enmState, SUPGIPCPUSTATE_ONLINE);
5425
5426 RTSpinlockReleaseNoInts(pDevExt->hGipSpinlock);
5427}
5428
5429
5430/**
5431 * The CPU should be accounted as offline, update the GIP accordingly.
5432 *
5433 * This is used by supdrvGipMpEvent.
5434 *
5435 * @param pDevExt The device extension.
5436 * @param idCpu The CPU ID.
5437 */
5438static void supdrvGipMpEventOffline(PSUPDRVDEVEXT pDevExt, RTCPUID idCpu)
5439{
5440 int iCpuSet;
5441 unsigned i;
5442
5443 PSUPGLOBALINFOPAGE pGip = pDevExt->pGip;
5444
5445 AssertPtrReturnVoid(pGip);
5446 RTSpinlockAcquire(pDevExt->hGipSpinlock);
5447
5448 iCpuSet = RTMpCpuIdToSetIndex(idCpu);
5449 AssertReturnVoid(iCpuSet >= 0);
5450
5451 i = pGip->aiCpuFromCpuSetIdx[iCpuSet];
5452 AssertReturnVoid(i < pGip->cCpus);
5453 AssertReturnVoid(pGip->aCPUs[i].idCpu == idCpu);
5454
5455 Assert(RTCpuSetIsMemberByIndex(&pGip->PossibleCpuSet, iCpuSet));
5456 RTCpuSetDelByIndex(&pGip->OnlineCpuSet, iCpuSet);
5457
5458 /* commit it */
5459 ASMAtomicWriteSize(&pGip->aCPUs[i].enmState, SUPGIPCPUSTATE_OFFLINE);
5460
5461 RTSpinlockReleaseNoInts(pDevExt->hGipSpinlock);
5462}
5463
5464
5465/**
5466 * Multiprocessor event notification callback.
5467 *
5468 * This is used to make sure that the GIP master gets passed on to
5469 * another CPU. It also updates the associated CPU data.
5470 *
5471 * @param enmEvent The event.
5472 * @param idCpu The cpu it applies to.
5473 * @param pvUser Pointer to the device extension.
5474 *
5475 * @remarks This function -must- fire on the newly online'd CPU for the
5476 * RTMPEVENT_ONLINE case and can fire on any CPU for the
5477 * RTMPEVENT_OFFLINE case.
5478 */
5479static DECLCALLBACK(void) supdrvGipMpEvent(RTMPEVENT enmEvent, RTCPUID idCpu, void *pvUser)
5480{
5481 PSUPDRVDEVEXT pDevExt = (PSUPDRVDEVEXT)pvUser;
5482 PSUPGLOBALINFOPAGE pGip = pDevExt->pGip;
5483
5484 AssertRelease(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
5485
5486 /*
5487 * Update the GIP CPU data.
5488 */
5489 if (pGip)
5490 {
5491 switch (enmEvent)
5492 {
5493 case RTMPEVENT_ONLINE:
5494 AssertRelease(idCpu == RTMpCpuId());
5495 supdrvGipMpEventOnline(pDevExt, idCpu);
5496 break;
5497 case RTMPEVENT_OFFLINE:
5498 supdrvGipMpEventOffline(pDevExt, idCpu);
5499 break;
5500
5501 }
5502 }
5503
5504 /*
5505 * Make sure there is a master GIP.
5506 */
5507 if (enmEvent == RTMPEVENT_OFFLINE)
5508 {
5509 RTCPUID idGipMaster = ASMAtomicReadU32(&pDevExt->idGipMaster);
5510 if (idGipMaster == idCpu)
5511 {
5512 /*
5513 * Find a new GIP master.
5514 */
5515 bool fIgnored;
5516 unsigned i;
5517 RTCPUID idNewGipMaster = NIL_RTCPUID;
5518 RTCPUSET OnlineCpus;
5519 RTMpGetOnlineSet(&OnlineCpus);
5520
5521 for (i = 0; i < RTCPUSET_MAX_CPUS; i++)
5522 {
5523 RTCPUID idCurCpu = RTMpCpuIdFromSetIndex(i);
5524 if ( RTCpuSetIsMember(&OnlineCpus, idCurCpu)
5525 && idCurCpu != idGipMaster)
5526 {
5527 idNewGipMaster = idCurCpu;
5528 break;
5529 }
5530 }
5531
5532 Log(("supdrvGipMpEvent: Gip master %#lx -> %#lx\n", (long)idGipMaster, (long)idNewGipMaster));
5533 ASMAtomicCmpXchgSize(&pDevExt->idGipMaster, idNewGipMaster, idGipMaster, fIgnored);
5534 NOREF(fIgnored);
5535 }
5536 }
5537}
5538
5539
5540/**
5541 * Callback used by supdrvDetermineAsyncTSC to read the TSC on a CPU.
5542 *
5543 * @param idCpu Ignored.
5544 * @param pvUser1 Where to put the TSC.
5545 * @param pvUser2 Ignored.
5546 */
5547static DECLCALLBACK(void) supdrvDetermineAsyncTscWorker(RTCPUID idCpu, void *pvUser1, void *pvUser2)
5548{
5549#if 1
5550 ASMAtomicWriteU64((uint64_t volatile *)pvUser1, ASMReadTSC());
5551#else
5552 *(uint64_t *)pvUser1 = ASMReadTSC();
5553#endif
5554}
5555
5556
5557/**
5558 * Determine if Async GIP mode is required because of TSC drift.
5559 *
5560 * When using the default/normal timer code it is essential that the time stamp counter
5561 * (TSC) runs never backwards, that is, a read operation to the counter should return
5562 * a bigger value than any previous read operation. This is guaranteed by the latest
5563 * AMD CPUs and by newer Intel CPUs which never enter the C2 state (P4). In any other
5564 * case we have to choose the asynchronous timer mode.
5565 *
5566 * @param poffMin Pointer to the determined difference between different cores.
5567 * @return false if the time stamp counters appear to be synchronized, true otherwise.
5568 */
5569static bool supdrvDetermineAsyncTsc(uint64_t *poffMin)
5570{
5571 /*
5572 * Just iterate all the cpus 8 times and make sure that the TSC is
5573 * ever increasing. We don't bother taking TSC rollover into account.
5574 */
5575 int iEndCpu = RTMpGetArraySize();
5576 int iCpu;
5577 int cLoops = 8;
5578 bool fAsync = false;
5579 int rc = VINF_SUCCESS;
5580 uint64_t offMax = 0;
5581 uint64_t offMin = ~(uint64_t)0;
5582 uint64_t PrevTsc = ASMReadTSC();
5583
5584 while (cLoops-- > 0)
5585 {
5586 for (iCpu = 0; iCpu < iEndCpu; iCpu++)
5587 {
5588 uint64_t CurTsc;
5589 rc = RTMpOnSpecific(RTMpCpuIdFromSetIndex(iCpu), supdrvDetermineAsyncTscWorker, &CurTsc, NULL);
5590 if (RT_SUCCESS(rc))
5591 {
5592 if (CurTsc <= PrevTsc)
5593 {
5594 fAsync = true;
5595 offMin = offMax = PrevTsc - CurTsc;
5596 Log(("supdrvDetermineAsyncTsc: iCpu=%d cLoops=%d CurTsc=%llx PrevTsc=%llx\n",
5597 iCpu, cLoops, CurTsc, PrevTsc));
5598 break;
5599 }
5600
5601 /* Gather statistics (except the first time). */
5602 if (iCpu != 0 || cLoops != 7)
5603 {
5604 uint64_t off = CurTsc - PrevTsc;
5605 if (off < offMin)
5606 offMin = off;
5607 if (off > offMax)
5608 offMax = off;
5609 Log2(("%d/%d: off=%llx\n", cLoops, iCpu, off));
5610 }
5611
5612 /* Next */
5613 PrevTsc = CurTsc;
5614 }
5615 else if (rc == VERR_NOT_SUPPORTED)
5616 break;
5617 else
5618 AssertMsg(rc == VERR_CPU_NOT_FOUND || rc == VERR_CPU_OFFLINE, ("%d\n", rc));
5619 }
5620
5621 /* broke out of the loop. */
5622 if (iCpu < iEndCpu)
5623 break;
5624 }
5625
5626 *poffMin = offMin; /* Almost RTMpOnSpecific profiling. */
5627 Log(("supdrvDetermineAsyncTsc: returns %d; iEndCpu=%d rc=%d offMin=%llx offMax=%llx\n",
5628 fAsync, iEndCpu, rc, offMin, offMax));
5629#if !defined(RT_OS_SOLARIS) && !defined(RT_OS_OS2) && !defined(RT_OS_WINDOWS)
5630 OSDBGPRINT(("vboxdrv: fAsync=%d offMin=%#lx offMax=%#lx\n", fAsync, (long)offMin, (long)offMax));
5631#endif
5632 return fAsync;
5633}
5634
5635
5636/**
5637 * Determine the GIP TSC mode.
5638 *
5639 * @returns The most suitable TSC mode.
5640 * @param pDevExt Pointer to the device instance data.
5641 */
5642static SUPGIPMODE supdrvGipDeterminTscMode(PSUPDRVDEVEXT pDevExt)
5643{
5644 /*
5645 * On SMP we're faced with two problems:
5646 * (1) There might be a skew between the CPU, so that cpu0
5647 * returns a TSC that is slightly different from cpu1.
5648 * (2) Power management (and other things) may cause the TSC
5649 * to run at a non-constant speed, and cause the speed
5650 * to be different on the cpus. This will result in (1).
5651 *
5652 * So, on SMP systems we'll have to select the ASYNC update method
5653 * if there are symptoms of these problems.
5654 */
5655 if (RTMpGetCount() > 1)
5656 {
5657 uint32_t uEAX, uEBX, uECX, uEDX;
5658 uint64_t u64DiffCoresIgnored;
5659
5660 /* Permit the user and/or the OS specific bits to force async mode. */
5661 if (supdrvOSGetForcedAsyncTscMode(pDevExt))
5662 return SUPGIPMODE_ASYNC_TSC;
5663
5664 /* Try check for current differences between the cpus. */
5665 if (supdrvDetermineAsyncTsc(&u64DiffCoresIgnored))
5666 return SUPGIPMODE_ASYNC_TSC;
5667
5668 /*
5669 * If the CPU supports power management and is an AMD one we
5670 * won't trust it unless it has the TscInvariant bit is set.
5671 */
5672 /* Check for "AuthenticAMD" */
5673 ASMCpuId(0, &uEAX, &uEBX, &uECX, &uEDX);
5674 if ( uEAX >= 1
5675 && ASMIsAmdCpuEx(uEBX, uECX, uEDX))
5676 {
5677 /* Check for APM support and that TscInvariant is cleared. */
5678 ASMCpuId(0x80000000, &uEAX, &uEBX, &uECX, &uEDX);
5679 if (uEAX >= 0x80000007)
5680 {
5681 ASMCpuId(0x80000007, &uEAX, &uEBX, &uECX, &uEDX);
5682 if ( !(uEDX & RT_BIT(8))/* TscInvariant */
5683 && (uEDX & 0x3e)) /* STC|TM|THERMTRIP|VID|FID. Ignore TS. */
5684 return SUPGIPMODE_ASYNC_TSC;
5685 }
5686 }
5687 }
5688 return SUPGIPMODE_SYNC_TSC;
5689}
5690
5691
5692/**
5693 * Initializes per-CPU GIP information.
5694 *
5695 * @param pGip Pointer to the read-write kernel mapping of the GIP.
5696 * @param pCpu Pointer to which GIP CPU to initalize.
5697 * @param u64NanoTS The current nanosecond timestamp.
5698 */
5699static void supdrvGipInitCpu(PSUPGLOBALINFOPAGE pGip, PSUPGIPCPU pCpu, uint64_t u64NanoTS)
5700{
5701 pCpu->u32TransactionId = 2;
5702 pCpu->u64NanoTS = u64NanoTS;
5703 pCpu->u64TSC = ASMReadTSC();
5704
5705 ASMAtomicWriteSize(&pCpu->enmState, SUPGIPCPUSTATE_INVALID);
5706 ASMAtomicWriteSize(&pCpu->idCpu, NIL_RTCPUID);
5707 ASMAtomicWriteS16(&pCpu->iCpuSet, -1);
5708 ASMAtomicWriteU16(&pCpu->idApic, UINT16_MAX);
5709
5710 /*
5711 * We don't know the following values until we've executed updates.
5712 * So, we'll just pretend it's a 4 GHz CPU and adjust the history it on
5713 * the 2nd timer callout.
5714 */
5715 pCpu->u64CpuHz = _4G + 1; /* tstGIP-2 depends on this. */
5716 pCpu->u32UpdateIntervalTSC
5717 = pCpu->au32TSCHistory[0]
5718 = pCpu->au32TSCHistory[1]
5719 = pCpu->au32TSCHistory[2]
5720 = pCpu->au32TSCHistory[3]
5721 = pCpu->au32TSCHistory[4]
5722 = pCpu->au32TSCHistory[5]
5723 = pCpu->au32TSCHistory[6]
5724 = pCpu->au32TSCHistory[7]
5725 = (uint32_t)(_4G / pGip->u32UpdateHz);
5726}
5727
5728
5729/**
5730 * Initializes the GIP data.
5731 *
5732 * @param pDevExt Pointer to the device instance data.
5733 * @param pGip Pointer to the read-write kernel mapping of the GIP.
5734 * @param HCPhys The physical address of the GIP.
5735 * @param u64NanoTS The current nanosecond timestamp.
5736 * @param uUpdateHz The update frequency.
5737 * @param cCpus The CPU count.
5738 */
5739static void supdrvGipInit(PSUPDRVDEVEXT pDevExt, PSUPGLOBALINFOPAGE pGip, RTHCPHYS HCPhys,
5740 uint64_t u64NanoTS, unsigned uUpdateHz, unsigned cCpus)
5741{
5742 size_t const cbGip = RT_ALIGN_Z(RT_OFFSETOF(SUPGLOBALINFOPAGE, aCPUs[cCpus]), PAGE_SIZE);
5743 unsigned i;
5744#ifdef DEBUG_DARWIN_GIP
5745 OSDBGPRINT(("supdrvGipInit: pGip=%p HCPhys=%lx u64NanoTS=%llu uUpdateHz=%d cCpus=%u\n", pGip, (long)HCPhys, u64NanoTS, uUpdateHz, cCpus));
5746#else
5747 LogFlow(("supdrvGipInit: pGip=%p HCPhys=%lx u64NanoTS=%llu uUpdateHz=%d cCpus=%u\n", pGip, (long)HCPhys, u64NanoTS, uUpdateHz, cCpus));
5748#endif
5749
5750 /*
5751 * Initialize the structure.
5752 */
5753 memset(pGip, 0, cbGip);
5754 pGip->u32Magic = SUPGLOBALINFOPAGE_MAGIC;
5755 pGip->u32Version = SUPGLOBALINFOPAGE_VERSION;
5756 pGip->u32Mode = supdrvGipDeterminTscMode(pDevExt);
5757 pGip->cCpus = (uint16_t)cCpus;
5758 pGip->cPages = (uint16_t)(cbGip / PAGE_SIZE);
5759 pGip->u32UpdateHz = uUpdateHz;
5760 pGip->u32UpdateIntervalNS = 1000000000 / uUpdateHz;
5761 pGip->u64NanoTSLastUpdateHz = u64NanoTS;
5762 RTCpuSetEmpty(&pGip->OnlineCpuSet);
5763 RTCpuSetEmpty(&pGip->PresentCpuSet);
5764 RTMpGetSet(&pGip->PossibleCpuSet);
5765 pGip->cOnlineCpus = RTMpGetOnlineCount();
5766 pGip->cPresentCpus = RTMpGetPresentCount();
5767 pGip->cPossibleCpus = RTMpGetCount();
5768 pGip->idCpuMax = RTMpGetMaxCpuId();
5769 for (i = 0; i < RT_ELEMENTS(pGip->aiCpuFromApicId); i++)
5770 pGip->aiCpuFromApicId[i] = 0;
5771 for (i = 0; i < RT_ELEMENTS(pGip->aiCpuFromCpuSetIdx); i++)
5772 pGip->aiCpuFromCpuSetIdx[i] = UINT16_MAX;
5773
5774 for (i = 0; i < cCpus; i++)
5775 supdrvGipInitCpu(pGip, &pGip->aCPUs[i], u64NanoTS);
5776
5777 /*
5778 * Link it to the device extension.
5779 */
5780 pDevExt->pGip = pGip;
5781 pDevExt->HCPhysGip = HCPhys;
5782 pDevExt->cGipUsers = 0;
5783}
5784
5785
5786/**
5787 * On CPU initialization callback for RTMpOnAll.
5788 *
5789 * @param idCpu The CPU ID.
5790 * @param pvUser1 The device extension.
5791 * @param pvUser2 The GIP.
5792 */
5793static DECLCALLBACK(void) supdrvGipInitOnCpu(RTCPUID idCpu, void *pvUser1, void *pvUser2)
5794{
5795 /* This is good enough, even though it will update some of the globals a
5796 bit to much. */
5797 supdrvGipMpEventOnline((PSUPDRVDEVEXT)pvUser1, idCpu);
5798}
5799
5800
5801/**
5802 * Invalidates the GIP data upon termination.
5803 *
5804 * @param pGip Pointer to the read-write kernel mapping of the GIP.
5805 */
5806static void supdrvGipTerm(PSUPGLOBALINFOPAGE pGip)
5807{
5808 unsigned i;
5809 pGip->u32Magic = 0;
5810 for (i = 0; i < RT_ELEMENTS(pGip->aCPUs); i++)
5811 {
5812 pGip->aCPUs[i].u64NanoTS = 0;
5813 pGip->aCPUs[i].u64TSC = 0;
5814 pGip->aCPUs[i].iTSCHistoryHead = 0;
5815 }
5816}
5817
5818
5819/**
5820 * Worker routine for supdrvGipUpdate and supdrvGipUpdatePerCpu that
5821 * updates all the per cpu data except the transaction id.
5822 *
5823 * @param pDevExt The device extension.
5824 * @param pGipCpu Pointer to the per cpu data.
5825 * @param u64NanoTS The current time stamp.
5826 * @param u64TSC The current TSC.
5827 * @param iTick The current timer tick.
5828 */
5829static void supdrvGipDoUpdateCpu(PSUPDRVDEVEXT pDevExt, PSUPGIPCPU pGipCpu, uint64_t u64NanoTS, uint64_t u64TSC, uint64_t iTick)
5830{
5831 uint64_t u64TSCDelta;
5832 uint32_t u32UpdateIntervalTSC;
5833 uint32_t u32UpdateIntervalTSCSlack;
5834 unsigned iTSCHistoryHead;
5835 uint64_t u64CpuHz;
5836 uint32_t u32TransactionId;
5837
5838 PSUPGLOBALINFOPAGE pGip = pDevExt->pGip;
5839 AssertPtrReturnVoid(pGip);
5840
5841 /* Delta between this and the previous update. */
5842 ASMAtomicUoWriteU32(&pGipCpu->u32PrevUpdateIntervalNS, (uint32_t)(u64NanoTS - pGipCpu->u64NanoTS));
5843
5844 /*
5845 * Update the NanoTS.
5846 */
5847 ASMAtomicWriteU64(&pGipCpu->u64NanoTS, u64NanoTS);
5848
5849 /*
5850 * Calc TSC delta.
5851 */
5852 /** @todo validate the NanoTS delta, don't trust the OS to call us when it should... */
5853 u64TSCDelta = u64TSC - pGipCpu->u64TSC;
5854 ASMAtomicWriteU64(&pGipCpu->u64TSC, u64TSC);
5855
5856 if (u64TSCDelta >> 32)
5857 {
5858 u64TSCDelta = pGipCpu->u32UpdateIntervalTSC;
5859 pGipCpu->cErrors++;
5860 }
5861
5862 /*
5863 * On the 2nd and 3rd callout, reset the history with the current TSC
5864 * interval since the values entered by supdrvGipInit are totally off.
5865 * The interval on the 1st callout completely unreliable, the 2nd is a bit
5866 * better, while the 3rd should be most reliable.
5867 */
5868 u32TransactionId = pGipCpu->u32TransactionId;
5869 if (RT_UNLIKELY( ( u32TransactionId == 5
5870 || u32TransactionId == 7)
5871 && ( iTick == 2
5872 || iTick == 3) ))
5873 {
5874 unsigned i;
5875 for (i = 0; i < RT_ELEMENTS(pGipCpu->au32TSCHistory); i++)
5876 ASMAtomicUoWriteU32(&pGipCpu->au32TSCHistory[i], (uint32_t)u64TSCDelta);
5877 }
5878
5879 /*
5880 * TSC History.
5881 */
5882 Assert(RT_ELEMENTS(pGipCpu->au32TSCHistory) == 8);
5883 iTSCHistoryHead = (pGipCpu->iTSCHistoryHead + 1) & 7;
5884 ASMAtomicWriteU32(&pGipCpu->iTSCHistoryHead, iTSCHistoryHead);
5885 ASMAtomicWriteU32(&pGipCpu->au32TSCHistory[iTSCHistoryHead], (uint32_t)u64TSCDelta);
5886
5887 /*
5888 * UpdateIntervalTSC = average of last 8,2,1 intervals depending on update HZ.
5889 */
5890 if (pGip->u32UpdateHz >= 1000)
5891 {
5892 uint32_t u32;
5893 u32 = pGipCpu->au32TSCHistory[0];
5894 u32 += pGipCpu->au32TSCHistory[1];
5895 u32 += pGipCpu->au32TSCHistory[2];
5896 u32 += pGipCpu->au32TSCHistory[3];
5897 u32 >>= 2;
5898 u32UpdateIntervalTSC = pGipCpu->au32TSCHistory[4];
5899 u32UpdateIntervalTSC += pGipCpu->au32TSCHistory[5];
5900 u32UpdateIntervalTSC += pGipCpu->au32TSCHistory[6];
5901 u32UpdateIntervalTSC += pGipCpu->au32TSCHistory[7];
5902 u32UpdateIntervalTSC >>= 2;
5903 u32UpdateIntervalTSC += u32;
5904 u32UpdateIntervalTSC >>= 1;
5905
5906 /* Value chosen for a 2GHz Athlon64 running linux 2.6.10/11, . */
5907 u32UpdateIntervalTSCSlack = u32UpdateIntervalTSC >> 14;
5908 }
5909 else if (pGip->u32UpdateHz >= 90)
5910 {
5911 u32UpdateIntervalTSC = (uint32_t)u64TSCDelta;
5912 u32UpdateIntervalTSC += pGipCpu->au32TSCHistory[(iTSCHistoryHead - 1) & 7];
5913 u32UpdateIntervalTSC >>= 1;
5914
5915 /* value chosen on a 2GHz thinkpad running windows */
5916 u32UpdateIntervalTSCSlack = u32UpdateIntervalTSC >> 7;
5917 }
5918 else
5919 {
5920 u32UpdateIntervalTSC = (uint32_t)u64TSCDelta;
5921
5922 /* This value hasn't be checked yet.. waiting for OS/2 and 33Hz timers.. :-) */
5923 u32UpdateIntervalTSCSlack = u32UpdateIntervalTSC >> 6;
5924 }
5925 ASMAtomicWriteU32(&pGipCpu->u32UpdateIntervalTSC, u32UpdateIntervalTSC + u32UpdateIntervalTSCSlack);
5926
5927 /*
5928 * CpuHz.
5929 */
5930 u64CpuHz = ASMMult2xU32RetU64(u32UpdateIntervalTSC, pGip->u32UpdateHz);
5931 ASMAtomicWriteU64(&pGipCpu->u64CpuHz, u64CpuHz);
5932}
5933
5934
5935/**
5936 * Updates the GIP.
5937 *
5938 * @param pDevExt The device extension.
5939 * @param u64NanoTS The current nanosecond timesamp.
5940 * @param u64TSC The current TSC timesamp.
5941 * @param idCpu The CPU ID.
5942 * @param iTick The current timer tick.
5943 */
5944static void supdrvGipUpdate(PSUPDRVDEVEXT pDevExt, uint64_t u64NanoTS, uint64_t u64TSC, RTCPUID idCpu, uint64_t iTick)
5945{
5946 /*
5947 * Determine the relevant CPU data.
5948 */
5949 PSUPGIPCPU pGipCpu;
5950 PSUPGLOBALINFOPAGE pGip = pDevExt->pGip;
5951 AssertPtrReturnVoid(pGip);
5952
5953 if (pGip->u32Mode != SUPGIPMODE_ASYNC_TSC)
5954 pGipCpu = &pGip->aCPUs[0];
5955 else
5956 {
5957 unsigned iCpu = pGip->aiCpuFromApicId[ASMGetApicId()];
5958 if (RT_UNLIKELY(iCpu >= pGip->cCpus))
5959 return;
5960 pGipCpu = &pGip->aCPUs[iCpu];
5961 if (RT_UNLIKELY(pGipCpu->idCpu != idCpu))
5962 return;
5963 }
5964
5965 /*
5966 * Start update transaction.
5967 */
5968 if (!(ASMAtomicIncU32(&pGipCpu->u32TransactionId) & 1))
5969 {
5970 /* this can happen on win32 if we're taking to long and there are more CPUs around. shouldn't happen though. */
5971 AssertMsgFailed(("Invalid transaction id, %#x, not odd!\n", pGipCpu->u32TransactionId));
5972 ASMAtomicIncU32(&pGipCpu->u32TransactionId);
5973 pGipCpu->cErrors++;
5974 return;
5975 }
5976
5977 /*
5978 * Recalc the update frequency every 0x800th time.
5979 */
5980 if (!(pGipCpu->u32TransactionId & (GIP_UPDATEHZ_RECALC_FREQ * 2 - 2)))
5981 {
5982 if (pGip->u64NanoTSLastUpdateHz)
5983 {
5984#ifdef RT_ARCH_AMD64 /** @todo fix 64-bit div here to work on x86 linux. */
5985 uint64_t u64Delta = u64NanoTS - pGip->u64NanoTSLastUpdateHz;
5986 uint32_t u32UpdateHz = (uint32_t)((UINT64_C(1000000000) * GIP_UPDATEHZ_RECALC_FREQ) / u64Delta);
5987 if (u32UpdateHz <= 2000 && u32UpdateHz >= 30)
5988 {
5989 ASMAtomicWriteU32(&pGip->u32UpdateHz, u32UpdateHz);
5990 ASMAtomicWriteU32(&pGip->u32UpdateIntervalNS, 1000000000 / u32UpdateHz);
5991 }
5992#endif
5993 }
5994 ASMAtomicWriteU64(&pGip->u64NanoTSLastUpdateHz, u64NanoTS);
5995 }
5996
5997 /*
5998 * Update the data.
5999 */
6000 supdrvGipDoUpdateCpu(pDevExt, pGipCpu, u64NanoTS, u64TSC, iTick);
6001
6002 /*
6003 * Complete transaction.
6004 */
6005 ASMAtomicIncU32(&pGipCpu->u32TransactionId);
6006}
6007
6008
6009/**
6010 * Updates the per cpu GIP data for the calling cpu.
6011 *
6012 * @param pDevExt The device extension.
6013 * @param u64NanoTS The current nanosecond timesamp.
6014 * @param u64TSC The current TSC timesamp.
6015 * @param idCpu The CPU ID.
6016 * @param idApic The APIC id for the CPU index.
6017 * @param iTick The current timer tick.
6018 */
6019static void supdrvGipUpdatePerCpu(PSUPDRVDEVEXT pDevExt, uint64_t u64NanoTS, uint64_t u64TSC,
6020 RTCPUID idCpu, uint8_t idApic, uint64_t iTick)
6021{
6022 uint32_t iCpu;
6023 PSUPGLOBALINFOPAGE pGip = pDevExt->pGip;
6024
6025 /*
6026 * Avoid a potential race when a CPU online notification doesn't fire on
6027 * the onlined CPU but the tick creeps in before the event notification is
6028 * run.
6029 */
6030 if (RT_UNLIKELY(iTick == 1))
6031 {
6032 iCpu = supdrvGipCpuIndexFromCpuId(pGip, idCpu);
6033 if (pGip->aCPUs[iCpu].enmState == SUPGIPCPUSTATE_OFFLINE)
6034 supdrvGipMpEventOnline(pDevExt, idCpu);
6035 }
6036
6037 iCpu = pGip->aiCpuFromApicId[idApic];
6038 if (RT_LIKELY(iCpu < pGip->cCpus))
6039 {
6040 PSUPGIPCPU pGipCpu = &pGip->aCPUs[iCpu];
6041 if (pGipCpu->idCpu == idCpu)
6042 {
6043 /*
6044 * Start update transaction.
6045 */
6046 if (!(ASMAtomicIncU32(&pGipCpu->u32TransactionId) & 1))
6047 {
6048 AssertMsgFailed(("Invalid transaction id, %#x, not odd!\n", pGipCpu->u32TransactionId));
6049 ASMAtomicIncU32(&pGipCpu->u32TransactionId);
6050 pGipCpu->cErrors++;
6051 return;
6052 }
6053
6054 /*
6055 * Update the data.
6056 */
6057 supdrvGipDoUpdateCpu(pDevExt, pGipCpu, u64NanoTS, u64TSC, iTick);
6058
6059 /*
6060 * Complete transaction.
6061 */
6062 ASMAtomicIncU32(&pGipCpu->u32TransactionId);
6063 }
6064 }
6065}
6066
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