VirtualBox

source: vbox/trunk/src/VBox/HostDrivers/Support/SUPDrv.cpp@ 91782

Last change on this file since 91782 was 91775, checked in by vboxsync, 3 years ago

SUPDrv/darwin,++: Switch back to the kernel stack before calling into SUPDrv to prevent panicing macOS 12. This is just a temporary measure on trunk, as the whole custom stack + call-ring-3 holdover from raw-mode will be eliminated soon. bugref:10124

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 277.2 KB
Line 
1/* $Id: SUPDrv.cpp 91775 2021-10-17 10:53:28Z vboxsync $ */
2/** @file
3 * VBoxDrv - The VirtualBox Support Driver - Common code.
4 */
5
6/*
7 * Copyright (C) 2006-2020 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/*********************************************************************************************************************************
29* Header Files *
30*********************************************************************************************************************************/
31#define LOG_GROUP LOG_GROUP_SUP_DRV
32#define SUPDRV_AGNOSTIC
33#include "SUPDrvInternal.h"
34#ifndef PAGE_SHIFT
35# include <iprt/param.h>
36#endif
37#include <iprt/asm.h>
38#include <iprt/asm-amd64-x86.h>
39#include <iprt/asm-math.h>
40#include <iprt/cpuset.h>
41#if defined(RT_OS_DARWIN) || defined(RT_OS_SOLARIS) || defined(RT_OS_WINDOWS)
42# include <iprt/dbg.h>
43#endif
44#include <iprt/handletable.h>
45#include <iprt/mem.h>
46#include <iprt/mp.h>
47#include <iprt/power.h>
48#include <iprt/process.h>
49#include <iprt/semaphore.h>
50#include <iprt/spinlock.h>
51#include <iprt/thread.h>
52#include <iprt/uuid.h>
53#include <iprt/net.h>
54#include <iprt/crc.h>
55#include <iprt/string.h>
56#include <iprt/timer.h>
57#if defined(RT_OS_DARWIN) || defined(RT_OS_SOLARIS) || defined(RT_OS_FREEBSD)
58# include <iprt/rand.h>
59# include <iprt/path.h>
60#endif
61#include <iprt/uint128.h>
62#include <iprt/x86.h>
63
64#include <VBox/param.h>
65#include <VBox/log.h>
66#include <VBox/err.h>
67#include <VBox/vmm/hm_vmx.h>
68
69#if defined(RT_OS_SOLARIS) || defined(RT_OS_DARWIN)
70# include "dtrace/SUPDrv.h"
71#else
72# define VBOXDRV_SESSION_CREATE(pvSession, fUser) do { } while (0)
73# define VBOXDRV_SESSION_CLOSE(pvSession) do { } while (0)
74# define VBOXDRV_IOCTL_ENTRY(pvSession, uIOCtl, pvReqHdr) do { } while (0)
75# define VBOXDRV_IOCTL_RETURN(pvSession, uIOCtl, pvReqHdr, rcRet, rcReq) do { } while (0)
76#endif
77
78/*
79 * Logging assignments:
80 * Log - useful stuff, like failures.
81 * LogFlow - program flow, except the really noisy bits.
82 * Log2 - Cleanup.
83 * Log3 - Loader flow noise.
84 * Log4 - Call VMMR0 flow noise.
85 * Log5 - Native yet-to-be-defined noise.
86 * Log6 - Native ioctl flow noise.
87 *
88 * Logging requires KBUILD_TYPE=debug and possibly changes to the logger
89 * instantiation in log-vbox.c(pp).
90 */
91
92
93/*********************************************************************************************************************************
94* Defined Constants And Macros *
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/** @ SUPDRV_CHECK_SMAP_SETUP
103 * SMAP check setup. */
104/** @def SUPDRV_CHECK_SMAP_CHECK
105 * Checks that the AC flag is set if SMAP is enabled. If AC is not set, it
106 * will be logged and @a a_BadExpr is executed. */
107#if (defined(RT_OS_DARWIN) || defined(RT_OS_LINUX)) && !defined(VBOX_WITHOUT_EFLAGS_AC_SET_IN_VBOXDRV)
108# define SUPDRV_CHECK_SMAP_SETUP() uint32_t const fKernelFeatures = SUPR0GetKernelFeatures()
109# define SUPDRV_CHECK_SMAP_CHECK(a_pDevExt, a_BadExpr) \
110 do { \
111 if (fKernelFeatures & SUPKERNELFEATURES_SMAP) \
112 { \
113 RTCCUINTREG fEfl = ASMGetFlags(); \
114 if (RT_LIKELY(fEfl & X86_EFL_AC)) \
115 { /* likely */ } \
116 else \
117 { \
118 supdrvBadContext(a_pDevExt, "SUPDrv.cpp", __LINE__, "EFLAGS.AC is 0!"); \
119 a_BadExpr; \
120 } \
121 } \
122 } while (0)
123#else
124# define SUPDRV_CHECK_SMAP_SETUP() uint32_t const fKernelFeatures = 0
125# define SUPDRV_CHECK_SMAP_CHECK(a_pDevExt, a_BadExpr) NOREF(fKernelFeatures)
126#endif
127
128
129/*********************************************************************************************************************************
130* Internal Functions *
131*********************************************************************************************************************************/
132static DECLCALLBACK(int) supdrvSessionObjHandleRetain(RTHANDLETABLE hHandleTable, void *pvObj, void *pvCtx, void *pvUser);
133static DECLCALLBACK(void) supdrvSessionObjHandleDelete(RTHANDLETABLE hHandleTable, uint32_t h, void *pvObj, void *pvCtx, void *pvUser);
134static int supdrvMemAdd(PSUPDRVMEMREF pMem, PSUPDRVSESSION pSession);
135static int supdrvMemRelease(PSUPDRVSESSION pSession, RTHCUINTPTR uPtr, SUPDRVMEMREFTYPE eType);
136static int supdrvIOCtl_LdrOpen(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPLDROPEN pReq);
137static int supdrvIOCtl_LdrLoad(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPLDRLOAD pReq);
138static int supdrvIOCtl_LdrFree(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPLDRFREE pReq);
139static int supdrvIOCtl_LdrLockDown(PSUPDRVDEVEXT pDevExt);
140static int supdrvIOCtl_LdrQuerySymbol(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPLDRGETSYMBOL pReq);
141static int supdrvIDC_LdrGetSymbol(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPDRVIDCREQGETSYM pReq);
142static int supdrvLdrAddUsage(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPDRVLDRIMAGE pImage, bool fRing3Usage);
143DECLINLINE(void) supdrvLdrSubtractUsage(PSUPDRVDEVEXT pDevExt, PSUPDRVLDRIMAGE pImage, uint32_t cReference);
144static void supdrvLdrFree(PSUPDRVDEVEXT pDevExt, PSUPDRVLDRIMAGE pImage);
145DECLINLINE(int) supdrvLdrLock(PSUPDRVDEVEXT pDevExt);
146DECLINLINE(int) supdrvLdrUnlock(PSUPDRVDEVEXT pDevExt);
147static int supdrvIOCtl_CallServiceModule(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPCALLSERVICE pReq);
148static int supdrvIOCtl_LoggerSettings(PSUPLOGGERSETTINGS pReq);
149static int supdrvIOCtl_MsrProber(PSUPDRVDEVEXT pDevExt, PSUPMSRPROBER pReq);
150static int supdrvIOCtl_ResumeSuspendedKbds(void);
151
152
153/*********************************************************************************************************************************
154* Global Variables *
155*********************************************************************************************************************************/
156/** @def STKBACK
157 * Indicates that the symbol needs to switch back to the kernel stack on darwin.
158 * See @bugref{10124} for details. */
159#if 1
160# define STKBACK(a) "StkBack_" a
161#else
162# define STKBACK(a) a
163#endif
164/** @def STKOKAY
165 * The oposite of STKBACK, just for make the table nicly aligned. */
166#define STKOKAY(a) a
167
168/**
169 * Array of the R0 SUP API.
170 *
171 * While making changes to these exports, make sure to update the IOC
172 * minor version (SUPDRV_IOC_VERSION).
173 *
174 * @remarks This array is processed by SUPR0-def-pe.sed and SUPR0-def-lx.sed to
175 * produce definition files from which import libraries are generated.
176 * Take care when commenting things and especially with \#ifdef'ing.
177 */
178static SUPFUNC g_aFunctions[] =
179{
180/* SED: START */
181 /* name function */
182 /* Entries with absolute addresses determined at runtime, fixup
183 code makes ugly ASSUMPTIONS about the order here: */
184 { STKOKAY("SUPR0AbsIs64bit"), (void *)0 },
185 { STKOKAY("SUPR0Abs64bitKernelCS"), (void *)0 },
186 { STKOKAY("SUPR0Abs64bitKernelSS"), (void *)0 },
187 { STKOKAY("SUPR0Abs64bitKernelDS"), (void *)0 },
188 { STKOKAY("SUPR0AbsKernelCS"), (void *)0 },
189 { STKOKAY("SUPR0AbsKernelSS"), (void *)0 },
190 { STKOKAY("SUPR0AbsKernelDS"), (void *)0 },
191 { STKOKAY("SUPR0AbsKernelES"), (void *)0 },
192 { STKOKAY("SUPR0AbsKernelFS"), (void *)0 },
193 { STKOKAY("SUPR0AbsKernelGS"), (void *)0 },
194 /* Normal function pointers: */
195 { STKOKAY("g_pSUPGlobalInfoPage"), (void *)&g_pSUPGlobalInfoPage }, /* SED: DATA */
196 { STKOKAY("SUPGetGIP"), (void *)(uintptr_t)SUPGetGIP },
197 { STKBACK("SUPReadTscWithDelta"), (void *)(uintptr_t)SUPReadTscWithDelta },
198 { STKBACK("SUPGetTscDeltaSlow"), (void *)(uintptr_t)SUPGetTscDeltaSlow },
199 { STKBACK("SUPGetCpuHzFromGipForAsyncMode"), (void *)(uintptr_t)SUPGetCpuHzFromGipForAsyncMode },
200 { STKOKAY("SUPIsTscFreqCompatible"), (void *)(uintptr_t)SUPIsTscFreqCompatible },
201 { STKOKAY("SUPIsTscFreqCompatibleEx"), (void *)(uintptr_t)SUPIsTscFreqCompatibleEx },
202 { STKBACK("SUPR0BadContext"), (void *)(uintptr_t)SUPR0BadContext },
203 { STKBACK("SUPR0ComponentDeregisterFactory"), (void *)(uintptr_t)SUPR0ComponentDeregisterFactory },
204 { STKBACK("SUPR0ComponentQueryFactory"), (void *)(uintptr_t)SUPR0ComponentQueryFactory },
205 { STKBACK("SUPR0ComponentRegisterFactory"), (void *)(uintptr_t)SUPR0ComponentRegisterFactory },
206 { STKBACK("SUPR0ContAlloc"), (void *)(uintptr_t)SUPR0ContAlloc },
207 { STKBACK("SUPR0ContFree"), (void *)(uintptr_t)SUPR0ContFree },
208 { STKBACK("SUPR0ChangeCR4"), (void *)(uintptr_t)SUPR0ChangeCR4 },
209 { STKBACK("SUPR0EnableVTx"), (void *)(uintptr_t)SUPR0EnableVTx },
210 { STKBACK("SUPR0SuspendVTxOnCpu"), (void *)(uintptr_t)SUPR0SuspendVTxOnCpu },
211 { STKBACK("SUPR0ResumeVTxOnCpu"), (void *)(uintptr_t)SUPR0ResumeVTxOnCpu },
212 { STKOKAY("SUPR0GetCurrentGdtRw"), (void *)(uintptr_t)SUPR0GetCurrentGdtRw },
213 { STKOKAY("SUPR0GetKernelFeatures"), (void *)(uintptr_t)SUPR0GetKernelFeatures },
214 { STKBACK("SUPR0GetHwvirtMsrs"), (void *)(uintptr_t)SUPR0GetHwvirtMsrs },
215 { STKBACK("SUPR0GetPagingMode"), (void *)(uintptr_t)SUPR0GetPagingMode },
216 { STKBACK("SUPR0GetSvmUsability"), (void *)(uintptr_t)SUPR0GetSvmUsability },
217 { STKBACK("SUPR0GetVTSupport"), (void *)(uintptr_t)SUPR0GetVTSupport },
218 { STKBACK("SUPR0GetVmxUsability"), (void *)(uintptr_t)SUPR0GetVmxUsability },
219 { STKBACK("SUPR0LdrIsLockOwnerByMod"), (void *)(uintptr_t)SUPR0LdrIsLockOwnerByMod },
220 { STKBACK("SUPR0LdrLock"), (void *)(uintptr_t)SUPR0LdrLock },
221 { STKBACK("SUPR0LdrUnlock"), (void *)(uintptr_t)SUPR0LdrUnlock },
222 { STKBACK("SUPR0LdrModByName"), (void *)(uintptr_t)SUPR0LdrModByName },
223 { STKBACK("SUPR0LdrModRelease"), (void *)(uintptr_t)SUPR0LdrModRelease },
224 { STKBACK("SUPR0LdrModRetain"), (void *)(uintptr_t)SUPR0LdrModRetain },
225 { STKBACK("SUPR0LockMem"), (void *)(uintptr_t)SUPR0LockMem },
226 { STKBACK("SUPR0LowAlloc"), (void *)(uintptr_t)SUPR0LowAlloc },
227 { STKBACK("SUPR0LowFree"), (void *)(uintptr_t)SUPR0LowFree },
228 { STKBACK("SUPR0MemAlloc"), (void *)(uintptr_t)SUPR0MemAlloc },
229 { STKBACK("SUPR0MemFree"), (void *)(uintptr_t)SUPR0MemFree },
230 { STKBACK("SUPR0MemGetPhys"), (void *)(uintptr_t)SUPR0MemGetPhys },
231 { STKBACK("SUPR0ObjAddRef"), (void *)(uintptr_t)SUPR0ObjAddRef },
232 { STKBACK("SUPR0ObjAddRefEx"), (void *)(uintptr_t)SUPR0ObjAddRefEx },
233 { STKBACK("SUPR0ObjRegister"), (void *)(uintptr_t)SUPR0ObjRegister },
234 { STKBACK("SUPR0ObjRelease"), (void *)(uintptr_t)SUPR0ObjRelease },
235 { STKBACK("SUPR0ObjVerifyAccess"), (void *)(uintptr_t)SUPR0ObjVerifyAccess },
236 { STKBACK("SUPR0PageAllocEx"), (void *)(uintptr_t)SUPR0PageAllocEx },
237 { STKBACK("SUPR0PageFree"), (void *)(uintptr_t)SUPR0PageFree },
238 { STKBACK("SUPR0PageMapKernel"), (void *)(uintptr_t)SUPR0PageMapKernel },
239 { STKBACK("SUPR0PageProtect"), (void *)(uintptr_t)SUPR0PageProtect },
240#if defined(RT_OS_LINUX) || defined(RT_OS_SOLARIS)
241 { STKBACK("SUPR0HCPhysToVirt"), (void *)(uintptr_t)SUPR0HCPhysToVirt }, /* only-linux, only solaris */
242#endif
243 { STKBACK("SUPR0Printf"), (void *)(uintptr_t)SUPR0Printf },
244 { STKBACK("SUPR0GetSessionGVM"), (void *)(uintptr_t)SUPR0GetSessionGVM },
245 { STKBACK("SUPR0GetSessionVM"), (void *)(uintptr_t)SUPR0GetSessionVM },
246 { STKBACK("SUPR0SetSessionVM"), (void *)(uintptr_t)SUPR0SetSessionVM },
247 { STKBACK("SUPR0TscDeltaMeasureBySetIndex"), (void *)(uintptr_t)SUPR0TscDeltaMeasureBySetIndex },
248 { STKBACK("SUPR0TracerDeregisterDrv"), (void *)(uintptr_t)SUPR0TracerDeregisterDrv },
249 { STKBACK("SUPR0TracerDeregisterImpl"), (void *)(uintptr_t)SUPR0TracerDeregisterImpl },
250 { STKBACK("SUPR0TracerFireProbe"), (void *)(uintptr_t)SUPR0TracerFireProbe },
251 { STKBACK("SUPR0TracerRegisterDrv"), (void *)(uintptr_t)SUPR0TracerRegisterDrv },
252 { STKBACK("SUPR0TracerRegisterImpl"), (void *)(uintptr_t)SUPR0TracerRegisterImpl },
253 { STKBACK("SUPR0TracerRegisterModule"), (void *)(uintptr_t)SUPR0TracerRegisterModule },
254 { STKBACK("SUPR0TracerUmodProbeFire"), (void *)(uintptr_t)SUPR0TracerUmodProbeFire },
255 { STKBACK("SUPR0UnlockMem"), (void *)(uintptr_t)SUPR0UnlockMem },
256#ifdef RT_OS_WINDOWS
257 { STKBACK("SUPR0IoCtlSetupForHandle"), (void *)(uintptr_t)SUPR0IoCtlSetupForHandle }, /* only-windows */
258 { STKBACK("SUPR0IoCtlPerform"), (void *)(uintptr_t)SUPR0IoCtlPerform }, /* only-windows */
259 { STKBACK("SUPR0IoCtlCleanup"), (void *)(uintptr_t)SUPR0IoCtlCleanup }, /* only-windows */
260#endif
261 { STKBACK("SUPSemEventClose"), (void *)(uintptr_t)SUPSemEventClose },
262 { STKBACK("SUPSemEventCreate"), (void *)(uintptr_t)SUPSemEventCreate },
263 { STKBACK("SUPSemEventGetResolution"), (void *)(uintptr_t)SUPSemEventGetResolution },
264 { STKBACK("SUPSemEventMultiClose"), (void *)(uintptr_t)SUPSemEventMultiClose },
265 { STKBACK("SUPSemEventMultiCreate"), (void *)(uintptr_t)SUPSemEventMultiCreate },
266 { STKBACK("SUPSemEventMultiGetResolution"), (void *)(uintptr_t)SUPSemEventMultiGetResolution },
267 { STKBACK("SUPSemEventMultiReset"), (void *)(uintptr_t)SUPSemEventMultiReset },
268 { STKBACK("SUPSemEventMultiSignal"), (void *)(uintptr_t)SUPSemEventMultiSignal },
269 { STKBACK("SUPSemEventMultiWait"), (void *)(uintptr_t)SUPSemEventMultiWait },
270 { STKBACK("SUPSemEventMultiWaitNoResume"), (void *)(uintptr_t)SUPSemEventMultiWaitNoResume },
271 { STKBACK("SUPSemEventMultiWaitNsAbsIntr"), (void *)(uintptr_t)SUPSemEventMultiWaitNsAbsIntr },
272 { STKBACK("SUPSemEventMultiWaitNsRelIntr"), (void *)(uintptr_t)SUPSemEventMultiWaitNsRelIntr },
273 { STKBACK("SUPSemEventSignal"), (void *)(uintptr_t)SUPSemEventSignal },
274 { STKBACK("SUPSemEventWait"), (void *)(uintptr_t)SUPSemEventWait },
275 { STKBACK("SUPSemEventWaitNoResume"), (void *)(uintptr_t)SUPSemEventWaitNoResume },
276 { STKBACK("SUPSemEventWaitNsAbsIntr"), (void *)(uintptr_t)SUPSemEventWaitNsAbsIntr },
277 { STKBACK("SUPSemEventWaitNsRelIntr"), (void *)(uintptr_t)SUPSemEventWaitNsRelIntr },
278
279 { STKBACK("RTAssertAreQuiet"), (void *)(uintptr_t)RTAssertAreQuiet },
280 { STKBACK("RTAssertMayPanic"), (void *)(uintptr_t)RTAssertMayPanic },
281 { STKBACK("RTAssertMsg1"), (void *)(uintptr_t)RTAssertMsg1 },
282 { STKBACK("RTAssertMsg2AddV"), (void *)(uintptr_t)RTAssertMsg2AddV },
283 { STKBACK("RTAssertMsg2V"), (void *)(uintptr_t)RTAssertMsg2V },
284 { STKBACK("RTAssertSetMayPanic"), (void *)(uintptr_t)RTAssertSetMayPanic },
285 { STKBACK("RTAssertSetQuiet"), (void *)(uintptr_t)RTAssertSetQuiet },
286 { STKOKAY("RTCrc32"), (void *)(uintptr_t)RTCrc32 },
287 { STKOKAY("RTCrc32Finish"), (void *)(uintptr_t)RTCrc32Finish },
288 { STKOKAY("RTCrc32Process"), (void *)(uintptr_t)RTCrc32Process },
289 { STKOKAY("RTCrc32Start"), (void *)(uintptr_t)RTCrc32Start },
290 { STKOKAY("RTErrConvertFromErrno"), (void *)(uintptr_t)RTErrConvertFromErrno },
291 { STKOKAY("RTErrConvertToErrno"), (void *)(uintptr_t)RTErrConvertToErrno },
292 { STKBACK("RTHandleTableAllocWithCtx"), (void *)(uintptr_t)RTHandleTableAllocWithCtx },
293 { STKBACK("RTHandleTableCreate"), (void *)(uintptr_t)RTHandleTableCreate },
294 { STKBACK("RTHandleTableCreateEx"), (void *)(uintptr_t)RTHandleTableCreateEx },
295 { STKBACK("RTHandleTableDestroy"), (void *)(uintptr_t)RTHandleTableDestroy },
296 { STKBACK("RTHandleTableFreeWithCtx"), (void *)(uintptr_t)RTHandleTableFreeWithCtx },
297 { STKBACK("RTHandleTableLookupWithCtx"), (void *)(uintptr_t)RTHandleTableLookupWithCtx },
298 { STKBACK("RTLogBulkUpdate"), (void *)(uintptr_t)RTLogBulkUpdate},
299 { STKBACK("RTLogCheckGroupFlags"), (void *)(uintptr_t)RTLogCheckGroupFlags },
300 { STKBACK("RTLogCreateEx"), (void *)(uintptr_t)RTLogCreateEx },
301 { STKBACK("RTLogDestroy"), (void *)(uintptr_t)RTLogDestroy },
302 { STKBACK("RTLogDefaultInstance"), (void *)(uintptr_t)RTLogDefaultInstance },
303 { STKBACK("RTLogDefaultInstanceEx"), (void *)(uintptr_t)RTLogDefaultInstanceEx },
304 { STKBACK("SUPR0DefaultLogInstanceEx"), (void *)(uintptr_t)SUPR0DefaultLogInstanceEx },
305 { STKBACK("RTLogGetDefaultInstance"), (void *)(uintptr_t)RTLogGetDefaultInstance },
306 { STKBACK("RTLogGetDefaultInstanceEx"), (void *)(uintptr_t)RTLogGetDefaultInstanceEx },
307 { STKBACK("SUPR0GetDefaultLogInstanceEx"), (void *)(uintptr_t)SUPR0GetDefaultLogInstanceEx },
308 { STKBACK("RTLogLoggerExV"), (void *)(uintptr_t)RTLogLoggerExV },
309 { STKBACK("RTLogPrintfV"), (void *)(uintptr_t)RTLogPrintfV },
310 { STKBACK("RTLogRelGetDefaultInstance"), (void *)(uintptr_t)RTLogRelGetDefaultInstance },
311 { STKBACK("RTLogRelGetDefaultInstanceEx"), (void *)(uintptr_t)RTLogRelGetDefaultInstanceEx },
312 { STKBACK("SUPR0GetDefaultLogRelInstanceEx"), (void *)(uintptr_t)SUPR0GetDefaultLogRelInstanceEx },
313 { STKBACK("RTLogSetDefaultInstanceThread"), (void *)(uintptr_t)RTLogSetDefaultInstanceThread },
314 { STKBACK("RTLogSetFlushCallback"), (void *)(uintptr_t)RTLogSetFlushCallback },
315 { STKBACK("RTLogSetR0ProgramStart"), (void *)(uintptr_t)RTLogSetR0ProgramStart },
316 { STKBACK("RTLogSetR0ThreadNameF"), (void *)(uintptr_t)RTLogSetR0ThreadNameF },
317 { STKBACK("RTMemAllocExTag"), (void *)(uintptr_t)RTMemAllocExTag },
318 { STKBACK("RTMemAllocTag"), (void *)(uintptr_t)RTMemAllocTag },
319 { STKBACK("RTMemAllocVarTag"), (void *)(uintptr_t)RTMemAllocVarTag },
320 { STKBACK("RTMemAllocZTag"), (void *)(uintptr_t)RTMemAllocZTag },
321 { STKBACK("RTMemAllocZVarTag"), (void *)(uintptr_t)RTMemAllocZVarTag },
322 { STKBACK("RTMemDupExTag"), (void *)(uintptr_t)RTMemDupExTag },
323 { STKBACK("RTMemDupTag"), (void *)(uintptr_t)RTMemDupTag },
324 { STKBACK("RTMemFree"), (void *)(uintptr_t)RTMemFree },
325 { STKBACK("RTMemFreeEx"), (void *)(uintptr_t)RTMemFreeEx },
326 { STKBACK("RTMemReallocTag"), (void *)(uintptr_t)RTMemReallocTag },
327 { STKBACK("RTMpCpuId"), (void *)(uintptr_t)RTMpCpuId },
328 { STKBACK("RTMpCpuIdFromSetIndex"), (void *)(uintptr_t)RTMpCpuIdFromSetIndex },
329 { STKBACK("RTMpCpuIdToSetIndex"), (void *)(uintptr_t)RTMpCpuIdToSetIndex },
330 { STKBACK("RTMpCurSetIndex"), (void *)(uintptr_t)RTMpCurSetIndex },
331 { STKBACK("RTMpCurSetIndexAndId"), (void *)(uintptr_t)RTMpCurSetIndexAndId },
332 { STKBACK("RTMpGetArraySize"), (void *)(uintptr_t)RTMpGetArraySize },
333 { STKBACK("RTMpGetCount"), (void *)(uintptr_t)RTMpGetCount },
334 { STKBACK("RTMpGetMaxCpuId"), (void *)(uintptr_t)RTMpGetMaxCpuId },
335 { STKBACK("RTMpGetOnlineCount"), (void *)(uintptr_t)RTMpGetOnlineCount },
336 { STKBACK("RTMpGetOnlineSet"), (void *)(uintptr_t)RTMpGetOnlineSet },
337 { STKBACK("RTMpGetSet"), (void *)(uintptr_t)RTMpGetSet },
338 { STKBACK("RTMpIsCpuOnline"), (void *)(uintptr_t)RTMpIsCpuOnline },
339 { STKBACK("RTMpIsCpuPossible"), (void *)(uintptr_t)RTMpIsCpuPossible },
340 { STKBACK("RTMpIsCpuWorkPending"), (void *)(uintptr_t)RTMpIsCpuWorkPending },
341 { STKBACK("RTMpNotificationDeregister"), (void *)(uintptr_t)RTMpNotificationDeregister },
342 { STKBACK("RTMpNotificationRegister"), (void *)(uintptr_t)RTMpNotificationRegister },
343 { STKBACK("RTMpOnAll"), (void *)(uintptr_t)RTMpOnAll },
344 { STKBACK("RTMpOnOthers"), (void *)(uintptr_t)RTMpOnOthers },
345 { STKBACK("RTMpOnSpecific"), (void *)(uintptr_t)RTMpOnSpecific },
346 { STKBACK("RTMpPokeCpu"), (void *)(uintptr_t)RTMpPokeCpu },
347 { STKBACK("RTNetIPv4AddDataChecksum"), (void *)(uintptr_t)RTNetIPv4AddDataChecksum },
348 { STKBACK("RTNetIPv4AddTCPChecksum"), (void *)(uintptr_t)RTNetIPv4AddTCPChecksum },
349 { STKBACK("RTNetIPv4AddUDPChecksum"), (void *)(uintptr_t)RTNetIPv4AddUDPChecksum },
350 { STKBACK("RTNetIPv4FinalizeChecksum"), (void *)(uintptr_t)RTNetIPv4FinalizeChecksum },
351 { STKOKAY("RTNetIPv4HdrChecksum"), (void *)(uintptr_t)RTNetIPv4HdrChecksum },
352 { STKOKAY("RTNetIPv4IsDHCPValid"), (void *)(uintptr_t)RTNetIPv4IsDHCPValid },
353 { STKOKAY("RTNetIPv4IsHdrValid"), (void *)(uintptr_t)RTNetIPv4IsHdrValid },
354 { STKOKAY("RTNetIPv4IsTCPSizeValid"), (void *)(uintptr_t)RTNetIPv4IsTCPSizeValid },
355 { STKOKAY("RTNetIPv4IsTCPValid"), (void *)(uintptr_t)RTNetIPv4IsTCPValid },
356 { STKOKAY("RTNetIPv4IsUDPSizeValid"), (void *)(uintptr_t)RTNetIPv4IsUDPSizeValid },
357 { STKOKAY("RTNetIPv4IsUDPValid"), (void *)(uintptr_t)RTNetIPv4IsUDPValid },
358 { STKOKAY("RTNetIPv4PseudoChecksum"), (void *)(uintptr_t)RTNetIPv4PseudoChecksum },
359 { STKOKAY("RTNetIPv4PseudoChecksumBits"), (void *)(uintptr_t)RTNetIPv4PseudoChecksumBits },
360 { STKOKAY("RTNetIPv4TCPChecksum"), (void *)(uintptr_t)RTNetIPv4TCPChecksum },
361 { STKOKAY("RTNetIPv4UDPChecksum"), (void *)(uintptr_t)RTNetIPv4UDPChecksum },
362 { STKOKAY("RTNetIPv6PseudoChecksum"), (void *)(uintptr_t)RTNetIPv6PseudoChecksum },
363 { STKOKAY("RTNetIPv6PseudoChecksumBits"), (void *)(uintptr_t)RTNetIPv6PseudoChecksumBits },
364 { STKOKAY("RTNetIPv6PseudoChecksumEx"), (void *)(uintptr_t)RTNetIPv6PseudoChecksumEx },
365 { STKOKAY("RTNetTCPChecksum"), (void *)(uintptr_t)RTNetTCPChecksum },
366 { STKOKAY("RTNetUDPChecksum"), (void *)(uintptr_t)RTNetUDPChecksum },
367 { STKBACK("RTPowerNotificationDeregister"), (void *)(uintptr_t)RTPowerNotificationDeregister },
368 { STKBACK("RTPowerNotificationRegister"), (void *)(uintptr_t)RTPowerNotificationRegister },
369 { STKBACK("RTProcSelf"), (void *)(uintptr_t)RTProcSelf },
370 { STKBACK("RTR0AssertPanicSystem"), (void *)(uintptr_t)RTR0AssertPanicSystem },
371#if defined(RT_OS_DARWIN) || defined(RT_OS_SOLARIS) || defined(RT_OS_WINDOWS)
372 { STKBACK("RTR0DbgKrnlInfoOpen"), (void *)(uintptr_t)RTR0DbgKrnlInfoOpen }, /* only-darwin, only-solaris, only-windows */
373 { STKBACK("RTR0DbgKrnlInfoQueryMember"), (void *)(uintptr_t)RTR0DbgKrnlInfoQueryMember }, /* only-darwin, only-solaris, only-windows */
374# if defined(RT_OS_SOLARIS)
375 { STKBACK("RTR0DbgKrnlInfoQuerySize"), (void *)(uintptr_t)RTR0DbgKrnlInfoQuerySize }, /* only-solaris */
376# endif
377 { STKBACK("RTR0DbgKrnlInfoQuerySymbol"), (void *)(uintptr_t)RTR0DbgKrnlInfoQuerySymbol }, /* only-darwin, only-solaris, only-windows */
378 { STKBACK("RTR0DbgKrnlInfoRelease"), (void *)(uintptr_t)RTR0DbgKrnlInfoRelease }, /* only-darwin, only-solaris, only-windows */
379 { STKBACK("RTR0DbgKrnlInfoRetain"), (void *)(uintptr_t)RTR0DbgKrnlInfoRetain }, /* only-darwin, only-solaris, only-windows */
380#endif
381 { STKBACK("RTR0MemAreKrnlAndUsrDifferent"), (void *)(uintptr_t)RTR0MemAreKrnlAndUsrDifferent },
382 { STKBACK("RTR0MemKernelIsValidAddr"), (void *)(uintptr_t)RTR0MemKernelIsValidAddr },
383 { STKBACK("RTR0MemKernelCopyFrom"), (void *)(uintptr_t)RTR0MemKernelCopyFrom },
384 { STKBACK("RTR0MemKernelCopyTo"), (void *)(uintptr_t)RTR0MemKernelCopyTo },
385 { STKOKAY("RTR0MemObjAddress"), (void *)(uintptr_t)RTR0MemObjAddress },
386 { STKOKAY("RTR0MemObjAddressR3"), (void *)(uintptr_t)RTR0MemObjAddressR3 },
387 { STKBACK("RTR0MemObjAllocContTag"), (void *)(uintptr_t)RTR0MemObjAllocContTag },
388 { STKBACK("RTR0MemObjAllocLargeTag"), (void *)(uintptr_t)RTR0MemObjAllocLargeTag },
389 { STKBACK("RTR0MemObjAllocLowTag"), (void *)(uintptr_t)RTR0MemObjAllocLowTag },
390 { STKBACK("RTR0MemObjAllocPageTag"), (void *)(uintptr_t)RTR0MemObjAllocPageTag },
391 { STKBACK("RTR0MemObjAllocPhysExTag"), (void *)(uintptr_t)RTR0MemObjAllocPhysExTag },
392 { STKBACK("RTR0MemObjAllocPhysNCTag"), (void *)(uintptr_t)RTR0MemObjAllocPhysNCTag },
393 { STKBACK("RTR0MemObjAllocPhysTag"), (void *)(uintptr_t)RTR0MemObjAllocPhysTag },
394 { STKBACK("RTR0MemObjEnterPhysTag"), (void *)(uintptr_t)RTR0MemObjEnterPhysTag },
395 { STKBACK("RTR0MemObjFree"), (void *)(uintptr_t)RTR0MemObjFree },
396 { STKBACK("RTR0MemObjGetPagePhysAddr"), (void *)(uintptr_t)RTR0MemObjGetPagePhysAddr },
397 { STKOKAY("RTR0MemObjIsMapping"), (void *)(uintptr_t)RTR0MemObjIsMapping },
398 { STKBACK("RTR0MemObjLockUserTag"), (void *)(uintptr_t)RTR0MemObjLockUserTag },
399 { STKBACK("RTR0MemObjLockKernelTag"), (void *)(uintptr_t)RTR0MemObjLockKernelTag },
400 { STKBACK("RTR0MemObjMapKernelExTag"), (void *)(uintptr_t)RTR0MemObjMapKernelExTag },
401 { STKBACK("RTR0MemObjMapKernelTag"), (void *)(uintptr_t)RTR0MemObjMapKernelTag },
402 { STKBACK("RTR0MemObjMapUserTag"), (void *)(uintptr_t)RTR0MemObjMapUserTag },
403 { STKBACK("RTR0MemObjMapUserExTag"), (void *)(uintptr_t)RTR0MemObjMapUserExTag },
404 { STKBACK("RTR0MemObjProtect"), (void *)(uintptr_t)RTR0MemObjProtect },
405 { STKOKAY("RTR0MemObjSize"), (void *)(uintptr_t)RTR0MemObjSize },
406 { STKBACK("RTR0MemUserCopyFrom"), (void *)(uintptr_t)RTR0MemUserCopyFrom },
407 { STKBACK("RTR0MemUserCopyTo"), (void *)(uintptr_t)RTR0MemUserCopyTo },
408 { STKBACK("RTR0MemUserIsValidAddr"), (void *)(uintptr_t)RTR0MemUserIsValidAddr },
409 { STKBACK("RTR0ProcHandleSelf"), (void *)(uintptr_t)RTR0ProcHandleSelf },
410 { STKBACK("RTSemEventCreate"), (void *)(uintptr_t)RTSemEventCreate },
411 { STKBACK("RTSemEventDestroy"), (void *)(uintptr_t)RTSemEventDestroy },
412 { STKBACK("RTSemEventGetResolution"), (void *)(uintptr_t)RTSemEventGetResolution },
413 { STKBACK("RTSemEventIsSignalSafe"), (void *)(uintptr_t)RTSemEventIsSignalSafe },
414 { STKBACK("RTSemEventMultiCreate"), (void *)(uintptr_t)RTSemEventMultiCreate },
415 { STKBACK("RTSemEventMultiDestroy"), (void *)(uintptr_t)RTSemEventMultiDestroy },
416 { STKBACK("RTSemEventMultiGetResolution"), (void *)(uintptr_t)RTSemEventMultiGetResolution },
417 { STKBACK("RTSemEventMultiIsSignalSafe"), (void *)(uintptr_t)RTSemEventMultiIsSignalSafe },
418 { STKBACK("RTSemEventMultiReset"), (void *)(uintptr_t)RTSemEventMultiReset },
419 { STKBACK("RTSemEventMultiSignal"), (void *)(uintptr_t)RTSemEventMultiSignal },
420 { STKBACK("RTSemEventMultiWait"), (void *)(uintptr_t)RTSemEventMultiWait },
421 { STKBACK("RTSemEventMultiWaitEx"), (void *)(uintptr_t)RTSemEventMultiWaitEx },
422 { STKBACK("RTSemEventMultiWaitExDebug"), (void *)(uintptr_t)RTSemEventMultiWaitExDebug },
423 { STKBACK("RTSemEventMultiWaitNoResume"), (void *)(uintptr_t)RTSemEventMultiWaitNoResume },
424 { STKBACK("RTSemEventSignal"), (void *)(uintptr_t)RTSemEventSignal },
425 { STKBACK("RTSemEventWait"), (void *)(uintptr_t)RTSemEventWait },
426 { STKBACK("RTSemEventWaitEx"), (void *)(uintptr_t)RTSemEventWaitEx },
427 { STKBACK("RTSemEventWaitExDebug"), (void *)(uintptr_t)RTSemEventWaitExDebug },
428 { STKBACK("RTSemEventWaitNoResume"), (void *)(uintptr_t)RTSemEventWaitNoResume },
429 { STKBACK("RTSemFastMutexCreate"), (void *)(uintptr_t)RTSemFastMutexCreate },
430 { STKBACK("RTSemFastMutexDestroy"), (void *)(uintptr_t)RTSemFastMutexDestroy },
431 { STKBACK("RTSemFastMutexRelease"), (void *)(uintptr_t)RTSemFastMutexRelease },
432 { STKBACK("RTSemFastMutexRequest"), (void *)(uintptr_t)RTSemFastMutexRequest },
433 { STKBACK("RTSemMutexCreate"), (void *)(uintptr_t)RTSemMutexCreate },
434 { STKBACK("RTSemMutexDestroy"), (void *)(uintptr_t)RTSemMutexDestroy },
435 { STKBACK("RTSemMutexRelease"), (void *)(uintptr_t)RTSemMutexRelease },
436 { STKBACK("RTSemMutexRequest"), (void *)(uintptr_t)RTSemMutexRequest },
437 { STKBACK("RTSemMutexRequestDebug"), (void *)(uintptr_t)RTSemMutexRequestDebug },
438 { STKBACK("RTSemMutexRequestNoResume"), (void *)(uintptr_t)RTSemMutexRequestNoResume },
439 { STKBACK("RTSemMutexRequestNoResumeDebug"), (void *)(uintptr_t)RTSemMutexRequestNoResumeDebug },
440 { STKBACK("RTSpinlockAcquire"), (void *)(uintptr_t)RTSpinlockAcquire },
441 { STKBACK("RTSpinlockCreate"), (void *)(uintptr_t)RTSpinlockCreate },
442 { STKBACK("RTSpinlockDestroy"), (void *)(uintptr_t)RTSpinlockDestroy },
443 { STKBACK("RTSpinlockRelease"), (void *)(uintptr_t)RTSpinlockRelease },
444 { STKOKAY("RTStrCopy"), (void *)(uintptr_t)RTStrCopy },
445 { STKBACK("RTStrDupTag"), (void *)(uintptr_t)RTStrDupTag },
446 { STKBACK("RTStrFormat"), (void *)(uintptr_t)RTStrFormat },
447 { STKBACK("RTStrFormatNumber"), (void *)(uintptr_t)RTStrFormatNumber },
448 { STKBACK("RTStrFormatTypeDeregister"), (void *)(uintptr_t)RTStrFormatTypeDeregister },
449 { STKBACK("RTStrFormatTypeRegister"), (void *)(uintptr_t)RTStrFormatTypeRegister },
450 { STKBACK("RTStrFormatTypeSetUser"), (void *)(uintptr_t)RTStrFormatTypeSetUser },
451 { STKBACK("RTStrFormatV"), (void *)(uintptr_t)RTStrFormatV },
452 { STKBACK("RTStrFree"), (void *)(uintptr_t)RTStrFree },
453 { STKOKAY("RTStrNCmp"), (void *)(uintptr_t)RTStrNCmp },
454 { STKBACK("RTStrPrintf"), (void *)(uintptr_t)RTStrPrintf },
455 { STKBACK("RTStrPrintfEx"), (void *)(uintptr_t)RTStrPrintfEx },
456 { STKBACK("RTStrPrintfExV"), (void *)(uintptr_t)RTStrPrintfExV },
457 { STKBACK("RTStrPrintfV"), (void *)(uintptr_t)RTStrPrintfV },
458 { STKBACK("RTThreadCreate"), (void *)(uintptr_t)RTThreadCreate },
459 { STKBACK("RTThreadCtxHookIsEnabled"), (void *)(uintptr_t)RTThreadCtxHookIsEnabled },
460 { STKBACK("RTThreadCtxHookCreate"), (void *)(uintptr_t)RTThreadCtxHookCreate },
461 { STKBACK("RTThreadCtxHookDestroy"), (void *)(uintptr_t)RTThreadCtxHookDestroy },
462 { STKBACK("RTThreadCtxHookDisable"), (void *)(uintptr_t)RTThreadCtxHookDisable },
463 { STKBACK("RTThreadCtxHookEnable"), (void *)(uintptr_t)RTThreadCtxHookEnable },
464 { STKBACK("RTThreadGetName"), (void *)(uintptr_t)RTThreadGetName },
465 { STKBACK("RTThreadGetNative"), (void *)(uintptr_t)RTThreadGetNative },
466 { STKBACK("RTThreadGetType"), (void *)(uintptr_t)RTThreadGetType },
467 { STKBACK("RTThreadIsInInterrupt"), (void *)(uintptr_t)RTThreadIsInInterrupt },
468 { STKBACK("RTThreadNativeSelf"), (void *)(uintptr_t)RTThreadNativeSelf },
469 { STKBACK("RTThreadPreemptDisable"), (void *)(uintptr_t)RTThreadPreemptDisable },
470 { STKBACK("RTThreadPreemptIsEnabled"), (void *)(uintptr_t)RTThreadPreemptIsEnabled },
471 { STKBACK("RTThreadPreemptIsPending"), (void *)(uintptr_t)RTThreadPreemptIsPending },
472 { STKBACK("RTThreadPreemptIsPendingTrusty"), (void *)(uintptr_t)RTThreadPreemptIsPendingTrusty },
473 { STKBACK("RTThreadPreemptIsPossible"), (void *)(uintptr_t)RTThreadPreemptIsPossible },
474 { STKBACK("RTThreadPreemptRestore"), (void *)(uintptr_t)RTThreadPreemptRestore },
475 { STKBACK("RTThreadQueryTerminationStatus"), (void *)(uintptr_t)RTThreadQueryTerminationStatus },
476 { STKBACK("RTThreadSelf"), (void *)(uintptr_t)RTThreadSelf },
477 { STKBACK("RTThreadSelfName"), (void *)(uintptr_t)RTThreadSelfName },
478 { STKBACK("RTThreadSleep"), (void *)(uintptr_t)RTThreadSleep },
479 { STKBACK("RTThreadUserReset"), (void *)(uintptr_t)RTThreadUserReset },
480 { STKBACK("RTThreadUserSignal"), (void *)(uintptr_t)RTThreadUserSignal },
481 { STKBACK("RTThreadUserWait"), (void *)(uintptr_t)RTThreadUserWait },
482 { STKBACK("RTThreadUserWaitNoResume"), (void *)(uintptr_t)RTThreadUserWaitNoResume },
483 { STKBACK("RTThreadWait"), (void *)(uintptr_t)RTThreadWait },
484 { STKBACK("RTThreadWaitNoResume"), (void *)(uintptr_t)RTThreadWaitNoResume },
485 { STKBACK("RTThreadYield"), (void *)(uintptr_t)RTThreadYield },
486 { STKBACK("RTTimeNow"), (void *)(uintptr_t)RTTimeNow },
487 { STKBACK("RTTimerCanDoHighResolution"), (void *)(uintptr_t)RTTimerCanDoHighResolution },
488 { STKBACK("RTTimerChangeInterval"), (void *)(uintptr_t)RTTimerChangeInterval },
489 { STKBACK("RTTimerCreate"), (void *)(uintptr_t)RTTimerCreate },
490 { STKBACK("RTTimerCreateEx"), (void *)(uintptr_t)RTTimerCreateEx },
491 { STKBACK("RTTimerDestroy"), (void *)(uintptr_t)RTTimerDestroy },
492 { STKBACK("RTTimerGetSystemGranularity"), (void *)(uintptr_t)RTTimerGetSystemGranularity },
493 { STKBACK("RTTimerReleaseSystemGranularity"), (void *)(uintptr_t)RTTimerReleaseSystemGranularity },
494 { STKBACK("RTTimerRequestSystemGranularity"), (void *)(uintptr_t)RTTimerRequestSystemGranularity },
495 { STKBACK("RTTimerStart"), (void *)(uintptr_t)RTTimerStart },
496 { STKBACK("RTTimerStop"), (void *)(uintptr_t)RTTimerStop },
497 { STKBACK("RTTimeSystemMilliTS"), (void *)(uintptr_t)RTTimeSystemMilliTS },
498 { STKBACK("RTTimeSystemNanoTS"), (void *)(uintptr_t)RTTimeSystemNanoTS },
499 { STKOKAY("RTUuidCompare"), (void *)(uintptr_t)RTUuidCompare },
500 { STKOKAY("RTUuidCompareStr"), (void *)(uintptr_t)RTUuidCompareStr },
501 { STKOKAY("RTUuidFromStr"), (void *)(uintptr_t)RTUuidFromStr },
502/* SED: END */
503};
504
505#if defined(RT_OS_DARWIN) || defined(RT_OS_SOLARIS) || defined(RT_OS_FREEBSD)
506/**
507 * Drag in the rest of IRPT since we share it with the
508 * rest of the kernel modules on darwin.
509 */
510struct CLANG11WERIDNESS { PFNRT pfn; } g_apfnVBoxDrvIPRTDeps[] =
511{
512 /* VBoxNetAdp */
513 { (PFNRT)RTRandBytes },
514 /* VBoxUSB */
515 { (PFNRT)RTPathStripFilename },
516#if !defined(RT_OS_FREEBSD)
517 { (PFNRT)RTHandleTableAlloc },
518 { (PFNRT)RTStrPurgeEncoding },
519#endif
520 { NULL }
521};
522#endif /* RT_OS_DARWIN || RT_OS_SOLARIS || RT_OS_FREEBSD */
523
524
525
526/**
527 * Initializes the device extentsion structure.
528 *
529 * @returns IPRT status code.
530 * @param pDevExt The device extension to initialize.
531 * @param cbSession The size of the session structure. The size of
532 * SUPDRVSESSION may be smaller when SUPDRV_AGNOSTIC is
533 * defined because we're skipping the OS specific members
534 * then.
535 */
536int VBOXCALL supdrvInitDevExt(PSUPDRVDEVEXT pDevExt, size_t cbSession)
537{
538 int rc;
539
540#ifdef SUPDRV_WITH_RELEASE_LOGGER
541 /*
542 * Create the release log.
543 */
544 static const char * const s_apszGroups[] = VBOX_LOGGROUP_NAMES;
545 PRTLOGGER pRelLogger;
546 rc = RTLogCreate(&pRelLogger, 0 /* fFlags */, "all",
547 "VBOX_RELEASE_LOG", RT_ELEMENTS(s_apszGroups), s_apszGroups, RTLOGDEST_STDOUT | RTLOGDEST_DEBUGGER, NULL);
548 if (RT_SUCCESS(rc))
549 RTLogRelSetDefaultInstance(pRelLogger);
550 /** @todo Add native hook for getting logger config parameters and setting
551 * them. On linux we should use the module parameter stuff... */
552#endif
553
554#if (defined(RT_ARCH_AMD64) || defined(RT_ARCH_X86)) && !defined(VBOX_WITH_OLD_CPU_SUPPORT)
555 /*
556 * Require SSE2 to be present.
557 */
558 if (!(ASMCpuId_EDX(1) & X86_CPUID_FEATURE_EDX_SSE2))
559 {
560 SUPR0Printf("vboxdrv: Requires SSE2 (cpuid(0).EDX=%#x)\n", ASMCpuId_EDX(1));
561 return VERR_UNSUPPORTED_CPU;
562 }
563#endif
564
565 /*
566 * Initialize it.
567 */
568 memset(pDevExt, 0, sizeof(*pDevExt)); /* Does not wipe OS specific tail section of the structure. */
569 pDevExt->Spinlock = NIL_RTSPINLOCK;
570 pDevExt->hGipSpinlock = NIL_RTSPINLOCK;
571 pDevExt->hSessionHashTabSpinlock = NIL_RTSPINLOCK;
572#ifdef SUPDRV_USE_MUTEX_FOR_LDR
573 pDevExt->mtxLdr = NIL_RTSEMMUTEX;
574#else
575 pDevExt->mtxLdr = NIL_RTSEMFASTMUTEX;
576#endif
577#ifdef SUPDRV_USE_MUTEX_FOR_GIP
578 pDevExt->mtxGip = NIL_RTSEMMUTEX;
579 pDevExt->mtxTscDelta = NIL_RTSEMMUTEX;
580#else
581 pDevExt->mtxGip = NIL_RTSEMFASTMUTEX;
582 pDevExt->mtxTscDelta = NIL_RTSEMFASTMUTEX;
583#endif
584
585 rc = RTSpinlockCreate(&pDevExt->Spinlock, RTSPINLOCK_FLAGS_INTERRUPT_SAFE, "SUPDrvDevExt");
586 if (RT_SUCCESS(rc))
587 rc = RTSpinlockCreate(&pDevExt->hGipSpinlock, RTSPINLOCK_FLAGS_INTERRUPT_SAFE, "SUPDrvGip");
588 if (RT_SUCCESS(rc))
589 rc = RTSpinlockCreate(&pDevExt->hSessionHashTabSpinlock, RTSPINLOCK_FLAGS_INTERRUPT_SAFE, "SUPDrvSession");
590
591 if (RT_SUCCESS(rc))
592#ifdef SUPDRV_USE_MUTEX_FOR_LDR
593 rc = RTSemMutexCreate(&pDevExt->mtxLdr);
594#else
595 rc = RTSemFastMutexCreate(&pDevExt->mtxLdr);
596#endif
597 if (RT_SUCCESS(rc))
598#ifdef SUPDRV_USE_MUTEX_FOR_GIP
599 rc = RTSemMutexCreate(&pDevExt->mtxTscDelta);
600#else
601 rc = RTSemFastMutexCreate(&pDevExt->mtxTscDelta);
602#endif
603 if (RT_SUCCESS(rc))
604 {
605 rc = RTSemFastMutexCreate(&pDevExt->mtxComponentFactory);
606 if (RT_SUCCESS(rc))
607 {
608#ifdef SUPDRV_USE_MUTEX_FOR_GIP
609 rc = RTSemMutexCreate(&pDevExt->mtxGip);
610#else
611 rc = RTSemFastMutexCreate(&pDevExt->mtxGip);
612#endif
613 if (RT_SUCCESS(rc))
614 {
615 rc = supdrvGipCreate(pDevExt);
616 if (RT_SUCCESS(rc))
617 {
618 rc = supdrvTracerInit(pDevExt);
619 if (RT_SUCCESS(rc))
620 {
621 pDevExt->pLdrInitImage = NULL;
622 pDevExt->hLdrInitThread = NIL_RTNATIVETHREAD;
623 pDevExt->hLdrTermThread = NIL_RTNATIVETHREAD;
624 pDevExt->u32Cookie = BIRD; /** @todo make this random? */
625 pDevExt->cbSession = (uint32_t)cbSession;
626
627 /*
628 * Fixup the absolute symbols.
629 *
630 * Because of the table indexing assumptions we'll have a little #ifdef orgy
631 * here rather than distributing this to OS specific files. At least for now.
632 */
633#ifdef RT_OS_DARWIN
634# if ARCH_BITS == 32
635 if (SUPR0GetPagingMode() >= SUPPAGINGMODE_AMD64)
636 {
637 g_aFunctions[0].pfn = (void *)1; /* SUPR0AbsIs64bit */
638 g_aFunctions[1].pfn = (void *)0x80; /* SUPR0Abs64bitKernelCS - KERNEL64_CS, seg.h */
639 g_aFunctions[2].pfn = (void *)0x88; /* SUPR0Abs64bitKernelSS - KERNEL64_SS, seg.h */
640 g_aFunctions[3].pfn = (void *)0x88; /* SUPR0Abs64bitKernelDS - KERNEL64_SS, seg.h */
641 }
642 else
643 g_aFunctions[0].pfn = g_aFunctions[1].pfn = g_aFunctions[2].pfn = g_aFunctions[3].pfn = (void *)0;
644 g_aFunctions[4].pfn = (void *)0x08; /* SUPR0AbsKernelCS - KERNEL_CS, seg.h */
645 g_aFunctions[5].pfn = (void *)0x10; /* SUPR0AbsKernelSS - KERNEL_DS, seg.h */
646 g_aFunctions[6].pfn = (void *)0x10; /* SUPR0AbsKernelDS - KERNEL_DS, seg.h */
647 g_aFunctions[7].pfn = (void *)0x10; /* SUPR0AbsKernelES - KERNEL_DS, seg.h */
648 g_aFunctions[8].pfn = (void *)0x10; /* SUPR0AbsKernelFS - KERNEL_DS, seg.h */
649 g_aFunctions[9].pfn = (void *)0x48; /* SUPR0AbsKernelGS - CPU_DATA_GS, seg.h */
650# else /* 64-bit darwin: */
651 g_aFunctions[0].pfn = (void *)1; /* SUPR0AbsIs64bit */
652 g_aFunctions[1].pfn = (void *)(uintptr_t)ASMGetCS(); /* SUPR0Abs64bitKernelCS */
653 g_aFunctions[2].pfn = (void *)(uintptr_t)ASMGetSS(); /* SUPR0Abs64bitKernelSS */
654 g_aFunctions[3].pfn = (void *)0; /* SUPR0Abs64bitKernelDS */
655 g_aFunctions[4].pfn = (void *)(uintptr_t)ASMGetCS(); /* SUPR0AbsKernelCS */
656 g_aFunctions[5].pfn = (void *)(uintptr_t)ASMGetSS(); /* SUPR0AbsKernelSS */
657 g_aFunctions[6].pfn = (void *)0; /* SUPR0AbsKernelDS */
658 g_aFunctions[7].pfn = (void *)0; /* SUPR0AbsKernelES */
659 g_aFunctions[8].pfn = (void *)0; /* SUPR0AbsKernelFS */
660 g_aFunctions[9].pfn = (void *)0; /* SUPR0AbsKernelGS */
661
662# endif
663#else /* !RT_OS_DARWIN */
664# if ARCH_BITS == 64
665 g_aFunctions[0].pfn = (void *)1; /* SUPR0AbsIs64bit */
666 g_aFunctions[1].pfn = (void *)(uintptr_t)ASMGetCS(); /* SUPR0Abs64bitKernelCS */
667 g_aFunctions[2].pfn = (void *)(uintptr_t)ASMGetSS(); /* SUPR0Abs64bitKernelSS */
668 g_aFunctions[3].pfn = (void *)(uintptr_t)ASMGetDS(); /* SUPR0Abs64bitKernelDS */
669# else
670 g_aFunctions[0].pfn = g_aFunctions[1].pfn = g_aFunctions[2].pfn = g_aFunctions[3].pfn = (void *)0;
671# endif
672 g_aFunctions[4].pfn = (void *)(uintptr_t)ASMGetCS(); /* SUPR0AbsKernelCS */
673 g_aFunctions[5].pfn = (void *)(uintptr_t)ASMGetSS(); /* SUPR0AbsKernelSS */
674 g_aFunctions[6].pfn = (void *)(uintptr_t)ASMGetDS(); /* SUPR0AbsKernelDS */
675 g_aFunctions[7].pfn = (void *)(uintptr_t)ASMGetES(); /* SUPR0AbsKernelES */
676 g_aFunctions[8].pfn = (void *)(uintptr_t)ASMGetFS(); /* SUPR0AbsKernelFS */
677 g_aFunctions[9].pfn = (void *)(uintptr_t)ASMGetGS(); /* SUPR0AbsKernelGS */
678#endif /* !RT_OS_DARWIN */
679 return VINF_SUCCESS;
680 }
681
682 supdrvGipDestroy(pDevExt);
683 }
684
685#ifdef SUPDRV_USE_MUTEX_FOR_GIP
686 RTSemMutexDestroy(pDevExt->mtxGip);
687 pDevExt->mtxGip = NIL_RTSEMMUTEX;
688#else
689 RTSemFastMutexDestroy(pDevExt->mtxGip);
690 pDevExt->mtxGip = NIL_RTSEMFASTMUTEX;
691#endif
692 }
693 RTSemFastMutexDestroy(pDevExt->mtxComponentFactory);
694 pDevExt->mtxComponentFactory = NIL_RTSEMFASTMUTEX;
695 }
696 }
697
698#ifdef SUPDRV_USE_MUTEX_FOR_GIP
699 RTSemMutexDestroy(pDevExt->mtxTscDelta);
700 pDevExt->mtxTscDelta = NIL_RTSEMMUTEX;
701#else
702 RTSemFastMutexDestroy(pDevExt->mtxTscDelta);
703 pDevExt->mtxTscDelta = NIL_RTSEMFASTMUTEX;
704#endif
705#ifdef SUPDRV_USE_MUTEX_FOR_LDR
706 RTSemMutexDestroy(pDevExt->mtxLdr);
707 pDevExt->mtxLdr = NIL_RTSEMMUTEX;
708#else
709 RTSemFastMutexDestroy(pDevExt->mtxLdr);
710 pDevExt->mtxLdr = NIL_RTSEMFASTMUTEX;
711#endif
712 RTSpinlockDestroy(pDevExt->Spinlock);
713 pDevExt->Spinlock = NIL_RTSPINLOCK;
714 RTSpinlockDestroy(pDevExt->hGipSpinlock);
715 pDevExt->hGipSpinlock = NIL_RTSPINLOCK;
716 RTSpinlockDestroy(pDevExt->hSessionHashTabSpinlock);
717 pDevExt->hSessionHashTabSpinlock = NIL_RTSPINLOCK;
718
719#ifdef SUPDRV_WITH_RELEASE_LOGGER
720 RTLogDestroy(RTLogRelSetDefaultInstance(NULL));
721 RTLogDestroy(RTLogSetDefaultInstance(NULL));
722#endif
723
724 return rc;
725}
726
727
728/**
729 * Delete the device extension (e.g. cleanup members).
730 *
731 * @param pDevExt The device extension to delete.
732 */
733void VBOXCALL supdrvDeleteDevExt(PSUPDRVDEVEXT pDevExt)
734{
735 PSUPDRVOBJ pObj;
736 PSUPDRVUSAGE pUsage;
737
738 /*
739 * Kill mutexes and spinlocks.
740 */
741#ifdef SUPDRV_USE_MUTEX_FOR_GIP
742 RTSemMutexDestroy(pDevExt->mtxGip);
743 pDevExt->mtxGip = NIL_RTSEMMUTEX;
744 RTSemMutexDestroy(pDevExt->mtxTscDelta);
745 pDevExt->mtxTscDelta = NIL_RTSEMMUTEX;
746#else
747 RTSemFastMutexDestroy(pDevExt->mtxGip);
748 pDevExt->mtxGip = NIL_RTSEMFASTMUTEX;
749 RTSemFastMutexDestroy(pDevExt->mtxTscDelta);
750 pDevExt->mtxTscDelta = NIL_RTSEMFASTMUTEX;
751#endif
752#ifdef SUPDRV_USE_MUTEX_FOR_LDR
753 RTSemMutexDestroy(pDevExt->mtxLdr);
754 pDevExt->mtxLdr = NIL_RTSEMMUTEX;
755#else
756 RTSemFastMutexDestroy(pDevExt->mtxLdr);
757 pDevExt->mtxLdr = NIL_RTSEMFASTMUTEX;
758#endif
759 RTSpinlockDestroy(pDevExt->Spinlock);
760 pDevExt->Spinlock = NIL_RTSPINLOCK;
761 RTSemFastMutexDestroy(pDevExt->mtxComponentFactory);
762 pDevExt->mtxComponentFactory = NIL_RTSEMFASTMUTEX;
763 RTSpinlockDestroy(pDevExt->hSessionHashTabSpinlock);
764 pDevExt->hSessionHashTabSpinlock = NIL_RTSPINLOCK;
765
766 /*
767 * Free lists.
768 */
769 /* objects. */
770 pObj = pDevExt->pObjs;
771 Assert(!pObj); /* (can trigger on forced unloads) */
772 pDevExt->pObjs = NULL;
773 while (pObj)
774 {
775 void *pvFree = pObj;
776 pObj = pObj->pNext;
777 RTMemFree(pvFree);
778 }
779
780 /* usage records. */
781 pUsage = pDevExt->pUsageFree;
782 pDevExt->pUsageFree = NULL;
783 while (pUsage)
784 {
785 void *pvFree = pUsage;
786 pUsage = pUsage->pNext;
787 RTMemFree(pvFree);
788 }
789
790 /* kill the GIP. */
791 supdrvGipDestroy(pDevExt);
792 RTSpinlockDestroy(pDevExt->hGipSpinlock);
793 pDevExt->hGipSpinlock = NIL_RTSPINLOCK;
794
795 supdrvTracerTerm(pDevExt);
796
797#ifdef SUPDRV_WITH_RELEASE_LOGGER
798 /* destroy the loggers. */
799 RTLogDestroy(RTLogRelSetDefaultInstance(NULL));
800 RTLogDestroy(RTLogSetDefaultInstance(NULL));
801#endif
802}
803
804
805/**
806 * Create session.
807 *
808 * @returns IPRT status code.
809 * @param pDevExt Device extension.
810 * @param fUser Flag indicating whether this is a user or kernel
811 * session.
812 * @param fUnrestricted Unrestricted access (system) or restricted access
813 * (user)?
814 * @param ppSession Where to store the pointer to the session data.
815 */
816int VBOXCALL supdrvCreateSession(PSUPDRVDEVEXT pDevExt, bool fUser, bool fUnrestricted, PSUPDRVSESSION *ppSession)
817{
818 int rc;
819 PSUPDRVSESSION pSession;
820
821 if (!SUP_IS_DEVEXT_VALID(pDevExt))
822 return VERR_INVALID_PARAMETER;
823
824 /*
825 * Allocate memory for the session data.
826 */
827 pSession = *ppSession = (PSUPDRVSESSION)RTMemAllocZ(pDevExt->cbSession);
828 if (pSession)
829 {
830 /* Initialize session data. */
831 rc = RTSpinlockCreate(&pSession->Spinlock, RTSPINLOCK_FLAGS_INTERRUPT_UNSAFE, "SUPDrvSession");
832 if (!rc)
833 {
834 rc = RTHandleTableCreateEx(&pSession->hHandleTable,
835 RTHANDLETABLE_FLAGS_LOCKED_IRQ_SAFE | RTHANDLETABLE_FLAGS_CONTEXT,
836 1 /*uBase*/, 32768 /*cMax*/, supdrvSessionObjHandleRetain, pSession);
837 if (RT_SUCCESS(rc))
838 {
839 Assert(pSession->Spinlock != NIL_RTSPINLOCK);
840 pSession->pDevExt = pDevExt;
841 pSession->u32Cookie = BIRD_INV;
842 pSession->fUnrestricted = fUnrestricted;
843 /*pSession->fInHashTable = false; */
844 pSession->cRefs = 1;
845 /*pSession->pCommonNextHash = NULL;
846 pSession->ppOsSessionPtr = NULL; */
847 if (fUser)
848 {
849 pSession->Process = RTProcSelf();
850 pSession->R0Process = RTR0ProcHandleSelf();
851 }
852 else
853 {
854 pSession->Process = NIL_RTPROCESS;
855 pSession->R0Process = NIL_RTR0PROCESS;
856 }
857 /*pSession->pLdrUsage = NULL;
858 pSession->pVM = NULL;
859 pSession->pUsage = NULL;
860 pSession->pGip = NULL;
861 pSession->fGipReferenced = false;
862 pSession->Bundle.cUsed = 0; */
863 pSession->Uid = NIL_RTUID;
864 pSession->Gid = NIL_RTGID;
865 /*pSession->uTracerData = 0;*/
866 pSession->hTracerCaller = NIL_RTNATIVETHREAD;
867 RTListInit(&pSession->TpProviders);
868 /*pSession->cTpProviders = 0;*/
869 /*pSession->cTpProbesFiring = 0;*/
870 RTListInit(&pSession->TpUmods);
871 /*RT_ZERO(pSession->apTpLookupTable);*/
872
873 VBOXDRV_SESSION_CREATE(pSession, fUser);
874 LogFlow(("Created session %p initial cookie=%#x\n", pSession, pSession->u32Cookie));
875 return VINF_SUCCESS;
876 }
877
878 RTSpinlockDestroy(pSession->Spinlock);
879 }
880 RTMemFree(pSession);
881 *ppSession = NULL;
882 Log(("Failed to create spinlock, rc=%d!\n", rc));
883 }
884 else
885 rc = VERR_NO_MEMORY;
886
887 return rc;
888}
889
890
891/**
892 * Cleans up the session in the context of the process to which it belongs, the
893 * caller will free the session and the session spinlock.
894 *
895 * This should normally occur when the session is closed or as the process
896 * exits. Careful reference counting in the OS specfic code makes sure that
897 * there cannot be any races between process/handle cleanup callbacks and
898 * threads doing I/O control calls.
899 *
900 * @param pDevExt The device extension.
901 * @param pSession Session data.
902 */
903static void supdrvCleanupSession(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession)
904{
905 int rc;
906 PSUPDRVBUNDLE pBundle;
907 LogFlow(("supdrvCleanupSession: pSession=%p\n", pSession));
908
909 Assert(!pSession->fInHashTable);
910 Assert(!pSession->ppOsSessionPtr);
911 AssertLogRelMsg(pSession->R0Process == RTR0ProcHandleSelf() || pSession->R0Process == NIL_RTR0PROCESS,
912 ("R0Process=%p cur=%p; curpid=%u\n",
913 pSession->R0Process, RTR0ProcHandleSelf(), RTProcSelf()));
914
915 /*
916 * Remove logger instances related to this session.
917 */
918 RTLogSetDefaultInstanceThread(NULL, (uintptr_t)pSession);
919
920 /*
921 * Destroy the handle table.
922 */
923 rc = RTHandleTableDestroy(pSession->hHandleTable, supdrvSessionObjHandleDelete, pSession);
924 AssertRC(rc);
925 pSession->hHandleTable = NIL_RTHANDLETABLE;
926
927 /*
928 * Release object references made in this session.
929 * In theory there should be noone racing us in this session.
930 */
931 Log2(("release objects - start\n"));
932 if (pSession->pUsage)
933 {
934 PSUPDRVUSAGE pUsage;
935 RTSpinlockAcquire(pDevExt->Spinlock);
936
937 while ((pUsage = pSession->pUsage) != NULL)
938 {
939 PSUPDRVOBJ pObj = pUsage->pObj;
940 pSession->pUsage = pUsage->pNext;
941
942 AssertMsg(pUsage->cUsage >= 1 && pObj->cUsage >= pUsage->cUsage, ("glob %d; sess %d\n", pObj->cUsage, pUsage->cUsage));
943 if (pUsage->cUsage < pObj->cUsage)
944 {
945 pObj->cUsage -= pUsage->cUsage;
946 RTSpinlockRelease(pDevExt->Spinlock);
947 }
948 else
949 {
950 /* Destroy the object and free the record. */
951 if (pDevExt->pObjs == pObj)
952 pDevExt->pObjs = pObj->pNext;
953 else
954 {
955 PSUPDRVOBJ pObjPrev;
956 for (pObjPrev = pDevExt->pObjs; pObjPrev; pObjPrev = pObjPrev->pNext)
957 if (pObjPrev->pNext == pObj)
958 {
959 pObjPrev->pNext = pObj->pNext;
960 break;
961 }
962 Assert(pObjPrev);
963 }
964 RTSpinlockRelease(pDevExt->Spinlock);
965
966 Log(("supdrvCleanupSession: destroying %p/%d (%p/%p) cpid=%RTproc pid=%RTproc dtor=%p\n",
967 pObj, pObj->enmType, pObj->pvUser1, pObj->pvUser2, pObj->CreatorProcess, RTProcSelf(), pObj->pfnDestructor));
968 if (pObj->pfnDestructor)
969 pObj->pfnDestructor(pObj, pObj->pvUser1, pObj->pvUser2);
970 RTMemFree(pObj);
971 }
972
973 /* free it and continue. */
974 RTMemFree(pUsage);
975
976 RTSpinlockAcquire(pDevExt->Spinlock);
977 }
978
979 RTSpinlockRelease(pDevExt->Spinlock);
980 AssertMsg(!pSession->pUsage, ("Some buster reregistered an object during desturction!\n"));
981 }
982 Log2(("release objects - done\n"));
983
984 /*
985 * Make sure the associated VM pointers are NULL.
986 */
987 if (pSession->pSessionGVM || pSession->pSessionVM || pSession->pFastIoCtrlVM)
988 {
989 SUPR0Printf("supdrvCleanupSession: VM not disassociated! pSessionGVM=%p pSessionVM=%p pFastIoCtrlVM=%p\n",
990 pSession->pSessionGVM, pSession->pSessionVM, pSession->pFastIoCtrlVM);
991 pSession->pSessionGVM = NULL;
992 pSession->pSessionVM = NULL;
993 pSession->pFastIoCtrlVM = NULL;
994 }
995
996 /*
997 * Do tracer cleanups related to this session.
998 */
999 Log2(("release tracer stuff - start\n"));
1000 supdrvTracerCleanupSession(pDevExt, pSession);
1001 Log2(("release tracer stuff - end\n"));
1002
1003 /*
1004 * Release memory allocated in the session.
1005 *
1006 * We do not serialize this as we assume that the application will
1007 * not allocated memory while closing the file handle object.
1008 */
1009 Log2(("freeing memory:\n"));
1010 pBundle = &pSession->Bundle;
1011 while (pBundle)
1012 {
1013 PSUPDRVBUNDLE pToFree;
1014 unsigned i;
1015
1016 /*
1017 * Check and unlock all entries in the bundle.
1018 */
1019 for (i = 0; i < RT_ELEMENTS(pBundle->aMem); i++)
1020 {
1021 if (pBundle->aMem[i].MemObj != NIL_RTR0MEMOBJ)
1022 {
1023 Log2(("eType=%d pvR0=%p pvR3=%p cb=%ld\n", pBundle->aMem[i].eType, RTR0MemObjAddress(pBundle->aMem[i].MemObj),
1024 (void *)RTR0MemObjAddressR3(pBundle->aMem[i].MapObjR3), (long)RTR0MemObjSize(pBundle->aMem[i].MemObj)));
1025 if (pBundle->aMem[i].MapObjR3 != NIL_RTR0MEMOBJ)
1026 {
1027 rc = RTR0MemObjFree(pBundle->aMem[i].MapObjR3, false);
1028 AssertRC(rc); /** @todo figure out how to handle this. */
1029 pBundle->aMem[i].MapObjR3 = NIL_RTR0MEMOBJ;
1030 }
1031 rc = RTR0MemObjFree(pBundle->aMem[i].MemObj, true /* fFreeMappings */);
1032 AssertRC(rc); /** @todo figure out how to handle this. */
1033 pBundle->aMem[i].MemObj = NIL_RTR0MEMOBJ;
1034 pBundle->aMem[i].eType = MEMREF_TYPE_UNUSED;
1035 }
1036 }
1037
1038 /*
1039 * Advance and free previous bundle.
1040 */
1041 pToFree = pBundle;
1042 pBundle = pBundle->pNext;
1043
1044 pToFree->pNext = NULL;
1045 pToFree->cUsed = 0;
1046 if (pToFree != &pSession->Bundle)
1047 RTMemFree(pToFree);
1048 }
1049 Log2(("freeing memory - done\n"));
1050
1051 /*
1052 * Deregister component factories.
1053 */
1054 RTSemFastMutexRequest(pDevExt->mtxComponentFactory);
1055 Log2(("deregistering component factories:\n"));
1056 if (pDevExt->pComponentFactoryHead)
1057 {
1058 PSUPDRVFACTORYREG pPrev = NULL;
1059 PSUPDRVFACTORYREG pCur = pDevExt->pComponentFactoryHead;
1060 while (pCur)
1061 {
1062 if (pCur->pSession == pSession)
1063 {
1064 /* unlink it */
1065 PSUPDRVFACTORYREG pNext = pCur->pNext;
1066 if (pPrev)
1067 pPrev->pNext = pNext;
1068 else
1069 pDevExt->pComponentFactoryHead = pNext;
1070
1071 /* free it */
1072 pCur->pNext = NULL;
1073 pCur->pSession = NULL;
1074 pCur->pFactory = NULL;
1075 RTMemFree(pCur);
1076
1077 /* next */
1078 pCur = pNext;
1079 }
1080 else
1081 {
1082 /* next */
1083 pPrev = pCur;
1084 pCur = pCur->pNext;
1085 }
1086 }
1087 }
1088 RTSemFastMutexRelease(pDevExt->mtxComponentFactory);
1089 Log2(("deregistering component factories - done\n"));
1090
1091 /*
1092 * Loaded images needs to be dereferenced and possibly freed up.
1093 */
1094 supdrvLdrLock(pDevExt);
1095 Log2(("freeing images:\n"));
1096 if (pSession->pLdrUsage)
1097 {
1098 PSUPDRVLDRUSAGE pUsage = pSession->pLdrUsage;
1099 pSession->pLdrUsage = NULL;
1100 while (pUsage)
1101 {
1102 void *pvFree = pUsage;
1103 PSUPDRVLDRIMAGE pImage = pUsage->pImage;
1104 uint32_t cUsage = pUsage->cRing0Usage + pUsage->cRing3Usage;
1105 if (pImage->cImgUsage > cUsage)
1106 supdrvLdrSubtractUsage(pDevExt, pImage, cUsage);
1107 else
1108 supdrvLdrFree(pDevExt, pImage);
1109 pUsage->pImage = NULL;
1110 pUsage = pUsage->pNext;
1111 RTMemFree(pvFree);
1112 }
1113 }
1114 supdrvLdrUnlock(pDevExt);
1115 Log2(("freeing images - done\n"));
1116
1117 /*
1118 * Unmap the GIP.
1119 */
1120 Log2(("umapping GIP:\n"));
1121 if (pSession->GipMapObjR3 != NIL_RTR0MEMOBJ)
1122 {
1123 SUPR0GipUnmap(pSession);
1124 pSession->fGipReferenced = 0;
1125 }
1126 Log2(("umapping GIP - done\n"));
1127}
1128
1129
1130/**
1131 * Common code for freeing a session when the reference count reaches zero.
1132 *
1133 * @param pDevExt Device extension.
1134 * @param pSession Session data.
1135 * This data will be freed by this routine.
1136 */
1137static void supdrvDestroySession(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession)
1138{
1139 VBOXDRV_SESSION_CLOSE(pSession);
1140
1141 /*
1142 * Cleanup the session first.
1143 */
1144 supdrvCleanupSession(pDevExt, pSession);
1145 supdrvOSCleanupSession(pDevExt, pSession);
1146
1147 /*
1148 * Free the rest of the session stuff.
1149 */
1150 RTSpinlockDestroy(pSession->Spinlock);
1151 pSession->Spinlock = NIL_RTSPINLOCK;
1152 pSession->pDevExt = NULL;
1153 RTMemFree(pSession);
1154 LogFlow(("supdrvDestroySession: returns\n"));
1155}
1156
1157
1158/**
1159 * Inserts the session into the global hash table.
1160 *
1161 * @retval VINF_SUCCESS on success.
1162 * @retval VERR_WRONG_ORDER if the session was already inserted (asserted).
1163 * @retval VERR_INVALID_PARAMETER if the session handle is invalid or a ring-0
1164 * session (asserted).
1165 * @retval VERR_DUPLICATE if there is already a session for that pid.
1166 *
1167 * @param pDevExt The device extension.
1168 * @param pSession The session.
1169 * @param ppOsSessionPtr Pointer to the OS session pointer, if any is
1170 * available and used. This will set to point to the
1171 * session while under the protection of the session
1172 * hash table spinlock. It will also be kept in
1173 * PSUPDRVSESSION::ppOsSessionPtr for lookup and
1174 * cleanup use.
1175 * @param pvUser Argument for supdrvOSSessionHashTabInserted.
1176 */
1177int VBOXCALL supdrvSessionHashTabInsert(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPDRVSESSION *ppOsSessionPtr,
1178 void *pvUser)
1179{
1180 PSUPDRVSESSION pCur;
1181 unsigned iHash;
1182
1183 /*
1184 * Validate input.
1185 */
1186 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
1187 AssertReturn(pSession->R0Process != NIL_RTR0PROCESS, VERR_INVALID_PARAMETER);
1188
1189 /*
1190 * Calculate the hash table index and acquire the spinlock.
1191 */
1192 iHash = SUPDRV_SESSION_HASH(pSession->Process);
1193
1194 RTSpinlockAcquire(pDevExt->hSessionHashTabSpinlock);
1195
1196 /*
1197 * If there are a collisions, we need to carefully check if we got a
1198 * duplicate. There can only be one open session per process.
1199 */
1200 pCur = pDevExt->apSessionHashTab[iHash];
1201 if (pCur)
1202 {
1203 while (pCur && pCur->Process != pSession->Process)
1204 pCur = pCur->pCommonNextHash;
1205
1206 if (pCur)
1207 {
1208 RTSpinlockRelease(pDevExt->hSessionHashTabSpinlock);
1209 if (pCur == pSession)
1210 {
1211 Assert(pSession->fInHashTable);
1212 AssertFailed();
1213 return VERR_WRONG_ORDER;
1214 }
1215 Assert(!pSession->fInHashTable);
1216 if (pCur->R0Process == pSession->R0Process)
1217 return VERR_RESOURCE_IN_USE;
1218 return VERR_DUPLICATE;
1219 }
1220 }
1221 Assert(!pSession->fInHashTable);
1222 Assert(!pSession->ppOsSessionPtr);
1223
1224 /*
1225 * Insert it, doing a callout to the OS specific code in case it has
1226 * anything it wishes to do while we're holding the spinlock.
1227 */
1228 pSession->pCommonNextHash = pDevExt->apSessionHashTab[iHash];
1229 pDevExt->apSessionHashTab[iHash] = pSession;
1230 pSession->fInHashTable = true;
1231 ASMAtomicIncS32(&pDevExt->cSessions);
1232
1233 pSession->ppOsSessionPtr = ppOsSessionPtr;
1234 if (ppOsSessionPtr)
1235 ASMAtomicWritePtr(ppOsSessionPtr, pSession);
1236
1237 supdrvOSSessionHashTabInserted(pDevExt, pSession, pvUser);
1238
1239 /*
1240 * Retain a reference for the pointer in the session table.
1241 */
1242 ASMAtomicIncU32(&pSession->cRefs);
1243
1244 RTSpinlockRelease(pDevExt->hSessionHashTabSpinlock);
1245 return VINF_SUCCESS;
1246}
1247
1248
1249/**
1250 * Removes the session from the global hash table.
1251 *
1252 * @retval VINF_SUCCESS on success.
1253 * @retval VERR_NOT_FOUND if the session was already removed (asserted).
1254 * @retval VERR_INVALID_PARAMETER if the session handle is invalid or a ring-0
1255 * session (asserted).
1256 *
1257 * @param pDevExt The device extension.
1258 * @param pSession The session. The caller is expected to have a reference
1259 * to this so it won't croak on us when we release the hash
1260 * table reference.
1261 * @param pvUser OS specific context value for the
1262 * supdrvOSSessionHashTabInserted callback.
1263 */
1264int VBOXCALL supdrvSessionHashTabRemove(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, void *pvUser)
1265{
1266 PSUPDRVSESSION pCur;
1267 unsigned iHash;
1268 int32_t cRefs;
1269
1270 /*
1271 * Validate input.
1272 */
1273 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
1274 AssertReturn(pSession->R0Process != NIL_RTR0PROCESS, VERR_INVALID_PARAMETER);
1275
1276 /*
1277 * Calculate the hash table index and acquire the spinlock.
1278 */
1279 iHash = SUPDRV_SESSION_HASH(pSession->Process);
1280
1281 RTSpinlockAcquire(pDevExt->hSessionHashTabSpinlock);
1282
1283 /*
1284 * Unlink it.
1285 */
1286 pCur = pDevExt->apSessionHashTab[iHash];
1287 if (pCur == pSession)
1288 pDevExt->apSessionHashTab[iHash] = pSession->pCommonNextHash;
1289 else
1290 {
1291 PSUPDRVSESSION pPrev = pCur;
1292 while (pCur && pCur != pSession)
1293 {
1294 pPrev = pCur;
1295 pCur = pCur->pCommonNextHash;
1296 }
1297 if (pCur)
1298 pPrev->pCommonNextHash = pCur->pCommonNextHash;
1299 else
1300 {
1301 Assert(!pSession->fInHashTable);
1302 RTSpinlockRelease(pDevExt->hSessionHashTabSpinlock);
1303 return VERR_NOT_FOUND;
1304 }
1305 }
1306
1307 pSession->pCommonNextHash = NULL;
1308 pSession->fInHashTable = false;
1309
1310 ASMAtomicDecS32(&pDevExt->cSessions);
1311
1312 /*
1313 * Clear OS specific session pointer if available and do the OS callback.
1314 */
1315 if (pSession->ppOsSessionPtr)
1316 {
1317 ASMAtomicCmpXchgPtr(pSession->ppOsSessionPtr, NULL, pSession);
1318 pSession->ppOsSessionPtr = NULL;
1319 }
1320
1321 supdrvOSSessionHashTabRemoved(pDevExt, pSession, pvUser);
1322
1323 RTSpinlockRelease(pDevExt->hSessionHashTabSpinlock);
1324
1325 /*
1326 * Drop the reference the hash table had to the session. This shouldn't
1327 * be the last reference!
1328 */
1329 cRefs = ASMAtomicDecU32(&pSession->cRefs);
1330 Assert(cRefs > 0 && cRefs < _1M);
1331 if (cRefs == 0)
1332 supdrvDestroySession(pDevExt, pSession);
1333
1334 return VINF_SUCCESS;
1335}
1336
1337
1338/**
1339 * Looks up the session for the current process in the global hash table or in
1340 * OS specific pointer.
1341 *
1342 * @returns Pointer to the session with a reference that the caller must
1343 * release. If no valid session was found, NULL is returned.
1344 *
1345 * @param pDevExt The device extension.
1346 * @param Process The process ID.
1347 * @param R0Process The ring-0 process handle.
1348 * @param ppOsSessionPtr The OS session pointer if available. If not NULL,
1349 * this is used instead of the hash table. For
1350 * additional safety it must then be equal to the
1351 * SUPDRVSESSION::ppOsSessionPtr member.
1352 * This can be NULL even if the OS has a session
1353 * pointer.
1354 */
1355PSUPDRVSESSION VBOXCALL supdrvSessionHashTabLookup(PSUPDRVDEVEXT pDevExt, RTPROCESS Process, RTR0PROCESS R0Process,
1356 PSUPDRVSESSION *ppOsSessionPtr)
1357{
1358 PSUPDRVSESSION pCur;
1359 unsigned iHash;
1360
1361 /*
1362 * Validate input.
1363 */
1364 AssertReturn(R0Process != NIL_RTR0PROCESS, NULL);
1365
1366 /*
1367 * Calculate the hash table index and acquire the spinlock.
1368 */
1369 iHash = SUPDRV_SESSION_HASH(Process);
1370
1371 RTSpinlockAcquire(pDevExt->hSessionHashTabSpinlock);
1372
1373 /*
1374 * If an OS session pointer is provided, always use it.
1375 */
1376 if (ppOsSessionPtr)
1377 {
1378 pCur = *ppOsSessionPtr;
1379 if ( pCur
1380 && ( pCur->ppOsSessionPtr != ppOsSessionPtr
1381 || pCur->Process != Process
1382 || pCur->R0Process != R0Process) )
1383 pCur = NULL;
1384 }
1385 else
1386 {
1387 /*
1388 * Otherwise, do the hash table lookup.
1389 */
1390 pCur = pDevExt->apSessionHashTab[iHash];
1391 while ( pCur
1392 && ( pCur->Process != Process
1393 || pCur->R0Process != R0Process) )
1394 pCur = pCur->pCommonNextHash;
1395 }
1396
1397 /*
1398 * Retain the session.
1399 */
1400 if (pCur)
1401 {
1402 uint32_t cRefs = ASMAtomicIncU32(&pCur->cRefs);
1403 NOREF(cRefs);
1404 Assert(cRefs > 1 && cRefs < _1M);
1405 }
1406
1407 RTSpinlockRelease(pDevExt->hSessionHashTabSpinlock);
1408
1409 return pCur;
1410}
1411
1412
1413/**
1414 * Retain a session to make sure it doesn't go away while it is in use.
1415 *
1416 * @returns New reference count on success, UINT32_MAX on failure.
1417 * @param pSession Session data.
1418 */
1419uint32_t VBOXCALL supdrvSessionRetain(PSUPDRVSESSION pSession)
1420{
1421 uint32_t cRefs;
1422 AssertPtrReturn(pSession, UINT32_MAX);
1423 AssertReturn(SUP_IS_SESSION_VALID(pSession), UINT32_MAX);
1424
1425 cRefs = ASMAtomicIncU32(&pSession->cRefs);
1426 AssertMsg(cRefs > 1 && cRefs < _1M, ("%#x %p\n", cRefs, pSession));
1427 return cRefs;
1428}
1429
1430
1431/**
1432 * Releases a given session.
1433 *
1434 * @returns New reference count on success (0 if closed), UINT32_MAX on failure.
1435 * @param pSession Session data.
1436 */
1437uint32_t VBOXCALL supdrvSessionRelease(PSUPDRVSESSION pSession)
1438{
1439 uint32_t cRefs;
1440 AssertPtrReturn(pSession, UINT32_MAX);
1441 AssertReturn(SUP_IS_SESSION_VALID(pSession), UINT32_MAX);
1442
1443 cRefs = ASMAtomicDecU32(&pSession->cRefs);
1444 AssertMsg(cRefs < _1M, ("%#x %p\n", cRefs, pSession));
1445 if (cRefs == 0)
1446 supdrvDestroySession(pSession->pDevExt, pSession);
1447 return cRefs;
1448}
1449
1450
1451/**
1452 * RTHandleTableDestroy callback used by supdrvCleanupSession.
1453 *
1454 * @returns IPRT status code, see SUPR0ObjAddRef.
1455 * @param hHandleTable The handle table handle. Ignored.
1456 * @param pvObj The object pointer.
1457 * @param pvCtx Context, the handle type. Ignored.
1458 * @param pvUser Session pointer.
1459 */
1460static DECLCALLBACK(int) supdrvSessionObjHandleRetain(RTHANDLETABLE hHandleTable, void *pvObj, void *pvCtx, void *pvUser)
1461{
1462 NOREF(pvCtx);
1463 NOREF(hHandleTable);
1464 return SUPR0ObjAddRefEx(pvObj, (PSUPDRVSESSION)pvUser, true /*fNoBlocking*/);
1465}
1466
1467
1468/**
1469 * RTHandleTableDestroy callback used by supdrvCleanupSession.
1470 *
1471 * @param hHandleTable The handle table handle. Ignored.
1472 * @param h The handle value. Ignored.
1473 * @param pvObj The object pointer.
1474 * @param pvCtx Context, the handle type. Ignored.
1475 * @param pvUser Session pointer.
1476 */
1477static DECLCALLBACK(void) supdrvSessionObjHandleDelete(RTHANDLETABLE hHandleTable, uint32_t h, void *pvObj, void *pvCtx, void *pvUser)
1478{
1479 NOREF(pvCtx);
1480 NOREF(h);
1481 NOREF(hHandleTable);
1482 SUPR0ObjRelease(pvObj, (PSUPDRVSESSION)pvUser);
1483}
1484
1485
1486/**
1487 * Fast path I/O Control worker.
1488 *
1489 * @returns VBox status code that should be passed down to ring-3 unchanged.
1490 * @param uOperation SUP_VMMR0_DO_XXX (not the I/O control number!).
1491 * @param idCpu VMCPU id.
1492 * @param pDevExt Device extention.
1493 * @param pSession Session data.
1494 */
1495int VBOXCALL supdrvIOCtlFast(uintptr_t uOperation, VMCPUID idCpu, PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession)
1496{
1497 /*
1498 * Validate input and check that the VM has a session.
1499 */
1500 if (RT_LIKELY(RT_VALID_PTR(pSession)))
1501 {
1502 PVM pVM = pSession->pSessionVM;
1503 PGVM pGVM = pSession->pSessionGVM;
1504 if (RT_LIKELY( pGVM != NULL
1505 && pVM != NULL
1506 && pVM == pSession->pFastIoCtrlVM))
1507 {
1508 if (RT_LIKELY(pDevExt->pfnVMMR0EntryFast))
1509 {
1510 /*
1511 * Make the call.
1512 */
1513 pDevExt->pfnVMMR0EntryFast(pGVM, pVM, idCpu, uOperation);
1514 return VINF_SUCCESS;
1515 }
1516
1517 SUPR0Printf("supdrvIOCtlFast: pfnVMMR0EntryFast is NULL\n");
1518 }
1519 else
1520 SUPR0Printf("supdrvIOCtlFast: Misconfig session: pGVM=%p pVM=%p pFastIoCtrlVM=%p\n",
1521 pGVM, pVM, pSession->pFastIoCtrlVM);
1522 }
1523 else
1524 SUPR0Printf("supdrvIOCtlFast: Bad session pointer %p\n", pSession);
1525 return VERR_INTERNAL_ERROR;
1526}
1527
1528
1529/**
1530 * Helper for supdrvIOCtl used to validate module names passed to SUP_IOCTL_LDR_OPEN.
1531 *
1532 * Check if pszStr contains any character of pszChars. We would use strpbrk
1533 * here if this function would be contained in the RedHat kABI white list, see
1534 * http://www.kerneldrivers.org/RHEL5.
1535 *
1536 * @returns true if fine, false if not.
1537 * @param pszName The module name to check.
1538 */
1539static bool supdrvIsLdrModuleNameValid(const char *pszName)
1540{
1541 int chCur;
1542 while ((chCur = *pszName++) != '\0')
1543 {
1544 static const char s_szInvalidChars[] = ";:()[]{}/\\|&*%#@!~`\"'";
1545 unsigned offInv = RT_ELEMENTS(s_szInvalidChars);
1546 while (offInv-- > 0)
1547 if (s_szInvalidChars[offInv] == chCur)
1548 return false;
1549 }
1550 return true;
1551}
1552
1553
1554
1555/**
1556 * I/O Control inner worker (tracing reasons).
1557 *
1558 * @returns IPRT status code.
1559 * @retval VERR_INVALID_PARAMETER if the request is invalid.
1560 *
1561 * @param uIOCtl Function number.
1562 * @param pDevExt Device extention.
1563 * @param pSession Session data.
1564 * @param pReqHdr The request header.
1565 */
1566static int supdrvIOCtlInnerUnrestricted(uintptr_t uIOCtl, PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPREQHDR pReqHdr)
1567{
1568 /*
1569 * Validation macros
1570 */
1571#define REQ_CHECK_SIZES_EX(Name, cbInExpect, cbOutExpect) \
1572 do { \
1573 if (RT_UNLIKELY(pReqHdr->cbIn != (cbInExpect) || pReqHdr->cbOut != (cbOutExpect))) \
1574 { \
1575 OSDBGPRINT(( #Name ": Invalid input/output sizes. cbIn=%ld expected %ld. cbOut=%ld expected %ld.\n", \
1576 (long)pReqHdr->cbIn, (long)(cbInExpect), (long)pReqHdr->cbOut, (long)(cbOutExpect))); \
1577 return pReqHdr->rc = VERR_INVALID_PARAMETER; \
1578 } \
1579 } while (0)
1580
1581#define REQ_CHECK_SIZES(Name) REQ_CHECK_SIZES_EX(Name, Name ## _SIZE_IN, Name ## _SIZE_OUT)
1582
1583#define REQ_CHECK_SIZE_IN(Name, cbInExpect) \
1584 do { \
1585 if (RT_UNLIKELY(pReqHdr->cbIn != (cbInExpect))) \
1586 { \
1587 OSDBGPRINT(( #Name ": Invalid input/output sizes. cbIn=%ld expected %ld.\n", \
1588 (long)pReqHdr->cbIn, (long)(cbInExpect))); \
1589 return pReqHdr->rc = VERR_INVALID_PARAMETER; \
1590 } \
1591 } while (0)
1592
1593#define REQ_CHECK_SIZE_OUT(Name, cbOutExpect) \
1594 do { \
1595 if (RT_UNLIKELY(pReqHdr->cbOut != (cbOutExpect))) \
1596 { \
1597 OSDBGPRINT(( #Name ": Invalid input/output sizes. cbOut=%ld expected %ld.\n", \
1598 (long)pReqHdr->cbOut, (long)(cbOutExpect))); \
1599 return pReqHdr->rc = VERR_INVALID_PARAMETER; \
1600 } \
1601 } while (0)
1602
1603#define REQ_CHECK_EXPR(Name, expr) \
1604 do { \
1605 if (RT_UNLIKELY(!(expr))) \
1606 { \
1607 OSDBGPRINT(( #Name ": %s\n", #expr)); \
1608 return pReqHdr->rc = VERR_INVALID_PARAMETER; \
1609 } \
1610 } while (0)
1611
1612#define REQ_CHECK_EXPR_FMT(expr, fmt) \
1613 do { \
1614 if (RT_UNLIKELY(!(expr))) \
1615 { \
1616 OSDBGPRINT( fmt ); \
1617 return pReqHdr->rc = VERR_INVALID_PARAMETER; \
1618 } \
1619 } while (0)
1620
1621 /*
1622 * The switch.
1623 */
1624 switch (SUP_CTL_CODE_NO_SIZE(uIOCtl))
1625 {
1626 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_COOKIE):
1627 {
1628 PSUPCOOKIE pReq = (PSUPCOOKIE)pReqHdr;
1629 REQ_CHECK_SIZES(SUP_IOCTL_COOKIE);
1630 if (strncmp(pReq->u.In.szMagic, SUPCOOKIE_MAGIC, sizeof(pReq->u.In.szMagic)))
1631 {
1632 OSDBGPRINT(("SUP_IOCTL_COOKIE: invalid magic %.16s\n", pReq->u.In.szMagic));
1633 pReq->Hdr.rc = VERR_INVALID_MAGIC;
1634 return 0;
1635 }
1636
1637#if 0
1638 /*
1639 * Call out to the OS specific code and let it do permission checks on the
1640 * client process.
1641 */
1642 if (!supdrvOSValidateClientProcess(pDevExt, pSession))
1643 {
1644 pReq->u.Out.u32Cookie = 0xffffffff;
1645 pReq->u.Out.u32SessionCookie = 0xffffffff;
1646 pReq->u.Out.u32SessionVersion = 0xffffffff;
1647 pReq->u.Out.u32DriverVersion = SUPDRV_IOC_VERSION;
1648 pReq->u.Out.pSession = NULL;
1649 pReq->u.Out.cFunctions = 0;
1650 pReq->Hdr.rc = VERR_PERMISSION_DENIED;
1651 return 0;
1652 }
1653#endif
1654
1655 /*
1656 * Match the version.
1657 * The current logic is very simple, match the major interface version.
1658 */
1659 if ( pReq->u.In.u32MinVersion > SUPDRV_IOC_VERSION
1660 || (pReq->u.In.u32MinVersion & 0xffff0000) != (SUPDRV_IOC_VERSION & 0xffff0000))
1661 {
1662 OSDBGPRINT(("SUP_IOCTL_COOKIE: Version mismatch. Requested: %#x Min: %#x Current: %#x\n",
1663 pReq->u.In.u32ReqVersion, pReq->u.In.u32MinVersion, SUPDRV_IOC_VERSION));
1664 pReq->u.Out.u32Cookie = 0xffffffff;
1665 pReq->u.Out.u32SessionCookie = 0xffffffff;
1666 pReq->u.Out.u32SessionVersion = 0xffffffff;
1667 pReq->u.Out.u32DriverVersion = SUPDRV_IOC_VERSION;
1668 pReq->u.Out.pSession = NULL;
1669 pReq->u.Out.cFunctions = 0;
1670 pReq->Hdr.rc = VERR_VERSION_MISMATCH;
1671 return 0;
1672 }
1673
1674 /*
1675 * Fill in return data and be gone.
1676 * N.B. The first one to change SUPDRV_IOC_VERSION shall makes sure that
1677 * u32SessionVersion <= u32ReqVersion!
1678 */
1679 /** @todo Somehow validate the client and negotiate a secure cookie... */
1680 pReq->u.Out.u32Cookie = pDevExt->u32Cookie;
1681 pReq->u.Out.u32SessionCookie = pSession->u32Cookie;
1682 pReq->u.Out.u32SessionVersion = SUPDRV_IOC_VERSION;
1683 pReq->u.Out.u32DriverVersion = SUPDRV_IOC_VERSION;
1684 pReq->u.Out.pSession = pSession;
1685 pReq->u.Out.cFunctions = sizeof(g_aFunctions) / sizeof(g_aFunctions[0]);
1686 pReq->Hdr.rc = VINF_SUCCESS;
1687 return 0;
1688 }
1689
1690 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_QUERY_FUNCS(0)):
1691 {
1692 /* validate */
1693 PSUPQUERYFUNCS pReq = (PSUPQUERYFUNCS)pReqHdr;
1694 REQ_CHECK_SIZES_EX(SUP_IOCTL_QUERY_FUNCS, SUP_IOCTL_QUERY_FUNCS_SIZE_IN, SUP_IOCTL_QUERY_FUNCS_SIZE_OUT(RT_ELEMENTS(g_aFunctions)));
1695
1696 /* execute */
1697 pReq->u.Out.cFunctions = RT_ELEMENTS(g_aFunctions);
1698 memcpy(&pReq->u.Out.aFunctions[0], g_aFunctions, sizeof(g_aFunctions));
1699 pReq->Hdr.rc = VINF_SUCCESS;
1700 return 0;
1701 }
1702
1703 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_PAGE_LOCK):
1704 {
1705 /* validate */
1706 PSUPPAGELOCK pReq = (PSUPPAGELOCK)pReqHdr;
1707 REQ_CHECK_SIZE_IN(SUP_IOCTL_PAGE_LOCK, SUP_IOCTL_PAGE_LOCK_SIZE_IN);
1708 REQ_CHECK_SIZE_OUT(SUP_IOCTL_PAGE_LOCK, SUP_IOCTL_PAGE_LOCK_SIZE_OUT(pReq->u.In.cPages));
1709 REQ_CHECK_EXPR(SUP_IOCTL_PAGE_LOCK, pReq->u.In.cPages > 0);
1710 REQ_CHECK_EXPR(SUP_IOCTL_PAGE_LOCK, pReq->u.In.pvR3 >= PAGE_SIZE);
1711
1712 /* execute */
1713 pReq->Hdr.rc = SUPR0LockMem(pSession, pReq->u.In.pvR3, pReq->u.In.cPages, &pReq->u.Out.aPages[0]);
1714 if (RT_FAILURE(pReq->Hdr.rc))
1715 pReq->Hdr.cbOut = sizeof(pReq->Hdr);
1716 return 0;
1717 }
1718
1719 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_PAGE_UNLOCK):
1720 {
1721 /* validate */
1722 PSUPPAGEUNLOCK pReq = (PSUPPAGEUNLOCK)pReqHdr;
1723 REQ_CHECK_SIZES(SUP_IOCTL_PAGE_UNLOCK);
1724
1725 /* execute */
1726 pReq->Hdr.rc = SUPR0UnlockMem(pSession, pReq->u.In.pvR3);
1727 return 0;
1728 }
1729
1730 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_CONT_ALLOC):
1731 {
1732 /* validate */
1733 PSUPCONTALLOC pReq = (PSUPCONTALLOC)pReqHdr;
1734 REQ_CHECK_SIZES(SUP_IOCTL_CONT_ALLOC);
1735
1736 /* execute */
1737 pReq->Hdr.rc = SUPR0ContAlloc(pSession, pReq->u.In.cPages, &pReq->u.Out.pvR0, &pReq->u.Out.pvR3, &pReq->u.Out.HCPhys);
1738 if (RT_FAILURE(pReq->Hdr.rc))
1739 pReq->Hdr.cbOut = sizeof(pReq->Hdr);
1740 return 0;
1741 }
1742
1743 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_CONT_FREE):
1744 {
1745 /* validate */
1746 PSUPCONTFREE pReq = (PSUPCONTFREE)pReqHdr;
1747 REQ_CHECK_SIZES(SUP_IOCTL_CONT_FREE);
1748
1749 /* execute */
1750 pReq->Hdr.rc = SUPR0ContFree(pSession, (RTHCUINTPTR)pReq->u.In.pvR3);
1751 return 0;
1752 }
1753
1754 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_LDR_OPEN):
1755 {
1756 /* validate */
1757 PSUPLDROPEN pReq = (PSUPLDROPEN)pReqHdr;
1758 REQ_CHECK_SIZES(SUP_IOCTL_LDR_OPEN);
1759 if ( pReq->u.In.cbImageWithEverything != 0
1760 || pReq->u.In.cbImageBits != 0)
1761 {
1762 REQ_CHECK_EXPR(SUP_IOCTL_LDR_OPEN, pReq->u.In.cbImageWithEverything > 0);
1763 REQ_CHECK_EXPR(SUP_IOCTL_LDR_OPEN, pReq->u.In.cbImageWithEverything < 16*_1M);
1764 REQ_CHECK_EXPR(SUP_IOCTL_LDR_OPEN, pReq->u.In.cbImageBits > 0);
1765 REQ_CHECK_EXPR(SUP_IOCTL_LDR_OPEN, pReq->u.In.cbImageBits < pReq->u.In.cbImageWithEverything);
1766 }
1767 REQ_CHECK_EXPR(SUP_IOCTL_LDR_OPEN, pReq->u.In.szName[0]);
1768 REQ_CHECK_EXPR(SUP_IOCTL_LDR_OPEN, RTStrEnd(pReq->u.In.szName, sizeof(pReq->u.In.szName)));
1769 REQ_CHECK_EXPR(SUP_IOCTL_LDR_OPEN, supdrvIsLdrModuleNameValid(pReq->u.In.szName));
1770 REQ_CHECK_EXPR(SUP_IOCTL_LDR_OPEN, RTStrEnd(pReq->u.In.szFilename, sizeof(pReq->u.In.szFilename)));
1771
1772 /* execute */
1773 pReq->Hdr.rc = supdrvIOCtl_LdrOpen(pDevExt, pSession, pReq);
1774 return 0;
1775 }
1776
1777 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_LDR_LOAD):
1778 {
1779 /* validate */
1780 PSUPLDRLOAD pReq = (PSUPLDRLOAD)pReqHdr;
1781 REQ_CHECK_EXPR(Name, pReq->Hdr.cbIn >= SUP_IOCTL_LDR_LOAD_SIZE_IN(32));
1782 REQ_CHECK_SIZES_EX(SUP_IOCTL_LDR_LOAD, SUP_IOCTL_LDR_LOAD_SIZE_IN(pReq->u.In.cbImageWithEverything), SUP_IOCTL_LDR_LOAD_SIZE_OUT);
1783 REQ_CHECK_EXPR_FMT( !pReq->u.In.cSymbols
1784 || ( pReq->u.In.cSymbols <= 16384
1785 && pReq->u.In.offSymbols >= pReq->u.In.cbImageBits
1786 && pReq->u.In.offSymbols < pReq->u.In.cbImageWithEverything
1787 && pReq->u.In.offSymbols + pReq->u.In.cSymbols * sizeof(SUPLDRSYM) <= pReq->u.In.cbImageWithEverything),
1788 ("SUP_IOCTL_LDR_LOAD: offSymbols=%#lx cSymbols=%#lx cbImageWithEverything=%#lx\n", (long)pReq->u.In.offSymbols,
1789 (long)pReq->u.In.cSymbols, (long)pReq->u.In.cbImageWithEverything));
1790 REQ_CHECK_EXPR_FMT( !pReq->u.In.cbStrTab
1791 || ( pReq->u.In.offStrTab < pReq->u.In.cbImageWithEverything
1792 && pReq->u.In.offStrTab >= pReq->u.In.cbImageBits
1793 && pReq->u.In.offStrTab + pReq->u.In.cbStrTab <= pReq->u.In.cbImageWithEverything
1794 && pReq->u.In.cbStrTab <= pReq->u.In.cbImageWithEverything),
1795 ("SUP_IOCTL_LDR_LOAD: offStrTab=%#lx cbStrTab=%#lx cbImageWithEverything=%#lx\n", (long)pReq->u.In.offStrTab,
1796 (long)pReq->u.In.cbStrTab, (long)pReq->u.In.cbImageWithEverything));
1797 REQ_CHECK_EXPR_FMT( pReq->u.In.cSegments >= 1
1798 && pReq->u.In.cSegments <= 128
1799 && pReq->u.In.cSegments <= (pReq->u.In.cbImageBits + PAGE_SIZE - 1) / PAGE_SIZE
1800 && pReq->u.In.offSegments >= pReq->u.In.cbImageBits
1801 && pReq->u.In.offSegments < pReq->u.In.cbImageWithEverything
1802 && pReq->u.In.offSegments + pReq->u.In.cSegments * sizeof(SUPLDRSEG) <= pReq->u.In.cbImageWithEverything,
1803 ("SUP_IOCTL_LDR_LOAD: offSegments=%#lx cSegments=%#lx cbImageWithEverything=%#lx\n", (long)pReq->u.In.offSegments,
1804 (long)pReq->u.In.cSegments, (long)pReq->u.In.cbImageWithEverything));
1805
1806 if (pReq->u.In.cSymbols)
1807 {
1808 uint32_t i;
1809 PSUPLDRSYM paSyms = (PSUPLDRSYM)&pReq->u.In.abImage[pReq->u.In.offSymbols];
1810 for (i = 0; i < pReq->u.In.cSymbols; i++)
1811 {
1812 REQ_CHECK_EXPR_FMT(paSyms[i].offSymbol < pReq->u.In.cbImageWithEverything,
1813 ("SUP_IOCTL_LDR_LOAD: sym #%ld: symb off %#lx (max=%#lx)\n", (long)i, (long)paSyms[i].offSymbol, (long)pReq->u.In.cbImageWithEverything));
1814 REQ_CHECK_EXPR_FMT(paSyms[i].offName < pReq->u.In.cbStrTab,
1815 ("SUP_IOCTL_LDR_LOAD: sym #%ld: name off %#lx (max=%#lx)\n", (long)i, (long)paSyms[i].offName, (long)pReq->u.In.cbImageWithEverything));
1816 REQ_CHECK_EXPR_FMT(RTStrEnd((char const *)&pReq->u.In.abImage[pReq->u.In.offStrTab + paSyms[i].offName],
1817 pReq->u.In.cbStrTab - paSyms[i].offName),
1818 ("SUP_IOCTL_LDR_LOAD: sym #%ld: unterminated name! (%#lx / %#lx)\n", (long)i, (long)paSyms[i].offName, (long)pReq->u.In.cbImageWithEverything));
1819 }
1820 }
1821 {
1822 uint32_t i;
1823 uint32_t offPrevEnd = 0;
1824 PSUPLDRSEG paSegs = (PSUPLDRSEG)&pReq->u.In.abImage[pReq->u.In.offSegments];
1825 for (i = 0; i < pReq->u.In.cSegments; i++)
1826 {
1827 REQ_CHECK_EXPR_FMT(paSegs[i].off < pReq->u.In.cbImageBits && !(paSegs[i].off & PAGE_OFFSET_MASK),
1828 ("SUP_IOCTL_LDR_LOAD: seg #%ld: off %#lx (max=%#lx)\n", (long)i, (long)paSegs[i].off, (long)pReq->u.In.cbImageBits));
1829 REQ_CHECK_EXPR_FMT(paSegs[i].cb <= pReq->u.In.cbImageBits,
1830 ("SUP_IOCTL_LDR_LOAD: seg #%ld: cb %#lx (max=%#lx)\n", (long)i, (long)paSegs[i].cb, (long)pReq->u.In.cbImageBits));
1831 REQ_CHECK_EXPR_FMT(paSegs[i].off + paSegs[i].cb <= pReq->u.In.cbImageBits,
1832 ("SUP_IOCTL_LDR_LOAD: seg #%ld: off %#lx + cb %#lx = %#lx (max=%#lx)\n", (long)i, (long)paSegs[i].off, (long)paSegs[i].cb, (long)(paSegs[i].off + paSegs[i].cb), (long)pReq->u.In.cbImageBits));
1833 REQ_CHECK_EXPR_FMT(paSegs[i].fProt != 0,
1834 ("SUP_IOCTL_LDR_LOAD: seg #%ld: off %#lx + cb %#lx\n", (long)i, (long)paSegs[i].off, (long)paSegs[i].cb));
1835 REQ_CHECK_EXPR_FMT(paSegs[i].fUnused == 0, ("SUP_IOCTL_LDR_LOAD: seg #%ld: fUnused=1\n", (long)i));
1836 REQ_CHECK_EXPR_FMT(offPrevEnd == paSegs[i].off,
1837 ("SUP_IOCTL_LDR_LOAD: seg #%ld: off %#lx offPrevEnd %#lx\n", (long)i, (long)paSegs[i].off, (long)offPrevEnd));
1838 offPrevEnd = paSegs[i].off + paSegs[i].cb;
1839 }
1840 REQ_CHECK_EXPR_FMT(offPrevEnd == pReq->u.In.cbImageBits,
1841 ("SUP_IOCTL_LDR_LOAD: offPrevEnd %#lx cbImageBits %#lx\n", (long)i, (long)offPrevEnd, (long)pReq->u.In.cbImageBits));
1842 }
1843 REQ_CHECK_EXPR_FMT(!(pReq->u.In.fFlags & ~SUPLDRLOAD_F_VALID_MASK),
1844 ("SUP_IOCTL_LDR_LOAD: fFlags=%#x\n", (unsigned)pReq->u.In.fFlags));
1845
1846 /* execute */
1847 pReq->Hdr.rc = supdrvIOCtl_LdrLoad(pDevExt, pSession, pReq);
1848 return 0;
1849 }
1850
1851 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_LDR_FREE):
1852 {
1853 /* validate */
1854 PSUPLDRFREE pReq = (PSUPLDRFREE)pReqHdr;
1855 REQ_CHECK_SIZES(SUP_IOCTL_LDR_FREE);
1856
1857 /* execute */
1858 pReq->Hdr.rc = supdrvIOCtl_LdrFree(pDevExt, pSession, pReq);
1859 return 0;
1860 }
1861
1862 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_LDR_LOCK_DOWN):
1863 {
1864 /* validate */
1865 REQ_CHECK_SIZES(SUP_IOCTL_LDR_LOCK_DOWN);
1866
1867 /* execute */
1868 pReqHdr->rc = supdrvIOCtl_LdrLockDown(pDevExt);
1869 return 0;
1870 }
1871
1872 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_LDR_GET_SYMBOL):
1873 {
1874 /* validate */
1875 PSUPLDRGETSYMBOL pReq = (PSUPLDRGETSYMBOL)pReqHdr;
1876 REQ_CHECK_SIZES(SUP_IOCTL_LDR_GET_SYMBOL);
1877 REQ_CHECK_EXPR(SUP_IOCTL_LDR_GET_SYMBOL, RTStrEnd(pReq->u.In.szSymbol, sizeof(pReq->u.In.szSymbol)));
1878
1879 /* execute */
1880 pReq->Hdr.rc = supdrvIOCtl_LdrQuerySymbol(pDevExt, pSession, pReq);
1881 return 0;
1882 }
1883
1884 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_CALL_VMMR0_NO_SIZE()):
1885 {
1886 /* validate */
1887 PSUPCALLVMMR0 pReq = (PSUPCALLVMMR0)pReqHdr;
1888 Log4(("SUP_IOCTL_CALL_VMMR0: op=%u in=%u arg=%RX64 p/t=%RTproc/%RTthrd\n",
1889 pReq->u.In.uOperation, pReq->Hdr.cbIn, pReq->u.In.u64Arg, RTProcSelf(), RTThreadNativeSelf()));
1890
1891 if (pReq->Hdr.cbIn == SUP_IOCTL_CALL_VMMR0_SIZE(0))
1892 {
1893 REQ_CHECK_SIZES_EX(SUP_IOCTL_CALL_VMMR0, SUP_IOCTL_CALL_VMMR0_SIZE_IN(0), SUP_IOCTL_CALL_VMMR0_SIZE_OUT(0));
1894
1895 /* execute */
1896 if (RT_LIKELY(pDevExt->pfnVMMR0EntryEx))
1897 {
1898 if (pReq->u.In.pVMR0 == NULL)
1899 pReq->Hdr.rc = pDevExt->pfnVMMR0EntryEx(NULL, NULL, pReq->u.In.idCpu,
1900 pReq->u.In.uOperation, NULL, pReq->u.In.u64Arg, pSession);
1901 else if (pReq->u.In.pVMR0 == pSession->pSessionVM)
1902 pReq->Hdr.rc = pDevExt->pfnVMMR0EntryEx(pSession->pSessionGVM, pSession->pSessionVM, pReq->u.In.idCpu,
1903 pReq->u.In.uOperation, NULL, pReq->u.In.u64Arg, pSession);
1904 else
1905 pReq->Hdr.rc = VERR_INVALID_VM_HANDLE;
1906 }
1907 else
1908 pReq->Hdr.rc = VERR_WRONG_ORDER;
1909 }
1910 else
1911 {
1912 PSUPVMMR0REQHDR pVMMReq = (PSUPVMMR0REQHDR)&pReq->abReqPkt[0];
1913 REQ_CHECK_EXPR_FMT(pReq->Hdr.cbIn >= SUP_IOCTL_CALL_VMMR0_SIZE(sizeof(SUPVMMR0REQHDR)),
1914 ("SUP_IOCTL_CALL_VMMR0: cbIn=%#x < %#lx\n", pReq->Hdr.cbIn, SUP_IOCTL_CALL_VMMR0_SIZE(sizeof(SUPVMMR0REQHDR))));
1915 REQ_CHECK_EXPR(SUP_IOCTL_CALL_VMMR0, pVMMReq->u32Magic == SUPVMMR0REQHDR_MAGIC);
1916 REQ_CHECK_SIZES_EX(SUP_IOCTL_CALL_VMMR0, SUP_IOCTL_CALL_VMMR0_SIZE_IN(pVMMReq->cbReq), SUP_IOCTL_CALL_VMMR0_SIZE_OUT(pVMMReq->cbReq));
1917
1918 /* execute */
1919 if (RT_LIKELY(pDevExt->pfnVMMR0EntryEx))
1920 {
1921 if (pReq->u.In.pVMR0 == NULL)
1922 pReq->Hdr.rc = pDevExt->pfnVMMR0EntryEx(NULL, NULL, pReq->u.In.idCpu,
1923 pReq->u.In.uOperation, pVMMReq, pReq->u.In.u64Arg, pSession);
1924 else if (pReq->u.In.pVMR0 == pSession->pSessionVM)
1925 pReq->Hdr.rc = pDevExt->pfnVMMR0EntryEx(pSession->pSessionGVM, pSession->pSessionVM, pReq->u.In.idCpu,
1926 pReq->u.In.uOperation, pVMMReq, pReq->u.In.u64Arg, pSession);
1927 else
1928 pReq->Hdr.rc = VERR_INVALID_VM_HANDLE;
1929 }
1930 else
1931 pReq->Hdr.rc = VERR_WRONG_ORDER;
1932 }
1933
1934 if ( RT_FAILURE(pReq->Hdr.rc)
1935 && pReq->Hdr.rc != VERR_INTERRUPTED
1936 && pReq->Hdr.rc != VERR_TIMEOUT)
1937 Log(("SUP_IOCTL_CALL_VMMR0: rc=%Rrc op=%u out=%u arg=%RX64 p/t=%RTproc/%RTthrd\n",
1938 pReq->Hdr.rc, pReq->u.In.uOperation, pReq->Hdr.cbOut, pReq->u.In.u64Arg, RTProcSelf(), RTThreadNativeSelf()));
1939 else
1940 Log4(("SUP_IOCTL_CALL_VMMR0: rc=%Rrc op=%u out=%u arg=%RX64 p/t=%RTproc/%RTthrd\n",
1941 pReq->Hdr.rc, pReq->u.In.uOperation, pReq->Hdr.cbOut, pReq->u.In.u64Arg, RTProcSelf(), RTThreadNativeSelf()));
1942 return 0;
1943 }
1944
1945 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_CALL_VMMR0_BIG):
1946 {
1947 /* validate */
1948 PSUPCALLVMMR0 pReq = (PSUPCALLVMMR0)pReqHdr;
1949 PSUPVMMR0REQHDR pVMMReq;
1950 Log4(("SUP_IOCTL_CALL_VMMR0_BIG: op=%u in=%u arg=%RX64 p/t=%RTproc/%RTthrd\n",
1951 pReq->u.In.uOperation, pReq->Hdr.cbIn, pReq->u.In.u64Arg, RTProcSelf(), RTThreadNativeSelf()));
1952
1953 pVMMReq = (PSUPVMMR0REQHDR)&pReq->abReqPkt[0];
1954 REQ_CHECK_EXPR_FMT(pReq->Hdr.cbIn >= SUP_IOCTL_CALL_VMMR0_BIG_SIZE(sizeof(SUPVMMR0REQHDR)),
1955 ("SUP_IOCTL_CALL_VMMR0_BIG: cbIn=%#x < %#lx\n", pReq->Hdr.cbIn, SUP_IOCTL_CALL_VMMR0_BIG_SIZE(sizeof(SUPVMMR0REQHDR))));
1956 REQ_CHECK_EXPR(SUP_IOCTL_CALL_VMMR0_BIG, pVMMReq->u32Magic == SUPVMMR0REQHDR_MAGIC);
1957 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));
1958
1959 /* execute */
1960 if (RT_LIKELY(pDevExt->pfnVMMR0EntryEx))
1961 {
1962 if (pReq->u.In.pVMR0 == NULL)
1963 pReq->Hdr.rc = pDevExt->pfnVMMR0EntryEx(NULL, NULL, pReq->u.In.idCpu, pReq->u.In.uOperation, pVMMReq, pReq->u.In.u64Arg, pSession);
1964 else if (pReq->u.In.pVMR0 == pSession->pSessionVM)
1965 pReq->Hdr.rc = pDevExt->pfnVMMR0EntryEx(pSession->pSessionGVM, pSession->pSessionVM, pReq->u.In.idCpu,
1966 pReq->u.In.uOperation, pVMMReq, pReq->u.In.u64Arg, pSession);
1967 else
1968 pReq->Hdr.rc = VERR_INVALID_VM_HANDLE;
1969 }
1970 else
1971 pReq->Hdr.rc = VERR_WRONG_ORDER;
1972
1973 if ( RT_FAILURE(pReq->Hdr.rc)
1974 && pReq->Hdr.rc != VERR_INTERRUPTED
1975 && pReq->Hdr.rc != VERR_TIMEOUT)
1976 Log(("SUP_IOCTL_CALL_VMMR0_BIG: rc=%Rrc op=%u out=%u arg=%RX64 p/t=%RTproc/%RTthrd\n",
1977 pReq->Hdr.rc, pReq->u.In.uOperation, pReq->Hdr.cbOut, pReq->u.In.u64Arg, RTProcSelf(), RTThreadNativeSelf()));
1978 else
1979 Log4(("SUP_IOCTL_CALL_VMMR0_BIG: rc=%Rrc op=%u out=%u arg=%RX64 p/t=%RTproc/%RTthrd\n",
1980 pReq->Hdr.rc, pReq->u.In.uOperation, pReq->Hdr.cbOut, pReq->u.In.u64Arg, RTProcSelf(), RTThreadNativeSelf()));
1981 return 0;
1982 }
1983
1984 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_GET_PAGING_MODE):
1985 {
1986 /* validate */
1987 PSUPGETPAGINGMODE pReq = (PSUPGETPAGINGMODE)pReqHdr;
1988 REQ_CHECK_SIZES(SUP_IOCTL_GET_PAGING_MODE);
1989
1990 /* execute */
1991 pReq->Hdr.rc = VINF_SUCCESS;
1992 pReq->u.Out.enmMode = SUPR0GetPagingMode();
1993 return 0;
1994 }
1995
1996 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_LOW_ALLOC):
1997 {
1998 /* validate */
1999 PSUPLOWALLOC pReq = (PSUPLOWALLOC)pReqHdr;
2000 REQ_CHECK_EXPR(SUP_IOCTL_LOW_ALLOC, pReq->Hdr.cbIn <= SUP_IOCTL_LOW_ALLOC_SIZE_IN);
2001 REQ_CHECK_SIZES_EX(SUP_IOCTL_LOW_ALLOC, SUP_IOCTL_LOW_ALLOC_SIZE_IN, SUP_IOCTL_LOW_ALLOC_SIZE_OUT(pReq->u.In.cPages));
2002
2003 /* execute */
2004 pReq->Hdr.rc = SUPR0LowAlloc(pSession, pReq->u.In.cPages, &pReq->u.Out.pvR0, &pReq->u.Out.pvR3, &pReq->u.Out.aPages[0]);
2005 if (RT_FAILURE(pReq->Hdr.rc))
2006 pReq->Hdr.cbOut = sizeof(pReq->Hdr);
2007 return 0;
2008 }
2009
2010 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_LOW_FREE):
2011 {
2012 /* validate */
2013 PSUPLOWFREE pReq = (PSUPLOWFREE)pReqHdr;
2014 REQ_CHECK_SIZES(SUP_IOCTL_LOW_FREE);
2015
2016 /* execute */
2017 pReq->Hdr.rc = SUPR0LowFree(pSession, (RTHCUINTPTR)pReq->u.In.pvR3);
2018 return 0;
2019 }
2020
2021 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_GIP_MAP):
2022 {
2023 /* validate */
2024 PSUPGIPMAP pReq = (PSUPGIPMAP)pReqHdr;
2025 REQ_CHECK_SIZES(SUP_IOCTL_GIP_MAP);
2026
2027 /* execute */
2028 pReq->Hdr.rc = SUPR0GipMap(pSession, &pReq->u.Out.pGipR3, &pReq->u.Out.HCPhysGip);
2029 if (RT_SUCCESS(pReq->Hdr.rc))
2030 pReq->u.Out.pGipR0 = pDevExt->pGip;
2031 return 0;
2032 }
2033
2034 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_GIP_UNMAP):
2035 {
2036 /* validate */
2037 PSUPGIPUNMAP pReq = (PSUPGIPUNMAP)pReqHdr;
2038 REQ_CHECK_SIZES(SUP_IOCTL_GIP_UNMAP);
2039
2040 /* execute */
2041 pReq->Hdr.rc = SUPR0GipUnmap(pSession);
2042 return 0;
2043 }
2044
2045 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_SET_VM_FOR_FAST):
2046 {
2047 /* validate */
2048 PSUPSETVMFORFAST pReq = (PSUPSETVMFORFAST)pReqHdr;
2049 REQ_CHECK_SIZES(SUP_IOCTL_SET_VM_FOR_FAST);
2050 REQ_CHECK_EXPR_FMT( !pReq->u.In.pVMR0
2051 || ( RT_VALID_PTR(pReq->u.In.pVMR0)
2052 && !((uintptr_t)pReq->u.In.pVMR0 & (PAGE_SIZE - 1))),
2053 ("SUP_IOCTL_SET_VM_FOR_FAST: pVMR0=%p!\n", pReq->u.In.pVMR0));
2054
2055 /* execute */
2056 RTSpinlockAcquire(pDevExt->Spinlock);
2057 if (pSession->pSessionVM == pReq->u.In.pVMR0)
2058 {
2059 if (pSession->pFastIoCtrlVM == NULL)
2060 {
2061 pSession->pFastIoCtrlVM = pSession->pSessionVM;
2062 RTSpinlockRelease(pDevExt->Spinlock);
2063 pReq->Hdr.rc = VINF_SUCCESS;
2064 }
2065 else
2066 {
2067 RTSpinlockRelease(pDevExt->Spinlock);
2068 OSDBGPRINT(("SUP_IOCTL_SET_VM_FOR_FAST: pSession->pFastIoCtrlVM=%p! (pVMR0=%p)\n",
2069 pSession->pFastIoCtrlVM, pReq->u.In.pVMR0));
2070 pReq->Hdr.rc = VERR_ALREADY_EXISTS;
2071 }
2072 }
2073 else
2074 {
2075 RTSpinlockRelease(pDevExt->Spinlock);
2076 OSDBGPRINT(("SUP_IOCTL_SET_VM_FOR_FAST: pSession->pSessionVM=%p vs pVMR0=%p)\n",
2077 pSession->pSessionVM, pReq->u.In.pVMR0));
2078 pReq->Hdr.rc = pSession->pSessionVM ? VERR_ACCESS_DENIED : VERR_WRONG_ORDER;
2079 }
2080 return 0;
2081 }
2082
2083 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_PAGE_ALLOC_EX):
2084 {
2085 /* validate */
2086 PSUPPAGEALLOCEX pReq = (PSUPPAGEALLOCEX)pReqHdr;
2087 REQ_CHECK_EXPR(SUP_IOCTL_PAGE_ALLOC_EX, pReq->Hdr.cbIn <= SUP_IOCTL_PAGE_ALLOC_EX_SIZE_IN);
2088 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));
2089 REQ_CHECK_EXPR_FMT(pReq->u.In.fKernelMapping || pReq->u.In.fUserMapping,
2090 ("SUP_IOCTL_PAGE_ALLOC_EX: No mapping requested!\n"));
2091 REQ_CHECK_EXPR_FMT(pReq->u.In.fUserMapping,
2092 ("SUP_IOCTL_PAGE_ALLOC_EX: Must have user mapping!\n"));
2093 REQ_CHECK_EXPR_FMT(!pReq->u.In.fReserved0 && !pReq->u.In.fReserved1,
2094 ("SUP_IOCTL_PAGE_ALLOC_EX: fReserved0=%d fReserved1=%d\n", pReq->u.In.fReserved0, pReq->u.In.fReserved1));
2095
2096 /* execute */
2097 pReq->Hdr.rc = SUPR0PageAllocEx(pSession, pReq->u.In.cPages, 0 /* fFlags */,
2098 pReq->u.In.fUserMapping ? &pReq->u.Out.pvR3 : NULL,
2099 pReq->u.In.fKernelMapping ? &pReq->u.Out.pvR0 : NULL,
2100 &pReq->u.Out.aPages[0]);
2101 if (RT_FAILURE(pReq->Hdr.rc))
2102 pReq->Hdr.cbOut = sizeof(pReq->Hdr);
2103 return 0;
2104 }
2105
2106 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_PAGE_MAP_KERNEL):
2107 {
2108 /* validate */
2109 PSUPPAGEMAPKERNEL pReq = (PSUPPAGEMAPKERNEL)pReqHdr;
2110 REQ_CHECK_SIZES(SUP_IOCTL_PAGE_MAP_KERNEL);
2111 REQ_CHECK_EXPR_FMT(!pReq->u.In.fFlags, ("SUP_IOCTL_PAGE_MAP_KERNEL: fFlags=%#x! MBZ\n", pReq->u.In.fFlags));
2112 REQ_CHECK_EXPR_FMT(!(pReq->u.In.offSub & PAGE_OFFSET_MASK), ("SUP_IOCTL_PAGE_MAP_KERNEL: offSub=%#x\n", pReq->u.In.offSub));
2113 REQ_CHECK_EXPR_FMT(pReq->u.In.cbSub && !(pReq->u.In.cbSub & PAGE_OFFSET_MASK),
2114 ("SUP_IOCTL_PAGE_MAP_KERNEL: cbSub=%#x\n", pReq->u.In.cbSub));
2115
2116 /* execute */
2117 pReq->Hdr.rc = SUPR0PageMapKernel(pSession, pReq->u.In.pvR3, pReq->u.In.offSub, pReq->u.In.cbSub,
2118 pReq->u.In.fFlags, &pReq->u.Out.pvR0);
2119 if (RT_FAILURE(pReq->Hdr.rc))
2120 pReq->Hdr.cbOut = sizeof(pReq->Hdr);
2121 return 0;
2122 }
2123
2124 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_PAGE_PROTECT):
2125 {
2126 /* validate */
2127 PSUPPAGEPROTECT pReq = (PSUPPAGEPROTECT)pReqHdr;
2128 REQ_CHECK_SIZES(SUP_IOCTL_PAGE_PROTECT);
2129 REQ_CHECK_EXPR_FMT(!(pReq->u.In.fProt & ~(RTMEM_PROT_READ | RTMEM_PROT_WRITE | RTMEM_PROT_EXEC | RTMEM_PROT_NONE)),
2130 ("SUP_IOCTL_PAGE_PROTECT: fProt=%#x!\n", pReq->u.In.fProt));
2131 REQ_CHECK_EXPR_FMT(!(pReq->u.In.offSub & PAGE_OFFSET_MASK), ("SUP_IOCTL_PAGE_PROTECT: offSub=%#x\n", pReq->u.In.offSub));
2132 REQ_CHECK_EXPR_FMT(pReq->u.In.cbSub && !(pReq->u.In.cbSub & PAGE_OFFSET_MASK),
2133 ("SUP_IOCTL_PAGE_PROTECT: cbSub=%#x\n", pReq->u.In.cbSub));
2134
2135 /* execute */
2136 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);
2137 return 0;
2138 }
2139
2140 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_PAGE_FREE):
2141 {
2142 /* validate */
2143 PSUPPAGEFREE pReq = (PSUPPAGEFREE)pReqHdr;
2144 REQ_CHECK_SIZES(SUP_IOCTL_PAGE_FREE);
2145
2146 /* execute */
2147 pReq->Hdr.rc = SUPR0PageFree(pSession, pReq->u.In.pvR3);
2148 return 0;
2149 }
2150
2151 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_CALL_SERVICE_NO_SIZE()):
2152 {
2153 /* validate */
2154 PSUPCALLSERVICE pReq = (PSUPCALLSERVICE)pReqHdr;
2155 Log4(("SUP_IOCTL_CALL_SERVICE: op=%u in=%u arg=%RX64 p/t=%RTproc/%RTthrd\n",
2156 pReq->u.In.uOperation, pReq->Hdr.cbIn, pReq->u.In.u64Arg, RTProcSelf(), RTThreadNativeSelf()));
2157
2158 if (pReq->Hdr.cbIn == SUP_IOCTL_CALL_SERVICE_SIZE(0))
2159 REQ_CHECK_SIZES_EX(SUP_IOCTL_CALL_SERVICE, SUP_IOCTL_CALL_SERVICE_SIZE_IN(0), SUP_IOCTL_CALL_SERVICE_SIZE_OUT(0));
2160 else
2161 {
2162 PSUPR0SERVICEREQHDR pSrvReq = (PSUPR0SERVICEREQHDR)&pReq->abReqPkt[0];
2163 REQ_CHECK_EXPR_FMT(pReq->Hdr.cbIn >= SUP_IOCTL_CALL_SERVICE_SIZE(sizeof(SUPR0SERVICEREQHDR)),
2164 ("SUP_IOCTL_CALL_SERVICE: cbIn=%#x < %#lx\n", pReq->Hdr.cbIn, SUP_IOCTL_CALL_SERVICE_SIZE(sizeof(SUPR0SERVICEREQHDR))));
2165 REQ_CHECK_EXPR(SUP_IOCTL_CALL_SERVICE, pSrvReq->u32Magic == SUPR0SERVICEREQHDR_MAGIC);
2166 REQ_CHECK_SIZES_EX(SUP_IOCTL_CALL_SERVICE, SUP_IOCTL_CALL_SERVICE_SIZE_IN(pSrvReq->cbReq), SUP_IOCTL_CALL_SERVICE_SIZE_OUT(pSrvReq->cbReq));
2167 }
2168 REQ_CHECK_EXPR(SUP_IOCTL_CALL_SERVICE, RTStrEnd(pReq->u.In.szName, sizeof(pReq->u.In.szName)));
2169
2170 /* execute */
2171 pReq->Hdr.rc = supdrvIOCtl_CallServiceModule(pDevExt, pSession, pReq);
2172 return 0;
2173 }
2174
2175 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_LOGGER_SETTINGS_NO_SIZE()):
2176 {
2177 /* validate */
2178 PSUPLOGGERSETTINGS pReq = (PSUPLOGGERSETTINGS)pReqHdr;
2179 size_t cbStrTab;
2180 REQ_CHECK_SIZE_OUT(SUP_IOCTL_LOGGER_SETTINGS, SUP_IOCTL_LOGGER_SETTINGS_SIZE_OUT);
2181 REQ_CHECK_EXPR(SUP_IOCTL_LOGGER_SETTINGS, pReq->Hdr.cbIn >= SUP_IOCTL_LOGGER_SETTINGS_SIZE_IN(1));
2182 cbStrTab = pReq->Hdr.cbIn - SUP_IOCTL_LOGGER_SETTINGS_SIZE_IN(0);
2183 REQ_CHECK_EXPR(SUP_IOCTL_LOGGER_SETTINGS, pReq->u.In.offGroups < cbStrTab);
2184 REQ_CHECK_EXPR(SUP_IOCTL_LOGGER_SETTINGS, pReq->u.In.offFlags < cbStrTab);
2185 REQ_CHECK_EXPR(SUP_IOCTL_LOGGER_SETTINGS, pReq->u.In.offDestination < cbStrTab);
2186 REQ_CHECK_EXPR_FMT(pReq->u.In.szStrings[cbStrTab - 1] == '\0',
2187 ("SUP_IOCTL_LOGGER_SETTINGS: cbIn=%#x cbStrTab=%#zx LastChar=%d\n",
2188 pReq->Hdr.cbIn, cbStrTab, pReq->u.In.szStrings[cbStrTab - 1]));
2189 REQ_CHECK_EXPR(SUP_IOCTL_LOGGER_SETTINGS, pReq->u.In.fWhich <= SUPLOGGERSETTINGS_WHICH_RELEASE);
2190 REQ_CHECK_EXPR(SUP_IOCTL_LOGGER_SETTINGS, pReq->u.In.fWhat <= SUPLOGGERSETTINGS_WHAT_DESTROY);
2191
2192 /* execute */
2193 pReq->Hdr.rc = supdrvIOCtl_LoggerSettings(pReq);
2194 return 0;
2195 }
2196
2197 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_SEM_OP2):
2198 {
2199 /* validate */
2200 PSUPSEMOP2 pReq = (PSUPSEMOP2)pReqHdr;
2201 REQ_CHECK_SIZES_EX(SUP_IOCTL_SEM_OP2, SUP_IOCTL_SEM_OP2_SIZE_IN, SUP_IOCTL_SEM_OP2_SIZE_OUT);
2202 REQ_CHECK_EXPR(SUP_IOCTL_SEM_OP2, pReq->u.In.uReserved == 0);
2203
2204 /* execute */
2205 switch (pReq->u.In.uType)
2206 {
2207 case SUP_SEM_TYPE_EVENT:
2208 {
2209 SUPSEMEVENT hEvent = (SUPSEMEVENT)(uintptr_t)pReq->u.In.hSem;
2210 switch (pReq->u.In.uOp)
2211 {
2212 case SUPSEMOP2_WAIT_MS_REL:
2213 pReq->Hdr.rc = SUPSemEventWaitNoResume(pSession, hEvent, pReq->u.In.uArg.cRelMsTimeout);
2214 break;
2215 case SUPSEMOP2_WAIT_NS_ABS:
2216 pReq->Hdr.rc = SUPSemEventWaitNsAbsIntr(pSession, hEvent, pReq->u.In.uArg.uAbsNsTimeout);
2217 break;
2218 case SUPSEMOP2_WAIT_NS_REL:
2219 pReq->Hdr.rc = SUPSemEventWaitNsRelIntr(pSession, hEvent, pReq->u.In.uArg.cRelNsTimeout);
2220 break;
2221 case SUPSEMOP2_SIGNAL:
2222 pReq->Hdr.rc = SUPSemEventSignal(pSession, hEvent);
2223 break;
2224 case SUPSEMOP2_CLOSE:
2225 pReq->Hdr.rc = SUPSemEventClose(pSession, hEvent);
2226 break;
2227 case SUPSEMOP2_RESET:
2228 default:
2229 pReq->Hdr.rc = VERR_INVALID_FUNCTION;
2230 break;
2231 }
2232 break;
2233 }
2234
2235 case SUP_SEM_TYPE_EVENT_MULTI:
2236 {
2237 SUPSEMEVENTMULTI hEventMulti = (SUPSEMEVENTMULTI)(uintptr_t)pReq->u.In.hSem;
2238 switch (pReq->u.In.uOp)
2239 {
2240 case SUPSEMOP2_WAIT_MS_REL:
2241 pReq->Hdr.rc = SUPSemEventMultiWaitNoResume(pSession, hEventMulti, pReq->u.In.uArg.cRelMsTimeout);
2242 break;
2243 case SUPSEMOP2_WAIT_NS_ABS:
2244 pReq->Hdr.rc = SUPSemEventMultiWaitNsAbsIntr(pSession, hEventMulti, pReq->u.In.uArg.uAbsNsTimeout);
2245 break;
2246 case SUPSEMOP2_WAIT_NS_REL:
2247 pReq->Hdr.rc = SUPSemEventMultiWaitNsRelIntr(pSession, hEventMulti, pReq->u.In.uArg.cRelNsTimeout);
2248 break;
2249 case SUPSEMOP2_SIGNAL:
2250 pReq->Hdr.rc = SUPSemEventMultiSignal(pSession, hEventMulti);
2251 break;
2252 case SUPSEMOP2_CLOSE:
2253 pReq->Hdr.rc = SUPSemEventMultiClose(pSession, hEventMulti);
2254 break;
2255 case SUPSEMOP2_RESET:
2256 pReq->Hdr.rc = SUPSemEventMultiReset(pSession, hEventMulti);
2257 break;
2258 default:
2259 pReq->Hdr.rc = VERR_INVALID_FUNCTION;
2260 break;
2261 }
2262 break;
2263 }
2264
2265 default:
2266 pReq->Hdr.rc = VERR_INVALID_PARAMETER;
2267 break;
2268 }
2269 return 0;
2270 }
2271
2272 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_SEM_OP3):
2273 {
2274 /* validate */
2275 PSUPSEMOP3 pReq = (PSUPSEMOP3)pReqHdr;
2276 REQ_CHECK_SIZES_EX(SUP_IOCTL_SEM_OP3, SUP_IOCTL_SEM_OP3_SIZE_IN, SUP_IOCTL_SEM_OP3_SIZE_OUT);
2277 REQ_CHECK_EXPR(SUP_IOCTL_SEM_OP3, pReq->u.In.u32Reserved == 0 && pReq->u.In.u64Reserved == 0);
2278
2279 /* execute */
2280 switch (pReq->u.In.uType)
2281 {
2282 case SUP_SEM_TYPE_EVENT:
2283 {
2284 SUPSEMEVENT hEvent = (SUPSEMEVENT)(uintptr_t)pReq->u.In.hSem;
2285 switch (pReq->u.In.uOp)
2286 {
2287 case SUPSEMOP3_CREATE:
2288 REQ_CHECK_EXPR(SUP_IOCTL_SEM_OP3, hEvent == NIL_SUPSEMEVENT);
2289 pReq->Hdr.rc = SUPSemEventCreate(pSession, &hEvent);
2290 pReq->u.Out.hSem = (uint32_t)(uintptr_t)hEvent;
2291 break;
2292 case SUPSEMOP3_GET_RESOLUTION:
2293 REQ_CHECK_EXPR(SUP_IOCTL_SEM_OP3, hEvent == NIL_SUPSEMEVENT);
2294 pReq->Hdr.rc = VINF_SUCCESS;
2295 pReq->Hdr.cbOut = sizeof(*pReq);
2296 pReq->u.Out.cNsResolution = SUPSemEventGetResolution(pSession);
2297 break;
2298 default:
2299 pReq->Hdr.rc = VERR_INVALID_FUNCTION;
2300 break;
2301 }
2302 break;
2303 }
2304
2305 case SUP_SEM_TYPE_EVENT_MULTI:
2306 {
2307 SUPSEMEVENTMULTI hEventMulti = (SUPSEMEVENTMULTI)(uintptr_t)pReq->u.In.hSem;
2308 switch (pReq->u.In.uOp)
2309 {
2310 case SUPSEMOP3_CREATE:
2311 REQ_CHECK_EXPR(SUP_IOCTL_SEM_OP3, hEventMulti == NIL_SUPSEMEVENTMULTI);
2312 pReq->Hdr.rc = SUPSemEventMultiCreate(pSession, &hEventMulti);
2313 pReq->u.Out.hSem = (uint32_t)(uintptr_t)hEventMulti;
2314 break;
2315 case SUPSEMOP3_GET_RESOLUTION:
2316 REQ_CHECK_EXPR(SUP_IOCTL_SEM_OP3, hEventMulti == NIL_SUPSEMEVENTMULTI);
2317 pReq->Hdr.rc = VINF_SUCCESS;
2318 pReq->u.Out.cNsResolution = SUPSemEventMultiGetResolution(pSession);
2319 break;
2320 default:
2321 pReq->Hdr.rc = VERR_INVALID_FUNCTION;
2322 break;
2323 }
2324 break;
2325 }
2326
2327 default:
2328 pReq->Hdr.rc = VERR_INVALID_PARAMETER;
2329 break;
2330 }
2331 return 0;
2332 }
2333
2334 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_VT_CAPS):
2335 {
2336 /* validate */
2337 PSUPVTCAPS pReq = (PSUPVTCAPS)pReqHdr;
2338 REQ_CHECK_SIZES(SUP_IOCTL_VT_CAPS);
2339
2340 /* execute */
2341 pReq->Hdr.rc = SUPR0QueryVTCaps(pSession, &pReq->u.Out.fCaps);
2342 if (RT_FAILURE(pReq->Hdr.rc))
2343 pReq->Hdr.cbOut = sizeof(pReq->Hdr);
2344 return 0;
2345 }
2346
2347 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_TRACER_OPEN):
2348 {
2349 /* validate */
2350 PSUPTRACEROPEN pReq = (PSUPTRACEROPEN)pReqHdr;
2351 REQ_CHECK_SIZES(SUP_IOCTL_TRACER_OPEN);
2352
2353 /* execute */
2354 pReq->Hdr.rc = supdrvIOCtl_TracerOpen(pDevExt, pSession, pReq->u.In.uCookie, pReq->u.In.uArg);
2355 return 0;
2356 }
2357
2358 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_TRACER_CLOSE):
2359 {
2360 /* validate */
2361 REQ_CHECK_SIZES(SUP_IOCTL_TRACER_CLOSE);
2362
2363 /* execute */
2364 pReqHdr->rc = supdrvIOCtl_TracerClose(pDevExt, pSession);
2365 return 0;
2366 }
2367
2368 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_TRACER_IOCTL):
2369 {
2370 /* validate */
2371 PSUPTRACERIOCTL pReq = (PSUPTRACERIOCTL)pReqHdr;
2372 REQ_CHECK_SIZES(SUP_IOCTL_TRACER_IOCTL);
2373
2374 /* execute */
2375 pReqHdr->rc = supdrvIOCtl_TracerIOCtl(pDevExt, pSession, pReq->u.In.uCmd, pReq->u.In.uArg, &pReq->u.Out.iRetVal);
2376 return 0;
2377 }
2378
2379 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_TRACER_UMOD_REG):
2380 {
2381 /* validate */
2382 PSUPTRACERUMODREG pReq = (PSUPTRACERUMODREG)pReqHdr;
2383 REQ_CHECK_SIZES(SUP_IOCTL_TRACER_UMOD_REG);
2384 if (!RTStrEnd(pReq->u.In.szName, sizeof(pReq->u.In.szName)))
2385 return VERR_INVALID_PARAMETER;
2386
2387 /* execute */
2388 pReqHdr->rc = supdrvIOCtl_TracerUmodRegister(pDevExt, pSession,
2389 pReq->u.In.R3PtrVtgHdr, pReq->u.In.uVtgHdrAddr,
2390 pReq->u.In.R3PtrStrTab, pReq->u.In.cbStrTab,
2391 pReq->u.In.szName, pReq->u.In.fFlags);
2392 return 0;
2393 }
2394
2395 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_TRACER_UMOD_DEREG):
2396 {
2397 /* validate */
2398 PSUPTRACERUMODDEREG pReq = (PSUPTRACERUMODDEREG)pReqHdr;
2399 REQ_CHECK_SIZES(SUP_IOCTL_TRACER_UMOD_DEREG);
2400
2401 /* execute */
2402 pReqHdr->rc = supdrvIOCtl_TracerUmodDeregister(pDevExt, pSession, pReq->u.In.pVtgHdr);
2403 return 0;
2404 }
2405
2406 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_TRACER_UMOD_FIRE_PROBE):
2407 {
2408 /* validate */
2409 PSUPTRACERUMODFIREPROBE pReq = (PSUPTRACERUMODFIREPROBE)pReqHdr;
2410 REQ_CHECK_SIZES(SUP_IOCTL_TRACER_UMOD_FIRE_PROBE);
2411
2412 supdrvIOCtl_TracerUmodProbeFire(pDevExt, pSession, &pReq->u.In);
2413 pReqHdr->rc = VINF_SUCCESS;
2414 return 0;
2415 }
2416
2417 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_MSR_PROBER):
2418 {
2419 /* validate */
2420 PSUPMSRPROBER pReq = (PSUPMSRPROBER)pReqHdr;
2421 REQ_CHECK_SIZES(SUP_IOCTL_MSR_PROBER);
2422 REQ_CHECK_EXPR(SUP_IOCTL_MSR_PROBER,
2423 pReq->u.In.enmOp > SUPMSRPROBEROP_INVALID && pReq->u.In.enmOp < SUPMSRPROBEROP_END);
2424
2425 pReqHdr->rc = supdrvIOCtl_MsrProber(pDevExt, pReq);
2426 return 0;
2427 }
2428
2429 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_RESUME_SUSPENDED_KBDS):
2430 {
2431 /* validate */
2432 REQ_CHECK_SIZES(SUP_IOCTL_RESUME_SUSPENDED_KBDS);
2433
2434 pReqHdr->rc = supdrvIOCtl_ResumeSuspendedKbds();
2435 return 0;
2436 }
2437
2438 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_TSC_DELTA_MEASURE):
2439 {
2440 /* validate */
2441 PSUPTSCDELTAMEASURE pReq = (PSUPTSCDELTAMEASURE)pReqHdr;
2442 REQ_CHECK_SIZES(SUP_IOCTL_TSC_DELTA_MEASURE);
2443
2444 pReqHdr->rc = supdrvIOCtl_TscDeltaMeasure(pDevExt, pSession, pReq);
2445 return 0;
2446 }
2447
2448 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_TSC_READ):
2449 {
2450 /* validate */
2451 PSUPTSCREAD pReq = (PSUPTSCREAD)pReqHdr;
2452 REQ_CHECK_SIZES(SUP_IOCTL_TSC_READ);
2453
2454 pReqHdr->rc = supdrvIOCtl_TscRead(pDevExt, pSession, pReq);
2455 return 0;
2456 }
2457
2458 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_GIP_SET_FLAGS):
2459 {
2460 /* validate */
2461 PSUPGIPSETFLAGS pReq = (PSUPGIPSETFLAGS)pReqHdr;
2462 REQ_CHECK_SIZES(SUP_IOCTL_GIP_SET_FLAGS);
2463
2464 pReqHdr->rc = supdrvIOCtl_GipSetFlags(pDevExt, pSession, pReq->u.In.fOrMask, pReq->u.In.fAndMask);
2465 return 0;
2466 }
2467
2468 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_UCODE_REV):
2469 {
2470 /* validate */
2471 PSUPUCODEREV pReq = (PSUPUCODEREV)pReqHdr;
2472 REQ_CHECK_SIZES(SUP_IOCTL_UCODE_REV);
2473
2474 /* execute */
2475 pReq->Hdr.rc = SUPR0QueryUcodeRev(pSession, &pReq->u.Out.MicrocodeRev);
2476 if (RT_FAILURE(pReq->Hdr.rc))
2477 pReq->Hdr.cbOut = sizeof(pReq->Hdr);
2478 return 0;
2479 }
2480
2481 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_GET_HWVIRT_MSRS):
2482 {
2483 /* validate */
2484 PSUPGETHWVIRTMSRS pReq = (PSUPGETHWVIRTMSRS)pReqHdr;
2485 REQ_CHECK_SIZES(SUP_IOCTL_GET_HWVIRT_MSRS);
2486 REQ_CHECK_EXPR_FMT(!pReq->u.In.fReserved0 && !pReq->u.In.fReserved1 && !pReq->u.In.fReserved2,
2487 ("SUP_IOCTL_GET_HWVIRT_MSRS: fReserved0=%d fReserved1=%d fReserved2=%d\n", pReq->u.In.fReserved0,
2488 pReq->u.In.fReserved1, pReq->u.In.fReserved2));
2489
2490 /* execute */
2491 pReq->Hdr.rc = SUPR0GetHwvirtMsrs(&pReq->u.Out.HwvirtMsrs, 0 /* fCaps */, pReq->u.In.fForce);
2492 if (RT_FAILURE(pReq->Hdr.rc))
2493 pReq->Hdr.cbOut = sizeof(pReq->Hdr);
2494 return 0;
2495 }
2496
2497 default:
2498 Log(("Unknown IOCTL %#lx\n", (long)uIOCtl));
2499 break;
2500 }
2501 return VERR_GENERAL_FAILURE;
2502}
2503
2504
2505/**
2506 * I/O Control inner worker for the restricted operations.
2507 *
2508 * @returns IPRT status code.
2509 * @retval VERR_INVALID_PARAMETER if the request is invalid.
2510 *
2511 * @param uIOCtl Function number.
2512 * @param pDevExt Device extention.
2513 * @param pSession Session data.
2514 * @param pReqHdr The request header.
2515 */
2516static int supdrvIOCtlInnerRestricted(uintptr_t uIOCtl, PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPREQHDR pReqHdr)
2517{
2518 /*
2519 * The switch.
2520 */
2521 switch (SUP_CTL_CODE_NO_SIZE(uIOCtl))
2522 {
2523 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_COOKIE):
2524 {
2525 PSUPCOOKIE pReq = (PSUPCOOKIE)pReqHdr;
2526 REQ_CHECK_SIZES(SUP_IOCTL_COOKIE);
2527 if (strncmp(pReq->u.In.szMagic, SUPCOOKIE_MAGIC, sizeof(pReq->u.In.szMagic)))
2528 {
2529 OSDBGPRINT(("SUP_IOCTL_COOKIE: invalid magic %.16s\n", pReq->u.In.szMagic));
2530 pReq->Hdr.rc = VERR_INVALID_MAGIC;
2531 return 0;
2532 }
2533
2534 /*
2535 * Match the version.
2536 * The current logic is very simple, match the major interface version.
2537 */
2538 if ( pReq->u.In.u32MinVersion > SUPDRV_IOC_VERSION
2539 || (pReq->u.In.u32MinVersion & 0xffff0000) != (SUPDRV_IOC_VERSION & 0xffff0000))
2540 {
2541 OSDBGPRINT(("SUP_IOCTL_COOKIE: Version mismatch. Requested: %#x Min: %#x Current: %#x\n",
2542 pReq->u.In.u32ReqVersion, pReq->u.In.u32MinVersion, SUPDRV_IOC_VERSION));
2543 pReq->u.Out.u32Cookie = 0xffffffff;
2544 pReq->u.Out.u32SessionCookie = 0xffffffff;
2545 pReq->u.Out.u32SessionVersion = 0xffffffff;
2546 pReq->u.Out.u32DriverVersion = SUPDRV_IOC_VERSION;
2547 pReq->u.Out.pSession = NULL;
2548 pReq->u.Out.cFunctions = 0;
2549 pReq->Hdr.rc = VERR_VERSION_MISMATCH;
2550 return 0;
2551 }
2552
2553 /*
2554 * Fill in return data and be gone.
2555 * N.B. The first one to change SUPDRV_IOC_VERSION shall makes sure that
2556 * u32SessionVersion <= u32ReqVersion!
2557 */
2558 /** @todo Somehow validate the client and negotiate a secure cookie... */
2559 pReq->u.Out.u32Cookie = pDevExt->u32Cookie;
2560 pReq->u.Out.u32SessionCookie = pSession->u32Cookie;
2561 pReq->u.Out.u32SessionVersion = SUPDRV_IOC_VERSION;
2562 pReq->u.Out.u32DriverVersion = SUPDRV_IOC_VERSION;
2563 pReq->u.Out.pSession = pSession;
2564 pReq->u.Out.cFunctions = 0;
2565 pReq->Hdr.rc = VINF_SUCCESS;
2566 return 0;
2567 }
2568
2569 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_VT_CAPS):
2570 {
2571 /* validate */
2572 PSUPVTCAPS pReq = (PSUPVTCAPS)pReqHdr;
2573 REQ_CHECK_SIZES(SUP_IOCTL_VT_CAPS);
2574
2575 /* execute */
2576 pReq->Hdr.rc = SUPR0QueryVTCaps(pSession, &pReq->u.Out.fCaps);
2577 if (RT_FAILURE(pReq->Hdr.rc))
2578 pReq->Hdr.cbOut = sizeof(pReq->Hdr);
2579 return 0;
2580 }
2581
2582 default:
2583 Log(("Unknown IOCTL %#lx\n", (long)uIOCtl));
2584 break;
2585 }
2586 return VERR_GENERAL_FAILURE;
2587}
2588
2589
2590/**
2591 * I/O Control worker.
2592 *
2593 * @returns IPRT status code.
2594 * @retval VERR_INVALID_PARAMETER if the request is invalid.
2595 *
2596 * @param uIOCtl Function number.
2597 * @param pDevExt Device extention.
2598 * @param pSession Session data.
2599 * @param pReqHdr The request header.
2600 * @param cbReq The size of the request buffer.
2601 */
2602int VBOXCALL supdrvIOCtl(uintptr_t uIOCtl, PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPREQHDR pReqHdr, size_t cbReq)
2603{
2604 int rc;
2605 VBOXDRV_IOCTL_ENTRY(pSession, uIOCtl, pReqHdr);
2606
2607 /*
2608 * Validate the request.
2609 */
2610 if (RT_UNLIKELY(cbReq < sizeof(*pReqHdr)))
2611 {
2612 OSDBGPRINT(("vboxdrv: Bad ioctl request size; cbReq=%#lx\n", (long)cbReq));
2613 VBOXDRV_IOCTL_RETURN(pSession, uIOCtl, pReqHdr, VERR_INVALID_PARAMETER, VINF_SUCCESS);
2614 return VERR_INVALID_PARAMETER;
2615 }
2616 if (RT_UNLIKELY( (pReqHdr->fFlags & SUPREQHDR_FLAGS_MAGIC_MASK) != SUPREQHDR_FLAGS_MAGIC
2617 || pReqHdr->cbIn < sizeof(*pReqHdr)
2618 || pReqHdr->cbIn > cbReq
2619 || pReqHdr->cbOut < sizeof(*pReqHdr)
2620 || pReqHdr->cbOut > cbReq))
2621 {
2622 OSDBGPRINT(("vboxdrv: Bad ioctl request header; cbIn=%#lx cbOut=%#lx fFlags=%#lx\n",
2623 (long)pReqHdr->cbIn, (long)pReqHdr->cbOut, (long)pReqHdr->fFlags));
2624 VBOXDRV_IOCTL_RETURN(pSession, uIOCtl, pReqHdr, VERR_INVALID_PARAMETER, VINF_SUCCESS);
2625 return VERR_INVALID_PARAMETER;
2626 }
2627 if (RT_UNLIKELY(!RT_VALID_PTR(pSession)))
2628 {
2629 OSDBGPRINT(("vboxdrv: Invalid pSession value %p (ioctl=%p)\n", pSession, (void *)uIOCtl));
2630 VBOXDRV_IOCTL_RETURN(pSession, uIOCtl, pReqHdr, VERR_INVALID_PARAMETER, VINF_SUCCESS);
2631 return VERR_INVALID_PARAMETER;
2632 }
2633 if (RT_UNLIKELY(uIOCtl == SUP_IOCTL_COOKIE))
2634 {
2635 if (pReqHdr->u32Cookie != SUPCOOKIE_INITIAL_COOKIE)
2636 {
2637 OSDBGPRINT(("SUP_IOCTL_COOKIE: bad cookie %#lx\n", (long)pReqHdr->u32Cookie));
2638 VBOXDRV_IOCTL_RETURN(pSession, uIOCtl, pReqHdr, VERR_INVALID_PARAMETER, VINF_SUCCESS);
2639 return VERR_INVALID_PARAMETER;
2640 }
2641 }
2642 else if (RT_UNLIKELY( pReqHdr->u32Cookie != pDevExt->u32Cookie
2643 || pReqHdr->u32SessionCookie != pSession->u32Cookie))
2644 {
2645 OSDBGPRINT(("vboxdrv: bad cookie %#lx / %#lx.\n", (long)pReqHdr->u32Cookie, (long)pReqHdr->u32SessionCookie));
2646 VBOXDRV_IOCTL_RETURN(pSession, uIOCtl, pReqHdr, VERR_INVALID_PARAMETER, VINF_SUCCESS);
2647 return VERR_INVALID_PARAMETER;
2648 }
2649
2650 /*
2651 * Hand it to an inner function to avoid lots of unnecessary return tracepoints.
2652 */
2653 if (pSession->fUnrestricted)
2654 rc = supdrvIOCtlInnerUnrestricted(uIOCtl, pDevExt, pSession, pReqHdr);
2655 else
2656 rc = supdrvIOCtlInnerRestricted(uIOCtl, pDevExt, pSession, pReqHdr);
2657
2658 VBOXDRV_IOCTL_RETURN(pSession, uIOCtl, pReqHdr, pReqHdr->rc, rc);
2659 return rc;
2660}
2661
2662
2663/**
2664 * Inter-Driver Communication (IDC) worker.
2665 *
2666 * @returns VBox status code.
2667 * @retval VINF_SUCCESS on success.
2668 * @retval VERR_INVALID_PARAMETER if the request is invalid.
2669 * @retval VERR_NOT_SUPPORTED if the request isn't supported.
2670 *
2671 * @param uReq The request (function) code.
2672 * @param pDevExt Device extention.
2673 * @param pSession Session data.
2674 * @param pReqHdr The request header.
2675 */
2676int VBOXCALL supdrvIDC(uintptr_t uReq, PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPDRVIDCREQHDR pReqHdr)
2677{
2678 /*
2679 * The OS specific code has already validated the pSession
2680 * pointer, and the request size being greater or equal to
2681 * size of the header.
2682 *
2683 * So, just check that pSession is a kernel context session.
2684 */
2685 if (RT_UNLIKELY( pSession
2686 && pSession->R0Process != NIL_RTR0PROCESS))
2687 return VERR_INVALID_PARAMETER;
2688
2689/*
2690 * Validation macro.
2691 */
2692#define REQ_CHECK_IDC_SIZE(Name, cbExpect) \
2693 do { \
2694 if (RT_UNLIKELY(pReqHdr->cb != (cbExpect))) \
2695 { \
2696 OSDBGPRINT(( #Name ": Invalid input/output sizes. cb=%ld expected %ld.\n", \
2697 (long)pReqHdr->cb, (long)(cbExpect))); \
2698 return pReqHdr->rc = VERR_INVALID_PARAMETER; \
2699 } \
2700 } while (0)
2701
2702 switch (uReq)
2703 {
2704 case SUPDRV_IDC_REQ_CONNECT:
2705 {
2706 PSUPDRVIDCREQCONNECT pReq = (PSUPDRVIDCREQCONNECT)pReqHdr;
2707 REQ_CHECK_IDC_SIZE(SUPDRV_IDC_REQ_CONNECT, sizeof(*pReq));
2708
2709 /*
2710 * Validate the cookie and other input.
2711 */
2712 if (pReq->Hdr.pSession != NULL)
2713 {
2714 OSDBGPRINT(("SUPDRV_IDC_REQ_CONNECT: Hdr.pSession=%p expected NULL!\n", pReq->Hdr.pSession));
2715 return pReqHdr->rc = VERR_INVALID_PARAMETER;
2716 }
2717 if (pReq->u.In.u32MagicCookie != SUPDRVIDCREQ_CONNECT_MAGIC_COOKIE)
2718 {
2719 OSDBGPRINT(("SUPDRV_IDC_REQ_CONNECT: u32MagicCookie=%#x expected %#x!\n",
2720 (unsigned)pReq->u.In.u32MagicCookie, (unsigned)SUPDRVIDCREQ_CONNECT_MAGIC_COOKIE));
2721 return pReqHdr->rc = VERR_INVALID_PARAMETER;
2722 }
2723 if ( pReq->u.In.uMinVersion > pReq->u.In.uReqVersion
2724 || (pReq->u.In.uMinVersion & UINT32_C(0xffff0000)) != (pReq->u.In.uReqVersion & UINT32_C(0xffff0000)))
2725 {
2726 OSDBGPRINT(("SUPDRV_IDC_REQ_CONNECT: uMinVersion=%#x uMaxVersion=%#x doesn't match!\n",
2727 pReq->u.In.uMinVersion, pReq->u.In.uReqVersion));
2728 return pReqHdr->rc = VERR_INVALID_PARAMETER;
2729 }
2730 if (pSession != NULL)
2731 {
2732 OSDBGPRINT(("SUPDRV_IDC_REQ_CONNECT: pSession=%p expected NULL!\n", pSession));
2733 return pReqHdr->rc = VERR_INVALID_PARAMETER;
2734 }
2735
2736 /*
2737 * Match the version.
2738 * The current logic is very simple, match the major interface version.
2739 */
2740 if ( pReq->u.In.uMinVersion > SUPDRV_IDC_VERSION
2741 || (pReq->u.In.uMinVersion & 0xffff0000) != (SUPDRV_IDC_VERSION & 0xffff0000))
2742 {
2743 OSDBGPRINT(("SUPDRV_IDC_REQ_CONNECT: Version mismatch. Requested: %#x Min: %#x Current: %#x\n",
2744 pReq->u.In.uReqVersion, pReq->u.In.uMinVersion, (unsigned)SUPDRV_IDC_VERSION));
2745 pReq->u.Out.pSession = NULL;
2746 pReq->u.Out.uSessionVersion = 0xffffffff;
2747 pReq->u.Out.uDriverVersion = SUPDRV_IDC_VERSION;
2748 pReq->u.Out.uDriverRevision = VBOX_SVN_REV;
2749 pReq->Hdr.rc = VERR_VERSION_MISMATCH;
2750 return VINF_SUCCESS;
2751 }
2752
2753 pReq->u.Out.pSession = NULL;
2754 pReq->u.Out.uSessionVersion = SUPDRV_IDC_VERSION;
2755 pReq->u.Out.uDriverVersion = SUPDRV_IDC_VERSION;
2756 pReq->u.Out.uDriverRevision = VBOX_SVN_REV;
2757
2758 pReq->Hdr.rc = supdrvCreateSession(pDevExt, false /* fUser */, true /*fUnrestricted*/, &pSession);
2759 if (RT_FAILURE(pReq->Hdr.rc))
2760 {
2761 OSDBGPRINT(("SUPDRV_IDC_REQ_CONNECT: failed to create session, rc=%d\n", pReq->Hdr.rc));
2762 return VINF_SUCCESS;
2763 }
2764
2765 pReq->u.Out.pSession = pSession;
2766 pReq->Hdr.pSession = pSession;
2767
2768 return VINF_SUCCESS;
2769 }
2770
2771 case SUPDRV_IDC_REQ_DISCONNECT:
2772 {
2773 REQ_CHECK_IDC_SIZE(SUPDRV_IDC_REQ_DISCONNECT, sizeof(*pReqHdr));
2774
2775 supdrvSessionRelease(pSession);
2776 return pReqHdr->rc = VINF_SUCCESS;
2777 }
2778
2779 case SUPDRV_IDC_REQ_GET_SYMBOL:
2780 {
2781 PSUPDRVIDCREQGETSYM pReq = (PSUPDRVIDCREQGETSYM)pReqHdr;
2782 REQ_CHECK_IDC_SIZE(SUPDRV_IDC_REQ_GET_SYMBOL, sizeof(*pReq));
2783
2784 pReq->Hdr.rc = supdrvIDC_LdrGetSymbol(pDevExt, pSession, pReq);
2785 return VINF_SUCCESS;
2786 }
2787
2788 case SUPDRV_IDC_REQ_COMPONENT_REGISTER_FACTORY:
2789 {
2790 PSUPDRVIDCREQCOMPREGFACTORY pReq = (PSUPDRVIDCREQCOMPREGFACTORY)pReqHdr;
2791 REQ_CHECK_IDC_SIZE(SUPDRV_IDC_REQ_COMPONENT_REGISTER_FACTORY, sizeof(*pReq));
2792
2793 pReq->Hdr.rc = SUPR0ComponentRegisterFactory(pSession, pReq->u.In.pFactory);
2794 return VINF_SUCCESS;
2795 }
2796
2797 case SUPDRV_IDC_REQ_COMPONENT_DEREGISTER_FACTORY:
2798 {
2799 PSUPDRVIDCREQCOMPDEREGFACTORY pReq = (PSUPDRVIDCREQCOMPDEREGFACTORY)pReqHdr;
2800 REQ_CHECK_IDC_SIZE(SUPDRV_IDC_REQ_COMPONENT_DEREGISTER_FACTORY, sizeof(*pReq));
2801
2802 pReq->Hdr.rc = SUPR0ComponentDeregisterFactory(pSession, pReq->u.In.pFactory);
2803 return VINF_SUCCESS;
2804 }
2805
2806 default:
2807 Log(("Unknown IDC %#lx\n", (long)uReq));
2808 break;
2809 }
2810
2811#undef REQ_CHECK_IDC_SIZE
2812 return VERR_NOT_SUPPORTED;
2813}
2814
2815
2816/**
2817 * Register a object for reference counting.
2818 * The object is registered with one reference in the specified session.
2819 *
2820 * @returns Unique identifier on success (pointer).
2821 * All future reference must use this identifier.
2822 * @returns NULL on failure.
2823 * @param pSession The caller's session.
2824 * @param enmType The object type.
2825 * @param pfnDestructor The destructore function which will be called when the reference count reaches 0.
2826 * @param pvUser1 The first user argument.
2827 * @param pvUser2 The second user argument.
2828 */
2829SUPR0DECL(void *) SUPR0ObjRegister(PSUPDRVSESSION pSession, SUPDRVOBJTYPE enmType, PFNSUPDRVDESTRUCTOR pfnDestructor, void *pvUser1, void *pvUser2)
2830{
2831 PSUPDRVDEVEXT pDevExt = pSession->pDevExt;
2832 PSUPDRVOBJ pObj;
2833 PSUPDRVUSAGE pUsage;
2834
2835 /*
2836 * Validate the input.
2837 */
2838 AssertReturn(SUP_IS_SESSION_VALID(pSession), NULL);
2839 AssertReturn(enmType > SUPDRVOBJTYPE_INVALID && enmType < SUPDRVOBJTYPE_END, NULL);
2840 AssertPtrReturn(pfnDestructor, NULL);
2841
2842 /*
2843 * Allocate and initialize the object.
2844 */
2845 pObj = (PSUPDRVOBJ)RTMemAlloc(sizeof(*pObj));
2846 if (!pObj)
2847 return NULL;
2848 pObj->u32Magic = SUPDRVOBJ_MAGIC;
2849 pObj->enmType = enmType;
2850 pObj->pNext = NULL;
2851 pObj->cUsage = 1;
2852 pObj->pfnDestructor = pfnDestructor;
2853 pObj->pvUser1 = pvUser1;
2854 pObj->pvUser2 = pvUser2;
2855 pObj->CreatorUid = pSession->Uid;
2856 pObj->CreatorGid = pSession->Gid;
2857 pObj->CreatorProcess= pSession->Process;
2858 supdrvOSObjInitCreator(pObj, pSession);
2859
2860 /*
2861 * Allocate the usage record.
2862 * (We keep freed usage records around to simplify SUPR0ObjAddRefEx().)
2863 */
2864 RTSpinlockAcquire(pDevExt->Spinlock);
2865
2866 pUsage = pDevExt->pUsageFree;
2867 if (pUsage)
2868 pDevExt->pUsageFree = pUsage->pNext;
2869 else
2870 {
2871 RTSpinlockRelease(pDevExt->Spinlock);
2872 pUsage = (PSUPDRVUSAGE)RTMemAlloc(sizeof(*pUsage));
2873 if (!pUsage)
2874 {
2875 RTMemFree(pObj);
2876 return NULL;
2877 }
2878 RTSpinlockAcquire(pDevExt->Spinlock);
2879 }
2880
2881 /*
2882 * Insert the object and create the session usage record.
2883 */
2884 /* The object. */
2885 pObj->pNext = pDevExt->pObjs;
2886 pDevExt->pObjs = pObj;
2887
2888 /* The session record. */
2889 pUsage->cUsage = 1;
2890 pUsage->pObj = pObj;
2891 pUsage->pNext = pSession->pUsage;
2892 /* Log2(("SUPR0ObjRegister: pUsage=%p:{.pObj=%p, .pNext=%p}\n", pUsage, pUsage->pObj, pUsage->pNext)); */
2893 pSession->pUsage = pUsage;
2894
2895 RTSpinlockRelease(pDevExt->Spinlock);
2896
2897 Log(("SUPR0ObjRegister: returns %p (pvUser1=%p, pvUser=%p)\n", pObj, pvUser1, pvUser2));
2898 return pObj;
2899}
2900SUPR0_EXPORT_SYMBOL(SUPR0ObjRegister);
2901
2902
2903/**
2904 * Increment the reference counter for the object associating the reference
2905 * with the specified session.
2906 *
2907 * @returns IPRT status code.
2908 * @param pvObj The identifier returned by SUPR0ObjRegister().
2909 * @param pSession The session which is referencing the object.
2910 *
2911 * @remarks The caller should not own any spinlocks and must carefully protect
2912 * itself against potential race with the destructor so freed memory
2913 * isn't accessed here.
2914 */
2915SUPR0DECL(int) SUPR0ObjAddRef(void *pvObj, PSUPDRVSESSION pSession)
2916{
2917 return SUPR0ObjAddRefEx(pvObj, pSession, false /* fNoBlocking */);
2918}
2919SUPR0_EXPORT_SYMBOL(SUPR0ObjAddRef);
2920
2921
2922/**
2923 * Increment the reference counter for the object associating the reference
2924 * with the specified session.
2925 *
2926 * @returns IPRT status code.
2927 * @retval VERR_TRY_AGAIN if fNoBlocking was set and a new usage record
2928 * couldn't be allocated. (If you see this you're not doing the right
2929 * thing and it won't ever work reliably.)
2930 *
2931 * @param pvObj The identifier returned by SUPR0ObjRegister().
2932 * @param pSession The session which is referencing the object.
2933 * @param fNoBlocking Set if it's not OK to block. Never try to make the
2934 * first reference to an object in a session with this
2935 * argument set.
2936 *
2937 * @remarks The caller should not own any spinlocks and must carefully protect
2938 * itself against potential race with the destructor so freed memory
2939 * isn't accessed here.
2940 */
2941SUPR0DECL(int) SUPR0ObjAddRefEx(void *pvObj, PSUPDRVSESSION pSession, bool fNoBlocking)
2942{
2943 PSUPDRVDEVEXT pDevExt = pSession->pDevExt;
2944 PSUPDRVOBJ pObj = (PSUPDRVOBJ)pvObj;
2945 int rc = VINF_SUCCESS;
2946 PSUPDRVUSAGE pUsagePre;
2947 PSUPDRVUSAGE pUsage;
2948
2949 /*
2950 * Validate the input.
2951 * Be ready for the destruction race (someone might be stuck in the
2952 * destructor waiting a lock we own).
2953 */
2954 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
2955 AssertPtrReturn(pObj, VERR_INVALID_POINTER);
2956 AssertMsgReturn(pObj->u32Magic == SUPDRVOBJ_MAGIC || pObj->u32Magic == SUPDRVOBJ_MAGIC_DEAD,
2957 ("Invalid pvObj=%p magic=%#x (expected %#x or %#x)\n", pvObj, pObj->u32Magic, SUPDRVOBJ_MAGIC, SUPDRVOBJ_MAGIC_DEAD),
2958 VERR_INVALID_PARAMETER);
2959
2960 RTSpinlockAcquire(pDevExt->Spinlock);
2961
2962 if (RT_UNLIKELY(pObj->u32Magic != SUPDRVOBJ_MAGIC))
2963 {
2964 RTSpinlockRelease(pDevExt->Spinlock);
2965
2966 AssertMsgFailed(("pvObj=%p magic=%#x\n", pvObj, pObj->u32Magic));
2967 return VERR_WRONG_ORDER;
2968 }
2969
2970 /*
2971 * Preallocate the usage record if we can.
2972 */
2973 pUsagePre = pDevExt->pUsageFree;
2974 if (pUsagePre)
2975 pDevExt->pUsageFree = pUsagePre->pNext;
2976 else if (!fNoBlocking)
2977 {
2978 RTSpinlockRelease(pDevExt->Spinlock);
2979 pUsagePre = (PSUPDRVUSAGE)RTMemAlloc(sizeof(*pUsagePre));
2980 if (!pUsagePre)
2981 return VERR_NO_MEMORY;
2982
2983 RTSpinlockAcquire(pDevExt->Spinlock);
2984 if (RT_UNLIKELY(pObj->u32Magic != SUPDRVOBJ_MAGIC))
2985 {
2986 RTSpinlockRelease(pDevExt->Spinlock);
2987
2988 AssertMsgFailed(("pvObj=%p magic=%#x\n", pvObj, pObj->u32Magic));
2989 return VERR_WRONG_ORDER;
2990 }
2991 }
2992
2993 /*
2994 * Reference the object.
2995 */
2996 pObj->cUsage++;
2997
2998 /*
2999 * Look for the session record.
3000 */
3001 for (pUsage = pSession->pUsage; pUsage; pUsage = pUsage->pNext)
3002 {
3003 /*Log(("SUPR0AddRef: pUsage=%p:{.pObj=%p, .pNext=%p}\n", pUsage, pUsage->pObj, pUsage->pNext));*/
3004 if (pUsage->pObj == pObj)
3005 break;
3006 }
3007 if (pUsage)
3008 pUsage->cUsage++;
3009 else if (pUsagePre)
3010 {
3011 /* create a new session record. */
3012 pUsagePre->cUsage = 1;
3013 pUsagePre->pObj = pObj;
3014 pUsagePre->pNext = pSession->pUsage;
3015 pSession->pUsage = pUsagePre;
3016 /*Log(("SUPR0AddRef: pUsagePre=%p:{.pObj=%p, .pNext=%p}\n", pUsagePre, pUsagePre->pObj, pUsagePre->pNext));*/
3017
3018 pUsagePre = NULL;
3019 }
3020 else
3021 {
3022 pObj->cUsage--;
3023 rc = VERR_TRY_AGAIN;
3024 }
3025
3026 /*
3027 * Put any unused usage record into the free list..
3028 */
3029 if (pUsagePre)
3030 {
3031 pUsagePre->pNext = pDevExt->pUsageFree;
3032 pDevExt->pUsageFree = pUsagePre;
3033 }
3034
3035 RTSpinlockRelease(pDevExt->Spinlock);
3036
3037 return rc;
3038}
3039SUPR0_EXPORT_SYMBOL(SUPR0ObjAddRefEx);
3040
3041
3042/**
3043 * Decrement / destroy a reference counter record for an object.
3044 *
3045 * The object is uniquely identified by pfnDestructor+pvUser1+pvUser2.
3046 *
3047 * @returns IPRT status code.
3048 * @retval VINF_SUCCESS if not destroyed.
3049 * @retval VINF_OBJECT_DESTROYED if it's destroyed by this release call.
3050 * @retval VERR_INVALID_PARAMETER if the object isn't valid. Will assert in
3051 * string builds.
3052 *
3053 * @param pvObj The identifier returned by SUPR0ObjRegister().
3054 * @param pSession The session which is referencing the object.
3055 */
3056SUPR0DECL(int) SUPR0ObjRelease(void *pvObj, PSUPDRVSESSION pSession)
3057{
3058 PSUPDRVDEVEXT pDevExt = pSession->pDevExt;
3059 PSUPDRVOBJ pObj = (PSUPDRVOBJ)pvObj;
3060 int rc = VERR_INVALID_PARAMETER;
3061 PSUPDRVUSAGE pUsage;
3062 PSUPDRVUSAGE pUsagePrev;
3063
3064 /*
3065 * Validate the input.
3066 */
3067 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
3068 AssertMsgReturn(RT_VALID_PTR(pObj) && pObj->u32Magic == SUPDRVOBJ_MAGIC,
3069 ("Invalid pvObj=%p magic=%#x (expected %#x)\n", pvObj, pObj ? pObj->u32Magic : 0, SUPDRVOBJ_MAGIC),
3070 VERR_INVALID_PARAMETER);
3071
3072 /*
3073 * Acquire the spinlock and look for the usage record.
3074 */
3075 RTSpinlockAcquire(pDevExt->Spinlock);
3076
3077 for (pUsagePrev = NULL, pUsage = pSession->pUsage;
3078 pUsage;
3079 pUsagePrev = pUsage, pUsage = pUsage->pNext)
3080 {
3081 /*Log2(("SUPR0ObjRelease: pUsage=%p:{.pObj=%p, .pNext=%p}\n", pUsage, pUsage->pObj, pUsage->pNext));*/
3082 if (pUsage->pObj == pObj)
3083 {
3084 rc = VINF_SUCCESS;
3085 AssertMsg(pUsage->cUsage >= 1 && pObj->cUsage >= pUsage->cUsage, ("glob %d; sess %d\n", pObj->cUsage, pUsage->cUsage));
3086 if (pUsage->cUsage > 1)
3087 {
3088 pObj->cUsage--;
3089 pUsage->cUsage--;
3090 }
3091 else
3092 {
3093 /*
3094 * Free the session record.
3095 */
3096 if (pUsagePrev)
3097 pUsagePrev->pNext = pUsage->pNext;
3098 else
3099 pSession->pUsage = pUsage->pNext;
3100 pUsage->pNext = pDevExt->pUsageFree;
3101 pDevExt->pUsageFree = pUsage;
3102
3103 /* What about the object? */
3104 if (pObj->cUsage > 1)
3105 pObj->cUsage--;
3106 else
3107 {
3108 /*
3109 * Object is to be destroyed, unlink it.
3110 */
3111 pObj->u32Magic = SUPDRVOBJ_MAGIC_DEAD;
3112 rc = VINF_OBJECT_DESTROYED;
3113 if (pDevExt->pObjs == pObj)
3114 pDevExt->pObjs = pObj->pNext;
3115 else
3116 {
3117 PSUPDRVOBJ pObjPrev;
3118 for (pObjPrev = pDevExt->pObjs; pObjPrev; pObjPrev = pObjPrev->pNext)
3119 if (pObjPrev->pNext == pObj)
3120 {
3121 pObjPrev->pNext = pObj->pNext;
3122 break;
3123 }
3124 Assert(pObjPrev);
3125 }
3126 }
3127 }
3128 break;
3129 }
3130 }
3131
3132 RTSpinlockRelease(pDevExt->Spinlock);
3133
3134 /*
3135 * Call the destructor and free the object if required.
3136 */
3137 if (rc == VINF_OBJECT_DESTROYED)
3138 {
3139 Log(("SUPR0ObjRelease: destroying %p/%d (%p/%p) cpid=%RTproc pid=%RTproc dtor=%p\n",
3140 pObj, pObj->enmType, pObj->pvUser1, pObj->pvUser2, pObj->CreatorProcess, RTProcSelf(), pObj->pfnDestructor));
3141 if (pObj->pfnDestructor)
3142 pObj->pfnDestructor(pObj, pObj->pvUser1, pObj->pvUser2);
3143 RTMemFree(pObj);
3144 }
3145
3146 AssertMsg(pUsage, ("pvObj=%p\n", pvObj));
3147 return rc;
3148}
3149SUPR0_EXPORT_SYMBOL(SUPR0ObjRelease);
3150
3151
3152/**
3153 * Verifies that the current process can access the specified object.
3154 *
3155 * @returns The following IPRT status code:
3156 * @retval VINF_SUCCESS if access was granted.
3157 * @retval VERR_PERMISSION_DENIED if denied access.
3158 * @retval VERR_INVALID_PARAMETER if invalid parameter.
3159 *
3160 * @param pvObj The identifier returned by SUPR0ObjRegister().
3161 * @param pSession The session which wishes to access the object.
3162 * @param pszObjName Object string name. This is optional and depends on the object type.
3163 *
3164 * @remark The caller is responsible for making sure the object isn't removed while
3165 * we're inside this function. If uncertain about this, just call AddRef before calling us.
3166 */
3167SUPR0DECL(int) SUPR0ObjVerifyAccess(void *pvObj, PSUPDRVSESSION pSession, const char *pszObjName)
3168{
3169 PSUPDRVOBJ pObj = (PSUPDRVOBJ)pvObj;
3170 int rc;
3171
3172 /*
3173 * Validate the input.
3174 */
3175 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
3176 AssertMsgReturn(RT_VALID_PTR(pObj) && pObj->u32Magic == SUPDRVOBJ_MAGIC,
3177 ("Invalid pvObj=%p magic=%#x (exepcted %#x)\n", pvObj, pObj ? pObj->u32Magic : 0, SUPDRVOBJ_MAGIC),
3178 VERR_INVALID_PARAMETER);
3179
3180 /*
3181 * Check access. (returns true if a decision has been made.)
3182 */
3183 rc = VERR_INTERNAL_ERROR;
3184 if (supdrvOSObjCanAccess(pObj, pSession, pszObjName, &rc))
3185 return rc;
3186
3187 /*
3188 * Default policy is to allow the user to access his own
3189 * stuff but nothing else.
3190 */
3191 if (pObj->CreatorUid == pSession->Uid)
3192 return VINF_SUCCESS;
3193 return VERR_PERMISSION_DENIED;
3194}
3195SUPR0_EXPORT_SYMBOL(SUPR0ObjVerifyAccess);
3196
3197
3198/**
3199 * API for the VMMR0 module to get the SUPDRVSESSION::pSessionVM member.
3200 *
3201 * @returns The associated VM pointer.
3202 * @param pSession The session of the current thread.
3203 */
3204SUPR0DECL(PVM) SUPR0GetSessionVM(PSUPDRVSESSION pSession)
3205{
3206 AssertReturn(SUP_IS_SESSION_VALID(pSession), NULL);
3207 return pSession->pSessionVM;
3208}
3209SUPR0_EXPORT_SYMBOL(SUPR0GetSessionVM);
3210
3211
3212/**
3213 * API for the VMMR0 module to get the SUPDRVSESSION::pSessionGVM member.
3214 *
3215 * @returns The associated GVM pointer.
3216 * @param pSession The session of the current thread.
3217 */
3218SUPR0DECL(PGVM) SUPR0GetSessionGVM(PSUPDRVSESSION pSession)
3219{
3220 AssertReturn(SUP_IS_SESSION_VALID(pSession), NULL);
3221 return pSession->pSessionGVM;
3222}
3223SUPR0_EXPORT_SYMBOL(SUPR0GetSessionGVM);
3224
3225
3226/**
3227 * API for the VMMR0 module to work the SUPDRVSESSION::pSessionVM member.
3228 *
3229 * This will fail if there is already a VM associated with the session and pVM
3230 * isn't NULL.
3231 *
3232 * @retval VINF_SUCCESS
3233 * @retval VERR_ALREADY_EXISTS if there already is a VM associated with the
3234 * session.
3235 * @retval VERR_INVALID_PARAMETER if only one of the parameters are NULL or if
3236 * the session is invalid.
3237 *
3238 * @param pSession The session of the current thread.
3239 * @param pGVM The GVM to associate with the session. Pass NULL to
3240 * dissassociate.
3241 * @param pVM The VM to associate with the session. Pass NULL to
3242 * dissassociate.
3243 */
3244SUPR0DECL(int) SUPR0SetSessionVM(PSUPDRVSESSION pSession, PGVM pGVM, PVM pVM)
3245{
3246 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
3247 AssertReturn((pGVM != NULL) == (pVM != NULL), VERR_INVALID_PARAMETER);
3248
3249 RTSpinlockAcquire(pSession->pDevExt->Spinlock);
3250 if (pGVM)
3251 {
3252 if (!pSession->pSessionGVM)
3253 {
3254 pSession->pSessionGVM = pGVM;
3255 pSession->pSessionVM = pVM;
3256 pSession->pFastIoCtrlVM = NULL;
3257 }
3258 else
3259 {
3260 RTSpinlockRelease(pSession->pDevExt->Spinlock);
3261 SUPR0Printf("SUPR0SetSessionVM: Unable to associated GVM/VM %p/%p with session %p as it has %p/%p already!\n",
3262 pGVM, pVM, pSession, pSession->pSessionGVM, pSession->pSessionVM);
3263 return VERR_ALREADY_EXISTS;
3264 }
3265 }
3266 else
3267 {
3268 pSession->pSessionGVM = NULL;
3269 pSession->pSessionVM = NULL;
3270 pSession->pFastIoCtrlVM = NULL;
3271 }
3272 RTSpinlockRelease(pSession->pDevExt->Spinlock);
3273 return VINF_SUCCESS;
3274}
3275SUPR0_EXPORT_SYMBOL(SUPR0SetSessionVM);
3276
3277
3278/** @copydoc RTLogDefaultInstanceEx
3279 * @remarks To allow overriding RTLogDefaultInstanceEx locally. */
3280SUPR0DECL(struct RTLOGGER *) SUPR0DefaultLogInstanceEx(uint32_t fFlagsAndGroup)
3281{
3282 return RTLogDefaultInstanceEx(fFlagsAndGroup);
3283}
3284SUPR0_EXPORT_SYMBOL(SUPR0DefaultLogInstanceEx);
3285
3286
3287/** @copydoc RTLogGetDefaultInstanceEx
3288 * @remarks To allow overriding RTLogGetDefaultInstanceEx locally. */
3289SUPR0DECL(struct RTLOGGER *) SUPR0GetDefaultLogInstanceEx(uint32_t fFlagsAndGroup)
3290{
3291 return RTLogGetDefaultInstanceEx(fFlagsAndGroup);
3292}
3293SUPR0_EXPORT_SYMBOL(SUPR0GetDefaultLogInstanceEx);
3294
3295
3296/** @copydoc RTLogRelGetDefaultInstanceEx
3297 * @remarks To allow overriding RTLogRelGetDefaultInstanceEx locally. */
3298SUPR0DECL(struct RTLOGGER *) SUPR0GetDefaultLogRelInstanceEx(uint32_t fFlagsAndGroup)
3299{
3300 return RTLogRelGetDefaultInstanceEx(fFlagsAndGroup);
3301}
3302SUPR0_EXPORT_SYMBOL(SUPR0GetDefaultLogRelInstanceEx);
3303
3304
3305/**
3306 * Lock pages.
3307 *
3308 * @returns IPRT status code.
3309 * @param pSession Session to which the locked memory should be associated.
3310 * @param pvR3 Start of the memory range to lock.
3311 * This must be page aligned.
3312 * @param cPages Number of pages to lock.
3313 * @param paPages Where to put the physical addresses of locked memory.
3314 */
3315SUPR0DECL(int) SUPR0LockMem(PSUPDRVSESSION pSession, RTR3PTR pvR3, uint32_t cPages, PRTHCPHYS paPages)
3316{
3317 int rc;
3318 SUPDRVMEMREF Mem = { NIL_RTR0MEMOBJ, NIL_RTR0MEMOBJ, MEMREF_TYPE_UNUSED };
3319 const size_t cb = (size_t)cPages << PAGE_SHIFT;
3320 LogFlow(("SUPR0LockMem: pSession=%p pvR3=%p cPages=%d paPages=%p\n", pSession, (void *)pvR3, cPages, paPages));
3321
3322 /*
3323 * Verify input.
3324 */
3325 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
3326 AssertPtrReturn(paPages, VERR_INVALID_PARAMETER);
3327 if ( RT_ALIGN_R3PT(pvR3, PAGE_SIZE, RTR3PTR) != pvR3
3328 || !pvR3)
3329 {
3330 Log(("pvR3 (%p) must be page aligned and not NULL!\n", (void *)pvR3));
3331 return VERR_INVALID_PARAMETER;
3332 }
3333
3334 /*
3335 * Let IPRT do the job.
3336 */
3337 Mem.eType = MEMREF_TYPE_LOCKED;
3338 rc = RTR0MemObjLockUser(&Mem.MemObj, pvR3, cb, RTMEM_PROT_READ | RTMEM_PROT_WRITE, NIL_RTR0PROCESS);
3339 if (RT_SUCCESS(rc))
3340 {
3341 uint32_t iPage = cPages;
3342 AssertMsg(RTR0MemObjAddressR3(Mem.MemObj) == pvR3, ("%p == %p\n", RTR0MemObjAddressR3(Mem.MemObj), pvR3));
3343 AssertMsg(RTR0MemObjSize(Mem.MemObj) == cb, ("%x == %x\n", RTR0MemObjSize(Mem.MemObj), cb));
3344
3345 while (iPage-- > 0)
3346 {
3347 paPages[iPage] = RTR0MemObjGetPagePhysAddr(Mem.MemObj, iPage);
3348 if (RT_UNLIKELY(paPages[iPage] == NIL_RTCCPHYS))
3349 {
3350 AssertMsgFailed(("iPage=%d\n", iPage));
3351 rc = VERR_INTERNAL_ERROR;
3352 break;
3353 }
3354 }
3355 if (RT_SUCCESS(rc))
3356 rc = supdrvMemAdd(&Mem, pSession);
3357 if (RT_FAILURE(rc))
3358 {
3359 int rc2 = RTR0MemObjFree(Mem.MemObj, false);
3360 AssertRC(rc2);
3361 }
3362 }
3363
3364 return rc;
3365}
3366SUPR0_EXPORT_SYMBOL(SUPR0LockMem);
3367
3368
3369/**
3370 * Unlocks the memory pointed to by pv.
3371 *
3372 * @returns IPRT status code.
3373 * @param pSession Session to which the memory was locked.
3374 * @param pvR3 Memory to unlock.
3375 */
3376SUPR0DECL(int) SUPR0UnlockMem(PSUPDRVSESSION pSession, RTR3PTR pvR3)
3377{
3378 LogFlow(("SUPR0UnlockMem: pSession=%p pvR3=%p\n", pSession, (void *)pvR3));
3379 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
3380 return supdrvMemRelease(pSession, (RTHCUINTPTR)pvR3, MEMREF_TYPE_LOCKED);
3381}
3382SUPR0_EXPORT_SYMBOL(SUPR0UnlockMem);
3383
3384
3385/**
3386 * Allocates a chunk of page aligned memory with contiguous and fixed physical
3387 * backing.
3388 *
3389 * @returns IPRT status code.
3390 * @param pSession Session data.
3391 * @param cPages Number of pages to allocate.
3392 * @param ppvR0 Where to put the address of Ring-0 mapping the allocated memory.
3393 * @param ppvR3 Where to put the address of Ring-3 mapping the allocated memory.
3394 * @param pHCPhys Where to put the physical address of allocated memory.
3395 */
3396SUPR0DECL(int) SUPR0ContAlloc(PSUPDRVSESSION pSession, uint32_t cPages, PRTR0PTR ppvR0, PRTR3PTR ppvR3, PRTHCPHYS pHCPhys)
3397{
3398 int rc;
3399 SUPDRVMEMREF Mem = { NIL_RTR0MEMOBJ, NIL_RTR0MEMOBJ, MEMREF_TYPE_UNUSED };
3400 LogFlow(("SUPR0ContAlloc: pSession=%p cPages=%d ppvR0=%p ppvR3=%p pHCPhys=%p\n", pSession, cPages, ppvR0, ppvR3, pHCPhys));
3401
3402 /*
3403 * Validate input.
3404 */
3405 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
3406 if (!ppvR3 || !ppvR0 || !pHCPhys)
3407 {
3408 Log(("Null pointer. All of these should be set: pSession=%p ppvR0=%p ppvR3=%p pHCPhys=%p\n",
3409 pSession, ppvR0, ppvR3, pHCPhys));
3410 return VERR_INVALID_PARAMETER;
3411
3412 }
3413 if (cPages < 1 || cPages >= 256)
3414 {
3415 Log(("Illegal request cPages=%d, must be greater than 0 and smaller than 256.\n", cPages));
3416 return VERR_PAGE_COUNT_OUT_OF_RANGE;
3417 }
3418
3419 /*
3420 * Let IPRT do the job.
3421 */
3422 rc = RTR0MemObjAllocCont(&Mem.MemObj, cPages << PAGE_SHIFT, true /* executable R0 mapping */);
3423 if (RT_SUCCESS(rc))
3424 {
3425 int rc2;
3426 rc = RTR0MemObjMapUser(&Mem.MapObjR3, Mem.MemObj, (RTR3PTR)-1, 0,
3427 RTMEM_PROT_EXEC | RTMEM_PROT_WRITE | RTMEM_PROT_READ, NIL_RTR0PROCESS);
3428 if (RT_SUCCESS(rc))
3429 {
3430 Mem.eType = MEMREF_TYPE_CONT;
3431 rc = supdrvMemAdd(&Mem, pSession);
3432 if (!rc)
3433 {
3434 *ppvR0 = RTR0MemObjAddress(Mem.MemObj);
3435 *ppvR3 = RTR0MemObjAddressR3(Mem.MapObjR3);
3436 *pHCPhys = RTR0MemObjGetPagePhysAddr(Mem.MemObj, 0);
3437 return 0;
3438 }
3439
3440 rc2 = RTR0MemObjFree(Mem.MapObjR3, false);
3441 AssertRC(rc2);
3442 }
3443 rc2 = RTR0MemObjFree(Mem.MemObj, false);
3444 AssertRC(rc2);
3445 }
3446
3447 return rc;
3448}
3449SUPR0_EXPORT_SYMBOL(SUPR0ContAlloc);
3450
3451
3452/**
3453 * Frees memory allocated using SUPR0ContAlloc().
3454 *
3455 * @returns IPRT status code.
3456 * @param pSession The session to which the memory was allocated.
3457 * @param uPtr Pointer to the memory (ring-3 or ring-0).
3458 */
3459SUPR0DECL(int) SUPR0ContFree(PSUPDRVSESSION pSession, RTHCUINTPTR uPtr)
3460{
3461 LogFlow(("SUPR0ContFree: pSession=%p uPtr=%p\n", pSession, (void *)uPtr));
3462 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
3463 return supdrvMemRelease(pSession, uPtr, MEMREF_TYPE_CONT);
3464}
3465SUPR0_EXPORT_SYMBOL(SUPR0ContFree);
3466
3467
3468/**
3469 * Allocates a chunk of page aligned memory with fixed physical backing below 4GB.
3470 *
3471 * The memory isn't zeroed.
3472 *
3473 * @returns IPRT status code.
3474 * @param pSession Session data.
3475 * @param cPages Number of pages to allocate.
3476 * @param ppvR0 Where to put the address of Ring-0 mapping of the allocated memory.
3477 * @param ppvR3 Where to put the address of Ring-3 mapping of the allocated memory.
3478 * @param paPages Where to put the physical addresses of allocated memory.
3479 */
3480SUPR0DECL(int) SUPR0LowAlloc(PSUPDRVSESSION pSession, uint32_t cPages, PRTR0PTR ppvR0, PRTR3PTR ppvR3, PRTHCPHYS paPages)
3481{
3482 unsigned iPage;
3483 int rc;
3484 SUPDRVMEMREF Mem = { NIL_RTR0MEMOBJ, NIL_RTR0MEMOBJ, MEMREF_TYPE_UNUSED };
3485 LogFlow(("SUPR0LowAlloc: pSession=%p cPages=%d ppvR3=%p ppvR0=%p paPages=%p\n", pSession, cPages, ppvR3, ppvR0, paPages));
3486
3487 /*
3488 * Validate input.
3489 */
3490 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
3491 if (!ppvR3 || !ppvR0 || !paPages)
3492 {
3493 Log(("Null pointer. All of these should be set: pSession=%p ppvR3=%p ppvR0=%p paPages=%p\n",
3494 pSession, ppvR3, ppvR0, paPages));
3495 return VERR_INVALID_PARAMETER;
3496
3497 }
3498 if (cPages < 1 || cPages >= 256)
3499 {
3500 Log(("Illegal request cPages=%d, must be greater than 0 and smaller than 256.\n", cPages));
3501 return VERR_PAGE_COUNT_OUT_OF_RANGE;
3502 }
3503
3504 /*
3505 * Let IPRT do the work.
3506 */
3507 rc = RTR0MemObjAllocLow(&Mem.MemObj, cPages << PAGE_SHIFT, true /* executable ring-0 mapping */);
3508 if (RT_SUCCESS(rc))
3509 {
3510 int rc2;
3511 rc = RTR0MemObjMapUser(&Mem.MapObjR3, Mem.MemObj, (RTR3PTR)-1, 0,
3512 RTMEM_PROT_EXEC | RTMEM_PROT_WRITE | RTMEM_PROT_READ, NIL_RTR0PROCESS);
3513 if (RT_SUCCESS(rc))
3514 {
3515 Mem.eType = MEMREF_TYPE_LOW;
3516 rc = supdrvMemAdd(&Mem, pSession);
3517 if (!rc)
3518 {
3519 for (iPage = 0; iPage < cPages; iPage++)
3520 {
3521 paPages[iPage] = RTR0MemObjGetPagePhysAddr(Mem.MemObj, iPage);
3522 AssertMsg(!(paPages[iPage] & (PAGE_SIZE - 1)), ("iPage=%d Phys=%RHp\n", paPages[iPage]));
3523 }
3524 *ppvR0 = RTR0MemObjAddress(Mem.MemObj);
3525 *ppvR3 = RTR0MemObjAddressR3(Mem.MapObjR3);
3526 return 0;
3527 }
3528
3529 rc2 = RTR0MemObjFree(Mem.MapObjR3, false);
3530 AssertRC(rc2);
3531 }
3532
3533 rc2 = RTR0MemObjFree(Mem.MemObj, false);
3534 AssertRC(rc2);
3535 }
3536
3537 return rc;
3538}
3539SUPR0_EXPORT_SYMBOL(SUPR0LowAlloc);
3540
3541
3542/**
3543 * Frees memory allocated using SUPR0LowAlloc().
3544 *
3545 * @returns IPRT status code.
3546 * @param pSession The session to which the memory was allocated.
3547 * @param uPtr Pointer to the memory (ring-3 or ring-0).
3548 */
3549SUPR0DECL(int) SUPR0LowFree(PSUPDRVSESSION pSession, RTHCUINTPTR uPtr)
3550{
3551 LogFlow(("SUPR0LowFree: pSession=%p uPtr=%p\n", pSession, (void *)uPtr));
3552 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
3553 return supdrvMemRelease(pSession, uPtr, MEMREF_TYPE_LOW);
3554}
3555SUPR0_EXPORT_SYMBOL(SUPR0LowFree);
3556
3557
3558
3559/**
3560 * Allocates a chunk of memory with both R0 and R3 mappings.
3561 * The memory is fixed and it's possible to query the physical addresses using SUPR0MemGetPhys().
3562 *
3563 * @returns IPRT status code.
3564 * @param pSession The session to associated the allocation with.
3565 * @param cb Number of bytes to allocate.
3566 * @param ppvR0 Where to store the address of the Ring-0 mapping.
3567 * @param ppvR3 Where to store the address of the Ring-3 mapping.
3568 */
3569SUPR0DECL(int) SUPR0MemAlloc(PSUPDRVSESSION pSession, uint32_t cb, PRTR0PTR ppvR0, PRTR3PTR ppvR3)
3570{
3571 int rc;
3572 SUPDRVMEMREF Mem = { NIL_RTR0MEMOBJ, NIL_RTR0MEMOBJ, MEMREF_TYPE_UNUSED };
3573 LogFlow(("SUPR0MemAlloc: pSession=%p cb=%d ppvR0=%p ppvR3=%p\n", pSession, cb, ppvR0, ppvR3));
3574
3575 /*
3576 * Validate input.
3577 */
3578 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
3579 AssertPtrReturn(ppvR0, VERR_INVALID_POINTER);
3580 AssertPtrReturn(ppvR3, VERR_INVALID_POINTER);
3581 if (cb < 1 || cb >= _4M)
3582 {
3583 Log(("Illegal request cb=%u; must be greater than 0 and smaller than 4MB.\n", cb));
3584 return VERR_INVALID_PARAMETER;
3585 }
3586
3587 /*
3588 * Let IPRT do the work.
3589 */
3590 rc = RTR0MemObjAllocPage(&Mem.MemObj, cb, true /* executable ring-0 mapping */);
3591 if (RT_SUCCESS(rc))
3592 {
3593 int rc2;
3594 rc = RTR0MemObjMapUser(&Mem.MapObjR3, Mem.MemObj, (RTR3PTR)-1, 0,
3595 RTMEM_PROT_EXEC | RTMEM_PROT_WRITE | RTMEM_PROT_READ, NIL_RTR0PROCESS);
3596 if (RT_SUCCESS(rc))
3597 {
3598 Mem.eType = MEMREF_TYPE_MEM;
3599 rc = supdrvMemAdd(&Mem, pSession);
3600 if (!rc)
3601 {
3602 *ppvR0 = RTR0MemObjAddress(Mem.MemObj);
3603 *ppvR3 = RTR0MemObjAddressR3(Mem.MapObjR3);
3604 return VINF_SUCCESS;
3605 }
3606
3607 rc2 = RTR0MemObjFree(Mem.MapObjR3, false);
3608 AssertRC(rc2);
3609 }
3610
3611 rc2 = RTR0MemObjFree(Mem.MemObj, false);
3612 AssertRC(rc2);
3613 }
3614
3615 return rc;
3616}
3617SUPR0_EXPORT_SYMBOL(SUPR0MemAlloc);
3618
3619
3620/**
3621 * Get the physical addresses of memory allocated using SUPR0MemAlloc().
3622 *
3623 * @returns IPRT status code.
3624 * @param pSession The session to which the memory was allocated.
3625 * @param uPtr The Ring-0 or Ring-3 address returned by SUPR0MemAlloc().
3626 * @param paPages Where to store the physical addresses.
3627 */
3628SUPR0DECL(int) SUPR0MemGetPhys(PSUPDRVSESSION pSession, RTHCUINTPTR uPtr, PSUPPAGE paPages) /** @todo switch this bugger to RTHCPHYS */
3629{
3630 PSUPDRVBUNDLE pBundle;
3631 LogFlow(("SUPR0MemGetPhys: pSession=%p uPtr=%p paPages=%p\n", pSession, (void *)uPtr, paPages));
3632
3633 /*
3634 * Validate input.
3635 */
3636 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
3637 AssertPtrReturn(paPages, VERR_INVALID_POINTER);
3638 AssertReturn(uPtr, VERR_INVALID_PARAMETER);
3639
3640 /*
3641 * Search for the address.
3642 */
3643 RTSpinlockAcquire(pSession->Spinlock);
3644 for (pBundle = &pSession->Bundle; pBundle; pBundle = pBundle->pNext)
3645 {
3646 if (pBundle->cUsed > 0)
3647 {
3648 unsigned i;
3649 for (i = 0; i < RT_ELEMENTS(pBundle->aMem); i++)
3650 {
3651 if ( pBundle->aMem[i].eType == MEMREF_TYPE_MEM
3652 && pBundle->aMem[i].MemObj != NIL_RTR0MEMOBJ
3653 && ( (RTHCUINTPTR)RTR0MemObjAddress(pBundle->aMem[i].MemObj) == uPtr
3654 || ( pBundle->aMem[i].MapObjR3 != NIL_RTR0MEMOBJ
3655 && RTR0MemObjAddressR3(pBundle->aMem[i].MapObjR3) == uPtr)
3656 )
3657 )
3658 {
3659 const size_t cPages = RTR0MemObjSize(pBundle->aMem[i].MemObj) >> PAGE_SHIFT;
3660 size_t iPage;
3661 for (iPage = 0; iPage < cPages; iPage++)
3662 {
3663 paPages[iPage].Phys = RTR0MemObjGetPagePhysAddr(pBundle->aMem[i].MemObj, iPage);
3664 paPages[iPage].uReserved = 0;
3665 }
3666 RTSpinlockRelease(pSession->Spinlock);
3667 return VINF_SUCCESS;
3668 }
3669 }
3670 }
3671 }
3672 RTSpinlockRelease(pSession->Spinlock);
3673 Log(("Failed to find %p!!!\n", (void *)uPtr));
3674 return VERR_INVALID_PARAMETER;
3675}
3676SUPR0_EXPORT_SYMBOL(SUPR0MemGetPhys);
3677
3678
3679/**
3680 * Free memory allocated by SUPR0MemAlloc().
3681 *
3682 * @returns IPRT status code.
3683 * @param pSession The session owning the allocation.
3684 * @param uPtr The Ring-0 or Ring-3 address returned by SUPR0MemAlloc().
3685 */
3686SUPR0DECL(int) SUPR0MemFree(PSUPDRVSESSION pSession, RTHCUINTPTR uPtr)
3687{
3688 LogFlow(("SUPR0MemFree: pSession=%p uPtr=%p\n", pSession, (void *)uPtr));
3689 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
3690 return supdrvMemRelease(pSession, uPtr, MEMREF_TYPE_MEM);
3691}
3692SUPR0_EXPORT_SYMBOL(SUPR0MemFree);
3693
3694
3695/**
3696 * Allocates a chunk of memory with a kernel or/and a user mode mapping.
3697 *
3698 * The memory is fixed and it's possible to query the physical addresses using
3699 * SUPR0MemGetPhys().
3700 *
3701 * @returns IPRT status code.
3702 * @param pSession The session to associated the allocation with.
3703 * @param cPages The number of pages to allocate.
3704 * @param fFlags Flags, reserved for the future. Must be zero.
3705 * @param ppvR3 Where to store the address of the Ring-3 mapping.
3706 * NULL if no ring-3 mapping.
3707 * @param ppvR0 Where to store the address of the Ring-0 mapping.
3708 * NULL if no ring-0 mapping.
3709 * @param paPages Where to store the addresses of the pages. Optional.
3710 */
3711SUPR0DECL(int) SUPR0PageAllocEx(PSUPDRVSESSION pSession, uint32_t cPages, uint32_t fFlags, PRTR3PTR ppvR3, PRTR0PTR ppvR0, PRTHCPHYS paPages)
3712{
3713 int rc;
3714 SUPDRVMEMREF Mem = { NIL_RTR0MEMOBJ, NIL_RTR0MEMOBJ, MEMREF_TYPE_UNUSED };
3715 LogFlow(("SUPR0PageAlloc: pSession=%p cb=%d ppvR3=%p\n", pSession, cPages, ppvR3));
3716
3717 /*
3718 * Validate input. The allowed allocation size must be at least equal to the maximum guest VRAM size.
3719 */
3720 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
3721 AssertPtrNullReturn(ppvR3, VERR_INVALID_POINTER);
3722 AssertPtrNullReturn(ppvR0, VERR_INVALID_POINTER);
3723 AssertReturn(ppvR3 || ppvR0, VERR_INVALID_PARAMETER);
3724 AssertReturn(!fFlags, VERR_INVALID_PARAMETER);
3725 if (cPages < 1 || cPages > VBOX_MAX_ALLOC_PAGE_COUNT)
3726 {
3727 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)));
3728 return VERR_PAGE_COUNT_OUT_OF_RANGE;
3729 }
3730
3731 /*
3732 * Let IPRT do the work.
3733 */
3734 if (ppvR0)
3735 rc = RTR0MemObjAllocPage(&Mem.MemObj, (size_t)cPages * PAGE_SIZE, true /* fExecutable */);
3736 else
3737 rc = RTR0MemObjAllocPhysNC(&Mem.MemObj, (size_t)cPages * PAGE_SIZE, NIL_RTHCPHYS);
3738 if (RT_SUCCESS(rc))
3739 {
3740 int rc2;
3741 if (ppvR3)
3742 rc = RTR0MemObjMapUser(&Mem.MapObjR3, Mem.MemObj, (RTR3PTR)-1, 0, RTMEM_PROT_WRITE | RTMEM_PROT_READ, NIL_RTR0PROCESS);
3743 else
3744 Mem.MapObjR3 = NIL_RTR0MEMOBJ;
3745 if (RT_SUCCESS(rc))
3746 {
3747 Mem.eType = MEMREF_TYPE_PAGE;
3748 rc = supdrvMemAdd(&Mem, pSession);
3749 if (!rc)
3750 {
3751 if (ppvR3)
3752 *ppvR3 = RTR0MemObjAddressR3(Mem.MapObjR3);
3753 if (ppvR0)
3754 *ppvR0 = RTR0MemObjAddress(Mem.MemObj);
3755 if (paPages)
3756 {
3757 uint32_t iPage = cPages;
3758 while (iPage-- > 0)
3759 {
3760 paPages[iPage] = RTR0MemObjGetPagePhysAddr(Mem.MapObjR3, iPage);
3761 Assert(paPages[iPage] != NIL_RTHCPHYS);
3762 }
3763 }
3764 return VINF_SUCCESS;
3765 }
3766
3767 rc2 = RTR0MemObjFree(Mem.MapObjR3, false);
3768 AssertRC(rc2);
3769 }
3770
3771 rc2 = RTR0MemObjFree(Mem.MemObj, false);
3772 AssertRC(rc2);
3773 }
3774 return rc;
3775}
3776SUPR0_EXPORT_SYMBOL(SUPR0PageAllocEx);
3777
3778
3779/**
3780 * Maps a chunk of memory previously allocated by SUPR0PageAllocEx into kernel
3781 * space.
3782 *
3783 * @returns IPRT status code.
3784 * @param pSession The session to associated the allocation with.
3785 * @param pvR3 The ring-3 address returned by SUPR0PageAllocEx.
3786 * @param offSub Where to start mapping. Must be page aligned.
3787 * @param cbSub How much to map. Must be page aligned.
3788 * @param fFlags Flags, MBZ.
3789 * @param ppvR0 Where to return the address of the ring-0 mapping on
3790 * success.
3791 */
3792SUPR0DECL(int) SUPR0PageMapKernel(PSUPDRVSESSION pSession, RTR3PTR pvR3, uint32_t offSub, uint32_t cbSub,
3793 uint32_t fFlags, PRTR0PTR ppvR0)
3794{
3795 int rc;
3796 PSUPDRVBUNDLE pBundle;
3797 RTR0MEMOBJ hMemObj = NIL_RTR0MEMOBJ;
3798 LogFlow(("SUPR0PageMapKernel: pSession=%p pvR3=%p offSub=%#x cbSub=%#x\n", pSession, pvR3, offSub, cbSub));
3799
3800 /*
3801 * Validate input. The allowed allocation size must be at least equal to the maximum guest VRAM size.
3802 */
3803 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
3804 AssertPtrNullReturn(ppvR0, VERR_INVALID_POINTER);
3805 AssertReturn(!fFlags, VERR_INVALID_PARAMETER);
3806 AssertReturn(!(offSub & PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
3807 AssertReturn(!(cbSub & PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
3808 AssertReturn(cbSub, VERR_INVALID_PARAMETER);
3809
3810 /*
3811 * Find the memory object.
3812 */
3813 RTSpinlockAcquire(pSession->Spinlock);
3814 for (pBundle = &pSession->Bundle; pBundle; pBundle = pBundle->pNext)
3815 {
3816 if (pBundle->cUsed > 0)
3817 {
3818 unsigned i;
3819 for (i = 0; i < RT_ELEMENTS(pBundle->aMem); i++)
3820 {
3821 if ( ( pBundle->aMem[i].eType == MEMREF_TYPE_PAGE
3822 && pBundle->aMem[i].MemObj != NIL_RTR0MEMOBJ
3823 && pBundle->aMem[i].MapObjR3 != NIL_RTR0MEMOBJ
3824 && RTR0MemObjAddressR3(pBundle->aMem[i].MapObjR3) == pvR3)
3825 || ( pBundle->aMem[i].eType == MEMREF_TYPE_LOCKED
3826 && pBundle->aMem[i].MemObj != NIL_RTR0MEMOBJ
3827 && pBundle->aMem[i].MapObjR3 == NIL_RTR0MEMOBJ
3828 && RTR0MemObjAddressR3(pBundle->aMem[i].MemObj) == pvR3))
3829 {
3830 hMemObj = pBundle->aMem[i].MemObj;
3831 break;
3832 }
3833 }
3834 }
3835 }
3836 RTSpinlockRelease(pSession->Spinlock);
3837
3838 rc = VERR_INVALID_PARAMETER;
3839 if (hMemObj != NIL_RTR0MEMOBJ)
3840 {
3841 /*
3842 * Do some further input validations before calling IPRT.
3843 * (Cleanup is done indirectly by telling RTR0MemObjFree to include mappings.)
3844 */
3845 size_t cbMemObj = RTR0MemObjSize(hMemObj);
3846 if ( offSub < cbMemObj
3847 && cbSub <= cbMemObj
3848 && offSub + cbSub <= cbMemObj)
3849 {
3850 RTR0MEMOBJ hMapObj;
3851 rc = RTR0MemObjMapKernelEx(&hMapObj, hMemObj, (void *)-1, 0,
3852 RTMEM_PROT_READ | RTMEM_PROT_WRITE, offSub, cbSub);
3853 if (RT_SUCCESS(rc))
3854 *ppvR0 = RTR0MemObjAddress(hMapObj);
3855 }
3856 else
3857 SUPR0Printf("SUPR0PageMapKernel: cbMemObj=%#x offSub=%#x cbSub=%#x\n", cbMemObj, offSub, cbSub);
3858
3859 }
3860 return rc;
3861}
3862SUPR0_EXPORT_SYMBOL(SUPR0PageMapKernel);
3863
3864
3865/**
3866 * Changes the page level protection of one or more pages previously allocated
3867 * by SUPR0PageAllocEx.
3868 *
3869 * @returns IPRT status code.
3870 * @param pSession The session to associated the allocation with.
3871 * @param pvR3 The ring-3 address returned by SUPR0PageAllocEx.
3872 * NIL_RTR3PTR if the ring-3 mapping should be unaffected.
3873 * @param pvR0 The ring-0 address returned by SUPR0PageAllocEx.
3874 * NIL_RTR0PTR if the ring-0 mapping should be unaffected.
3875 * @param offSub Where to start changing. Must be page aligned.
3876 * @param cbSub How much to change. Must be page aligned.
3877 * @param fProt The new page level protection, see RTMEM_PROT_*.
3878 */
3879SUPR0DECL(int) SUPR0PageProtect(PSUPDRVSESSION pSession, RTR3PTR pvR3, RTR0PTR pvR0, uint32_t offSub, uint32_t cbSub, uint32_t fProt)
3880{
3881 int rc;
3882 PSUPDRVBUNDLE pBundle;
3883 RTR0MEMOBJ hMemObjR0 = NIL_RTR0MEMOBJ;
3884 RTR0MEMOBJ hMemObjR3 = NIL_RTR0MEMOBJ;
3885 LogFlow(("SUPR0PageProtect: pSession=%p pvR3=%p pvR0=%p offSub=%#x cbSub=%#x fProt-%#x\n", pSession, pvR3, pvR0, offSub, cbSub, fProt));
3886
3887 /*
3888 * Validate input. The allowed allocation size must be at least equal to the maximum guest VRAM size.
3889 */
3890 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
3891 AssertReturn(!(fProt & ~(RTMEM_PROT_READ | RTMEM_PROT_WRITE | RTMEM_PROT_EXEC | RTMEM_PROT_NONE)), VERR_INVALID_PARAMETER);
3892 AssertReturn(!(offSub & PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
3893 AssertReturn(!(cbSub & PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
3894 AssertReturn(cbSub, VERR_INVALID_PARAMETER);
3895
3896 /*
3897 * Find the memory object.
3898 */
3899 RTSpinlockAcquire(pSession->Spinlock);
3900 for (pBundle = &pSession->Bundle; pBundle; pBundle = pBundle->pNext)
3901 {
3902 if (pBundle->cUsed > 0)
3903 {
3904 unsigned i;
3905 for (i = 0; i < RT_ELEMENTS(pBundle->aMem); i++)
3906 {
3907 if ( pBundle->aMem[i].eType == MEMREF_TYPE_PAGE
3908 && pBundle->aMem[i].MemObj != NIL_RTR0MEMOBJ
3909 && ( pBundle->aMem[i].MapObjR3 != NIL_RTR0MEMOBJ
3910 || pvR3 == NIL_RTR3PTR)
3911 && ( pvR0 == NIL_RTR0PTR
3912 || RTR0MemObjAddress(pBundle->aMem[i].MemObj) == pvR0)
3913 && ( pvR3 == NIL_RTR3PTR
3914 || RTR0MemObjAddressR3(pBundle->aMem[i].MapObjR3) == pvR3))
3915 {
3916 if (pvR0 != NIL_RTR0PTR)
3917 hMemObjR0 = pBundle->aMem[i].MemObj;
3918 if (pvR3 != NIL_RTR3PTR)
3919 hMemObjR3 = pBundle->aMem[i].MapObjR3;
3920 break;
3921 }
3922 }
3923 }
3924 }
3925 RTSpinlockRelease(pSession->Spinlock);
3926
3927 rc = VERR_INVALID_PARAMETER;
3928 if ( hMemObjR0 != NIL_RTR0MEMOBJ
3929 || hMemObjR3 != NIL_RTR0MEMOBJ)
3930 {
3931 /*
3932 * Do some further input validations before calling IPRT.
3933 */
3934 size_t cbMemObj = hMemObjR0 != NIL_RTR0PTR ? RTR0MemObjSize(hMemObjR0) : RTR0MemObjSize(hMemObjR3);
3935 if ( offSub < cbMemObj
3936 && cbSub <= cbMemObj
3937 && offSub + cbSub <= cbMemObj)
3938 {
3939 rc = VINF_SUCCESS;
3940 if (hMemObjR3 != NIL_RTR0PTR)
3941 rc = RTR0MemObjProtect(hMemObjR3, offSub, cbSub, fProt);
3942 if (hMemObjR0 != NIL_RTR0PTR && RT_SUCCESS(rc))
3943 rc = RTR0MemObjProtect(hMemObjR0, offSub, cbSub, fProt);
3944 }
3945 else
3946 SUPR0Printf("SUPR0PageMapKernel: cbMemObj=%#x offSub=%#x cbSub=%#x\n", cbMemObj, offSub, cbSub);
3947
3948 }
3949 return rc;
3950
3951}
3952SUPR0_EXPORT_SYMBOL(SUPR0PageProtect);
3953
3954
3955/**
3956 * Free memory allocated by SUPR0PageAlloc() and SUPR0PageAllocEx().
3957 *
3958 * @returns IPRT status code.
3959 * @param pSession The session owning the allocation.
3960 * @param pvR3 The Ring-3 address returned by SUPR0PageAlloc() or
3961 * SUPR0PageAllocEx().
3962 */
3963SUPR0DECL(int) SUPR0PageFree(PSUPDRVSESSION pSession, RTR3PTR pvR3)
3964{
3965 LogFlow(("SUPR0PageFree: pSession=%p pvR3=%p\n", pSession, (void *)pvR3));
3966 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
3967 return supdrvMemRelease(pSession, (RTHCUINTPTR)pvR3, MEMREF_TYPE_PAGE);
3968}
3969SUPR0_EXPORT_SYMBOL(SUPR0PageFree);
3970
3971
3972/**
3973 * Reports a bad context, currenctly that means EFLAGS.AC is 0 instead of 1.
3974 *
3975 * @param pDevExt The device extension.
3976 * @param pszFile The source file where the caller detected the bad
3977 * context.
3978 * @param uLine The line number in @a pszFile.
3979 * @param pszExtra Optional additional message to give further hints.
3980 */
3981void VBOXCALL supdrvBadContext(PSUPDRVDEVEXT pDevExt, const char *pszFile, uint32_t uLine, const char *pszExtra)
3982{
3983 uint32_t cCalls;
3984
3985 /*
3986 * Shorten the filename before displaying the message.
3987 */
3988 for (;;)
3989 {
3990 const char *pszTmp = strchr(pszFile, '/');
3991 if (!pszTmp)
3992 pszTmp = strchr(pszFile, '\\');
3993 if (!pszTmp)
3994 break;
3995 pszFile = pszTmp + 1;
3996 }
3997 if (RT_VALID_PTR(pszExtra) && *pszExtra)
3998 SUPR0Printf("vboxdrv: Bad CPU context error at line %u in %s: %s\n", uLine, pszFile, pszExtra);
3999 else
4000 SUPR0Printf("vboxdrv: Bad CPU context error at line %u in %s!\n", uLine, pszFile);
4001
4002 /*
4003 * Record the incident so that we stand a chance of blocking I/O controls
4004 * before panicing the system.
4005 */
4006 cCalls = ASMAtomicIncU32(&pDevExt->cBadContextCalls);
4007 if (cCalls > UINT32_MAX - _1K)
4008 ASMAtomicWriteU32(&pDevExt->cBadContextCalls, UINT32_MAX - _1K);
4009}
4010
4011
4012/**
4013 * Reports a bad context, currenctly that means EFLAGS.AC is 0 instead of 1.
4014 *
4015 * @param pSession The session of the caller.
4016 * @param pszFile The source file where the caller detected the bad
4017 * context.
4018 * @param uLine The line number in @a pszFile.
4019 * @param pszExtra Optional additional message to give further hints.
4020 */
4021SUPR0DECL(void) SUPR0BadContext(PSUPDRVSESSION pSession, const char *pszFile, uint32_t uLine, const char *pszExtra)
4022{
4023 PSUPDRVDEVEXT pDevExt;
4024
4025 AssertReturnVoid(SUP_IS_SESSION_VALID(pSession));
4026 pDevExt = pSession->pDevExt;
4027
4028 supdrvBadContext(pDevExt, pszFile, uLine, pszExtra);
4029}
4030SUPR0_EXPORT_SYMBOL(SUPR0BadContext);
4031
4032
4033/**
4034 * Gets the paging mode of the current CPU.
4035 *
4036 * @returns Paging mode, SUPPAGEINGMODE_INVALID on error.
4037 */
4038SUPR0DECL(SUPPAGINGMODE) SUPR0GetPagingMode(void)
4039{
4040 SUPPAGINGMODE enmMode;
4041
4042 RTR0UINTREG cr0 = ASMGetCR0();
4043 if ((cr0 & (X86_CR0_PG | X86_CR0_PE)) != (X86_CR0_PG | X86_CR0_PE))
4044 enmMode = SUPPAGINGMODE_INVALID;
4045 else
4046 {
4047 RTR0UINTREG cr4 = ASMGetCR4();
4048 uint32_t fNXEPlusLMA = 0;
4049 if (cr4 & X86_CR4_PAE)
4050 {
4051 uint32_t fExtFeatures = ASMCpuId_EDX(0x80000001);
4052 if (fExtFeatures & (X86_CPUID_EXT_FEATURE_EDX_NX | X86_CPUID_EXT_FEATURE_EDX_LONG_MODE))
4053 {
4054 uint64_t efer = ASMRdMsr(MSR_K6_EFER);
4055 if ((fExtFeatures & X86_CPUID_EXT_FEATURE_EDX_NX) && (efer & MSR_K6_EFER_NXE))
4056 fNXEPlusLMA |= RT_BIT(0);
4057 if ((fExtFeatures & X86_CPUID_EXT_FEATURE_EDX_LONG_MODE) && (efer & MSR_K6_EFER_LMA))
4058 fNXEPlusLMA |= RT_BIT(1);
4059 }
4060 }
4061
4062 switch ((cr4 & (X86_CR4_PAE | X86_CR4_PGE)) | fNXEPlusLMA)
4063 {
4064 case 0:
4065 enmMode = SUPPAGINGMODE_32_BIT;
4066 break;
4067
4068 case X86_CR4_PGE:
4069 enmMode = SUPPAGINGMODE_32_BIT_GLOBAL;
4070 break;
4071
4072 case X86_CR4_PAE:
4073 enmMode = SUPPAGINGMODE_PAE;
4074 break;
4075
4076 case X86_CR4_PAE | RT_BIT(0):
4077 enmMode = SUPPAGINGMODE_PAE_NX;
4078 break;
4079
4080 case X86_CR4_PAE | X86_CR4_PGE:
4081 enmMode = SUPPAGINGMODE_PAE_GLOBAL;
4082 break;
4083
4084 case X86_CR4_PAE | X86_CR4_PGE | RT_BIT(0):
4085 enmMode = SUPPAGINGMODE_PAE_GLOBAL;
4086 break;
4087
4088 case RT_BIT(1) | X86_CR4_PAE:
4089 enmMode = SUPPAGINGMODE_AMD64;
4090 break;
4091
4092 case RT_BIT(1) | X86_CR4_PAE | RT_BIT(0):
4093 enmMode = SUPPAGINGMODE_AMD64_NX;
4094 break;
4095
4096 case RT_BIT(1) | X86_CR4_PAE | X86_CR4_PGE:
4097 enmMode = SUPPAGINGMODE_AMD64_GLOBAL;
4098 break;
4099
4100 case RT_BIT(1) | X86_CR4_PAE | X86_CR4_PGE | RT_BIT(0):
4101 enmMode = SUPPAGINGMODE_AMD64_GLOBAL_NX;
4102 break;
4103
4104 default:
4105 AssertMsgFailed(("Cannot happen! cr4=%#x fNXEPlusLMA=%d\n", cr4, fNXEPlusLMA));
4106 enmMode = SUPPAGINGMODE_INVALID;
4107 break;
4108 }
4109 }
4110 return enmMode;
4111}
4112SUPR0_EXPORT_SYMBOL(SUPR0GetPagingMode);
4113
4114
4115/**
4116 * Change CR4 and take care of the kernel CR4 shadow if applicable.
4117 *
4118 * CR4 shadow handling is required for Linux >= 4.0. Calling this function
4119 * instead of ASMSetCR4() is only necessary for semi-permanent CR4 changes
4120 * for code with interrupts enabled.
4121 *
4122 * @returns the old CR4 value.
4123 *
4124 * @param fOrMask bits to be set in CR4.
4125 * @param fAndMask bits to be cleard in CR4.
4126 *
4127 * @remarks Must be called with preemption/interrupts disabled.
4128 */
4129SUPR0DECL(RTCCUINTREG) SUPR0ChangeCR4(RTCCUINTREG fOrMask, RTCCUINTREG fAndMask)
4130{
4131#ifdef RT_OS_LINUX
4132 return supdrvOSChangeCR4(fOrMask, fAndMask);
4133#else
4134 RTCCUINTREG uOld = ASMGetCR4();
4135 RTCCUINTREG uNew = (uOld & fAndMask) | fOrMask;
4136 if (uNew != uOld)
4137 ASMSetCR4(uNew);
4138 return uOld;
4139#endif
4140}
4141SUPR0_EXPORT_SYMBOL(SUPR0ChangeCR4);
4142
4143
4144/**
4145 * Enables or disabled hardware virtualization extensions using native OS APIs.
4146 *
4147 * @returns VBox status code.
4148 * @retval VINF_SUCCESS on success.
4149 * @retval VERR_NOT_SUPPORTED if not supported by the native OS.
4150 *
4151 * @param fEnable Whether to enable or disable.
4152 */
4153SUPR0DECL(int) SUPR0EnableVTx(bool fEnable)
4154{
4155#ifdef RT_OS_DARWIN
4156 return supdrvOSEnableVTx(fEnable);
4157#else
4158 RT_NOREF1(fEnable);
4159 return VERR_NOT_SUPPORTED;
4160#endif
4161}
4162SUPR0_EXPORT_SYMBOL(SUPR0EnableVTx);
4163
4164
4165/**
4166 * Suspends hardware virtualization extensions using the native OS API.
4167 *
4168 * This is called prior to entering raw-mode context.
4169 *
4170 * @returns @c true if suspended, @c false if not.
4171 */
4172SUPR0DECL(bool) SUPR0SuspendVTxOnCpu(void)
4173{
4174#ifdef RT_OS_DARWIN
4175 return supdrvOSSuspendVTxOnCpu();
4176#else
4177 return false;
4178#endif
4179}
4180SUPR0_EXPORT_SYMBOL(SUPR0SuspendVTxOnCpu);
4181
4182
4183/**
4184 * Resumes hardware virtualization extensions using the native OS API.
4185 *
4186 * This is called after to entering raw-mode context.
4187 *
4188 * @param fSuspended The return value of SUPR0SuspendVTxOnCpu.
4189 */
4190SUPR0DECL(void) SUPR0ResumeVTxOnCpu(bool fSuspended)
4191{
4192#ifdef RT_OS_DARWIN
4193 supdrvOSResumeVTxOnCpu(fSuspended);
4194#else
4195 RT_NOREF1(fSuspended);
4196 Assert(!fSuspended);
4197#endif
4198}
4199SUPR0_EXPORT_SYMBOL(SUPR0ResumeVTxOnCpu);
4200
4201
4202SUPR0DECL(int) SUPR0GetCurrentGdtRw(RTHCUINTPTR *pGdtRw)
4203{
4204#ifdef RT_OS_LINUX
4205 return supdrvOSGetCurrentGdtRw(pGdtRw);
4206#else
4207 NOREF(pGdtRw);
4208 return VERR_NOT_IMPLEMENTED;
4209#endif
4210}
4211SUPR0_EXPORT_SYMBOL(SUPR0GetCurrentGdtRw);
4212
4213
4214/**
4215 * Gets AMD-V and VT-x support for the calling CPU.
4216 *
4217 * @returns VBox status code.
4218 * @param pfCaps Where to store whether VT-x (SUPVTCAPS_VT_X) or AMD-V
4219 * (SUPVTCAPS_AMD_V) is supported.
4220 */
4221SUPR0DECL(int) SUPR0GetVTSupport(uint32_t *pfCaps)
4222{
4223 Assert(pfCaps);
4224 *pfCaps = 0;
4225
4226 /* Check if the CPU even supports CPUID (extremely ancient CPUs). */
4227 if (ASMHasCpuId())
4228 {
4229 /* Check the range of standard CPUID leafs. */
4230 uint32_t uMaxLeaf, uVendorEbx, uVendorEcx, uVendorEdx;
4231 ASMCpuId(0, &uMaxLeaf, &uVendorEbx, &uVendorEcx, &uVendorEdx);
4232 if (ASMIsValidStdRange(uMaxLeaf))
4233 {
4234 /* Query the standard CPUID leaf. */
4235 uint32_t fFeatEcx, fFeatEdx, uDummy;
4236 ASMCpuId(1, &uDummy, &uDummy, &fFeatEcx, &fFeatEdx);
4237
4238 /* Check if the vendor is Intel (or compatible). */
4239 if ( ASMIsIntelCpuEx(uVendorEbx, uVendorEcx, uVendorEdx)
4240 || ASMIsViaCentaurCpuEx(uVendorEbx, uVendorEcx, uVendorEdx)
4241 || ASMIsShanghaiCpuEx(uVendorEbx, uVendorEcx, uVendorEdx))
4242 {
4243 /* Check VT-x support. In addition, VirtualBox requires MSR and FXSAVE/FXRSTOR to function. */
4244 if ( (fFeatEcx & X86_CPUID_FEATURE_ECX_VMX)
4245 && (fFeatEdx & X86_CPUID_FEATURE_EDX_MSR)
4246 && (fFeatEdx & X86_CPUID_FEATURE_EDX_FXSR))
4247 {
4248 *pfCaps = SUPVTCAPS_VT_X;
4249 return VINF_SUCCESS;
4250 }
4251 return VERR_VMX_NO_VMX;
4252 }
4253
4254 /* Check if the vendor is AMD (or compatible). */
4255 if ( ASMIsAmdCpuEx(uVendorEbx, uVendorEcx, uVendorEdx)
4256 || ASMIsHygonCpuEx(uVendorEbx, uVendorEcx, uVendorEdx))
4257 {
4258 uint32_t fExtFeatEcx, uExtMaxId;
4259 ASMCpuId(0x80000000, &uExtMaxId, &uDummy, &uDummy, &uDummy);
4260 ASMCpuId(0x80000001, &uDummy, &uDummy, &fExtFeatEcx, &uDummy);
4261
4262 /* Check AMD-V support. In addition, VirtualBox requires MSR and FXSAVE/FXRSTOR to function. */
4263 if ( ASMIsValidExtRange(uExtMaxId)
4264 && uExtMaxId >= 0x8000000a
4265 && (fExtFeatEcx & X86_CPUID_AMD_FEATURE_ECX_SVM)
4266 && (fFeatEdx & X86_CPUID_FEATURE_EDX_MSR)
4267 && (fFeatEdx & X86_CPUID_FEATURE_EDX_FXSR))
4268 {
4269 *pfCaps = SUPVTCAPS_AMD_V;
4270 return VINF_SUCCESS;
4271 }
4272 return VERR_SVM_NO_SVM;
4273 }
4274 }
4275 }
4276 return VERR_UNSUPPORTED_CPU;
4277}
4278SUPR0_EXPORT_SYMBOL(SUPR0GetVTSupport);
4279
4280
4281/**
4282 * Checks if Intel VT-x feature is usable on this CPU.
4283 *
4284 * @returns VBox status code.
4285 * @param pfIsSmxModeAmbiguous Where to return whether the SMX mode causes
4286 * ambiguity that makes us unsure whether we
4287 * really can use VT-x or not.
4288 *
4289 * @remarks Must be called with preemption disabled.
4290 * The caller is also expected to check that the CPU is an Intel (or
4291 * VIA/Shanghai) CPU -and- that it supports VT-x. Otherwise, this
4292 * function might throw a \#GP fault as it tries to read/write MSRs
4293 * that may not be present!
4294 */
4295SUPR0DECL(int) SUPR0GetVmxUsability(bool *pfIsSmxModeAmbiguous)
4296{
4297 uint64_t fFeatMsr;
4298 bool fMaybeSmxMode;
4299 bool fMsrLocked;
4300 bool fSmxVmxAllowed;
4301 bool fVmxAllowed;
4302 bool fIsSmxModeAmbiguous;
4303 int rc;
4304
4305 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
4306
4307 fFeatMsr = ASMRdMsr(MSR_IA32_FEATURE_CONTROL);
4308 fMaybeSmxMode = RT_BOOL(ASMGetCR4() & X86_CR4_SMXE);
4309 fMsrLocked = RT_BOOL(fFeatMsr & MSR_IA32_FEATURE_CONTROL_LOCK);
4310 fSmxVmxAllowed = RT_BOOL(fFeatMsr & MSR_IA32_FEATURE_CONTROL_SMX_VMXON);
4311 fVmxAllowed = RT_BOOL(fFeatMsr & MSR_IA32_FEATURE_CONTROL_VMXON);
4312 fIsSmxModeAmbiguous = false;
4313 rc = VERR_INTERNAL_ERROR_5;
4314
4315 /* Check if the LOCK bit is set but excludes the required VMXON bit. */
4316 if (fMsrLocked)
4317 {
4318 if (fVmxAllowed && fSmxVmxAllowed)
4319 rc = VINF_SUCCESS;
4320 else if (!fVmxAllowed && !fSmxVmxAllowed)
4321 rc = VERR_VMX_MSR_ALL_VMX_DISABLED;
4322 else if (!fMaybeSmxMode)
4323 {
4324 if (fVmxAllowed)
4325 rc = VINF_SUCCESS;
4326 else
4327 rc = VERR_VMX_MSR_VMX_DISABLED;
4328 }
4329 else
4330 {
4331 /*
4332 * CR4.SMXE is set but this doesn't mean the CPU is necessarily in SMX mode. We shall assume
4333 * that it is -not- and that it is a stupid BIOS/OS setting CR4.SMXE for no good reason.
4334 * See @bugref{6873}.
4335 */
4336 Assert(fMaybeSmxMode == true);
4337 fIsSmxModeAmbiguous = true;
4338 rc = VINF_SUCCESS;
4339 }
4340 }
4341 else
4342 {
4343 /*
4344 * MSR is not yet locked; we can change it ourselves here. Once the lock bit is set,
4345 * this MSR can no longer be modified.
4346 *
4347 * Set both the VMX and SMX_VMX bits (if supported) as we can't determine SMX mode
4348 * accurately. See @bugref{6873}.
4349 *
4350 * We need to check for SMX hardware support here, before writing the MSR as
4351 * otherwise we will #GP fault on CPUs that do not support it. Callers do not check
4352 * for it.
4353 */
4354 uint32_t fFeaturesECX, uDummy;
4355#ifdef VBOX_STRICT
4356 /* Callers should have verified these at some point. */
4357 uint32_t uMaxId, uVendorEBX, uVendorECX, uVendorEDX;
4358 ASMCpuId(0, &uMaxId, &uVendorEBX, &uVendorECX, &uVendorEDX);
4359 Assert(ASMIsValidStdRange(uMaxId));
4360 Assert( ASMIsIntelCpuEx( uVendorEBX, uVendorECX, uVendorEDX)
4361 || ASMIsViaCentaurCpuEx(uVendorEBX, uVendorECX, uVendorEDX)
4362 || ASMIsShanghaiCpuEx( uVendorEBX, uVendorECX, uVendorEDX));
4363#endif
4364 ASMCpuId(1, &uDummy, &uDummy, &fFeaturesECX, &uDummy);
4365 bool fSmxVmxHwSupport = false;
4366 if ( (fFeaturesECX & X86_CPUID_FEATURE_ECX_VMX)
4367 && (fFeaturesECX & X86_CPUID_FEATURE_ECX_SMX))
4368 fSmxVmxHwSupport = true;
4369
4370 fFeatMsr |= MSR_IA32_FEATURE_CONTROL_LOCK
4371 | MSR_IA32_FEATURE_CONTROL_VMXON;
4372 if (fSmxVmxHwSupport)
4373 fFeatMsr |= MSR_IA32_FEATURE_CONTROL_SMX_VMXON;
4374
4375 /*
4376 * Commit.
4377 */
4378 ASMWrMsr(MSR_IA32_FEATURE_CONTROL, fFeatMsr);
4379
4380 /*
4381 * Verify.
4382 */
4383 fFeatMsr = ASMRdMsr(MSR_IA32_FEATURE_CONTROL);
4384 fMsrLocked = RT_BOOL(fFeatMsr & MSR_IA32_FEATURE_CONTROL_LOCK);
4385 if (fMsrLocked)
4386 {
4387 fSmxVmxAllowed = RT_BOOL(fFeatMsr & MSR_IA32_FEATURE_CONTROL_SMX_VMXON);
4388 fVmxAllowed = RT_BOOL(fFeatMsr & MSR_IA32_FEATURE_CONTROL_VMXON);
4389 if ( fVmxAllowed
4390 && ( !fSmxVmxHwSupport
4391 || fSmxVmxAllowed))
4392 rc = VINF_SUCCESS;
4393 else
4394 rc = !fSmxVmxHwSupport ? VERR_VMX_MSR_VMX_ENABLE_FAILED : VERR_VMX_MSR_SMX_VMX_ENABLE_FAILED;
4395 }
4396 else
4397 rc = VERR_VMX_MSR_LOCKING_FAILED;
4398 }
4399
4400 if (pfIsSmxModeAmbiguous)
4401 *pfIsSmxModeAmbiguous = fIsSmxModeAmbiguous;
4402
4403 return rc;
4404}
4405SUPR0_EXPORT_SYMBOL(SUPR0GetVmxUsability);
4406
4407
4408/**
4409 * Checks if AMD-V SVM feature is usable on this CPU.
4410 *
4411 * @returns VBox status code.
4412 * @param fInitSvm If usable, try to initialize SVM on this CPU.
4413 *
4414 * @remarks Must be called with preemption disabled.
4415 */
4416SUPR0DECL(int) SUPR0GetSvmUsability(bool fInitSvm)
4417{
4418 int rc;
4419 uint64_t fVmCr;
4420 uint64_t fEfer;
4421
4422 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
4423 fVmCr = ASMRdMsr(MSR_K8_VM_CR);
4424 if (!(fVmCr & MSR_K8_VM_CR_SVM_DISABLE))
4425 {
4426 rc = VINF_SUCCESS;
4427 if (fInitSvm)
4428 {
4429 /* Turn on SVM in the EFER MSR. */
4430 fEfer = ASMRdMsr(MSR_K6_EFER);
4431 if (fEfer & MSR_K6_EFER_SVME)
4432 rc = VERR_SVM_IN_USE;
4433 else
4434 {
4435 ASMWrMsr(MSR_K6_EFER, fEfer | MSR_K6_EFER_SVME);
4436
4437 /* Paranoia. */
4438 fEfer = ASMRdMsr(MSR_K6_EFER);
4439 if (fEfer & MSR_K6_EFER_SVME)
4440 {
4441 /* Restore previous value. */
4442 ASMWrMsr(MSR_K6_EFER, fEfer & ~MSR_K6_EFER_SVME);
4443 }
4444 else
4445 rc = VERR_SVM_ILLEGAL_EFER_MSR;
4446 }
4447 }
4448 }
4449 else
4450 rc = VERR_SVM_DISABLED;
4451 return rc;
4452}
4453SUPR0_EXPORT_SYMBOL(SUPR0GetSvmUsability);
4454
4455
4456/**
4457 * Queries the AMD-V and VT-x capabilities of the calling CPU.
4458 *
4459 * @returns VBox status code.
4460 * @retval VERR_VMX_NO_VMX
4461 * @retval VERR_VMX_MSR_ALL_VMX_DISABLED
4462 * @retval VERR_VMX_MSR_VMX_DISABLED
4463 * @retval VERR_VMX_MSR_LOCKING_FAILED
4464 * @retval VERR_VMX_MSR_VMX_ENABLE_FAILED
4465 * @retval VERR_VMX_MSR_SMX_VMX_ENABLE_FAILED
4466 * @retval VERR_SVM_NO_SVM
4467 * @retval VERR_SVM_DISABLED
4468 * @retval VERR_UNSUPPORTED_CPU if not identifiable as an AMD, Intel or VIA
4469 * (centaur)/Shanghai CPU.
4470 *
4471 * @param pfCaps Where to store the capabilities.
4472 */
4473int VBOXCALL supdrvQueryVTCapsInternal(uint32_t *pfCaps)
4474{
4475 int rc = VERR_UNSUPPORTED_CPU;
4476 bool fIsSmxModeAmbiguous = false;
4477 RTTHREADPREEMPTSTATE PreemptState = RTTHREADPREEMPTSTATE_INITIALIZER;
4478
4479 /*
4480 * Input validation.
4481 */
4482 AssertPtrReturn(pfCaps, VERR_INVALID_POINTER);
4483 *pfCaps = 0;
4484
4485 /* We may modify MSRs and re-read them, disable preemption so we make sure we don't migrate CPUs. */
4486 RTThreadPreemptDisable(&PreemptState);
4487
4488 /* Check if VT-x/AMD-V is supported. */
4489 rc = SUPR0GetVTSupport(pfCaps);
4490 if (RT_SUCCESS(rc))
4491 {
4492 /* Check if VT-x is supported. */
4493 if (*pfCaps & SUPVTCAPS_VT_X)
4494 {
4495 /* Check if VT-x is usable. */
4496 rc = SUPR0GetVmxUsability(&fIsSmxModeAmbiguous);
4497 if (RT_SUCCESS(rc))
4498 {
4499 /* Query some basic VT-x capabilities (mainly required by our GUI). */
4500 VMXCTLSMSR vtCaps;
4501 vtCaps.u = ASMRdMsr(MSR_IA32_VMX_PROCBASED_CTLS);
4502 if (vtCaps.n.allowed1 & VMX_PROC_CTLS_USE_SECONDARY_CTLS)
4503 {
4504 vtCaps.u = ASMRdMsr(MSR_IA32_VMX_PROCBASED_CTLS2);
4505 if (vtCaps.n.allowed1 & VMX_PROC_CTLS2_EPT)
4506 *pfCaps |= SUPVTCAPS_NESTED_PAGING;
4507 if (vtCaps.n.allowed1 & VMX_PROC_CTLS2_UNRESTRICTED_GUEST)
4508 *pfCaps |= SUPVTCAPS_VTX_UNRESTRICTED_GUEST;
4509 if (vtCaps.n.allowed1 & VMX_PROC_CTLS2_VMCS_SHADOWING)
4510 *pfCaps |= SUPVTCAPS_VTX_VMCS_SHADOWING;
4511 }
4512 }
4513 }
4514 /* Check if AMD-V is supported. */
4515 else if (*pfCaps & SUPVTCAPS_AMD_V)
4516 {
4517 /* Check is SVM is usable. */
4518 rc = SUPR0GetSvmUsability(false /* fInitSvm */);
4519 if (RT_SUCCESS(rc))
4520 {
4521 /* Query some basic AMD-V capabilities (mainly required by our GUI). */
4522 uint32_t uDummy, fSvmFeatures;
4523 ASMCpuId(0x8000000a, &uDummy, &uDummy, &uDummy, &fSvmFeatures);
4524 if (fSvmFeatures & X86_CPUID_SVM_FEATURE_EDX_NESTED_PAGING)
4525 *pfCaps |= SUPVTCAPS_NESTED_PAGING;
4526 if (fSvmFeatures & X86_CPUID_SVM_FEATURE_EDX_VIRT_VMSAVE_VMLOAD)
4527 *pfCaps |= SUPVTCAPS_AMDV_VIRT_VMSAVE_VMLOAD;
4528 }
4529 }
4530 }
4531
4532 /* Restore preemption. */
4533 RTThreadPreemptRestore(&PreemptState);
4534
4535 /* After restoring preemption, if we may be in SMX mode, print a warning as it's difficult to debug such problems. */
4536 if (fIsSmxModeAmbiguous)
4537 SUPR0Printf(("WARNING! CR4 hints SMX mode but your CPU is too secretive. Proceeding anyway... We wish you good luck!\n"));
4538
4539 return rc;
4540}
4541
4542
4543/**
4544 * Queries the AMD-V and VT-x capabilities of the calling CPU.
4545 *
4546 * @returns VBox status code.
4547 * @retval VERR_VMX_NO_VMX
4548 * @retval VERR_VMX_MSR_ALL_VMX_DISABLED
4549 * @retval VERR_VMX_MSR_VMX_DISABLED
4550 * @retval VERR_VMX_MSR_LOCKING_FAILED
4551 * @retval VERR_VMX_MSR_VMX_ENABLE_FAILED
4552 * @retval VERR_VMX_MSR_SMX_VMX_ENABLE_FAILED
4553 * @retval VERR_SVM_NO_SVM
4554 * @retval VERR_SVM_DISABLED
4555 * @retval VERR_UNSUPPORTED_CPU if not identifiable as an AMD, Intel or VIA
4556 * (centaur)/Shanghai CPU.
4557 *
4558 * @param pSession The session handle.
4559 * @param pfCaps Where to store the capabilities.
4560 */
4561SUPR0DECL(int) SUPR0QueryVTCaps(PSUPDRVSESSION pSession, uint32_t *pfCaps)
4562{
4563 /*
4564 * Input validation.
4565 */
4566 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
4567 AssertPtrReturn(pfCaps, VERR_INVALID_POINTER);
4568
4569 /*
4570 * Call common worker.
4571 */
4572 return supdrvQueryVTCapsInternal(pfCaps);
4573}
4574SUPR0_EXPORT_SYMBOL(SUPR0QueryVTCaps);
4575
4576
4577/**
4578 * Queries the CPU microcode revision.
4579 *
4580 * @returns VBox status code.
4581 * @retval VERR_UNSUPPORTED_CPU if not identifiable as a processor with
4582 * readable microcode rev.
4583 *
4584 * @param puRevision Where to store the microcode revision.
4585 */
4586static int VBOXCALL supdrvQueryUcodeRev(uint32_t *puRevision)
4587{
4588 int rc = VERR_UNSUPPORTED_CPU;
4589 RTTHREADPREEMPTSTATE PreemptState = RTTHREADPREEMPTSTATE_INITIALIZER;
4590
4591 /*
4592 * Input validation.
4593 */
4594 AssertPtrReturn(puRevision, VERR_INVALID_POINTER);
4595
4596 *puRevision = 0;
4597
4598 /* Disable preemption so we make sure we don't migrate CPUs, just in case. */
4599 /* NB: We assume that there aren't mismatched microcode revs in the system. */
4600 RTThreadPreemptDisable(&PreemptState);
4601
4602 if (ASMHasCpuId())
4603 {
4604 uint32_t uDummy, uTFMSEAX;
4605 uint32_t uMaxId, uVendorEBX, uVendorECX, uVendorEDX;
4606
4607 ASMCpuId(0, &uMaxId, &uVendorEBX, &uVendorECX, &uVendorEDX);
4608 ASMCpuId(1, &uTFMSEAX, &uDummy, &uDummy, &uDummy);
4609
4610 if (ASMIsValidStdRange(uMaxId))
4611 {
4612 uint64_t uRevMsr;
4613 if (ASMIsIntelCpuEx(uVendorEBX, uVendorECX, uVendorEDX))
4614 {
4615 /* Architectural MSR available on Pentium Pro and later. */
4616 if (ASMGetCpuFamily(uTFMSEAX) >= 6)
4617 {
4618 /* Revision is in the high dword. */
4619 uRevMsr = ASMRdMsr(MSR_IA32_BIOS_SIGN_ID);
4620 *puRevision = RT_HIDWORD(uRevMsr);
4621 rc = VINF_SUCCESS;
4622 }
4623 }
4624 else if ( ASMIsAmdCpuEx(uVendorEBX, uVendorECX, uVendorEDX)
4625 || ASMIsHygonCpuEx(uVendorEBX, uVendorECX, uVendorEDX))
4626 {
4627 /* Not well documented, but at least all AMD64 CPUs support this. */
4628 if (ASMGetCpuFamily(uTFMSEAX) >= 15)
4629 {
4630 /* Revision is in the low dword. */
4631 uRevMsr = ASMRdMsr(MSR_IA32_BIOS_SIGN_ID); /* Same MSR as Intel. */
4632 *puRevision = RT_LODWORD(uRevMsr);
4633 rc = VINF_SUCCESS;
4634 }
4635 }
4636 }
4637 }
4638
4639 RTThreadPreemptRestore(&PreemptState);
4640
4641 return rc;
4642}
4643
4644
4645/**
4646 * Queries the CPU microcode revision.
4647 *
4648 * @returns VBox status code.
4649 * @retval VERR_UNSUPPORTED_CPU if not identifiable as a processor with
4650 * readable microcode rev.
4651 *
4652 * @param pSession The session handle.
4653 * @param puRevision Where to store the microcode revision.
4654 */
4655SUPR0DECL(int) SUPR0QueryUcodeRev(PSUPDRVSESSION pSession, uint32_t *puRevision)
4656{
4657 /*
4658 * Input validation.
4659 */
4660 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
4661 AssertPtrReturn(puRevision, VERR_INVALID_POINTER);
4662
4663 /*
4664 * Call common worker.
4665 */
4666 return supdrvQueryUcodeRev(puRevision);
4667}
4668SUPR0_EXPORT_SYMBOL(SUPR0QueryUcodeRev);
4669
4670
4671/**
4672 * Gets hardware-virtualization MSRs of the calling CPU.
4673 *
4674 * @returns VBox status code.
4675 * @param pMsrs Where to store the hardware-virtualization MSRs.
4676 * @param fCaps Hardware virtualization capabilities (SUPVTCAPS_XXX). Pass 0
4677 * to explicitly check for the presence of VT-x/AMD-V before
4678 * querying MSRs.
4679 * @param fForce Force querying of MSRs from the hardware.
4680 */
4681SUPR0DECL(int) SUPR0GetHwvirtMsrs(PSUPHWVIRTMSRS pMsrs, uint32_t fCaps, bool fForce)
4682{
4683 NOREF(fForce);
4684
4685 int rc;
4686 RTTHREADPREEMPTSTATE PreemptState = RTTHREADPREEMPTSTATE_INITIALIZER;
4687
4688 /*
4689 * Input validation.
4690 */
4691 AssertPtrReturn(pMsrs, VERR_INVALID_POINTER);
4692
4693 /*
4694 * Disable preemption so we make sure we don't migrate CPUs and because
4695 * we access global data.
4696 */
4697 RTThreadPreemptDisable(&PreemptState);
4698
4699 /*
4700 * Query the MSRs from the hardware.
4701 */
4702 SUPHWVIRTMSRS Msrs;
4703 RT_ZERO(Msrs);
4704
4705 /* If the caller claims VT-x/AMD-V is supported, don't need to recheck it. */
4706 if (!(fCaps & (SUPVTCAPS_VT_X | SUPVTCAPS_AMD_V)))
4707 rc = SUPR0GetVTSupport(&fCaps);
4708 else
4709 rc = VINF_SUCCESS;
4710 if (RT_SUCCESS(rc))
4711 {
4712 if (fCaps & SUPVTCAPS_VT_X)
4713 {
4714 Msrs.u.vmx.u64FeatCtrl = ASMRdMsr(MSR_IA32_FEATURE_CONTROL);
4715 Msrs.u.vmx.u64Basic = ASMRdMsr(MSR_IA32_VMX_BASIC);
4716 Msrs.u.vmx.PinCtls.u = ASMRdMsr(MSR_IA32_VMX_PINBASED_CTLS);
4717 Msrs.u.vmx.ProcCtls.u = ASMRdMsr(MSR_IA32_VMX_PROCBASED_CTLS);
4718 Msrs.u.vmx.ExitCtls.u = ASMRdMsr(MSR_IA32_VMX_EXIT_CTLS);
4719 Msrs.u.vmx.EntryCtls.u = ASMRdMsr(MSR_IA32_VMX_ENTRY_CTLS);
4720 Msrs.u.vmx.u64Misc = ASMRdMsr(MSR_IA32_VMX_MISC);
4721 Msrs.u.vmx.u64Cr0Fixed0 = ASMRdMsr(MSR_IA32_VMX_CR0_FIXED0);
4722 Msrs.u.vmx.u64Cr0Fixed1 = ASMRdMsr(MSR_IA32_VMX_CR0_FIXED1);
4723 Msrs.u.vmx.u64Cr4Fixed0 = ASMRdMsr(MSR_IA32_VMX_CR4_FIXED0);
4724 Msrs.u.vmx.u64Cr4Fixed1 = ASMRdMsr(MSR_IA32_VMX_CR4_FIXED1);
4725 Msrs.u.vmx.u64VmcsEnum = ASMRdMsr(MSR_IA32_VMX_VMCS_ENUM);
4726
4727 if (RT_BF_GET(Msrs.u.vmx.u64Basic, VMX_BF_BASIC_TRUE_CTLS))
4728 {
4729 Msrs.u.vmx.TruePinCtls.u = ASMRdMsr(MSR_IA32_VMX_TRUE_PINBASED_CTLS);
4730 Msrs.u.vmx.TrueProcCtls.u = ASMRdMsr(MSR_IA32_VMX_TRUE_PROCBASED_CTLS);
4731 Msrs.u.vmx.TrueEntryCtls.u = ASMRdMsr(MSR_IA32_VMX_TRUE_ENTRY_CTLS);
4732 Msrs.u.vmx.TrueExitCtls.u = ASMRdMsr(MSR_IA32_VMX_TRUE_EXIT_CTLS);
4733 }
4734
4735 if (Msrs.u.vmx.ProcCtls.n.allowed1 & VMX_PROC_CTLS_USE_SECONDARY_CTLS)
4736 {
4737 Msrs.u.vmx.ProcCtls2.u = ASMRdMsr(MSR_IA32_VMX_PROCBASED_CTLS2);
4738
4739 if (Msrs.u.vmx.ProcCtls2.n.allowed1 & (VMX_PROC_CTLS2_EPT | VMX_PROC_CTLS2_VPID))
4740 Msrs.u.vmx.u64EptVpidCaps = ASMRdMsr(MSR_IA32_VMX_EPT_VPID_CAP);
4741
4742 if (Msrs.u.vmx.ProcCtls2.n.allowed1 & VMX_PROC_CTLS2_VMFUNC)
4743 Msrs.u.vmx.u64VmFunc = ASMRdMsr(MSR_IA32_VMX_VMFUNC);
4744 }
4745
4746 if (Msrs.u.vmx.ProcCtls.n.allowed1 & VMX_PROC_CTLS_USE_TERTIARY_CTLS)
4747 Msrs.u.vmx.u64ProcCtls3 = ASMRdMsr(MSR_IA32_VMX_PROCBASED_CTLS3);
4748 }
4749 else if (fCaps & SUPVTCAPS_AMD_V)
4