VirtualBox

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

Last change on this file since 46861 was 45935, checked in by vboxsync, 12 years ago

Export RTLogGetDefaultInstance.

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