VirtualBox

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

Last change on this file since 102493 was 101358, checked in by vboxsync, 16 months ago

Linux: vboxdrv: Replace SUPDRV_UNFORTIFIED_MEMCPY with RT_BCOPY_UNFORTIFIED, bugref:10209.

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