VirtualBox

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

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

SUPDrv,SUPLib: Introducing /dev/vboxdrvu on darwin (other platforms soon to follow).

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