VirtualBox

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

Last change on this file since 104448 was 103684, checked in by vboxsync, 8 months ago

Linux kernel modules: Fix UBSAN warnings by switching to flexible arrays where possible, bugref:10585.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 266.1 KB
Line 
1/* $Id: SUPDrv.cpp 103684 2024-03-05 15:27:02Z 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 uint8_t const * const pbSrcImage = pReq->u.In.abImage;
1851 REQ_CHECK_EXPR(Name, pReq->Hdr.cbIn >= SUP_IOCTL_LDR_LOAD_SIZE_IN(32));
1852 REQ_CHECK_SIZES_EX(SUP_IOCTL_LDR_LOAD, SUP_IOCTL_LDR_LOAD_SIZE_IN(pReq->u.In.cbImageWithEverything), SUP_IOCTL_LDR_LOAD_SIZE_OUT);
1853 REQ_CHECK_EXPR_FMT( !pReq->u.In.cSymbols
1854 || ( pReq->u.In.cSymbols <= 16384
1855 && pReq->u.In.offSymbols >= pReq->u.In.cbImageBits
1856 && pReq->u.In.offSymbols < pReq->u.In.cbImageWithEverything
1857 && pReq->u.In.offSymbols + pReq->u.In.cSymbols * sizeof(SUPLDRSYM) <= pReq->u.In.cbImageWithEverything),
1858 ("SUP_IOCTL_LDR_LOAD: offSymbols=%#lx cSymbols=%#lx cbImageWithEverything=%#lx\n", (long)pReq->u.In.offSymbols,
1859 (long)pReq->u.In.cSymbols, (long)pReq->u.In.cbImageWithEverything));
1860 REQ_CHECK_EXPR_FMT( !pReq->u.In.cbStrTab
1861 || ( pReq->u.In.offStrTab < pReq->u.In.cbImageWithEverything
1862 && pReq->u.In.offStrTab >= pReq->u.In.cbImageBits
1863 && pReq->u.In.offStrTab + pReq->u.In.cbStrTab <= pReq->u.In.cbImageWithEverything
1864 && pReq->u.In.cbStrTab <= pReq->u.In.cbImageWithEverything),
1865 ("SUP_IOCTL_LDR_LOAD: offStrTab=%#lx cbStrTab=%#lx cbImageWithEverything=%#lx\n", (long)pReq->u.In.offStrTab,
1866 (long)pReq->u.In.cbStrTab, (long)pReq->u.In.cbImageWithEverything));
1867 REQ_CHECK_EXPR_FMT( pReq->u.In.cSegments >= 1
1868 && pReq->u.In.cSegments <= 128
1869 && pReq->u.In.cSegments <= (pReq->u.In.cbImageBits + PAGE_SIZE - 1) / PAGE_SIZE
1870 && pReq->u.In.offSegments >= pReq->u.In.cbImageBits
1871 && pReq->u.In.offSegments < pReq->u.In.cbImageWithEverything
1872 && pReq->u.In.offSegments + pReq->u.In.cSegments * sizeof(SUPLDRSEG) <= pReq->u.In.cbImageWithEverything,
1873 ("SUP_IOCTL_LDR_LOAD: offSegments=%#lx cSegments=%#lx cbImageWithEverything=%#lx\n", (long)pReq->u.In.offSegments,
1874 (long)pReq->u.In.cSegments, (long)pReq->u.In.cbImageWithEverything));
1875
1876 if (pReq->u.In.cSymbols)
1877 {
1878 uint32_t i;
1879 PSUPLDRSYM paSyms = (PSUPLDRSYM)(&pbSrcImage[pReq->u.In.offSymbols]);
1880 for (i = 0; i < pReq->u.In.cSymbols; i++)
1881 {
1882 REQ_CHECK_EXPR_FMT(paSyms[i].offSymbol < pReq->u.In.cbImageWithEverything,
1883 ("SUP_IOCTL_LDR_LOAD: sym #%ld: symb off %#lx (max=%#lx)\n", (long)i, (long)paSyms[i].offSymbol, (long)pReq->u.In.cbImageWithEverything));
1884 REQ_CHECK_EXPR_FMT(paSyms[i].offName < pReq->u.In.cbStrTab,
1885 ("SUP_IOCTL_LDR_LOAD: sym #%ld: name off %#lx (max=%#lx)\n", (long)i, (long)paSyms[i].offName, (long)pReq->u.In.cbImageWithEverything));
1886 REQ_CHECK_EXPR_FMT(RTStrEnd((char const *)(&pbSrcImage[pReq->u.In.offStrTab + paSyms[i].offName]),
1887 pReq->u.In.cbStrTab - paSyms[i].offName),
1888 ("SUP_IOCTL_LDR_LOAD: sym #%ld: unterminated name! (%#lx / %#lx)\n", (long)i, (long)paSyms[i].offName, (long)pReq->u.In.cbImageWithEverything));
1889 }
1890 }
1891 {
1892 uint32_t i;
1893 uint32_t offPrevEnd = 0;
1894 PSUPLDRSEG paSegs = (PSUPLDRSEG)(&pbSrcImage[pReq->u.In.offSegments]);
1895 for (i = 0; i < pReq->u.In.cSegments; i++)
1896 {
1897 REQ_CHECK_EXPR_FMT(paSegs[i].off < pReq->u.In.cbImageBits && !(paSegs[i].off & PAGE_OFFSET_MASK),
1898 ("SUP_IOCTL_LDR_LOAD: seg #%ld: off %#lx (max=%#lx)\n", (long)i, (long)paSegs[i].off, (long)pReq->u.In.cbImageBits));
1899 REQ_CHECK_EXPR_FMT(paSegs[i].cb <= pReq->u.In.cbImageBits,
1900 ("SUP_IOCTL_LDR_LOAD: seg #%ld: cb %#lx (max=%#lx)\n", (long)i, (long)paSegs[i].cb, (long)pReq->u.In.cbImageBits));
1901 REQ_CHECK_EXPR_FMT(paSegs[i].off + paSegs[i].cb <= pReq->u.In.cbImageBits,
1902 ("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));
1903 REQ_CHECK_EXPR_FMT(paSegs[i].fProt != 0,
1904 ("SUP_IOCTL_LDR_LOAD: seg #%ld: off %#lx + cb %#lx\n", (long)i, (long)paSegs[i].off, (long)paSegs[i].cb));
1905 REQ_CHECK_EXPR_FMT(paSegs[i].fUnused == 0, ("SUP_IOCTL_LDR_LOAD: seg #%ld: fUnused=1\n", (long)i));
1906 REQ_CHECK_EXPR_FMT(offPrevEnd == paSegs[i].off,
1907 ("SUP_IOCTL_LDR_LOAD: seg #%ld: off %#lx offPrevEnd %#lx\n", (long)i, (long)paSegs[i].off, (long)offPrevEnd));
1908 offPrevEnd = paSegs[i].off + paSegs[i].cb;
1909 }
1910 REQ_CHECK_EXPR_FMT(offPrevEnd == pReq->u.In.cbImageBits,
1911 ("SUP_IOCTL_LDR_LOAD: offPrevEnd %#lx cbImageBits %#lx\n", (long)i, (long)offPrevEnd, (long)pReq->u.In.cbImageBits));
1912 }
1913 REQ_CHECK_EXPR_FMT(!(pReq->u.In.fFlags & ~SUPLDRLOAD_F_VALID_MASK),
1914 ("SUP_IOCTL_LDR_LOAD: fFlags=%#x\n", (unsigned)pReq->u.In.fFlags));
1915
1916 /* execute */
1917 pReq->Hdr.rc = supdrvIOCtl_LdrLoad(pDevExt, pSession, pReq);
1918 return 0;
1919 }
1920
1921 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_LDR_FREE):
1922 {
1923 /* validate */
1924 PSUPLDRFREE pReq = (PSUPLDRFREE)pReqHdr;
1925 REQ_CHECK_SIZES(SUP_IOCTL_LDR_FREE);
1926
1927 /* execute */
1928 pReq->Hdr.rc = supdrvIOCtl_LdrFree(pDevExt, pSession, pReq);
1929 return 0;
1930 }
1931
1932 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_LDR_LOCK_DOWN):
1933 {
1934 /* validate */
1935 REQ_CHECK_SIZES(SUP_IOCTL_LDR_LOCK_DOWN);
1936
1937 /* execute */
1938 pReqHdr->rc = supdrvIOCtl_LdrLockDown(pDevExt);
1939 return 0;
1940 }
1941
1942 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_LDR_GET_SYMBOL):
1943 {
1944 /* validate */
1945 PSUPLDRGETSYMBOL pReq = (PSUPLDRGETSYMBOL)pReqHdr;
1946 REQ_CHECK_SIZES(SUP_IOCTL_LDR_GET_SYMBOL);
1947 REQ_CHECK_EXPR(SUP_IOCTL_LDR_GET_SYMBOL, RTStrEnd(pReq->u.In.szSymbol, sizeof(pReq->u.In.szSymbol)));
1948
1949 /* execute */
1950 pReq->Hdr.rc = supdrvIOCtl_LdrQuerySymbol(pDevExt, pSession, pReq);
1951 return 0;
1952 }
1953
1954 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_CALL_VMMR0_NO_SIZE()):
1955 {
1956 /* validate */
1957 PSUPCALLVMMR0 pReq = (PSUPCALLVMMR0)pReqHdr;
1958 Log4(("SUP_IOCTL_CALL_VMMR0: op=%u in=%u arg=%RX64 p/t=%RTproc/%RTthrd\n",
1959 pReq->u.In.uOperation, pReq->Hdr.cbIn, pReq->u.In.u64Arg, RTProcSelf(), RTThreadNativeSelf()));
1960
1961 if (pReq->Hdr.cbIn == SUP_IOCTL_CALL_VMMR0_SIZE(0))
1962 {
1963 REQ_CHECK_SIZES_EX(SUP_IOCTL_CALL_VMMR0, SUP_IOCTL_CALL_VMMR0_SIZE_IN(0), SUP_IOCTL_CALL_VMMR0_SIZE_OUT(0));
1964
1965 /* execute */
1966 if (RT_LIKELY(pDevExt->pfnVMMR0EntryEx))
1967 {
1968 if (pReq->u.In.pVMR0 == NULL)
1969 pReq->Hdr.rc = pDevExt->pfnVMMR0EntryEx(NULL, NULL, pReq->u.In.idCpu,
1970 pReq->u.In.uOperation, NULL, pReq->u.In.u64Arg, pSession);
1971 else if (pReq->u.In.pVMR0 == pSession->pSessionVM)
1972 pReq->Hdr.rc = pDevExt->pfnVMMR0EntryEx(pSession->pSessionGVM, pSession->pSessionVM, pReq->u.In.idCpu,
1973 pReq->u.In.uOperation, NULL, pReq->u.In.u64Arg, pSession);
1974 else
1975 pReq->Hdr.rc = VERR_INVALID_VM_HANDLE;
1976 }
1977 else
1978 pReq->Hdr.rc = VERR_WRONG_ORDER;
1979 }
1980 else
1981 {
1982 PSUPVMMR0REQHDR pVMMReq = (PSUPVMMR0REQHDR)&pReq->abReqPkt[0];
1983 REQ_CHECK_EXPR_FMT(pReq->Hdr.cbIn >= SUP_IOCTL_CALL_VMMR0_SIZE(sizeof(SUPVMMR0REQHDR)),
1984 ("SUP_IOCTL_CALL_VMMR0: cbIn=%#x < %#lx\n", pReq->Hdr.cbIn, SUP_IOCTL_CALL_VMMR0_SIZE(sizeof(SUPVMMR0REQHDR))));
1985 REQ_CHECK_EXPR(SUP_IOCTL_CALL_VMMR0, pVMMReq->u32Magic == SUPVMMR0REQHDR_MAGIC);
1986 REQ_CHECK_SIZES_EX(SUP_IOCTL_CALL_VMMR0, SUP_IOCTL_CALL_VMMR0_SIZE_IN(pVMMReq->cbReq), SUP_IOCTL_CALL_VMMR0_SIZE_OUT(pVMMReq->cbReq));
1987
1988 /* execute */
1989 if (RT_LIKELY(pDevExt->pfnVMMR0EntryEx))
1990 {
1991 if (pReq->u.In.pVMR0 == NULL)
1992 pReq->Hdr.rc = pDevExt->pfnVMMR0EntryEx(NULL, NULL, pReq->u.In.idCpu,
1993 pReq->u.In.uOperation, pVMMReq, pReq->u.In.u64Arg, pSession);
1994 else if (pReq->u.In.pVMR0 == pSession->pSessionVM)
1995 pReq->Hdr.rc = pDevExt->pfnVMMR0EntryEx(pSession->pSessionGVM, pSession->pSessionVM, pReq->u.In.idCpu,
1996 pReq->u.In.uOperation, pVMMReq, pReq->u.In.u64Arg, pSession);
1997 else
1998 pReq->Hdr.rc = VERR_INVALID_VM_HANDLE;
1999 }
2000 else
2001 pReq->Hdr.rc = VERR_WRONG_ORDER;
2002 }
2003
2004 if ( RT_FAILURE(pReq->Hdr.rc)
2005 && pReq->Hdr.rc != VERR_INTERRUPTED
2006 && pReq->Hdr.rc != VERR_TIMEOUT)
2007 Log(("SUP_IOCTL_CALL_VMMR0: rc=%Rrc op=%u out=%u arg=%RX64 p/t=%RTproc/%RTthrd\n",
2008 pReq->Hdr.rc, pReq->u.In.uOperation, pReq->Hdr.cbOut, pReq->u.In.u64Arg, RTProcSelf(), RTThreadNativeSelf()));
2009 else
2010 Log4(("SUP_IOCTL_CALL_VMMR0: rc=%Rrc op=%u out=%u arg=%RX64 p/t=%RTproc/%RTthrd\n",
2011 pReq->Hdr.rc, pReq->u.In.uOperation, pReq->Hdr.cbOut, pReq->u.In.u64Arg, RTProcSelf(), RTThreadNativeSelf()));
2012 return 0;
2013 }
2014
2015 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_CALL_VMMR0_BIG):
2016 {
2017 /* validate */
2018 PSUPCALLVMMR0 pReq = (PSUPCALLVMMR0)pReqHdr;
2019 PSUPVMMR0REQHDR pVMMReq;
2020 Log4(("SUP_IOCTL_CALL_VMMR0_BIG: op=%u in=%u arg=%RX64 p/t=%RTproc/%RTthrd\n",
2021 pReq->u.In.uOperation, pReq->Hdr.cbIn, pReq->u.In.u64Arg, RTProcSelf(), RTThreadNativeSelf()));
2022
2023 pVMMReq = (PSUPVMMR0REQHDR)&pReq->abReqPkt[0];
2024 REQ_CHECK_EXPR_FMT(pReq->Hdr.cbIn >= SUP_IOCTL_CALL_VMMR0_BIG_SIZE(sizeof(SUPVMMR0REQHDR)),
2025 ("SUP_IOCTL_CALL_VMMR0_BIG: cbIn=%#x < %#lx\n", pReq->Hdr.cbIn, SUP_IOCTL_CALL_VMMR0_BIG_SIZE(sizeof(SUPVMMR0REQHDR))));
2026 REQ_CHECK_EXPR(SUP_IOCTL_CALL_VMMR0_BIG, pVMMReq->u32Magic == SUPVMMR0REQHDR_MAGIC);
2027 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));
2028
2029 /* execute */
2030 if (RT_LIKELY(pDevExt->pfnVMMR0EntryEx))
2031 {
2032 if (pReq->u.In.pVMR0 == NULL)
2033 pReq->Hdr.rc = pDevExt->pfnVMMR0EntryEx(NULL, NULL, pReq->u.In.idCpu, pReq->u.In.uOperation, pVMMReq, pReq->u.In.u64Arg, pSession);
2034 else if (pReq->u.In.pVMR0 == pSession->pSessionVM)
2035 pReq->Hdr.rc = pDevExt->pfnVMMR0EntryEx(pSession->pSessionGVM, pSession->pSessionVM, pReq->u.In.idCpu,
2036 pReq->u.In.uOperation, pVMMReq, pReq->u.In.u64Arg, pSession);
2037 else
2038 pReq->Hdr.rc = VERR_INVALID_VM_HANDLE;
2039 }
2040 else
2041 pReq->Hdr.rc = VERR_WRONG_ORDER;
2042
2043 if ( RT_FAILURE(pReq->Hdr.rc)
2044 && pReq->Hdr.rc != VERR_INTERRUPTED
2045 && pReq->Hdr.rc != VERR_TIMEOUT)
2046 Log(("SUP_IOCTL_CALL_VMMR0_BIG: rc=%Rrc op=%u out=%u arg=%RX64 p/t=%RTproc/%RTthrd\n",
2047 pReq->Hdr.rc, pReq->u.In.uOperation, pReq->Hdr.cbOut, pReq->u.In.u64Arg, RTProcSelf(), RTThreadNativeSelf()));
2048 else
2049 Log4(("SUP_IOCTL_CALL_VMMR0_BIG: rc=%Rrc op=%u out=%u arg=%RX64 p/t=%RTproc/%RTthrd\n",
2050 pReq->Hdr.rc, pReq->u.In.uOperation, pReq->Hdr.cbOut, pReq->u.In.u64Arg, RTProcSelf(), RTThreadNativeSelf()));
2051 return 0;
2052 }
2053
2054 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_GET_PAGING_MODE):
2055 {
2056 /* validate */
2057 PSUPGETPAGINGMODE pReq = (PSUPGETPAGINGMODE)pReqHdr;
2058 REQ_CHECK_SIZES(SUP_IOCTL_GET_PAGING_MODE);
2059
2060 /* execute */
2061 pReq->Hdr.rc = VINF_SUCCESS;
2062 pReq->u.Out.enmMode = SUPR0GetPagingMode();
2063 return 0;
2064 }
2065
2066 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_LOW_ALLOC):
2067 {
2068 /* validate */
2069 PSUPLOWALLOC pReq = (PSUPLOWALLOC)pReqHdr;
2070 REQ_CHECK_EXPR(SUP_IOCTL_LOW_ALLOC, pReq->Hdr.cbIn <= SUP_IOCTL_LOW_ALLOC_SIZE_IN);
2071 REQ_CHECK_SIZES_EX(SUP_IOCTL_LOW_ALLOC, SUP_IOCTL_LOW_ALLOC_SIZE_IN, SUP_IOCTL_LOW_ALLOC_SIZE_OUT(pReq->u.In.cPages));
2072
2073 /* execute */
2074 pReq->Hdr.rc = SUPR0LowAlloc(pSession, pReq->u.In.cPages, &pReq->u.Out.pvR0, &pReq->u.Out.pvR3, &pReq->u.Out.aPages[0]);
2075 if (RT_FAILURE(pReq->Hdr.rc))
2076 pReq->Hdr.cbOut = sizeof(pReq->Hdr);
2077 return 0;
2078 }
2079
2080 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_LOW_FREE):
2081 {
2082 /* validate */
2083 PSUPLOWFREE pReq = (PSUPLOWFREE)pReqHdr;
2084 REQ_CHECK_SIZES(SUP_IOCTL_LOW_FREE);
2085
2086 /* execute */
2087 pReq->Hdr.rc = SUPR0LowFree(pSession, (RTHCUINTPTR)pReq->u.In.pvR3);
2088 return 0;
2089 }
2090
2091 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_GIP_MAP):
2092 {
2093 /* validate */
2094 PSUPGIPMAP pReq = (PSUPGIPMAP)pReqHdr;
2095 REQ_CHECK_SIZES(SUP_IOCTL_GIP_MAP);
2096
2097 /* execute */
2098 pReq->Hdr.rc = SUPR0GipMap(pSession, &pReq->u.Out.pGipR3, &pReq->u.Out.HCPhysGip);
2099 if (RT_SUCCESS(pReq->Hdr.rc))
2100 pReq->u.Out.pGipR0 = pDevExt->pGip;
2101 return 0;
2102 }
2103
2104 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_GIP_UNMAP):
2105 {
2106 /* validate */
2107 PSUPGIPUNMAP pReq = (PSUPGIPUNMAP)pReqHdr;
2108 REQ_CHECK_SIZES(SUP_IOCTL_GIP_UNMAP);
2109
2110 /* execute */
2111 pReq->Hdr.rc = SUPR0GipUnmap(pSession);
2112 return 0;
2113 }
2114
2115 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_SET_VM_FOR_FAST):
2116 {
2117 /* validate */
2118 PSUPSETVMFORFAST pReq = (PSUPSETVMFORFAST)pReqHdr;
2119 REQ_CHECK_SIZES(SUP_IOCTL_SET_VM_FOR_FAST);
2120 REQ_CHECK_EXPR_FMT( !pReq->u.In.pVMR0
2121 || ( RT_VALID_PTR(pReq->u.In.pVMR0)
2122 && !((uintptr_t)pReq->u.In.pVMR0 & (PAGE_SIZE - 1))),
2123 ("SUP_IOCTL_SET_VM_FOR_FAST: pVMR0=%p!\n", pReq->u.In.pVMR0));
2124
2125 /* execute */
2126 RTSpinlockAcquire(pDevExt->Spinlock);
2127 if (pSession->pSessionVM == pReq->u.In.pVMR0)
2128 {
2129 if (pSession->pFastIoCtrlVM == NULL)
2130 {
2131 pSession->pFastIoCtrlVM = pSession->pSessionVM;
2132 RTSpinlockRelease(pDevExt->Spinlock);
2133 pReq->Hdr.rc = VINF_SUCCESS;
2134 }
2135 else
2136 {
2137 RTSpinlockRelease(pDevExt->Spinlock);
2138 OSDBGPRINT(("SUP_IOCTL_SET_VM_FOR_FAST: pSession->pFastIoCtrlVM=%p! (pVMR0=%p)\n",
2139 pSession->pFastIoCtrlVM, pReq->u.In.pVMR0));
2140 pReq->Hdr.rc = VERR_ALREADY_EXISTS;
2141 }
2142 }
2143 else
2144 {
2145 RTSpinlockRelease(pDevExt->Spinlock);
2146 OSDBGPRINT(("SUP_IOCTL_SET_VM_FOR_FAST: pSession->pSessionVM=%p vs pVMR0=%p)\n",
2147 pSession->pSessionVM, pReq->u.In.pVMR0));
2148 pReq->Hdr.rc = pSession->pSessionVM ? VERR_ACCESS_DENIED : VERR_WRONG_ORDER;
2149 }
2150 return 0;
2151 }
2152
2153 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_PAGE_ALLOC_EX):
2154 {
2155 /* validate */
2156 PSUPPAGEALLOCEX pReq = (PSUPPAGEALLOCEX)pReqHdr;
2157 REQ_CHECK_EXPR(SUP_IOCTL_PAGE_ALLOC_EX, pReq->Hdr.cbIn <= SUP_IOCTL_PAGE_ALLOC_EX_SIZE_IN);
2158 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));
2159 REQ_CHECK_EXPR_FMT(pReq->u.In.fKernelMapping || pReq->u.In.fUserMapping,
2160 ("SUP_IOCTL_PAGE_ALLOC_EX: No mapping requested!\n"));
2161 REQ_CHECK_EXPR_FMT(pReq->u.In.fUserMapping,
2162 ("SUP_IOCTL_PAGE_ALLOC_EX: Must have user mapping!\n"));
2163 REQ_CHECK_EXPR_FMT(!pReq->u.In.fReserved0 && !pReq->u.In.fReserved1,
2164 ("SUP_IOCTL_PAGE_ALLOC_EX: fReserved0=%d fReserved1=%d\n", pReq->u.In.fReserved0, pReq->u.In.fReserved1));
2165
2166 /* execute */
2167 pReq->Hdr.rc = SUPR0PageAllocEx(pSession, pReq->u.In.cPages, 0 /* fFlags */,
2168 pReq->u.In.fUserMapping ? &pReq->u.Out.pvR3 : NULL,
2169 pReq->u.In.fKernelMapping ? &pReq->u.Out.pvR0 : NULL,
2170 &pReq->u.Out.aPages[0]);
2171 if (RT_FAILURE(pReq->Hdr.rc))
2172 pReq->Hdr.cbOut = sizeof(pReq->Hdr);
2173 return 0;
2174 }
2175
2176 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_PAGE_MAP_KERNEL):
2177 {
2178 /* validate */
2179 PSUPPAGEMAPKERNEL pReq = (PSUPPAGEMAPKERNEL)pReqHdr;
2180 REQ_CHECK_SIZES(SUP_IOCTL_PAGE_MAP_KERNEL);
2181 REQ_CHECK_EXPR_FMT(!pReq->u.In.fFlags, ("SUP_IOCTL_PAGE_MAP_KERNEL: fFlags=%#x! MBZ\n", pReq->u.In.fFlags));
2182 REQ_CHECK_EXPR_FMT(!(pReq->u.In.offSub & PAGE_OFFSET_MASK), ("SUP_IOCTL_PAGE_MAP_KERNEL: offSub=%#x\n", pReq->u.In.offSub));
2183 REQ_CHECK_EXPR_FMT(pReq->u.In.cbSub && !(pReq->u.In.cbSub & PAGE_OFFSET_MASK),
2184 ("SUP_IOCTL_PAGE_MAP_KERNEL: cbSub=%#x\n", pReq->u.In.cbSub));
2185
2186 /* execute */
2187 pReq->Hdr.rc = SUPR0PageMapKernel(pSession, pReq->u.In.pvR3, pReq->u.In.offSub, pReq->u.In.cbSub,
2188 pReq->u.In.fFlags, &pReq->u.Out.pvR0);
2189 if (RT_FAILURE(pReq->Hdr.rc))
2190 pReq->Hdr.cbOut = sizeof(pReq->Hdr);
2191 return 0;
2192 }
2193
2194 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_PAGE_PROTECT):
2195 {
2196 /* validate */
2197 PSUPPAGEPROTECT pReq = (PSUPPAGEPROTECT)pReqHdr;
2198 REQ_CHECK_SIZES(SUP_IOCTL_PAGE_PROTECT);
2199 REQ_CHECK_EXPR_FMT(!(pReq->u.In.fProt & ~(RTMEM_PROT_READ | RTMEM_PROT_WRITE | RTMEM_PROT_EXEC | RTMEM_PROT_NONE)),
2200 ("SUP_IOCTL_PAGE_PROTECT: fProt=%#x!\n", pReq->u.In.fProt));
2201 REQ_CHECK_EXPR_FMT(!(pReq->u.In.offSub & PAGE_OFFSET_MASK), ("SUP_IOCTL_PAGE_PROTECT: offSub=%#x\n", pReq->u.In.offSub));
2202 REQ_CHECK_EXPR_FMT(pReq->u.In.cbSub && !(pReq->u.In.cbSub & PAGE_OFFSET_MASK),
2203 ("SUP_IOCTL_PAGE_PROTECT: cbSub=%#x\n", pReq->u.In.cbSub));
2204
2205 /* execute */
2206 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);
2207 return 0;
2208 }
2209
2210 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_PAGE_FREE):
2211 {
2212 /* validate */
2213 PSUPPAGEFREE pReq = (PSUPPAGEFREE)pReqHdr;
2214 REQ_CHECK_SIZES(SUP_IOCTL_PAGE_FREE);
2215
2216 /* execute */
2217 pReq->Hdr.rc = SUPR0PageFree(pSession, pReq->u.In.pvR3);
2218 return 0;
2219 }
2220
2221 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_CALL_SERVICE_NO_SIZE()):
2222 {
2223 /* validate */
2224 PSUPCALLSERVICE pReq = (PSUPCALLSERVICE)pReqHdr;
2225 Log4(("SUP_IOCTL_CALL_SERVICE: op=%u in=%u arg=%RX64 p/t=%RTproc/%RTthrd\n",
2226 pReq->u.In.uOperation, pReq->Hdr.cbIn, pReq->u.In.u64Arg, RTProcSelf(), RTThreadNativeSelf()));
2227
2228 if (pReq->Hdr.cbIn == SUP_IOCTL_CALL_SERVICE_SIZE(0))
2229 REQ_CHECK_SIZES_EX(SUP_IOCTL_CALL_SERVICE, SUP_IOCTL_CALL_SERVICE_SIZE_IN(0), SUP_IOCTL_CALL_SERVICE_SIZE_OUT(0));
2230 else
2231 {
2232 PSUPR0SERVICEREQHDR pSrvReq = (PSUPR0SERVICEREQHDR)&pReq->abReqPkt[0];
2233 REQ_CHECK_EXPR_FMT(pReq->Hdr.cbIn >= SUP_IOCTL_CALL_SERVICE_SIZE(sizeof(SUPR0SERVICEREQHDR)),
2234 ("SUP_IOCTL_CALL_SERVICE: cbIn=%#x < %#lx\n", pReq->Hdr.cbIn, SUP_IOCTL_CALL_SERVICE_SIZE(sizeof(SUPR0SERVICEREQHDR))));
2235 REQ_CHECK_EXPR(SUP_IOCTL_CALL_SERVICE, pSrvReq->u32Magic == SUPR0SERVICEREQHDR_MAGIC);
2236 REQ_CHECK_SIZES_EX(SUP_IOCTL_CALL_SERVICE, SUP_IOCTL_CALL_SERVICE_SIZE_IN(pSrvReq->cbReq), SUP_IOCTL_CALL_SERVICE_SIZE_OUT(pSrvReq->cbReq));
2237 }
2238 REQ_CHECK_EXPR(SUP_IOCTL_CALL_SERVICE, RTStrEnd(pReq->u.In.szName, sizeof(pReq->u.In.szName)));
2239
2240 /* execute */
2241 pReq->Hdr.rc = supdrvIOCtl_CallServiceModule(pDevExt, pSession, pReq);
2242 return 0;
2243 }
2244
2245 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_LOGGER_SETTINGS_NO_SIZE()):
2246 {
2247 /* validate */
2248 PSUPLOGGERSETTINGS pReq = (PSUPLOGGERSETTINGS)pReqHdr;
2249 size_t cbStrTab;
2250 REQ_CHECK_SIZE_OUT(SUP_IOCTL_LOGGER_SETTINGS, SUP_IOCTL_LOGGER_SETTINGS_SIZE_OUT);
2251 REQ_CHECK_EXPR(SUP_IOCTL_LOGGER_SETTINGS, pReq->Hdr.cbIn >= SUP_IOCTL_LOGGER_SETTINGS_SIZE_IN(1));
2252 cbStrTab = pReq->Hdr.cbIn - SUP_IOCTL_LOGGER_SETTINGS_SIZE_IN(0);
2253 REQ_CHECK_EXPR(SUP_IOCTL_LOGGER_SETTINGS, pReq->u.In.offGroups < cbStrTab);
2254 REQ_CHECK_EXPR(SUP_IOCTL_LOGGER_SETTINGS, pReq->u.In.offFlags < cbStrTab);
2255 REQ_CHECK_EXPR(SUP_IOCTL_LOGGER_SETTINGS, pReq->u.In.offDestination < cbStrTab);
2256 REQ_CHECK_EXPR_FMT(pReq->u.In.szStrings[cbStrTab - 1] == '\0',
2257 ("SUP_IOCTL_LOGGER_SETTINGS: cbIn=%#x cbStrTab=%#zx LastChar=%d\n",
2258 pReq->Hdr.cbIn, cbStrTab, pReq->u.In.szStrings[cbStrTab - 1]));
2259 REQ_CHECK_EXPR(SUP_IOCTL_LOGGER_SETTINGS, pReq->u.In.fWhich <= SUPLOGGERSETTINGS_WHICH_RELEASE);
2260 REQ_CHECK_EXPR(SUP_IOCTL_LOGGER_SETTINGS, pReq->u.In.fWhat <= SUPLOGGERSETTINGS_WHAT_DESTROY);
2261
2262 /* execute */
2263 pReq->Hdr.rc = supdrvIOCtl_LoggerSettings(pReq);
2264 return 0;
2265 }
2266
2267 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_SEM_OP2):
2268 {
2269 /* validate */
2270 PSUPSEMOP2 pReq = (PSUPSEMOP2)pReqHdr;
2271 REQ_CHECK_SIZES_EX(SUP_IOCTL_SEM_OP2, SUP_IOCTL_SEM_OP2_SIZE_IN, SUP_IOCTL_SEM_OP2_SIZE_OUT);
2272 REQ_CHECK_EXPR(SUP_IOCTL_SEM_OP2, pReq->u.In.uReserved == 0);
2273
2274 /* execute */
2275 switch (pReq->u.In.uType)
2276 {
2277 case SUP_SEM_TYPE_EVENT:
2278 {
2279 SUPSEMEVENT hEvent = (SUPSEMEVENT)(uintptr_t)pReq->u.In.hSem;
2280 switch (pReq->u.In.uOp)
2281 {
2282 case SUPSEMOP2_WAIT_MS_REL:
2283 pReq->Hdr.rc = SUPSemEventWaitNoResume(pSession, hEvent, pReq->u.In.uArg.cRelMsTimeout);
2284 break;
2285 case SUPSEMOP2_WAIT_NS_ABS:
2286 pReq->Hdr.rc = SUPSemEventWaitNsAbsIntr(pSession, hEvent, pReq->u.In.uArg.uAbsNsTimeout);
2287 break;
2288 case SUPSEMOP2_WAIT_NS_REL:
2289 pReq->Hdr.rc = SUPSemEventWaitNsRelIntr(pSession, hEvent, pReq->u.In.uArg.cRelNsTimeout);
2290 break;
2291 case SUPSEMOP2_SIGNAL:
2292 pReq->Hdr.rc = SUPSemEventSignal(pSession, hEvent);
2293 break;
2294 case SUPSEMOP2_CLOSE:
2295 pReq->Hdr.rc = SUPSemEventClose(pSession, hEvent);
2296 break;
2297 case SUPSEMOP2_RESET:
2298 default:
2299 pReq->Hdr.rc = VERR_INVALID_FUNCTION;
2300 break;
2301 }
2302 break;
2303 }
2304
2305 case SUP_SEM_TYPE_EVENT_MULTI:
2306 {
2307 SUPSEMEVENTMULTI hEventMulti = (SUPSEMEVENTMULTI)(uintptr_t)pReq->u.In.hSem;
2308 switch (pReq->u.In.uOp)
2309 {
2310 case SUPSEMOP2_WAIT_MS_REL:
2311 pReq->Hdr.rc = SUPSemEventMultiWaitNoResume(pSession, hEventMulti, pReq->u.In.uArg.cRelMsTimeout);
2312 break;
2313 case SUPSEMOP2_WAIT_NS_ABS:
2314 pReq->Hdr.rc = SUPSemEventMultiWaitNsAbsIntr(pSession, hEventMulti, pReq->u.In.uArg.uAbsNsTimeout);
2315 break;
2316 case SUPSEMOP2_WAIT_NS_REL:
2317 pReq->Hdr.rc = SUPSemEventMultiWaitNsRelIntr(pSession, hEventMulti, pReq->u.In.uArg.cRelNsTimeout);
2318 break;
2319 case SUPSEMOP2_SIGNAL:
2320 pReq->Hdr.rc = SUPSemEventMultiSignal(pSession, hEventMulti);
2321 break;
2322 case SUPSEMOP2_CLOSE:
2323 pReq->Hdr.rc = SUPSemEventMultiClose(pSession, hEventMulti);
2324 break;
2325 case SUPSEMOP2_RESET:
2326 pReq->Hdr.rc = SUPSemEventMultiReset(pSession, hEventMulti);
2327 break;
2328 default:
2329 pReq->Hdr.rc = VERR_INVALID_FUNCTION;
2330 break;
2331 }
2332 break;
2333 }
2334
2335 default:
2336 pReq->Hdr.rc = VERR_INVALID_PARAMETER;
2337 break;
2338 }
2339 return 0;
2340 }
2341
2342 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_SEM_OP3):
2343 {
2344 /* validate */
2345 PSUPSEMOP3 pReq = (PSUPSEMOP3)pReqHdr;
2346 REQ_CHECK_SIZES_EX(SUP_IOCTL_SEM_OP3, SUP_IOCTL_SEM_OP3_SIZE_IN, SUP_IOCTL_SEM_OP3_SIZE_OUT);
2347 REQ_CHECK_EXPR(SUP_IOCTL_SEM_OP3, pReq->u.In.u32Reserved == 0 && pReq->u.In.u64Reserved == 0);
2348
2349 /* execute */
2350 switch (pReq->u.In.uType)
2351 {
2352 case SUP_SEM_TYPE_EVENT:
2353 {
2354 SUPSEMEVENT hEvent = (SUPSEMEVENT)(uintptr_t)pReq->u.In.hSem;
2355 switch (pReq->u.In.uOp)
2356 {
2357 case SUPSEMOP3_CREATE:
2358 REQ_CHECK_EXPR(SUP_IOCTL_SEM_OP3, hEvent == NIL_SUPSEMEVENT);
2359 pReq->Hdr.rc = SUPSemEventCreate(pSession, &hEvent);
2360 pReq->u.Out.hSem = (uint32_t)(uintptr_t)hEvent;
2361 break;
2362 case SUPSEMOP3_GET_RESOLUTION:
2363 REQ_CHECK_EXPR(SUP_IOCTL_SEM_OP3, hEvent == NIL_SUPSEMEVENT);
2364 pReq->Hdr.rc = VINF_SUCCESS;
2365 pReq->Hdr.cbOut = sizeof(*pReq);
2366 pReq->u.Out.cNsResolution = SUPSemEventGetResolution(pSession);
2367 break;
2368 default:
2369 pReq->Hdr.rc = VERR_INVALID_FUNCTION;
2370 break;
2371 }
2372 break;
2373 }
2374
2375 case SUP_SEM_TYPE_EVENT_MULTI:
2376 {
2377 SUPSEMEVENTMULTI hEventMulti = (SUPSEMEVENTMULTI)(uintptr_t)pReq->u.In.hSem;
2378 switch (pReq->u.In.uOp)
2379 {
2380 case SUPSEMOP3_CREATE:
2381 REQ_CHECK_EXPR(SUP_IOCTL_SEM_OP3, hEventMulti == NIL_SUPSEMEVENTMULTI);
2382 pReq->Hdr.rc = SUPSemEventMultiCreate(pSession, &hEventMulti);
2383 pReq->u.Out.hSem = (uint32_t)(uintptr_t)hEventMulti;
2384 break;
2385 case SUPSEMOP3_GET_RESOLUTION:
2386 REQ_CHECK_EXPR(SUP_IOCTL_SEM_OP3, hEventMulti == NIL_SUPSEMEVENTMULTI);
2387 pReq->Hdr.rc = VINF_SUCCESS;
2388 pReq->u.Out.cNsResolution = SUPSemEventMultiGetResolution(pSession);
2389 break;
2390 default:
2391 pReq->Hdr.rc = VERR_INVALID_FUNCTION;
2392 break;
2393 }
2394 break;
2395 }
2396
2397 default:
2398 pReq->Hdr.rc = VERR_INVALID_PARAMETER;
2399 break;
2400 }
2401 return 0;
2402 }
2403
2404 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_VT_CAPS):
2405 {
2406 /* validate */
2407 PSUPVTCAPS pReq = (PSUPVTCAPS)pReqHdr;
2408 REQ_CHECK_SIZES(SUP_IOCTL_VT_CAPS);
2409
2410 /* execute */
2411 pReq->Hdr.rc = SUPR0QueryVTCaps(pSession, &pReq->u.Out.fCaps);
2412 if (RT_FAILURE(pReq->Hdr.rc))
2413 pReq->Hdr.cbOut = sizeof(pReq->Hdr);
2414 return 0;
2415 }
2416
2417 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_TRACER_OPEN):
2418 {
2419 /* validate */
2420 PSUPTRACEROPEN pReq = (PSUPTRACEROPEN)pReqHdr;
2421 REQ_CHECK_SIZES(SUP_IOCTL_TRACER_OPEN);
2422
2423 /* execute */
2424 pReq->Hdr.rc = supdrvIOCtl_TracerOpen(pDevExt, pSession, pReq->u.In.uCookie, pReq->u.In.uArg);
2425 return 0;
2426 }
2427
2428 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_TRACER_CLOSE):
2429 {
2430 /* validate */
2431 REQ_CHECK_SIZES(SUP_IOCTL_TRACER_CLOSE);
2432
2433 /* execute */
2434 pReqHdr->rc = supdrvIOCtl_TracerClose(pDevExt, pSession);
2435 return 0;
2436 }
2437
2438 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_TRACER_IOCTL):
2439 {
2440 /* validate */
2441 PSUPTRACERIOCTL pReq = (PSUPTRACERIOCTL)pReqHdr;
2442 REQ_CHECK_SIZES(SUP_IOCTL_TRACER_IOCTL);
2443
2444 /* execute */
2445 pReqHdr->rc = supdrvIOCtl_TracerIOCtl(pDevExt, pSession, pReq->u.In.uCmd, pReq->u.In.uArg, &pReq->u.Out.iRetVal);
2446 return 0;
2447 }
2448
2449 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_TRACER_UMOD_REG):
2450 {
2451 /* validate */
2452 PSUPTRACERUMODREG pReq = (PSUPTRACERUMODREG)pReqHdr;
2453 REQ_CHECK_SIZES(SUP_IOCTL_TRACER_UMOD_REG);
2454 if (!RTStrEnd(pReq->u.In.szName, sizeof(pReq->u.In.szName)))
2455 return VERR_INVALID_PARAMETER;
2456
2457 /* execute */
2458 pReqHdr->rc = supdrvIOCtl_TracerUmodRegister(pDevExt, pSession,
2459 pReq->u.In.R3PtrVtgHdr, pReq->u.In.uVtgHdrAddr,
2460 pReq->u.In.R3PtrStrTab, pReq->u.In.cbStrTab,
2461 pReq->u.In.szName, pReq->u.In.fFlags);
2462 return 0;
2463 }
2464
2465 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_TRACER_UMOD_DEREG):
2466 {
2467 /* validate */
2468 PSUPTRACERUMODDEREG pReq = (PSUPTRACERUMODDEREG)pReqHdr;
2469 REQ_CHECK_SIZES(SUP_IOCTL_TRACER_UMOD_DEREG);
2470
2471 /* execute */
2472 pReqHdr->rc = supdrvIOCtl_TracerUmodDeregister(pDevExt, pSession, pReq->u.In.pVtgHdr);
2473 return 0;
2474 }
2475
2476 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_TRACER_UMOD_FIRE_PROBE):
2477 {
2478 /* validate */
2479 PSUPTRACERUMODFIREPROBE pReq = (PSUPTRACERUMODFIREPROBE)pReqHdr;
2480 REQ_CHECK_SIZES(SUP_IOCTL_TRACER_UMOD_FIRE_PROBE);
2481
2482 supdrvIOCtl_TracerUmodProbeFire(pDevExt, pSession, &pReq->u.In);
2483 pReqHdr->rc = VINF_SUCCESS;
2484 return 0;
2485 }
2486
2487 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_MSR_PROBER):
2488 {
2489 /* validate */
2490 PSUPMSRPROBER pReq = (PSUPMSRPROBER)pReqHdr;
2491 REQ_CHECK_SIZES(SUP_IOCTL_MSR_PROBER);
2492 REQ_CHECK_EXPR(SUP_IOCTL_MSR_PROBER,
2493 pReq->u.In.enmOp > SUPMSRPROBEROP_INVALID && pReq->u.In.enmOp < SUPMSRPROBEROP_END);
2494
2495 pReqHdr->rc = supdrvIOCtl_MsrProber(pDevExt, pReq);
2496 return 0;
2497 }
2498
2499 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_RESUME_SUSPENDED_KBDS):
2500 {
2501 /* validate */
2502 REQ_CHECK_SIZES(SUP_IOCTL_RESUME_SUSPENDED_KBDS);
2503
2504 pReqHdr->rc = supdrvIOCtl_ResumeSuspendedKbds();
2505 return 0;
2506 }
2507
2508 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_TSC_DELTA_MEASURE):
2509 {
2510 /* validate */
2511 PSUPTSCDELTAMEASURE pReq = (PSUPTSCDELTAMEASURE)pReqHdr;
2512 REQ_CHECK_SIZES(SUP_IOCTL_TSC_DELTA_MEASURE);
2513
2514 pReqHdr->rc = supdrvIOCtl_TscDeltaMeasure(pDevExt, pSession, pReq);
2515 return 0;
2516 }
2517
2518 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_TSC_READ):
2519 {
2520 /* validate */
2521 PSUPTSCREAD pReq = (PSUPTSCREAD)pReqHdr;
2522 REQ_CHECK_SIZES(SUP_IOCTL_TSC_READ);
2523
2524 pReqHdr->rc = supdrvIOCtl_TscRead(pDevExt, pSession, pReq);
2525 return 0;
2526 }
2527
2528 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_GIP_SET_FLAGS):
2529 {
2530 /* validate */
2531 PSUPGIPSETFLAGS pReq = (PSUPGIPSETFLAGS)pReqHdr;
2532 REQ_CHECK_SIZES(SUP_IOCTL_GIP_SET_FLAGS);
2533
2534 pReqHdr->rc = supdrvIOCtl_GipSetFlags(pDevExt, pSession, pReq->u.In.fOrMask, pReq->u.In.fAndMask);
2535 return 0;
2536 }
2537
2538 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_UCODE_REV):
2539 {
2540 /* validate */
2541 PSUPUCODEREV pReq = (PSUPUCODEREV)pReqHdr;
2542 REQ_CHECK_SIZES(SUP_IOCTL_UCODE_REV);
2543
2544 /* execute */
2545 pReq->Hdr.rc = SUPR0QueryUcodeRev(pSession, &pReq->u.Out.MicrocodeRev);
2546 if (RT_FAILURE(pReq->Hdr.rc))
2547 pReq->Hdr.cbOut = sizeof(pReq->Hdr);
2548 return 0;
2549 }
2550
2551 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_GET_HWVIRT_MSRS):
2552 {
2553 /* validate */
2554 PSUPGETHWVIRTMSRS pReq = (PSUPGETHWVIRTMSRS)pReqHdr;
2555 REQ_CHECK_SIZES(SUP_IOCTL_GET_HWVIRT_MSRS);
2556 REQ_CHECK_EXPR_FMT(!pReq->u.In.fReserved0 && !pReq->u.In.fReserved1 && !pReq->u.In.fReserved2,
2557 ("SUP_IOCTL_GET_HWVIRT_MSRS: fReserved0=%d fReserved1=%d fReserved2=%d\n", pReq->u.In.fReserved0,
2558 pReq->u.In.fReserved1, pReq->u.In.fReserved2));
2559
2560 /* execute */
2561 pReq->Hdr.rc = SUPR0GetHwvirtMsrs(&pReq->u.Out.HwvirtMsrs, 0 /* fCaps */, pReq->u.In.fForce);
2562 if (RT_FAILURE(pReq->Hdr.rc))
2563 pReq->Hdr.cbOut = sizeof(pReq->Hdr);
2564 return 0;
2565 }
2566
2567 default:
2568 Log(("Unknown IOCTL %#lx\n", (long)uIOCtl));
2569 break;
2570 }
2571 return VERR_GENERAL_FAILURE;
2572}
2573
2574
2575/**
2576 * I/O Control inner worker for the restricted operations.
2577 *
2578 * @returns IPRT status code.
2579 * @retval VERR_INVALID_PARAMETER if the request is invalid.
2580 *
2581 * @param uIOCtl Function number.
2582 * @param pDevExt Device extention.
2583 * @param pSession Session data.
2584 * @param pReqHdr The request header.
2585 */
2586static int supdrvIOCtlInnerRestricted(uintptr_t uIOCtl, PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPREQHDR pReqHdr)
2587{
2588 /*
2589 * The switch.
2590 */
2591 switch (SUP_CTL_CODE_NO_SIZE(uIOCtl))
2592 {
2593 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_COOKIE):
2594 {
2595 PSUPCOOKIE pReq = (PSUPCOOKIE)pReqHdr;
2596 REQ_CHECK_SIZES(SUP_IOCTL_COOKIE);
2597 if (strncmp(pReq->u.In.szMagic, SUPCOOKIE_MAGIC, sizeof(pReq->u.In.szMagic)))
2598 {
2599 OSDBGPRINT(("SUP_IOCTL_COOKIE: invalid magic %.16s\n", pReq->u.In.szMagic));
2600 pReq->Hdr.rc = VERR_INVALID_MAGIC;
2601 return 0;
2602 }
2603
2604 /*
2605 * Match the version.
2606 * The current logic is very simple, match the major interface version.
2607 */
2608 if ( pReq->u.In.u32MinVersion > SUPDRV_IOC_VERSION
2609 || (pReq->u.In.u32MinVersion & 0xffff0000) != (SUPDRV_IOC_VERSION & 0xffff0000))
2610 {
2611 OSDBGPRINT(("SUP_IOCTL_COOKIE: Version mismatch. Requested: %#x Min: %#x Current: %#x\n",
2612 pReq->u.In.u32ReqVersion, pReq->u.In.u32MinVersion, SUPDRV_IOC_VERSION));
2613 pReq->u.Out.u32Cookie = 0xffffffff;
2614 pReq->u.Out.u32SessionCookie = 0xffffffff;
2615 pReq->u.Out.u32SessionVersion = 0xffffffff;
2616 pReq->u.Out.u32DriverVersion = SUPDRV_IOC_VERSION;
2617 pReq->u.Out.pSession = NULL;
2618 pReq->u.Out.cFunctions = 0;
2619 pReq->Hdr.rc = VERR_VERSION_MISMATCH;
2620 return 0;
2621 }
2622
2623 /*
2624 * Fill in return data and be gone.
2625 * N.B. The first one to change SUPDRV_IOC_VERSION shall makes sure that
2626 * u32SessionVersion <= u32ReqVersion!
2627 */
2628 /** @todo Somehow validate the client and negotiate a secure cookie... */
2629 pReq->u.Out.u32Cookie = pDevExt->u32Cookie;
2630 pReq->u.Out.u32SessionCookie = pSession->u32Cookie;
2631 pReq->u.Out.u32SessionVersion = SUPDRV_IOC_VERSION;
2632 pReq->u.Out.u32DriverVersion = SUPDRV_IOC_VERSION;
2633 pReq->u.Out.pSession = NULL;
2634 pReq->u.Out.cFunctions = 0;
2635 pReq->Hdr.rc = VINF_SUCCESS;
2636 return 0;
2637 }
2638
2639 case SUP_CTL_CODE_NO_SIZE(SUP_IOCTL_VT_CAPS):
2640 {
2641 /* validate */
2642 PSUPVTCAPS pReq = (PSUPVTCAPS)pReqHdr;
2643 REQ_CHECK_SIZES(SUP_IOCTL_VT_CAPS);
2644
2645 /* execute */
2646 pReq->Hdr.rc = SUPR0QueryVTCaps(pSession, &pReq->u.Out.fCaps);
2647 if (RT_FAILURE(pReq->Hdr.rc))
2648 pReq->Hdr.cbOut = sizeof(pReq->Hdr);
2649 return 0;
2650 }
2651
2652 default:
2653 Log(("Unknown IOCTL %#lx\n", (long)uIOCtl));
2654 break;
2655 }
2656 return VERR_GENERAL_FAILURE;
2657}
2658
2659
2660/**
2661 * I/O Control worker.
2662 *
2663 * @returns IPRT status code.
2664 * @retval VERR_INVALID_PARAMETER if the request is invalid.
2665 *
2666 * @param uIOCtl Function number.
2667 * @param pDevExt Device extention.
2668 * @param pSession Session data.
2669 * @param pReqHdr The request header.
2670 * @param cbReq The size of the request buffer.
2671 */
2672int VBOXCALL supdrvIOCtl(uintptr_t uIOCtl, PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPREQHDR pReqHdr, size_t cbReq)
2673{
2674 int rc;
2675 VBOXDRV_IOCTL_ENTRY(pSession, uIOCtl, pReqHdr);
2676
2677 /*
2678 * Validate the request.
2679 */
2680 if (RT_UNLIKELY(cbReq < sizeof(*pReqHdr)))
2681 {
2682 OSDBGPRINT(("vboxdrv: Bad ioctl request size; cbReq=%#lx\n", (long)cbReq));
2683 VBOXDRV_IOCTL_RETURN(pSession, uIOCtl, pReqHdr, VERR_INVALID_PARAMETER, VINF_SUCCESS);
2684 return VERR_INVALID_PARAMETER;
2685 }
2686 if (RT_UNLIKELY( (pReqHdr->fFlags & SUPREQHDR_FLAGS_MAGIC_MASK) != SUPREQHDR_FLAGS_MAGIC
2687 || pReqHdr->cbIn < sizeof(*pReqHdr)
2688 || pReqHdr->cbIn > cbReq
2689 || pReqHdr->cbOut < sizeof(*pReqHdr)
2690 || pReqHdr->cbOut > cbReq))
2691 {
2692 OSDBGPRINT(("vboxdrv: Bad ioctl request header; cbIn=%#lx cbOut=%#lx fFlags=%#lx\n",
2693 (long)pReqHdr->cbIn, (long)pReqHdr->cbOut, (long)pReqHdr->fFlags));
2694 VBOXDRV_IOCTL_RETURN(pSession, uIOCtl, pReqHdr, VERR_INVALID_PARAMETER, VINF_SUCCESS);
2695 return VERR_INVALID_PARAMETER;
2696 }
2697 if (RT_UNLIKELY(!RT_VALID_PTR(pSession)))
2698 {
2699 OSDBGPRINT(("vboxdrv: Invalid pSession value %p (ioctl=%p)\n", pSession, (void *)uIOCtl));
2700 VBOXDRV_IOCTL_RETURN(pSession, uIOCtl, pReqHdr, VERR_INVALID_PARAMETER, VINF_SUCCESS);
2701 return VERR_INVALID_PARAMETER;
2702 }
2703 if (RT_UNLIKELY(uIOCtl == SUP_IOCTL_COOKIE))
2704 {
2705 if (pReqHdr->u32Cookie != SUPCOOKIE_INITIAL_COOKIE)
2706 {
2707 OSDBGPRINT(("SUP_IOCTL_COOKIE: bad cookie %#lx\n", (long)pReqHdr->u32Cookie));
2708 VBOXDRV_IOCTL_RETURN(pSession, uIOCtl, pReqHdr, VERR_INVALID_PARAMETER, VINF_SUCCESS);
2709 return VERR_INVALID_PARAMETER;
2710 }
2711 }
2712 else if (RT_UNLIKELY( pReqHdr->u32Cookie != pDevExt->u32Cookie
2713 || pReqHdr->u32SessionCookie != pSession->u32Cookie))
2714 {
2715 OSDBGPRINT(("vboxdrv: bad cookie %#lx / %#lx.\n", (long)pReqHdr->u32Cookie, (long)pReqHdr->u32SessionCookie));
2716 VBOXDRV_IOCTL_RETURN(pSession, uIOCtl, pReqHdr, VERR_INVALID_PARAMETER, VINF_SUCCESS);
2717 return VERR_INVALID_PARAMETER;
2718 }
2719
2720 /*
2721 * Hand it to an inner function to avoid lots of unnecessary return tracepoints.
2722 */
2723 if (pSession->fUnrestricted)
2724 rc = supdrvIOCtlInnerUnrestricted(uIOCtl, pDevExt, pSession, pReqHdr);
2725 else
2726 rc = supdrvIOCtlInnerRestricted(uIOCtl, pDevExt, pSession, pReqHdr);
2727
2728 VBOXDRV_IOCTL_RETURN(pSession, uIOCtl, pReqHdr, pReqHdr->rc, rc);
2729 return rc;
2730}
2731
2732
2733/**
2734 * Inter-Driver Communication (IDC) worker.
2735 *
2736 * @returns VBox status code.
2737 * @retval VINF_SUCCESS on success.
2738 * @retval VERR_INVALID_PARAMETER if the request is invalid.
2739 * @retval VERR_NOT_SUPPORTED if the request isn't supported.
2740 *
2741 * @param uReq The request (function) code.
2742 * @param pDevExt Device extention.
2743 * @param pSession Session data.
2744 * @param pReqHdr The request header.
2745 */
2746int VBOXCALL supdrvIDC(uintptr_t uReq, PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPDRVIDCREQHDR pReqHdr)
2747{
2748 /*
2749 * The OS specific code has already validated the pSession
2750 * pointer, and the request size being greater or equal to
2751 * size of the header.
2752 *
2753 * So, just check that pSession is a kernel context session.
2754 */
2755 if (RT_UNLIKELY( pSession
2756 && pSession->R0Process != NIL_RTR0PROCESS))
2757 return VERR_INVALID_PARAMETER;
2758
2759/*
2760 * Validation macro.
2761 */
2762#define REQ_CHECK_IDC_SIZE(Name, cbExpect) \
2763 do { \
2764 if (RT_UNLIKELY(pReqHdr->cb != (cbExpect))) \
2765 { \
2766 OSDBGPRINT(( #Name ": Invalid input/output sizes. cb=%ld expected %ld.\n", \
2767 (long)pReqHdr->cb, (long)(cbExpect))); \
2768 return pReqHdr->rc = VERR_INVALID_PARAMETER; \
2769 } \
2770 } while (0)
2771
2772 switch (uReq)
2773 {
2774 case SUPDRV_IDC_REQ_CONNECT:
2775 {
2776 PSUPDRVIDCREQCONNECT pReq = (PSUPDRVIDCREQCONNECT)pReqHdr;
2777 REQ_CHECK_IDC_SIZE(SUPDRV_IDC_REQ_CONNECT, sizeof(*pReq));
2778
2779 /*
2780 * Validate the cookie and other input.
2781 */
2782 if (pReq->Hdr.pSession != NULL)
2783 {
2784 OSDBGPRINT(("SUPDRV_IDC_REQ_CONNECT: Hdr.pSession=%p expected NULL!\n", pReq->Hdr.pSession));
2785 return pReqHdr->rc = VERR_INVALID_PARAMETER;
2786 }
2787 if (pReq->u.In.u32MagicCookie != SUPDRVIDCREQ_CONNECT_MAGIC_COOKIE)
2788 {
2789 OSDBGPRINT(("SUPDRV_IDC_REQ_CONNECT: u32MagicCookie=%#x expected %#x!\n",
2790 (unsigned)pReq->u.In.u32MagicCookie, (unsigned)SUPDRVIDCREQ_CONNECT_MAGIC_COOKIE));
2791 return pReqHdr->rc = VERR_INVALID_PARAMETER;
2792 }
2793 if ( pReq->u.In.uMinVersion > pReq->u.In.uReqVersion
2794 || (pReq->u.In.uMinVersion & UINT32_C(0xffff0000)) != (pReq->u.In.uReqVersion & UINT32_C(0xffff0000)))
2795 {
2796 OSDBGPRINT(("SUPDRV_IDC_REQ_CONNECT: uMinVersion=%#x uMaxVersion=%#x doesn't match!\n",
2797 pReq->u.In.uMinVersion, pReq->u.In.uReqVersion));
2798 return pReqHdr->rc = VERR_INVALID_PARAMETER;
2799 }
2800 if (pSession != NULL)
2801 {
2802 OSDBGPRINT(("SUPDRV_IDC_REQ_CONNECT: pSession=%p expected NULL!\n", pSession));
2803 return pReqHdr->rc = VERR_INVALID_PARAMETER;
2804 }
2805
2806 /*
2807 * Match the version.
2808 * The current logic is very simple, match the major interface version.
2809 */
2810 if ( pReq->u.In.uMinVersion > SUPDRV_IDC_VERSION
2811 || (pReq->u.In.uMinVersion & 0xffff0000) != (SUPDRV_IDC_VERSION & 0xffff0000))
2812 {
2813 OSDBGPRINT(("SUPDRV_IDC_REQ_CONNECT: Version mismatch. Requested: %#x Min: %#x Current: %#x\n",
2814 pReq->u.In.uReqVersion, pReq->u.In.uMinVersion, (unsigned)SUPDRV_IDC_VERSION));
2815 pReq->u.Out.pSession = NULL;
2816 pReq->u.Out.uSessionVersion = 0xffffffff;
2817 pReq->u.Out.uDriverVersion = SUPDRV_IDC_VERSION;
2818 pReq->u.Out.uDriverRevision = VBOX_SVN_REV;
2819 pReq->Hdr.rc = VERR_VERSION_MISMATCH;
2820 return VINF_SUCCESS;
2821 }
2822
2823 pReq->u.Out.pSession = NULL;
2824 pReq->u.Out.uSessionVersion = SUPDRV_IDC_VERSION;
2825 pReq->u.Out.uDriverVersion = SUPDRV_IDC_VERSION;
2826 pReq->u.Out.uDriverRevision = VBOX_SVN_REV;
2827
2828 pReq->Hdr.rc = supdrvCreateSession(pDevExt, false /* fUser */, true /*fUnrestricted*/, &pSession);
2829 if (RT_FAILURE(pReq->Hdr.rc))
2830 {
2831 OSDBGPRINT(("SUPDRV_IDC_REQ_CONNECT: failed to create session, rc=%d\n", pReq->Hdr.rc));
2832 return VINF_SUCCESS;
2833 }
2834
2835 pReq->u.Out.pSession = pSession;
2836 pReq->Hdr.pSession = pSession;
2837
2838 return VINF_SUCCESS;
2839 }
2840
2841 case SUPDRV_IDC_REQ_DISCONNECT:
2842 {
2843 REQ_CHECK_IDC_SIZE(SUPDRV_IDC_REQ_DISCONNECT, sizeof(*pReqHdr));
2844
2845 supdrvSessionRelease(pSession);
2846 return pReqHdr->rc = VINF_SUCCESS;
2847 }
2848
2849 case SUPDRV_IDC_REQ_GET_SYMBOL:
2850 {
2851 PSUPDRVIDCREQGETSYM pReq = (PSUPDRVIDCREQGETSYM)pReqHdr;
2852 REQ_CHECK_IDC_SIZE(SUPDRV_IDC_REQ_GET_SYMBOL, sizeof(*pReq));
2853
2854 pReq->Hdr.rc = supdrvIDC_LdrGetSymbol(pDevExt, pSession, pReq);
2855 return VINF_SUCCESS;
2856 }
2857
2858 case SUPDRV_IDC_REQ_COMPONENT_REGISTER_FACTORY:
2859 {
2860 PSUPDRVIDCREQCOMPREGFACTORY pReq = (PSUPDRVIDCREQCOMPREGFACTORY)pReqHdr;
2861 REQ_CHECK_IDC_SIZE(SUPDRV_IDC_REQ_COMPONENT_REGISTER_FACTORY, sizeof(*pReq));
2862
2863 pReq->Hdr.rc = SUPR0ComponentRegisterFactory(pSession, pReq->u.In.pFactory);
2864 return VINF_SUCCESS;
2865 }
2866
2867 case SUPDRV_IDC_REQ_COMPONENT_DEREGISTER_FACTORY:
2868 {
2869 PSUPDRVIDCREQCOMPDEREGFACTORY pReq = (PSUPDRVIDCREQCOMPDEREGFACTORY)pReqHdr;
2870 REQ_CHECK_IDC_SIZE(SUPDRV_IDC_REQ_COMPONENT_DEREGISTER_FACTORY, sizeof(*pReq));
2871
2872 pReq->Hdr.rc = SUPR0ComponentDeregisterFactory(pSession, pReq->u.In.pFactory);
2873 return VINF_SUCCESS;
2874 }
2875
2876 default:
2877 Log(("Unknown IDC %#lx\n", (long)uReq));
2878 break;
2879 }
2880
2881#undef REQ_CHECK_IDC_SIZE
2882 return VERR_NOT_SUPPORTED;
2883}
2884
2885
2886/**
2887 * Register a object for reference counting.
2888 * The object is registered with one reference in the specified session.
2889 *
2890 * @returns Unique identifier on success (pointer).
2891 * All future reference must use this identifier.
2892 * @returns NULL on failure.
2893 * @param pSession The caller's session.
2894 * @param enmType The object type.
2895 * @param pfnDestructor The destructore function which will be called when the reference count reaches 0.
2896 * @param pvUser1 The first user argument.
2897 * @param pvUser2 The second user argument.
2898 */
2899SUPR0DECL(void *) SUPR0ObjRegister(PSUPDRVSESSION pSession, SUPDRVOBJTYPE enmType, PFNSUPDRVDESTRUCTOR pfnDestructor, void *pvUser1, void *pvUser2)
2900{
2901 PSUPDRVDEVEXT pDevExt = pSession->pDevExt;
2902 PSUPDRVOBJ pObj;
2903 PSUPDRVUSAGE pUsage;
2904
2905 /*
2906 * Validate the input.
2907 */
2908 AssertReturn(SUP_IS_SESSION_VALID(pSession), NULL);
2909 AssertReturn(enmType > SUPDRVOBJTYPE_INVALID && enmType < SUPDRVOBJTYPE_END, NULL);
2910 AssertPtrReturn(pfnDestructor, NULL);
2911
2912 /*
2913 * Allocate and initialize the object.
2914 */
2915 pObj = (PSUPDRVOBJ)RTMemAlloc(sizeof(*pObj));
2916 if (!pObj)
2917 return NULL;
2918 pObj->u32Magic = SUPDRVOBJ_MAGIC;
2919 pObj->enmType = enmType;
2920 pObj->pNext = NULL;
2921 pObj->cUsage = 1;
2922 pObj->pfnDestructor = pfnDestructor;
2923 pObj->pvUser1 = pvUser1;
2924 pObj->pvUser2 = pvUser2;
2925 pObj->CreatorUid = pSession->Uid;
2926 pObj->CreatorGid = pSession->Gid;
2927 pObj->CreatorProcess= pSession->Process;
2928 supdrvOSObjInitCreator(pObj, pSession);
2929
2930 /*
2931 * Allocate the usage record.
2932 * (We keep freed usage records around to simplify SUPR0ObjAddRefEx().)
2933 */
2934 RTSpinlockAcquire(pDevExt->Spinlock);
2935
2936 pUsage = pDevExt->pUsageFree;
2937 if (pUsage)
2938 pDevExt->pUsageFree = pUsage->pNext;
2939 else
2940 {
2941 RTSpinlockRelease(pDevExt->Spinlock);
2942 pUsage = (PSUPDRVUSAGE)RTMemAlloc(sizeof(*pUsage));
2943 if (!pUsage)
2944 {
2945 RTMemFree(pObj);
2946 return NULL;
2947 }
2948 RTSpinlockAcquire(pDevExt->Spinlock);
2949 }
2950
2951 /*
2952 * Insert the object and create the session usage record.
2953 */
2954 /* The object. */
2955 pObj->pNext = pDevExt->pObjs;
2956 pDevExt->pObjs = pObj;
2957
2958 /* The session record. */
2959 pUsage->cUsage = 1;
2960 pUsage->pObj = pObj;
2961 pUsage->pNext = pSession->pUsage;
2962 /* Log2(("SUPR0ObjRegister: pUsage=%p:{.pObj=%p, .pNext=%p}\n", pUsage, pUsage->pObj, pUsage->pNext)); */
2963 pSession->pUsage = pUsage;
2964
2965 RTSpinlockRelease(pDevExt->Spinlock);
2966
2967 Log(("SUPR0ObjRegister: returns %p (pvUser1=%p, pvUser=%p)\n", pObj, pvUser1, pvUser2));
2968 return pObj;
2969}
2970SUPR0_EXPORT_SYMBOL(SUPR0ObjRegister);
2971
2972
2973/**
2974 * Increment the reference counter for the object associating the reference
2975 * with the specified session.
2976 *
2977 * @returns IPRT status code.
2978 * @param pvObj The identifier returned by SUPR0ObjRegister().
2979 * @param pSession The session which is referencing the object.
2980 *
2981 * @remarks The caller should not own any spinlocks and must carefully protect
2982 * itself against potential race with the destructor so freed memory
2983 * isn't accessed here.
2984 */
2985SUPR0DECL(int) SUPR0ObjAddRef(void *pvObj, PSUPDRVSESSION pSession)
2986{
2987 return SUPR0ObjAddRefEx(pvObj, pSession, false /* fNoBlocking */);
2988}
2989SUPR0_EXPORT_SYMBOL(SUPR0ObjAddRef);
2990
2991
2992/**
2993 * Increment the reference counter for the object associating the reference
2994 * with the specified session.
2995 *
2996 * @returns IPRT status code.
2997 * @retval VERR_TRY_AGAIN if fNoBlocking was set and a new usage record
2998 * couldn't be allocated. (If you see this you're not doing the right
2999 * thing and it won't ever work reliably.)
3000 *
3001 * @param pvObj The identifier returned by SUPR0ObjRegister().
3002 * @param pSession The session which is referencing the object.
3003 * @param fNoBlocking Set if it's not OK to block. Never try to make the
3004 * first reference to an object in a session with this
3005 * argument set.
3006 *
3007 * @remarks The caller should not own any spinlocks and must carefully protect
3008 * itself against potential race with the destructor so freed memory
3009 * isn't accessed here.
3010 */
3011SUPR0DECL(int) SUPR0ObjAddRefEx(void *pvObj, PSUPDRVSESSION pSession, bool fNoBlocking)
3012{
3013 PSUPDRVDEVEXT pDevExt = pSession->pDevExt;
3014 PSUPDRVOBJ pObj = (PSUPDRVOBJ)pvObj;
3015 int rc = VINF_SUCCESS;
3016 PSUPDRVUSAGE pUsagePre;
3017 PSUPDRVUSAGE pUsage;
3018
3019 /*
3020 * Validate the input.
3021 * Be ready for the destruction race (someone might be stuck in the
3022 * destructor waiting a lock we own).
3023 */
3024 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
3025 AssertPtrReturn(pObj, VERR_INVALID_POINTER);
3026 AssertMsgReturn(pObj->u32Magic == SUPDRVOBJ_MAGIC || pObj->u32Magic == SUPDRVOBJ_MAGIC_DEAD,
3027 ("Invalid pvObj=%p magic=%#x (expected %#x or %#x)\n", pvObj, pObj->u32Magic, SUPDRVOBJ_MAGIC, SUPDRVOBJ_MAGIC_DEAD),
3028 VERR_INVALID_PARAMETER);
3029
3030 RTSpinlockAcquire(pDevExt->Spinlock);
3031
3032 if (RT_UNLIKELY(pObj->u32Magic != SUPDRVOBJ_MAGIC))
3033 {
3034 RTSpinlockRelease(pDevExt->Spinlock);
3035
3036 AssertMsgFailed(("pvObj=%p magic=%#x\n", pvObj, pObj->u32Magic));
3037 return VERR_WRONG_ORDER;
3038 }
3039
3040 /*
3041 * Preallocate the usage record if we can.
3042 */
3043 pUsagePre = pDevExt->pUsageFree;
3044 if (pUsagePre)
3045 pDevExt->pUsageFree = pUsagePre->pNext;
3046 else if (!fNoBlocking)
3047 {
3048 RTSpinlockRelease(pDevExt->Spinlock);
3049 pUsagePre = (PSUPDRVUSAGE)RTMemAlloc(sizeof(*pUsagePre));
3050 if (!pUsagePre)
3051 return VERR_NO_MEMORY;
3052
3053 RTSpinlockAcquire(pDevExt->Spinlock);
3054 if (RT_UNLIKELY(pObj->u32Magic != SUPDRVOBJ_MAGIC))
3055 {
3056 RTSpinlockRelease(pDevExt->Spinlock);
3057
3058 AssertMsgFailed(("pvObj=%p magic=%#x\n", pvObj, pObj->u32Magic));
3059 return VERR_WRONG_ORDER;
3060 }
3061 }
3062
3063 /*
3064 * Reference the object.
3065 */
3066 pObj->cUsage++;
3067
3068 /*
3069 * Look for the session record.
3070 */
3071 for (pUsage = pSession->pUsage; pUsage; pUsage = pUsage->pNext)
3072 {
3073 /*Log(("SUPR0AddRef: pUsage=%p:{.pObj=%p, .pNext=%p}\n", pUsage, pUsage->pObj, pUsage->pNext));*/
3074 if (pUsage->pObj == pObj)
3075 break;
3076 }
3077 if (pUsage)
3078 pUsage->cUsage++;
3079 else if (pUsagePre)
3080 {
3081 /* create a new session record. */
3082 pUsagePre->cUsage = 1;
3083 pUsagePre->pObj = pObj;
3084 pUsagePre->pNext = pSession->pUsage;
3085 pSession->pUsage = pUsagePre;
3086 /*Log(("SUPR0AddRef: pUsagePre=%p:{.pObj=%p, .pNext=%p}\n", pUsagePre, pUsagePre->pObj, pUsagePre->pNext));*/
3087
3088 pUsagePre = NULL;
3089 }
3090 else
3091 {
3092 pObj->cUsage--;
3093 rc = VERR_TRY_AGAIN;
3094 }
3095
3096 /*
3097 * Put any unused usage record into the free list..
3098 */
3099 if (pUsagePre)
3100 {
3101 pUsagePre->pNext = pDevExt->pUsageFree;
3102 pDevExt->pUsageFree = pUsagePre;
3103 }
3104
3105 RTSpinlockRelease(pDevExt->Spinlock);
3106
3107 return rc;
3108}
3109SUPR0_EXPORT_SYMBOL(SUPR0ObjAddRefEx);
3110
3111
3112/**
3113 * Decrement / destroy a reference counter record for an object.
3114 *
3115 * The object is uniquely identified by pfnDestructor+pvUser1+pvUser2.
3116 *
3117 * @returns IPRT status code.
3118 * @retval VINF_SUCCESS if not destroyed.
3119 * @retval VINF_OBJECT_DESTROYED if it's destroyed by this release call.
3120 * @retval VERR_INVALID_PARAMETER if the object isn't valid. Will assert in
3121 * string builds.
3122 *
3123 * @param pvObj The identifier returned by SUPR0ObjRegister().
3124 * @param pSession The session which is referencing the object.
3125 */
3126SUPR0DECL(int) SUPR0ObjRelease(void *pvObj, PSUPDRVSESSION pSession)
3127{
3128 PSUPDRVDEVEXT pDevExt = pSession->pDevExt;
3129 PSUPDRVOBJ pObj = (PSUPDRVOBJ)pvObj;
3130 int rc = VERR_INVALID_PARAMETER;
3131 PSUPDRVUSAGE pUsage;
3132 PSUPDRVUSAGE pUsagePrev;
3133
3134 /*
3135 * Validate the input.
3136 */
3137 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
3138 AssertMsgReturn(RT_VALID_PTR(pObj) && pObj->u32Magic == SUPDRVOBJ_MAGIC,
3139 ("Invalid pvObj=%p magic=%#x (expected %#x)\n", pvObj, pObj ? pObj->u32Magic : 0, SUPDRVOBJ_MAGIC),
3140 VERR_INVALID_PARAMETER);
3141
3142 /*
3143 * Acquire the spinlock and look for the usage record.
3144 */
3145 RTSpinlockAcquire(pDevExt->Spinlock);
3146
3147 for (pUsagePrev = NULL, pUsage = pSession->pUsage;
3148 pUsage;
3149 pUsagePrev = pUsage, pUsage = pUsage->pNext)
3150 {
3151 /*Log2(("SUPR0ObjRelease: pUsage=%p:{.pObj=%p, .pNext=%p}\n", pUsage, pUsage->pObj, pUsage->pNext));*/
3152 if (pUsage->pObj == pObj)
3153 {
3154 rc = VINF_SUCCESS;
3155 AssertMsg(pUsage->cUsage >= 1 && pObj->cUsage >= pUsage->cUsage, ("glob %d; sess %d\n", pObj->cUsage, pUsage->cUsage));
3156 if (pUsage->cUsage > 1)
3157 {
3158 pObj->cUsage--;
3159 pUsage->cUsage--;
3160 }
3161 else
3162 {
3163 /*
3164 * Free the session record.
3165 */
3166 if (pUsagePrev)
3167 pUsagePrev->pNext = pUsage->pNext;
3168 else
3169 pSession->pUsage = pUsage->pNext;
3170 pUsage->pNext = pDevExt->pUsageFree;
3171 pDevExt->pUsageFree = pUsage;
3172
3173 /* What about the object? */
3174 if (pObj->cUsage > 1)
3175 pObj->cUsage--;
3176 else
3177 {
3178 /*
3179 * Object is to be destroyed, unlink it.
3180 */
3181 pObj->u32Magic = SUPDRVOBJ_MAGIC_DEAD;
3182 rc = VINF_OBJECT_DESTROYED;
3183 if (pDevExt->pObjs == pObj)
3184 pDevExt->pObjs = pObj->pNext;
3185 else
3186 {
3187 PSUPDRVOBJ pObjPrev;
3188 for (pObjPrev = pDevExt->pObjs; pObjPrev; pObjPrev = pObjPrev->pNext)
3189 if (pObjPrev->pNext == pObj)
3190 {
3191 pObjPrev->pNext = pObj->pNext;
3192 break;
3193 }
3194 Assert(pObjPrev);
3195 }
3196 }
3197 }
3198 break;
3199 }
3200 }
3201
3202 RTSpinlockRelease(pDevExt->Spinlock);
3203
3204 /*
3205 * Call the destructor and free the object if required.
3206 */
3207 if (rc == VINF_OBJECT_DESTROYED)
3208 {
3209 Log(("SUPR0ObjRelease: destroying %p/%d (%p/%p) cpid=%RTproc pid=%RTproc dtor=%p\n",
3210 pObj, pObj->enmType, pObj->pvUser1, pObj->pvUser2, pObj->CreatorProcess, RTProcSelf(), pObj->pfnDestructor));
3211 if (pObj->pfnDestructor)
3212 pObj->pfnDestructor(pObj, pObj->pvUser1, pObj->pvUser2);
3213 RTMemFree(pObj);
3214 }
3215
3216 AssertMsg(pUsage, ("pvObj=%p\n", pvObj));
3217 return rc;
3218}
3219SUPR0_EXPORT_SYMBOL(SUPR0ObjRelease);
3220
3221
3222/**
3223 * Verifies that the current process can access the specified object.
3224 *
3225 * @returns The following IPRT status code:
3226 * @retval VINF_SUCCESS if access was granted.
3227 * @retval VERR_PERMISSION_DENIED if denied access.
3228 * @retval VERR_INVALID_PARAMETER if invalid parameter.
3229 *
3230 * @param pvObj The identifier returned by SUPR0ObjRegister().
3231 * @param pSession The session which wishes to access the object.
3232 * @param pszObjName Object string name. This is optional and depends on the object type.
3233 *
3234 * @remark The caller is responsible for making sure the object isn't removed while
3235 * we're inside this function. If uncertain about this, just call AddRef before calling us.
3236 */
3237SUPR0DECL(int) SUPR0ObjVerifyAccess(void *pvObj, PSUPDRVSESSION pSession, const char *pszObjName)
3238{
3239 PSUPDRVOBJ pObj = (PSUPDRVOBJ)pvObj;
3240 int rc;
3241
3242 /*
3243 * Validate the input.
3244 */
3245 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
3246 AssertMsgReturn(RT_VALID_PTR(pObj) && pObj->u32Magic == SUPDRVOBJ_MAGIC,
3247 ("Invalid pvObj=%p magic=%#x (exepcted %#x)\n", pvObj, pObj ? pObj->u32Magic : 0, SUPDRVOBJ_MAGIC),
3248 VERR_INVALID_PARAMETER);
3249
3250 /*
3251 * Check access. (returns true if a decision has been made.)
3252 */
3253 rc = VERR_INTERNAL_ERROR;
3254 if (supdrvOSObjCanAccess(pObj, pSession, pszObjName, &rc))
3255 return rc;
3256
3257 /*
3258 * Default policy is to allow the user to access his own
3259 * stuff but nothing else.
3260 */
3261 if (pObj->CreatorUid == pSession->Uid)
3262 return VINF_SUCCESS;
3263 return VERR_PERMISSION_DENIED;
3264}
3265SUPR0_EXPORT_SYMBOL(SUPR0ObjVerifyAccess);
3266
3267
3268/**
3269 * API for the VMMR0 module to get the SUPDRVSESSION::pSessionVM member.
3270 *
3271 * @returns The associated VM pointer.
3272 * @param pSession The session of the current thread.
3273 */
3274SUPR0DECL(PVM) SUPR0GetSessionVM(PSUPDRVSESSION pSession)
3275{
3276 AssertReturn(SUP_IS_SESSION_VALID(pSession), NULL);
3277 return pSession->pSessionVM;
3278}
3279SUPR0_EXPORT_SYMBOL(SUPR0GetSessionVM);
3280
3281
3282/**
3283 * API for the VMMR0 module to get the SUPDRVSESSION::pSessionGVM member.
3284 *
3285 * @returns The associated GVM pointer.
3286 * @param pSession The session of the current thread.
3287 */
3288SUPR0DECL(PGVM) SUPR0GetSessionGVM(PSUPDRVSESSION pSession)
3289{
3290 AssertReturn(SUP_IS_SESSION_VALID(pSession), NULL);
3291 return pSession->pSessionGVM;
3292}
3293SUPR0_EXPORT_SYMBOL(SUPR0GetSessionGVM);
3294
3295
3296/**
3297 * API for the VMMR0 module to work the SUPDRVSESSION::pSessionVM member.
3298 *
3299 * This will fail if there is already a VM associated with the session and pVM
3300 * isn't NULL.
3301 *
3302 * @retval VINF_SUCCESS
3303 * @retval VERR_ALREADY_EXISTS if there already is a VM associated with the
3304 * session.
3305 * @retval VERR_INVALID_PARAMETER if only one of the parameters are NULL or if
3306 * the session is invalid.
3307 *
3308 * @param pSession The session of the current thread.
3309 * @param pGVM The GVM to associate with the session. Pass NULL to
3310 * dissassociate.
3311 * @param pVM The VM to associate with the session. Pass NULL to
3312 * dissassociate.
3313 */
3314SUPR0DECL(int) SUPR0SetSessionVM(PSUPDRVSESSION pSession, PGVM pGVM, PVM pVM)
3315{
3316 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
3317 AssertReturn((pGVM != NULL) == (pVM != NULL), VERR_INVALID_PARAMETER);
3318
3319 RTSpinlockAcquire(pSession->pDevExt->Spinlock);
3320 if (pGVM)
3321 {
3322 if (!pSession->pSessionGVM)
3323 {
3324 pSession->pSessionGVM = pGVM;
3325 pSession->pSessionVM = pVM;
3326 pSession->pFastIoCtrlVM = NULL;
3327 }
3328 else
3329 {
3330 RTSpinlockRelease(pSession->pDevExt->Spinlock);
3331 SUPR0Printf("SUPR0SetSessionVM: Unable to associated GVM/VM %p/%p with session %p as it has %p/%p already!\n",
3332 pGVM, pVM, pSession, pSession->pSessionGVM, pSession->pSessionVM);
3333 return VERR_ALREADY_EXISTS;
3334 }
3335 }
3336 else
3337 {
3338 pSession->pSessionGVM = NULL;
3339 pSession->pSessionVM = NULL;
3340 pSession->pFastIoCtrlVM = NULL;
3341 }
3342 RTSpinlockRelease(pSession->pDevExt->Spinlock);
3343 return VINF_SUCCESS;
3344}
3345SUPR0_EXPORT_SYMBOL(SUPR0SetSessionVM);
3346
3347
3348/**
3349 * For getting SUPDRVSESSION::Uid.
3350 *
3351 * @returns The session UID. NIL_RTUID if invalid pointer or not successfully
3352 * set by the host code.
3353 * @param pSession The session of the current thread.
3354 */
3355SUPR0DECL(RTUID) SUPR0GetSessionUid(PSUPDRVSESSION pSession)
3356{
3357 AssertReturn(SUP_IS_SESSION_VALID(pSession), NIL_RTUID);
3358 return pSession->Uid;
3359}
3360SUPR0_EXPORT_SYMBOL(SUPR0GetSessionUid);
3361
3362
3363/** @copydoc RTLogDefaultInstanceEx
3364 * @remarks To allow overriding RTLogDefaultInstanceEx locally. */
3365SUPR0DECL(struct RTLOGGER *) SUPR0DefaultLogInstanceEx(uint32_t fFlagsAndGroup)
3366{
3367 return RTLogDefaultInstanceEx(fFlagsAndGroup);
3368}
3369SUPR0_EXPORT_SYMBOL(SUPR0DefaultLogInstanceEx);
3370
3371
3372/** @copydoc RTLogGetDefaultInstanceEx
3373 * @remarks To allow overriding RTLogGetDefaultInstanceEx locally. */
3374SUPR0DECL(struct RTLOGGER *) SUPR0GetDefaultLogInstanceEx(uint32_t fFlagsAndGroup)
3375{
3376 return RTLogGetDefaultInstanceEx(fFlagsAndGroup);
3377}
3378SUPR0_EXPORT_SYMBOL(SUPR0GetDefaultLogInstanceEx);
3379
3380
3381/** @copydoc RTLogRelGetDefaultInstanceEx
3382 * @remarks To allow overriding RTLogRelGetDefaultInstanceEx locally. */
3383SUPR0DECL(struct RTLOGGER *) SUPR0GetDefaultLogRelInstanceEx(uint32_t fFlagsAndGroup)
3384{
3385 return RTLogRelGetDefaultInstanceEx(fFlagsAndGroup);
3386}
3387SUPR0_EXPORT_SYMBOL(SUPR0GetDefaultLogRelInstanceEx);
3388
3389
3390/**
3391 * Lock pages.
3392 *
3393 * @returns IPRT status code.
3394 * @param pSession Session to which the locked memory should be associated.
3395 * @param pvR3 Start of the memory range to lock.
3396 * This must be page aligned.
3397 * @param cPages Number of pages to lock.
3398 * @param paPages Where to put the physical addresses of locked memory.
3399 */
3400SUPR0DECL(int) SUPR0LockMem(PSUPDRVSESSION pSession, RTR3PTR pvR3, uint32_t cPages, PRTHCPHYS paPages)
3401{
3402 int rc;
3403 SUPDRVMEMREF Mem = { NIL_RTR0MEMOBJ, NIL_RTR0MEMOBJ, MEMREF_TYPE_UNUSED };
3404 const size_t cb = (size_t)cPages << PAGE_SHIFT;
3405 LogFlow(("SUPR0LockMem: pSession=%p pvR3=%p cPages=%d paPages=%p\n", pSession, (void *)pvR3, cPages, paPages));
3406
3407 /*
3408 * Verify input.
3409 */
3410 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
3411 AssertPtrReturn(paPages, VERR_INVALID_PARAMETER);
3412 if ( RT_ALIGN_R3PT(pvR3, PAGE_SIZE, RTR3PTR) != pvR3
3413 || !pvR3)
3414 {
3415 Log(("pvR3 (%p) must be page aligned and not NULL!\n", (void *)pvR3));
3416 return VERR_INVALID_PARAMETER;
3417 }
3418
3419 /*
3420 * Let IPRT do the job.
3421 */
3422 Mem.eType = MEMREF_TYPE_LOCKED;
3423 rc = RTR0MemObjLockUser(&Mem.MemObj, pvR3, cb, RTMEM_PROT_READ | RTMEM_PROT_WRITE, NIL_RTR0PROCESS);
3424 if (RT_SUCCESS(rc))
3425 {
3426 uint32_t iPage = cPages;
3427 AssertMsg(RTR0MemObjAddressR3(Mem.MemObj) == pvR3, ("%p == %p\n", RTR0MemObjAddressR3(Mem.MemObj), pvR3));
3428 AssertMsg(RTR0MemObjSize(Mem.MemObj) == cb, ("%x == %x\n", RTR0MemObjSize(Mem.MemObj), cb));
3429
3430 while (iPage-- > 0)
3431 {
3432 paPages[iPage] = RTR0MemObjGetPagePhysAddr(Mem.MemObj, iPage);
3433 if (RT_UNLIKELY(paPages[iPage] == NIL_RTCCPHYS))
3434 {
3435 AssertMsgFailed(("iPage=%d\n", iPage));
3436 rc = VERR_INTERNAL_ERROR;
3437 break;
3438 }
3439 }
3440 if (RT_SUCCESS(rc))
3441 rc = supdrvMemAdd(&Mem, pSession);
3442 if (RT_FAILURE(rc))
3443 {
3444 int rc2 = RTR0MemObjFree(Mem.MemObj, false);
3445 AssertRC(rc2);
3446 }
3447 }
3448
3449 return rc;
3450}
3451SUPR0_EXPORT_SYMBOL(SUPR0LockMem);
3452
3453
3454/**
3455 * Unlocks the memory pointed to by pv.
3456 *
3457 * @returns IPRT status code.
3458 * @param pSession Session to which the memory was locked.
3459 * @param pvR3 Memory to unlock.
3460 */
3461SUPR0DECL(int) SUPR0UnlockMem(PSUPDRVSESSION pSession, RTR3PTR pvR3)
3462{
3463 LogFlow(("SUPR0UnlockMem: pSession=%p pvR3=%p\n", pSession, (void *)pvR3));
3464 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
3465 return supdrvMemRelease(pSession, (RTHCUINTPTR)pvR3, MEMREF_TYPE_LOCKED);
3466}
3467SUPR0_EXPORT_SYMBOL(SUPR0UnlockMem);
3468
3469
3470/**
3471 * Allocates a chunk of page aligned memory with contiguous and fixed physical
3472 * backing.
3473 *
3474 * @returns IPRT status code.
3475 * @param pSession Session data.
3476 * @param cPages Number of pages to allocate.
3477 * @param ppvR0 Where to put the address of Ring-0 mapping the allocated memory.
3478 * @param ppvR3 Where to put the address of Ring-3 mapping the allocated memory.
3479 * @param pHCPhys Where to put the physical address of allocated memory.
3480 */
3481SUPR0DECL(int) SUPR0ContAlloc(PSUPDRVSESSION pSession, uint32_t cPages, PRTR0PTR ppvR0, PRTR3PTR ppvR3, PRTHCPHYS pHCPhys)
3482{
3483 int rc;
3484 SUPDRVMEMREF Mem = { NIL_RTR0MEMOBJ, NIL_RTR0MEMOBJ, MEMREF_TYPE_UNUSED };
3485 LogFlow(("SUPR0ContAlloc: pSession=%p cPages=%d ppvR0=%p ppvR3=%p pHCPhys=%p\n", pSession, cPages, ppvR0, ppvR3, pHCPhys));
3486
3487 /*
3488 * Validate input.
3489 */
3490 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
3491 if (!ppvR3 || !ppvR0 || !pHCPhys)
3492 {
3493 Log(("Null pointer. All of these should be set: pSession=%p ppvR0=%p ppvR3=%p pHCPhys=%p\n",
3494 pSession, ppvR0, ppvR3, pHCPhys));
3495 return VERR_INVALID_PARAMETER;
3496
3497 }
3498 if (cPages < 1 || cPages >= 256)
3499 {
3500 Log(("Illegal request cPages=%d, must be greater than 0 and smaller than 256.\n", cPages));
3501 return VERR_PAGE_COUNT_OUT_OF_RANGE;
3502 }
3503
3504 /*
3505 * Let IPRT do the job.
3506 */
3507 /** @todo Is the 4GiB requirement actually necessray? */
3508 rc = RTR0MemObjAllocCont(&Mem.MemObj, cPages << PAGE_SHIFT, _4G-1 /*PhysHighest*/, true /* executable R0 mapping */);
3509 if (RT_SUCCESS(rc))
3510 {
3511 int rc2;
3512 rc = RTR0MemObjMapUser(&Mem.MapObjR3, Mem.MemObj, (RTR3PTR)-1, 0,
3513 RTMEM_PROT_EXEC | RTMEM_PROT_WRITE | RTMEM_PROT_READ, NIL_RTR0PROCESS);
3514 if (RT_SUCCESS(rc))
3515 {
3516 Mem.eType = MEMREF_TYPE_CONT;
3517 rc = supdrvMemAdd(&Mem, pSession);
3518 if (!rc)
3519 {
3520 *ppvR0 = RTR0MemObjAddress(Mem.MemObj);
3521 *ppvR3 = RTR0MemObjAddressR3(Mem.MapObjR3);
3522 *pHCPhys = RTR0MemObjGetPagePhysAddr(Mem.MemObj, 0);
3523 return 0;
3524 }
3525
3526 rc2 = RTR0MemObjFree(Mem.MapObjR3, false);
3527 AssertRC(rc2);
3528 }
3529 rc2 = RTR0MemObjFree(Mem.MemObj, false);
3530 AssertRC(rc2);
3531 }
3532
3533 return rc;
3534}
3535SUPR0_EXPORT_SYMBOL(SUPR0ContAlloc);
3536
3537
3538/**
3539 * Frees memory allocated using SUPR0ContAlloc().
3540 *
3541 * @returns IPRT status code.
3542 * @param pSession The session to which the memory was allocated.
3543 * @param uPtr Pointer to the memory (ring-3 or ring-0).
3544 */
3545SUPR0DECL(int) SUPR0ContFree(PSUPDRVSESSION pSession, RTHCUINTPTR uPtr)
3546{
3547 LogFlow(("SUPR0ContFree: pSession=%p uPtr=%p\n", pSession, (void *)uPtr));
3548 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
3549 return supdrvMemRelease(pSession, uPtr, MEMREF_TYPE_CONT);
3550}
3551SUPR0_EXPORT_SYMBOL(SUPR0ContFree);
3552
3553
3554/**
3555 * Allocates a chunk of page aligned memory with fixed physical backing below 4GB.
3556 *
3557 * The memory isn't zeroed.
3558 *
3559 * @returns IPRT status code.
3560 * @param pSession Session data.
3561 * @param cPages Number of pages to allocate.
3562 * @param ppvR0 Where to put the address of Ring-0 mapping of the allocated memory.
3563 * @param ppvR3 Where to put the address of Ring-3 mapping of the allocated memory.
3564 * @param paPages Where to put the physical addresses of allocated memory.
3565 */
3566SUPR0DECL(int) SUPR0LowAlloc(PSUPDRVSESSION pSession, uint32_t cPages, PRTR0PTR ppvR0, PRTR3PTR ppvR3, PRTHCPHYS paPages)
3567{
3568 unsigned iPage;
3569 int rc;
3570 SUPDRVMEMREF Mem = { NIL_RTR0MEMOBJ, NIL_RTR0MEMOBJ, MEMREF_TYPE_UNUSED };
3571 LogFlow(("SUPR0LowAlloc: pSession=%p cPages=%d ppvR3=%p ppvR0=%p paPages=%p\n", pSession, cPages, ppvR3, ppvR0, paPages));
3572
3573 /*
3574 * Validate input.
3575 */
3576 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
3577 if (!ppvR3 || !ppvR0 || !paPages)
3578 {
3579 Log(("Null pointer. All of these should be set: pSession=%p ppvR3=%p ppvR0=%p paPages=%p\n",
3580 pSession, ppvR3, ppvR0, paPages));
3581 return VERR_INVALID_PARAMETER;
3582
3583 }
3584 if (cPages < 1 || cPages >= 256)
3585 {
3586 Log(("Illegal request cPages=%d, must be greater than 0 and smaller than 256.\n", cPages));
3587 return VERR_PAGE_COUNT_OUT_OF_RANGE;
3588 }
3589
3590 /*
3591 * Let IPRT do the work.
3592 */
3593 rc = RTR0MemObjAllocLow(&Mem.MemObj, cPages << PAGE_SHIFT, true /* executable ring-0 mapping */);
3594 if (RT_SUCCESS(rc))
3595 {
3596 int rc2;
3597 rc = RTR0MemObjMapUser(&Mem.MapObjR3, Mem.MemObj, (RTR3PTR)-1, 0,
3598 RTMEM_PROT_EXEC | RTMEM_PROT_WRITE | RTMEM_PROT_READ, NIL_RTR0PROCESS);
3599 if (RT_SUCCESS(rc))
3600 {
3601 Mem.eType = MEMREF_TYPE_LOW;
3602 rc = supdrvMemAdd(&Mem, pSession);
3603 if (!rc)
3604 {
3605 for (iPage = 0; iPage < cPages; iPage++)
3606 {
3607 paPages[iPage] = RTR0MemObjGetPagePhysAddr(Mem.MemObj, iPage);
3608 AssertMsg(!(paPages[iPage] & (PAGE_SIZE - 1)), ("iPage=%d Phys=%RHp\n", paPages[iPage]));
3609 }
3610 *ppvR0 = RTR0MemObjAddress(Mem.MemObj);
3611 *ppvR3 = RTR0MemObjAddressR3(Mem.MapObjR3);
3612 return 0;
3613 }
3614
3615 rc2 = RTR0MemObjFree(Mem.MapObjR3, false);
3616 AssertRC(rc2);
3617 }
3618
3619 rc2 = RTR0MemObjFree(Mem.MemObj, false);
3620 AssertRC(rc2);
3621 }
3622
3623 return rc;
3624}
3625SUPR0_EXPORT_SYMBOL(SUPR0LowAlloc);
3626
3627
3628/**
3629 * Frees memory allocated using SUPR0LowAlloc().
3630 *
3631 * @returns IPRT status code.
3632 * @param pSession The session to which the memory was allocated.
3633 * @param uPtr Pointer to the memory (ring-3 or ring-0).
3634 */
3635SUPR0DECL(int) SUPR0LowFree(PSUPDRVSESSION pSession, RTHCUINTPTR uPtr)
3636{
3637 LogFlow(("SUPR0LowFree: pSession=%p uPtr=%p\n", pSession, (void *)uPtr));
3638 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
3639 return supdrvMemRelease(pSession, uPtr, MEMREF_TYPE_LOW);
3640}
3641SUPR0_EXPORT_SYMBOL(SUPR0LowFree);
3642
3643
3644
3645/**
3646 * Allocates a chunk of memory with both R0 and R3 mappings.
3647 * The memory is fixed and it's possible to query the physical addresses using SUPR0MemGetPhys().
3648 *
3649 * @returns IPRT status code.
3650 * @param pSession The session to associated the allocation with.
3651 * @param cb Number of bytes to allocate.
3652 * @param ppvR0 Where to store the address of the Ring-0 mapping.
3653 * @param ppvR3 Where to store the address of the Ring-3 mapping.
3654 */
3655SUPR0DECL(int) SUPR0MemAlloc(PSUPDRVSESSION pSession, uint32_t cb, PRTR0PTR ppvR0, PRTR3PTR ppvR3)
3656{
3657 int rc;
3658 SUPDRVMEMREF Mem = { NIL_RTR0MEMOBJ, NIL_RTR0MEMOBJ, MEMREF_TYPE_UNUSED };
3659 LogFlow(("SUPR0MemAlloc: pSession=%p cb=%d ppvR0=%p ppvR3=%p\n", pSession, cb, ppvR0, ppvR3));
3660
3661 /*
3662 * Validate input.
3663 */
3664 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
3665 AssertPtrReturn(ppvR0, VERR_INVALID_POINTER);
3666 AssertPtrReturn(ppvR3, VERR_INVALID_POINTER);
3667 if (cb < 1 || cb >= _4M)
3668 {
3669 Log(("Illegal request cb=%u; must be greater than 0 and smaller than 4MB.\n", cb));
3670 return VERR_INVALID_PARAMETER;
3671 }
3672
3673 /*
3674 * Let IPRT do the work.
3675 */
3676 rc = RTR0MemObjAllocPage(&Mem.MemObj, cb, true /* executable ring-0 mapping */);
3677 if (RT_SUCCESS(rc))
3678 {
3679 int rc2;
3680 rc = RTR0MemObjMapUser(&Mem.MapObjR3, Mem.MemObj, (RTR3PTR)-1, 0,
3681 RTMEM_PROT_EXEC | RTMEM_PROT_WRITE | RTMEM_PROT_READ, NIL_RTR0PROCESS);
3682 if (RT_SUCCESS(rc))
3683 {
3684 Mem.eType = MEMREF_TYPE_MEM;
3685 rc = supdrvMemAdd(&Mem, pSession);
3686 if (!rc)
3687 {
3688 *ppvR0 = RTR0MemObjAddress(Mem.MemObj);
3689 *ppvR3 = RTR0MemObjAddressR3(Mem.MapObjR3);
3690 return VINF_SUCCESS;
3691 }
3692
3693 rc2 = RTR0MemObjFree(Mem.MapObjR3, false);
3694 AssertRC(rc2);
3695 }
3696
3697 rc2 = RTR0MemObjFree(Mem.MemObj, false);
3698 AssertRC(rc2);
3699 }
3700
3701 return rc;
3702}
3703SUPR0_EXPORT_SYMBOL(SUPR0MemAlloc);
3704
3705
3706/**
3707 * Get the physical addresses of memory allocated using SUPR0MemAlloc().
3708 *
3709 * @returns IPRT status code.
3710 * @param pSession The session to which the memory was allocated.
3711 * @param uPtr The Ring-0 or Ring-3 address returned by SUPR0MemAlloc().
3712 * @param paPages Where to store the physical addresses.
3713 */
3714SUPR0DECL(int) SUPR0MemGetPhys(PSUPDRVSESSION pSession, RTHCUINTPTR uPtr, PSUPPAGE paPages) /** @todo switch this bugger to RTHCPHYS */
3715{
3716 PSUPDRVBUNDLE pBundle;
3717 LogFlow(("SUPR0MemGetPhys: pSession=%p uPtr=%p paPages=%p\n", pSession, (void *)uPtr, paPages));
3718
3719 /*
3720 * Validate input.
3721 */
3722 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
3723 AssertPtrReturn(paPages, VERR_INVALID_POINTER);
3724 AssertReturn(uPtr, VERR_INVALID_PARAMETER);
3725
3726 /*
3727 * Search for the address.
3728 */
3729 RTSpinlockAcquire(pSession->Spinlock);
3730 for (pBundle = &pSession->Bundle; pBundle; pBundle = pBundle->pNext)
3731 {
3732 if (pBundle->cUsed > 0)
3733 {
3734 unsigned i;
3735 for (i = 0; i < RT_ELEMENTS(pBundle->aMem); i++)
3736 {
3737 if ( pBundle->aMem[i].eType == MEMREF_TYPE_MEM
3738 && pBundle->aMem[i].MemObj != NIL_RTR0MEMOBJ
3739 && ( (RTHCUINTPTR)RTR0MemObjAddress(pBundle->aMem[i].MemObj) == uPtr
3740 || ( pBundle->aMem[i].MapObjR3 != NIL_RTR0MEMOBJ
3741 && RTR0MemObjAddressR3(pBundle->aMem[i].MapObjR3) == uPtr)
3742 )
3743 )
3744 {
3745 const size_t cPages = RTR0MemObjSize(pBundle->aMem[i].MemObj) >> PAGE_SHIFT;
3746 size_t iPage;
3747 for (iPage = 0; iPage < cPages; iPage++)
3748 {
3749 paPages[iPage].Phys = RTR0MemObjGetPagePhysAddr(pBundle->aMem[i].MemObj, iPage);
3750 paPages[iPage].uReserved = 0;
3751 }
3752 RTSpinlockRelease(pSession->Spinlock);
3753 return VINF_SUCCESS;
3754 }
3755 }
3756 }
3757 }
3758 RTSpinlockRelease(pSession->Spinlock);
3759 Log(("Failed to find %p!!!\n", (void *)uPtr));
3760 return VERR_INVALID_PARAMETER;
3761}
3762SUPR0_EXPORT_SYMBOL(SUPR0MemGetPhys);
3763
3764
3765/**
3766 * Free memory allocated by SUPR0MemAlloc().
3767 *
3768 * @returns IPRT status code.
3769 * @param pSession The session owning the allocation.
3770 * @param uPtr The Ring-0 or Ring-3 address returned by SUPR0MemAlloc().
3771 */
3772SUPR0DECL(int) SUPR0MemFree(PSUPDRVSESSION pSession, RTHCUINTPTR uPtr)
3773{
3774 LogFlow(("SUPR0MemFree: pSession=%p uPtr=%p\n", pSession, (void *)uPtr));
3775 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
3776 return supdrvMemRelease(pSession, uPtr, MEMREF_TYPE_MEM);
3777}
3778SUPR0_EXPORT_SYMBOL(SUPR0MemFree);
3779
3780
3781/**
3782 * Allocates a chunk of memory with a kernel or/and a user mode mapping.
3783 *
3784 * The memory is fixed and it's possible to query the physical addresses using
3785 * SUPR0MemGetPhys().
3786 *
3787 * @returns IPRT status code.
3788 * @param pSession The session to associated the allocation with.
3789 * @param cPages The number of pages to allocate.
3790 * @param fFlags Flags, reserved for the future. Must be zero.
3791 * @param ppvR3 Where to store the address of the Ring-3 mapping.
3792 * NULL if no ring-3 mapping.
3793 * @param ppvR0 Where to store the address of the Ring-0 mapping.
3794 * NULL if no ring-0 mapping.
3795 * @param paPages Where to store the addresses of the pages. Optional.
3796 */
3797SUPR0DECL(int) SUPR0PageAllocEx(PSUPDRVSESSION pSession, uint32_t cPages, uint32_t fFlags, PRTR3PTR ppvR3, PRTR0PTR ppvR0, PRTHCPHYS paPages)
3798{
3799 int rc;
3800 SUPDRVMEMREF Mem = { NIL_RTR0MEMOBJ, NIL_RTR0MEMOBJ, MEMREF_TYPE_UNUSED };
3801 LogFlow(("SUPR0PageAlloc: pSession=%p cb=%d ppvR3=%p\n", pSession, cPages, ppvR3));
3802
3803 /*
3804 * Validate input. The allowed allocation size must be at least equal to the maximum guest VRAM size.
3805 */
3806 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
3807 AssertPtrNullReturn(ppvR3, VERR_INVALID_POINTER);
3808 AssertPtrNullReturn(ppvR0, VERR_INVALID_POINTER);
3809 AssertReturn(ppvR3 || ppvR0, VERR_INVALID_PARAMETER);
3810 AssertReturn(!fFlags, VERR_INVALID_PARAMETER);
3811 if (cPages < 1 || cPages > VBOX_MAX_ALLOC_PAGE_COUNT)
3812 {
3813 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)));
3814 return VERR_PAGE_COUNT_OUT_OF_RANGE;
3815 }
3816
3817 /*
3818 * Let IPRT do the work.
3819 */
3820 if (ppvR0)
3821 rc = RTR0MemObjAllocPage(&Mem.MemObj, (size_t)cPages * PAGE_SIZE, false /*fExecutable*/);
3822 else
3823 rc = RTR0MemObjAllocPhysNC(&Mem.MemObj, (size_t)cPages * PAGE_SIZE, NIL_RTHCPHYS);
3824 if (RT_SUCCESS(rc))
3825 {
3826 int rc2;
3827 if (ppvR3)
3828 {
3829 /* Make sure memory mapped into ring-3 is zero initialized if we can: */
3830 if ( ppvR0
3831 && !RTR0MemObjWasZeroInitialized(Mem.MemObj))
3832 {
3833 void *pv = RTR0MemObjAddress(Mem.MemObj);
3834 Assert(pv || !ppvR0);
3835 if (pv)
3836 RT_BZERO(pv, (size_t)cPages * PAGE_SIZE);
3837 }
3838
3839 rc = RTR0MemObjMapUser(&Mem.MapObjR3, Mem.MemObj, (RTR3PTR)-1, 0, RTMEM_PROT_WRITE | RTMEM_PROT_READ, NIL_RTR0PROCESS);
3840 }
3841 else
3842 Mem.MapObjR3 = NIL_RTR0MEMOBJ;
3843 if (RT_SUCCESS(rc))
3844 {
3845 Mem.eType = MEMREF_TYPE_PAGE;
3846 rc = supdrvMemAdd(&Mem, pSession);
3847 if (!rc)
3848 {
3849 if (ppvR3)
3850 *ppvR3 = RTR0MemObjAddressR3(Mem.MapObjR3);
3851 if (ppvR0)
3852 *ppvR0 = RTR0MemObjAddress(Mem.MemObj);
3853 if (paPages)
3854 {
3855 uint32_t iPage = cPages;
3856 while (iPage-- > 0)
3857 {
3858 paPages[iPage] = RTR0MemObjGetPagePhysAddr(Mem.MapObjR3, iPage);
3859 Assert(paPages[iPage] != NIL_RTHCPHYS);
3860 }
3861 }
3862 return VINF_SUCCESS;
3863 }
3864
3865 rc2 = RTR0MemObjFree(Mem.MapObjR3, false);
3866 AssertRC(rc2);
3867 }
3868
3869 rc2 = RTR0MemObjFree(Mem.MemObj, false);
3870 AssertRC(rc2);
3871 }
3872 return rc;
3873}
3874SUPR0_EXPORT_SYMBOL(SUPR0PageAllocEx);
3875
3876
3877/**
3878 * Maps a chunk of memory previously allocated by SUPR0PageAllocEx into kernel
3879 * space.
3880 *
3881 * @returns IPRT status code.
3882 * @param pSession The session to associated the allocation with.
3883 * @param pvR3 The ring-3 address returned by SUPR0PageAllocEx.
3884 * @param offSub Where to start mapping. Must be page aligned.
3885 * @param cbSub How much to map. Must be page aligned.
3886 * @param fFlags Flags, MBZ.
3887 * @param ppvR0 Where to return the address of the ring-0 mapping on
3888 * success.
3889 */
3890SUPR0DECL(int) SUPR0PageMapKernel(PSUPDRVSESSION pSession, RTR3PTR pvR3, uint32_t offSub, uint32_t cbSub,
3891 uint32_t fFlags, PRTR0PTR ppvR0)
3892{
3893 int rc;
3894 PSUPDRVBUNDLE pBundle;
3895 RTR0MEMOBJ hMemObj = NIL_RTR0MEMOBJ;
3896 LogFlow(("SUPR0PageMapKernel: pSession=%p pvR3=%p offSub=%#x cbSub=%#x\n", pSession, pvR3, offSub, cbSub));
3897
3898 /*
3899 * Validate input. The allowed allocation size must be at least equal to the maximum guest VRAM size.
3900 */
3901 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
3902 AssertPtrNullReturn(ppvR0, VERR_INVALID_POINTER);
3903 AssertReturn(!fFlags, VERR_INVALID_PARAMETER);
3904 AssertReturn(!(offSub & PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
3905 AssertReturn(!(cbSub & PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
3906 AssertReturn(cbSub, VERR_INVALID_PARAMETER);
3907
3908 /*
3909 * Find the memory object.
3910 */
3911 RTSpinlockAcquire(pSession->Spinlock);
3912 for (pBundle = &pSession->Bundle; pBundle; pBundle = pBundle->pNext)
3913 {
3914 if (pBundle->cUsed > 0)
3915 {
3916 unsigned i;
3917 for (i = 0; i < RT_ELEMENTS(pBundle->aMem); i++)
3918 {
3919 if ( ( pBundle->aMem[i].eType == MEMREF_TYPE_PAGE
3920 && pBundle->aMem[i].MemObj != NIL_RTR0MEMOBJ
3921 && pBundle->aMem[i].MapObjR3 != NIL_RTR0MEMOBJ
3922 && RTR0MemObjAddressR3(pBundle->aMem[i].MapObjR3) == pvR3)
3923 || ( pBundle->aMem[i].eType == MEMREF_TYPE_LOCKED
3924 && pBundle->aMem[i].MemObj != NIL_RTR0MEMOBJ
3925 && pBundle->aMem[i].MapObjR3 == NIL_RTR0MEMOBJ
3926 && RTR0MemObjAddressR3(pBundle->aMem[i].MemObj) == pvR3))
3927 {
3928 hMemObj = pBundle->aMem[i].MemObj;
3929 break;
3930 }
3931 }
3932 }
3933 }
3934 RTSpinlockRelease(pSession->Spinlock);
3935
3936 rc = VERR_INVALID_PARAMETER;
3937 if (hMemObj != NIL_RTR0MEMOBJ)
3938 {
3939 /*
3940 * Do some further input validations before calling IPRT.
3941 * (Cleanup is done indirectly by telling RTR0MemObjFree to include mappings.)
3942 */
3943 size_t cbMemObj = RTR0MemObjSize(hMemObj);
3944 if ( offSub < cbMemObj
3945 && cbSub <= cbMemObj
3946 && offSub + cbSub <= cbMemObj)
3947 {
3948 RTR0MEMOBJ hMapObj;
3949 rc = RTR0MemObjMapKernelEx(&hMapObj, hMemObj, (void *)-1, 0,
3950 RTMEM_PROT_READ | RTMEM_PROT_WRITE, offSub, cbSub);
3951 if (RT_SUCCESS(rc))
3952 *ppvR0 = RTR0MemObjAddress(hMapObj);
3953 }
3954 else
3955 SUPR0Printf("SUPR0PageMapKernel: cbMemObj=%#x offSub=%#x cbSub=%#x\n", cbMemObj, offSub, cbSub);
3956
3957 }
3958 return rc;
3959}
3960SUPR0_EXPORT_SYMBOL(SUPR0PageMapKernel);
3961
3962
3963/**
3964 * Changes the page level protection of one or more pages previously allocated
3965 * by SUPR0PageAllocEx.
3966 *
3967 * @returns IPRT status code.
3968 * @param pSession The session to associated the allocation with.
3969 * @param pvR3 The ring-3 address returned by SUPR0PageAllocEx.
3970 * NIL_RTR3PTR if the ring-3 mapping should be unaffected.
3971 * @param pvR0 The ring-0 address returned by SUPR0PageAllocEx.
3972 * NIL_RTR0PTR if the ring-0 mapping should be unaffected.
3973 * @param offSub Where to start changing. Must be page aligned.
3974 * @param cbSub How much to change. Must be page aligned.
3975 * @param fProt The new page level protection, see RTMEM_PROT_*.
3976 */
3977SUPR0DECL(int) SUPR0PageProtect(PSUPDRVSESSION pSession, RTR3PTR pvR3, RTR0PTR pvR0, uint32_t offSub, uint32_t cbSub, uint32_t fProt)
3978{
3979 int rc;
3980 PSUPDRVBUNDLE pBundle;
3981 RTR0MEMOBJ hMemObjR0 = NIL_RTR0MEMOBJ;
3982 RTR0MEMOBJ hMemObjR3 = NIL_RTR0MEMOBJ;
3983 LogFlow(("SUPR0PageProtect: pSession=%p pvR3=%p pvR0=%p offSub=%#x cbSub=%#x fProt-%#x\n", pSession, pvR3, pvR0, offSub, cbSub, fProt));
3984
3985 /*
3986 * Validate input. The allowed allocation size must be at least equal to the maximum guest VRAM size.
3987 */
3988 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
3989 AssertReturn(!(fProt & ~(RTMEM_PROT_READ | RTMEM_PROT_WRITE | RTMEM_PROT_EXEC | RTMEM_PROT_NONE)), VERR_INVALID_PARAMETER);
3990 AssertReturn(!(offSub & PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
3991 AssertReturn(!(cbSub & PAGE_OFFSET_MASK), VERR_INVALID_PARAMETER);
3992 AssertReturn(cbSub, VERR_INVALID_PARAMETER);
3993
3994 /*
3995 * Find the memory object.
3996 */
3997 RTSpinlockAcquire(pSession->Spinlock);
3998 for (pBundle = &pSession->Bundle; pBundle; pBundle = pBundle->pNext)
3999 {
4000 if (pBundle->cUsed > 0)
4001 {
4002 unsigned i;
4003 for (i = 0; i < RT_ELEMENTS(pBundle->aMem); i++)
4004 {
4005 if ( pBundle->aMem[i].eType == MEMREF_TYPE_PAGE
4006 && pBundle->aMem[i].MemObj != NIL_RTR0MEMOBJ
4007 && ( pBundle->aMem[i].MapObjR3 != NIL_RTR0MEMOBJ
4008 || pvR3 == NIL_RTR3PTR)
4009 && ( pvR0 == NIL_RTR0PTR
4010 || RTR0MemObjAddress(pBundle->aMem[i].MemObj) == pvR0)
4011 && ( pvR3 == NIL_RTR3PTR
4012 || RTR0MemObjAddressR3(pBundle->aMem[i].MapObjR3) == pvR3))
4013 {
4014 if (pvR0 != NIL_RTR0PTR)
4015 hMemObjR0 = pBundle->aMem[i].MemObj;
4016 if (pvR3 != NIL_RTR3PTR)
4017 hMemObjR3 = pBundle->aMem[i].MapObjR3;
4018 break;
4019 }
4020 }
4021 }
4022 }
4023 RTSpinlockRelease(pSession->Spinlock);
4024
4025 rc = VERR_INVALID_PARAMETER;
4026 if ( hMemObjR0 != NIL_RTR0MEMOBJ
4027 || hMemObjR3 != NIL_RTR0MEMOBJ)
4028 {
4029 /*
4030 * Do some further input validations before calling IPRT.
4031 */
4032 size_t cbMemObj = hMemObjR0 != NIL_RTR0PTR ? RTR0MemObjSize(hMemObjR0) : RTR0MemObjSize(hMemObjR3);
4033 if ( offSub < cbMemObj
4034 && cbSub <= cbMemObj
4035 && offSub + cbSub <= cbMemObj)
4036 {
4037 rc = VINF_SUCCESS;
4038 if (hMemObjR3 != NIL_RTR0PTR)
4039 rc = RTR0MemObjProtect(hMemObjR3, offSub, cbSub, fProt);
4040 if (hMemObjR0 != NIL_RTR0PTR && RT_SUCCESS(rc))
4041 rc = RTR0MemObjProtect(hMemObjR0, offSub, cbSub, fProt);
4042 }
4043 else
4044 SUPR0Printf("SUPR0PageMapKernel: cbMemObj=%#x offSub=%#x cbSub=%#x\n", cbMemObj, offSub, cbSub);
4045
4046 }
4047 return rc;
4048
4049}
4050SUPR0_EXPORT_SYMBOL(SUPR0PageProtect);
4051
4052
4053/**
4054 * Free memory allocated by SUPR0PageAlloc() and SUPR0PageAllocEx().
4055 *
4056 * @returns IPRT status code.
4057 * @param pSession The session owning the allocation.
4058 * @param pvR3 The Ring-3 address returned by SUPR0PageAlloc() or
4059 * SUPR0PageAllocEx().
4060 */
4061SUPR0DECL(int) SUPR0PageFree(PSUPDRVSESSION pSession, RTR3PTR pvR3)
4062{
4063 LogFlow(("SUPR0PageFree: pSession=%p pvR3=%p\n", pSession, (void *)pvR3));
4064 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
4065 return supdrvMemRelease(pSession, (RTHCUINTPTR)pvR3, MEMREF_TYPE_PAGE);
4066}
4067SUPR0_EXPORT_SYMBOL(SUPR0PageFree);
4068
4069
4070/**
4071 * Reports a bad context, currenctly that means EFLAGS.AC is 0 instead of 1.
4072 *
4073 * @param pDevExt The device extension.
4074 * @param pszFile The source file where the caller detected the bad
4075 * context.
4076 * @param uLine The line number in @a pszFile.
4077 * @param pszExtra Optional additional message to give further hints.
4078 */
4079void VBOXCALL supdrvBadContext(PSUPDRVDEVEXT pDevExt, const char *pszFile, uint32_t uLine, const char *pszExtra)
4080{
4081 uint32_t cCalls;
4082
4083 /*
4084 * Shorten the filename before displaying the message.
4085 */
4086 for (;;)
4087 {
4088 const char *pszTmp = strchr(pszFile, '/');
4089 if (!pszTmp)
4090 pszTmp = strchr(pszFile, '\\');
4091 if (!pszTmp)
4092 break;
4093 pszFile = pszTmp + 1;
4094 }
4095 if (RT_VALID_PTR(pszExtra) && *pszExtra)
4096 SUPR0Printf("vboxdrv: Bad CPU context error at line %u in %s: %s\n", uLine, pszFile, pszExtra);
4097 else
4098 SUPR0Printf("vboxdrv: Bad CPU context error at line %u in %s!\n", uLine, pszFile);
4099
4100 /*
4101 * Record the incident so that we stand a chance of blocking I/O controls
4102 * before panicing the system.
4103 */
4104 cCalls = ASMAtomicIncU32(&pDevExt->cBadContextCalls);
4105 if (cCalls > UINT32_MAX - _1K)
4106 ASMAtomicWriteU32(&pDevExt->cBadContextCalls, UINT32_MAX - _1K);
4107}
4108
4109
4110/**
4111 * Reports a bad context, currenctly that means EFLAGS.AC is 0 instead of 1.
4112 *
4113 * @param pSession The session of the caller.
4114 * @param pszFile The source file where the caller detected the bad
4115 * context.
4116 * @param uLine The line number in @a pszFile.
4117 * @param pszExtra Optional additional message to give further hints.
4118 */
4119SUPR0DECL(void) SUPR0BadContext(PSUPDRVSESSION pSession, const char *pszFile, uint32_t uLine, const char *pszExtra)
4120{
4121 PSUPDRVDEVEXT pDevExt;
4122
4123 AssertReturnVoid(SUP_IS_SESSION_VALID(pSession));
4124 pDevExt = pSession->pDevExt;
4125
4126 supdrvBadContext(pDevExt, pszFile, uLine, pszExtra);
4127}
4128SUPR0_EXPORT_SYMBOL(SUPR0BadContext);
4129
4130
4131/**
4132 * Gets the paging mode of the current CPU.
4133 *
4134 * @returns Paging mode, SUPPAGEINGMODE_INVALID on error.
4135 */
4136SUPR0DECL(SUPPAGINGMODE) SUPR0GetPagingMode(void)
4137{
4138 SUPPAGINGMODE enmMode;
4139
4140 RTR0UINTREG cr0 = ASMGetCR0();
4141 if ((cr0 & (X86_CR0_PG | X86_CR0_PE)) != (X86_CR0_PG | X86_CR0_PE))
4142 enmMode = SUPPAGINGMODE_INVALID;
4143 else
4144 {
4145 RTR0UINTREG cr4 = ASMGetCR4();
4146 uint32_t fNXEPlusLMA = 0;
4147 if (cr4 & X86_CR4_PAE)
4148 {
4149 uint32_t fExtFeatures = ASMCpuId_EDX(0x80000001);
4150 if (fExtFeatures & (X86_CPUID_EXT_FEATURE_EDX_NX | X86_CPUID_EXT_FEATURE_EDX_LONG_MODE))
4151 {
4152 uint64_t efer = ASMRdMsr(MSR_K6_EFER);
4153 if ((fExtFeatures & X86_CPUID_EXT_FEATURE_EDX_NX) && (efer & MSR_K6_EFER_NXE))
4154 fNXEPlusLMA |= RT_BIT(0);
4155 if ((fExtFeatures & X86_CPUID_EXT_FEATURE_EDX_LONG_MODE) && (efer & MSR_K6_EFER_LMA))
4156 fNXEPlusLMA |= RT_BIT(1);
4157 }
4158 }
4159
4160 switch ((cr4 & (X86_CR4_PAE | X86_CR4_PGE)) | fNXEPlusLMA)
4161 {
4162 case 0:
4163 enmMode = SUPPAGINGMODE_32_BIT;
4164 break;
4165
4166 case X86_CR4_PGE:
4167 enmMode = SUPPAGINGMODE_32_BIT_GLOBAL;
4168 break;
4169
4170 case X86_CR4_PAE:
4171 enmMode = SUPPAGINGMODE_PAE;
4172 break;
4173
4174 case X86_CR4_PAE | RT_BIT(0):
4175 enmMode = SUPPAGINGMODE_PAE_NX;
4176 break;
4177
4178 case X86_CR4_PAE | X86_CR4_PGE:
4179 enmMode = SUPPAGINGMODE_PAE_GLOBAL;
4180 break;
4181
4182 case X86_CR4_PAE | X86_CR4_PGE | RT_BIT(0):
4183 enmMode = SUPPAGINGMODE_PAE_GLOBAL;
4184 break;
4185
4186 case RT_BIT(1) | X86_CR4_PAE:
4187 enmMode = SUPPAGINGMODE_AMD64;
4188 break;
4189
4190 case RT_BIT(1) | X86_CR4_PAE | RT_BIT(0):
4191 enmMode = SUPPAGINGMODE_AMD64_NX;
4192 break;
4193
4194 case RT_BIT(1) | X86_CR4_PAE | X86_CR4_PGE:
4195 enmMode = SUPPAGINGMODE_AMD64_GLOBAL;
4196 break;
4197
4198 case RT_BIT(1) | X86_CR4_PAE | X86_CR4_PGE | RT_BIT(0):
4199 enmMode = SUPPAGINGMODE_AMD64_GLOBAL_NX;
4200 break;
4201
4202 default:
4203 AssertMsgFailed(("Cannot happen! cr4=%#x fNXEPlusLMA=%d\n", cr4, fNXEPlusLMA));
4204 enmMode = SUPPAGINGMODE_INVALID;
4205 break;
4206 }
4207 }
4208 return enmMode;
4209}
4210SUPR0_EXPORT_SYMBOL(SUPR0GetPagingMode);
4211
4212
4213/**
4214 * Change CR4 and take care of the kernel CR4 shadow if applicable.
4215 *
4216 * CR4 shadow handling is required for Linux >= 4.0. Calling this function
4217 * instead of ASMSetCR4() is only necessary for semi-permanent CR4 changes
4218 * for code with interrupts enabled.
4219 *
4220 * @returns the old CR4 value.
4221 *
4222 * @param fOrMask bits to be set in CR4.
4223 * @param fAndMask bits to be cleard in CR4.
4224 *
4225 * @remarks Must be called with preemption/interrupts disabled.
4226 */
4227SUPR0DECL(RTCCUINTREG) SUPR0ChangeCR4(RTCCUINTREG fOrMask, RTCCUINTREG fAndMask)
4228{
4229#ifdef RT_OS_LINUX
4230 return supdrvOSChangeCR4(fOrMask, fAndMask);
4231#else
4232 RTCCUINTREG uOld = ASMGetCR4();
4233 RTCCUINTREG uNew = (uOld & fAndMask) | fOrMask;
4234 if (uNew != uOld)
4235 ASMSetCR4(uNew);
4236 return uOld;
4237#endif
4238}
4239SUPR0_EXPORT_SYMBOL(SUPR0ChangeCR4);
4240
4241
4242/**
4243 * Enables or disabled hardware virtualization extensions using native OS APIs.
4244 *
4245 * @returns VBox status code.
4246 * @retval VINF_SUCCESS on success.
4247 * @retval VERR_NOT_SUPPORTED if not supported by the native OS.
4248 *
4249 * @param fEnable Whether to enable or disable.
4250 */
4251SUPR0DECL(int) SUPR0EnableVTx(bool fEnable)
4252{
4253#ifdef RT_OS_DARWIN
4254 return supdrvOSEnableVTx(fEnable);
4255#else
4256 RT_NOREF1(fEnable);
4257 return VERR_NOT_SUPPORTED;
4258#endif
4259}
4260SUPR0_EXPORT_SYMBOL(SUPR0EnableVTx);
4261
4262
4263/**
4264 * Suspends hardware virtualization extensions using the native OS API.
4265 *
4266 * This is called prior to entering raw-mode context.
4267 *
4268 * @returns @c true if suspended, @c false if not.
4269 */
4270SUPR0DECL(bool) SUPR0SuspendVTxOnCpu(void)
4271{
4272#ifdef RT_OS_DARWIN
4273 return supdrvOSSuspendVTxOnCpu();
4274#else
4275 return false;
4276#endif
4277}
4278SUPR0_EXPORT_SYMBOL(SUPR0SuspendVTxOnCpu);
4279
4280
4281/**
4282 * Resumes hardware virtualization extensions using the native OS API.
4283 *
4284 * This is called after to entering raw-mode context.
4285 *
4286 * @param fSuspended The return value of SUPR0SuspendVTxOnCpu.
4287 */
4288SUPR0DECL(void) SUPR0ResumeVTxOnCpu(bool fSuspended)
4289{
4290#ifdef RT_OS_DARWIN
4291 supdrvOSResumeVTxOnCpu(fSuspended);
4292#else
4293 RT_NOREF1(fSuspended);
4294 Assert(!fSuspended);
4295#endif
4296}
4297SUPR0_EXPORT_SYMBOL(SUPR0ResumeVTxOnCpu);
4298
4299
4300SUPR0DECL(int) SUPR0GetCurrentGdtRw(RTHCUINTPTR *pGdtRw)
4301{
4302#ifdef RT_OS_LINUX
4303 return supdrvOSGetCurrentGdtRw(pGdtRw);
4304#else
4305 NOREF(pGdtRw);
4306 return VERR_NOT_IMPLEMENTED;
4307#endif
4308}
4309SUPR0_EXPORT_SYMBOL(SUPR0GetCurrentGdtRw);
4310
4311
4312/**
4313 * Gets AMD-V and VT-x support for the calling CPU.
4314 *
4315 * @returns VBox status code.
4316 * @param pfCaps Where to store whether VT-x (SUPVTCAPS_VT_X) or AMD-V
4317 * (SUPVTCAPS_AMD_V) is supported.
4318 */
4319SUPR0DECL(int) SUPR0GetVTSupport(uint32_t *pfCaps)
4320{
4321 Assert(pfCaps);
4322 *pfCaps = 0;
4323
4324 /* Check if the CPU even supports CPUID (extremely ancient CPUs). */
4325 if (ASMHasCpuId())
4326 {
4327 /* Check the range of standard CPUID leafs. */
4328 uint32_t uMaxLeaf, uVendorEbx, uVendorEcx, uVendorEdx;
4329 ASMCpuId(0, &uMaxLeaf, &uVendorEbx, &uVendorEcx, &uVendorEdx);
4330 if (RTX86IsValidStdRange(uMaxLeaf))
4331 {
4332 /* Query the standard CPUID leaf. */
4333 uint32_t fFeatEcx, fFeatEdx, uDummy;
4334 ASMCpuId(1, &uDummy, &uDummy, &fFeatEcx, &fFeatEdx);
4335
4336 /* Check if the vendor is Intel (or compatible). */
4337 if ( RTX86IsIntelCpu(uVendorEbx, uVendorEcx, uVendorEdx)
4338 || RTX86IsViaCentaurCpu(uVendorEbx, uVendorEcx, uVendorEdx)
4339 || RTX86IsShanghaiCpu(uVendorEbx, uVendorEcx, uVendorEdx))
4340 {
4341 /* Check VT-x support. In addition, VirtualBox requires MSR and FXSAVE/FXRSTOR to function. */
4342 if ( (fFeatEcx & X86_CPUID_FEATURE_ECX_VMX)
4343 && (fFeatEdx & X86_CPUID_FEATURE_EDX_MSR)
4344 && (fFeatEdx & X86_CPUID_FEATURE_EDX_FXSR))
4345 {
4346 *pfCaps = SUPVTCAPS_VT_X;
4347 return VINF_SUCCESS;
4348 }
4349 return VERR_VMX_NO_VMX;
4350 }
4351
4352 /* Check if the vendor is AMD (or compatible). */
4353 if ( RTX86IsAmdCpu(uVendorEbx, uVendorEcx, uVendorEdx)
4354 || RTX86IsHygonCpu(uVendorEbx, uVendorEcx, uVendorEdx))
4355 {
4356 uint32_t fExtFeatEcx, uExtMaxId;
4357 ASMCpuId(0x80000000, &uExtMaxId, &uDummy, &uDummy, &uDummy);
4358 ASMCpuId(0x80000001, &uDummy, &uDummy, &fExtFeatEcx, &uDummy);
4359
4360 /* Check AMD-V support. In addition, VirtualBox requires MSR and FXSAVE/FXRSTOR to function. */
4361 if ( RTX86IsValidExtRange(uExtMaxId)
4362 && uExtMaxId >= 0x8000000a
4363 && (fExtFeatEcx & X86_CPUID_AMD_FEATURE_ECX_SVM)
4364 && (fFeatEdx & X86_CPUID_FEATURE_EDX_MSR)
4365 && (fFeatEdx & X86_CPUID_FEATURE_EDX_FXSR))
4366 {
4367 *pfCaps = SUPVTCAPS_AMD_V;
4368 return VINF_SUCCESS;
4369 }
4370 return VERR_SVM_NO_SVM;
4371 }
4372 }
4373 }
4374 return VERR_UNSUPPORTED_CPU;
4375}
4376SUPR0_EXPORT_SYMBOL(SUPR0GetVTSupport);
4377
4378
4379/**
4380 * Checks if Intel VT-x feature is usable on this CPU.
4381 *
4382 * @returns VBox status code.
4383 * @param pfIsSmxModeAmbiguous Where to return whether the SMX mode causes
4384 * ambiguity that makes us unsure whether we
4385 * really can use VT-x or not.
4386 *
4387 * @remarks Must be called with preemption disabled.
4388 * The caller is also expected to check that the CPU is an Intel (or
4389 * VIA/Shanghai) CPU -and- that it supports VT-x. Otherwise, this
4390 * function might throw a \#GP fault as it tries to read/write MSRs
4391 * that may not be present!
4392 */
4393SUPR0DECL(int) SUPR0GetVmxUsability(bool *pfIsSmxModeAmbiguous)
4394{
4395 uint64_t fFeatMsr;
4396 bool fMaybeSmxMode;
4397 bool fMsrLocked;
4398 bool fSmxVmxAllowed;
4399 bool fVmxAllowed;
4400 bool fIsSmxModeAmbiguous;
4401 int rc;
4402
4403 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
4404
4405 fFeatMsr = ASMRdMsr(MSR_IA32_FEATURE_CONTROL);
4406 fMaybeSmxMode = RT_BOOL(ASMGetCR4() & X86_CR4_SMXE);
4407 fMsrLocked = RT_BOOL(fFeatMsr & MSR_IA32_FEATURE_CONTROL_LOCK);
4408 fSmxVmxAllowed = RT_BOOL(fFeatMsr & MSR_IA32_FEATURE_CONTROL_SMX_VMXON);
4409 fVmxAllowed = RT_BOOL(fFeatMsr & MSR_IA32_FEATURE_CONTROL_VMXON);
4410 fIsSmxModeAmbiguous = false;
4411 rc = VERR_INTERNAL_ERROR_5;
4412
4413 /* Check if the LOCK bit is set but excludes the required VMXON bit. */
4414 if (fMsrLocked)
4415 {
4416 if (fVmxAllowed && fSmxVmxAllowed)
4417 rc = VINF_SUCCESS;
4418 else if (!fVmxAllowed && !fSmxVmxAllowed)
4419 rc = VERR_VMX_MSR_ALL_VMX_DISABLED;
4420 else if (!fMaybeSmxMode)
4421 {
4422 if (fVmxAllowed)
4423 rc = VINF_SUCCESS;
4424 else
4425 rc = VERR_VMX_MSR_VMX_DISABLED;
4426 }
4427 else
4428 {
4429 /*
4430 * CR4.SMXE is set but this doesn't mean the CPU is necessarily in SMX mode. We shall assume
4431 * that it is -not- and that it is a stupid BIOS/OS setting CR4.SMXE for no good reason.
4432 * See @bugref{6873}.
4433 */
4434 Assert(fMaybeSmxMode == true);
4435 fIsSmxModeAmbiguous = true;
4436 rc = VINF_SUCCESS;
4437 }
4438 }
4439 else
4440 {
4441 /*
4442 * MSR is not yet locked; we can change it ourselves here. Once the lock bit is set,
4443 * this MSR can no longer be modified.
4444 *
4445 * Set both the VMX and SMX_VMX bits (if supported) as we can't determine SMX mode
4446 * accurately. See @bugref{6873}.
4447 *
4448 * We need to check for SMX hardware support here, before writing the MSR as
4449 * otherwise we will #GP fault on CPUs that do not support it. Callers do not check
4450 * for it.
4451 */
4452 uint32_t fFeaturesECX, uDummy;
4453#ifdef VBOX_STRICT
4454 /* Callers should have verified these at some point. */
4455 uint32_t uMaxId, uVendorEBX, uVendorECX, uVendorEDX;
4456 ASMCpuId(0, &uMaxId, &uVendorEBX, &uVendorECX, &uVendorEDX);
4457 Assert(RTX86IsValidStdRange(uMaxId));
4458 Assert( RTX86IsIntelCpu( uVendorEBX, uVendorECX, uVendorEDX)
4459 || RTX86IsViaCentaurCpu(uVendorEBX, uVendorECX, uVendorEDX)
4460 || RTX86IsShanghaiCpu( uVendorEBX, uVendorECX, uVendorEDX));
4461#endif
4462 ASMCpuId(1, &uDummy, &uDummy, &fFeaturesECX, &uDummy);
4463 bool fSmxVmxHwSupport = false;
4464 if ( (fFeaturesECX & X86_CPUID_FEATURE_ECX_VMX)
4465 && (fFeaturesECX & X86_CPUID_FEATURE_ECX_SMX))
4466 fSmxVmxHwSupport = true;
4467
4468 fFeatMsr |= MSR_IA32_FEATURE_CONTROL_LOCK
4469 | MSR_IA32_FEATURE_CONTROL_VMXON;
4470 if (fSmxVmxHwSupport)
4471 fFeatMsr |= MSR_IA32_FEATURE_CONTROL_SMX_VMXON;
4472
4473 /*
4474 * Commit.
4475 */
4476 ASMWrMsr(MSR_IA32_FEATURE_CONTROL, fFeatMsr);
4477
4478 /*
4479 * Verify.
4480 */
4481 fFeatMsr = ASMRdMsr(MSR_IA32_FEATURE_CONTROL);
4482 fMsrLocked = RT_BOOL(fFeatMsr & MSR_IA32_FEATURE_CONTROL_LOCK);
4483 if (fMsrLocked)
4484 {
4485 fSmxVmxAllowed = RT_BOOL(fFeatMsr & MSR_IA32_FEATURE_CONTROL_SMX_VMXON);
4486 fVmxAllowed = RT_BOOL(fFeatMsr & MSR_IA32_FEATURE_CONTROL_VMXON);
4487 if ( fVmxAllowed
4488 && ( !fSmxVmxHwSupport
4489 || fSmxVmxAllowed))
4490 rc = VINF_SUCCESS;
4491 else
4492 rc = !fSmxVmxHwSupport ? VERR_VMX_MSR_VMX_ENABLE_FAILED : VERR_VMX_MSR_SMX_VMX_ENABLE_FAILED;
4493 }
4494 else
4495 rc = VERR_VMX_MSR_LOCKING_FAILED;
4496 }
4497
4498 if (pfIsSmxModeAmbiguous)
4499 *pfIsSmxModeAmbiguous = fIsSmxModeAmbiguous;
4500
4501 return rc;
4502}
4503SUPR0_EXPORT_SYMBOL(SUPR0GetVmxUsability);
4504
4505
4506/**
4507 * Checks if AMD-V SVM feature is usable on this CPU.
4508 *
4509 * @returns VBox status code.
4510 * @param fInitSvm If usable, try to initialize SVM on this CPU.
4511 *
4512 * @remarks Must be called with preemption disabled.
4513 */
4514SUPR0DECL(int) SUPR0GetSvmUsability(bool fInitSvm)
4515{
4516 int rc;
4517 uint64_t fVmCr;
4518 uint64_t fEfer;
4519
4520 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
4521 fVmCr = ASMRdMsr(MSR_K8_VM_CR);
4522 if (!(fVmCr & MSR_K8_VM_CR_SVM_DISABLE))
4523 {
4524 rc = VINF_SUCCESS;
4525 if (fInitSvm)
4526 {
4527 /* Turn on SVM in the EFER MSR. */
4528 fEfer = ASMRdMsr(MSR_K6_EFER);
4529 if (fEfer & MSR_K6_EFER_SVME)
4530 rc = VERR_SVM_IN_USE;
4531 else
4532 {
4533 ASMWrMsr(MSR_K6_EFER, fEfer | MSR_K6_EFER_SVME);
4534
4535 /* Paranoia. */
4536 fEfer = ASMRdMsr(MSR_K6_EFER);
4537 if (fEfer & MSR_K6_EFER_SVME)
4538 {
4539 /* Restore previous value. */
4540 ASMWrMsr(MSR_K6_EFER, fEfer & ~MSR_K6_EFER_SVME);
4541 }
4542 else
4543 rc = VERR_SVM_ILLEGAL_EFER_MSR;
4544 }
4545 }
4546 }
4547 else
4548 rc = VERR_SVM_DISABLED;
4549 return rc;
4550}
4551SUPR0_EXPORT_SYMBOL(SUPR0GetSvmUsability);
4552
4553
4554/**
4555 * Queries the AMD-V and VT-x capabilities of the calling CPU.
4556 *
4557 * @returns VBox status code.
4558 * @retval VERR_VMX_NO_VMX
4559 * @retval VERR_VMX_MSR_ALL_VMX_DISABLED
4560 * @retval VERR_VMX_MSR_VMX_DISABLED
4561 * @retval VERR_VMX_MSR_LOCKING_FAILED
4562 * @retval VERR_VMX_MSR_VMX_ENABLE_FAILED
4563 * @retval VERR_VMX_MSR_SMX_VMX_ENABLE_FAILED
4564 * @retval VERR_SVM_NO_SVM
4565 * @retval VERR_SVM_DISABLED
4566 * @retval VERR_UNSUPPORTED_CPU if not identifiable as an AMD, Intel or VIA
4567 * (centaur)/Shanghai CPU.
4568 *
4569 * @param pfCaps Where to store the capabilities.
4570 */
4571int VBOXCALL supdrvQueryVTCapsInternal(uint32_t *pfCaps)
4572{
4573 int rc = VERR_UNSUPPORTED_CPU;
4574 bool fIsSmxModeAmbiguous = false;
4575 RTTHREADPREEMPTSTATE PreemptState = RTTHREADPREEMPTSTATE_INITIALIZER;
4576
4577 /*
4578 * Input validation.
4579 */
4580 AssertPtrReturn(pfCaps, VERR_INVALID_POINTER);
4581 *pfCaps = 0;
4582
4583 /* We may modify MSRs and re-read them, disable preemption so we make sure we don't migrate CPUs. */
4584 RTThreadPreemptDisable(&PreemptState);
4585
4586 /* Check if VT-x/AMD-V is supported. */
4587 rc = SUPR0GetVTSupport(pfCaps);
4588 if (RT_SUCCESS(rc))
4589 {
4590 /* Check if VT-x is supported. */
4591 if (*pfCaps & SUPVTCAPS_VT_X)
4592 {
4593 /* Check if VT-x is usable. */
4594 rc = SUPR0GetVmxUsability(&fIsSmxModeAmbiguous);
4595 if (RT_SUCCESS(rc))
4596 {
4597 /* Query some basic VT-x capabilities (mainly required by our GUI). */
4598 VMXCTLSMSR vtCaps;
4599 vtCaps.u = ASMRdMsr(MSR_IA32_VMX_PROCBASED_CTLS);
4600 if (vtCaps.n.allowed1 & VMX_PROC_CTLS_USE_SECONDARY_CTLS)
4601 {
4602 vtCaps.u = ASMRdMsr(MSR_IA32_VMX_PROCBASED_CTLS2);
4603 if (vtCaps.n.allowed1 & VMX_PROC_CTLS2_EPT)
4604 *pfCaps |= SUPVTCAPS_NESTED_PAGING;
4605 if (vtCaps.n.allowed1 & VMX_PROC_CTLS2_UNRESTRICTED_GUEST)
4606 *pfCaps |= SUPVTCAPS_VTX_UNRESTRICTED_GUEST;
4607 if (vtCaps.n.allowed1 & VMX_PROC_CTLS2_VMCS_SHADOWING)
4608 *pfCaps |= SUPVTCAPS_VTX_VMCS_SHADOWING;
4609 }
4610 }
4611 }
4612 /* Check if AMD-V is supported. */
4613 else if (*pfCaps & SUPVTCAPS_AMD_V)
4614 {
4615 /* Check is SVM is usable. */
4616 rc = SUPR0GetSvmUsability(false /* fInitSvm */);
4617 if (RT_SUCCESS(rc))
4618 {
4619 /* Query some basic AMD-V capabilities (mainly required by our GUI). */
4620 uint32_t uDummy, fSvmFeatures;
4621 ASMCpuId(0x8000000a, &uDummy, &uDummy, &uDummy, &fSvmFeatures);
4622 if (fSvmFeatures & X86_CPUID_SVM_FEATURE_EDX_NESTED_PAGING)
4623 *pfCaps |= SUPVTCAPS_NESTED_PAGING;
4624 if (fSvmFeatures & X86_CPUID_SVM_FEATURE_EDX_VIRT_VMSAVE_VMLOAD)
4625 *pfCaps |= SUPVTCAPS_AMDV_VIRT_VMSAVE_VMLOAD;
4626 }
4627 }
4628 }
4629
4630 /* Restore preemption. */
4631 RTThreadPreemptRestore(&PreemptState);
4632
4633 /* After restoring preemption, if we may be in SMX mode, print a warning as it's difficult to debug such problems. */
4634 if (fIsSmxModeAmbiguous)
4635 SUPR0Printf(("WARNING! CR4 hints SMX mode but your CPU is too secretive. Proceeding anyway... We wish you good luck!\n"));
4636
4637 return rc;
4638}
4639
4640
4641/**
4642 * Queries the AMD-V and VT-x capabilities of the calling CPU.
4643 *
4644 * @returns VBox status code.
4645 * @retval VERR_VMX_NO_VMX
4646 * @retval VERR_VMX_MSR_ALL_VMX_DISABLED
4647 * @retval VERR_VMX_MSR_VMX_DISABLED
4648 * @retval VERR_VMX_MSR_LOCKING_FAILED
4649 * @retval VERR_VMX_MSR_VMX_ENABLE_FAILED
4650 * @retval VERR_VMX_MSR_SMX_VMX_ENABLE_FAILED
4651 * @retval VERR_SVM_NO_SVM
4652 * @retval VERR_SVM_DISABLED
4653 * @retval VERR_UNSUPPORTED_CPU if not identifiable as an AMD, Intel or VIA
4654 * (centaur)/Shanghai CPU.
4655 *
4656 * @param pSession The session handle.
4657 * @param pfCaps Where to store the capabilities.
4658 */
4659SUPR0DECL(int) SUPR0QueryVTCaps(PSUPDRVSESSION pSession, uint32_t *pfCaps)
4660{
4661 /*
4662 * Input validation.
4663 */
4664 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
4665 AssertPtrReturn(pfCaps, VERR_INVALID_POINTER);
4666
4667 /*
4668 * Call common worker.
4669 */
4670 return supdrvQueryVTCapsInternal(pfCaps);
4671}
4672SUPR0_EXPORT_SYMBOL(SUPR0QueryVTCaps);
4673
4674
4675/**
4676 * Queries the CPU microcode revision.
4677 *
4678 * @returns VBox status code.
4679 * @retval VERR_UNSUPPORTED_CPU if not identifiable as a processor with
4680 * readable microcode rev.
4681 *
4682 * @param puRevision Where to store the microcode revision.
4683 */
4684static int VBOXCALL supdrvQueryUcodeRev(uint32_t *puRevision)
4685{
4686 int rc = VERR_UNSUPPORTED_CPU;
4687 RTTHREADPREEMPTSTATE PreemptState = RTTHREADPREEMPTSTATE_INITIALIZER;
4688
4689 /*
4690 * Input validation.
4691 */
4692 AssertPtrReturn(puRevision, VERR_INVALID_POINTER);
4693
4694 *puRevision = 0;
4695
4696 /* Disable preemption so we make sure we don't migrate CPUs, just in case. */
4697 /* NB: We assume that there aren't mismatched microcode revs in the system. */
4698 RTThreadPreemptDisable(&PreemptState);
4699
4700 if (ASMHasCpuId())
4701 {
4702 uint32_t uDummy, uTFMSEAX;
4703 uint32_t uMaxId, uVendorEBX, uVendorECX, uVendorEDX;
4704
4705 ASMCpuId(0, &uMaxId, &uVendorEBX, &uVendorECX, &uVendorEDX);
4706 ASMCpuId(1, &uTFMSEAX, &uDummy, &uDummy, &uDummy);
4707
4708 if (RTX86IsValidStdRange(uMaxId))
4709 {
4710 uint64_t uRevMsr;
4711 if (RTX86IsIntelCpu(uVendorEBX, uVendorECX, uVendorEDX))
4712 {
4713 /* Architectural MSR available on Pentium Pro and later. */
4714 if (RTX86GetCpuFamily(uTFMSEAX) >= 6)
4715 {
4716 /* Revision is in the high dword. */
4717 uRevMsr = ASMRdMsr(MSR_IA32_BIOS_SIGN_ID);
4718 *puRevision = RT_HIDWORD(uRevMsr);
4719 rc = VINF_SUCCESS;
4720 }
4721 }
4722 else if ( RTX86IsAmdCpu(uVendorEBX, uVendorECX, uVendorEDX)
4723 || RTX86IsHygonCpu(uVendorEBX, uVendorECX, uVendorEDX))
4724 {
4725 /* Not well documented, but at least all AMD64 CPUs support this. */
4726 if (RTX86GetCpuFamily(uTFMSEAX) >= 15)
4727 {
4728 /* Revision is in the low dword. */
4729 uRevMsr = ASMRdMsr(MSR_IA32_BIOS_SIGN_ID); /* Same MSR as Intel. */
4730 *puRevision = RT_LODWORD(uRevMsr);
4731 rc = VINF_SUCCESS;
4732 }
4733 }
4734 }
4735 }
4736
4737 RTThreadPreemptRestore(&PreemptState);
4738
4739 return rc;
4740}
4741
4742
4743/**
4744 * Queries the CPU microcode revision.
4745 *
4746 * @returns VBox status code.
4747 * @retval VERR_UNSUPPORTED_CPU if not identifiable as a processor with
4748 * readable microcode rev.
4749 *
4750 * @param pSession The session handle.
4751 * @param puRevision Where to store the microcode revision.
4752 */
4753SUPR0DECL(int) SUPR0QueryUcodeRev(PSUPDRVSESSION pSession, uint32_t *puRevision)
4754{
4755 /*
4756 * Input validation.
4757 */
4758 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
4759 AssertPtrReturn(puRevision, VERR_INVALID_POINTER);
4760
4761 /*
4762 * Call common worker.
4763 */
4764 return supdrvQueryUcodeRev(puRevision);
4765}
4766SUPR0_EXPORT_SYMBOL(SUPR0QueryUcodeRev);
4767
4768
4769/**
4770 * Gets hardware-virtualization MSRs of the calling CPU.
4771 *
4772 * @returns VBox status code.
4773 * @param pMsrs Where to store the hardware-virtualization MSRs.
4774 * @param fCaps Hardware virtualization capabilities (SUPVTCAPS_XXX). Pass 0
4775 * to explicitly check for the presence of VT-x/AMD-V before
4776 * querying MSRs.
4777 * @param fForce Force querying of MSRs from the hardware.
4778 */
4779SUPR0DECL(int) SUPR0GetHwvirtMsrs(PSUPHWVIRTMSRS pMsrs, uint32_t fCaps, bool fForce)
4780{
4781 NOREF(fForce);
4782
4783 int rc;
4784 RTTHREADPREEMPTSTATE PreemptState = RTTHREADPREEMPTSTATE_INITIALIZER;
4785
4786 /*
4787 * Input validation.
4788 */
4789 AssertPtrReturn(pMsrs, VERR_INVALID_POINTER);
4790
4791 /*
4792 * Disable preemption so we make sure we don't migrate CPUs and because
4793 * we access global data.
4794 */
4795 RTThreadPreemptDisable(&PreemptState);
4796
4797 /*
4798 * Query the MSRs from the hardware.
4799 */
4800 SUPHWVIRTMSRS Msrs;
4801 RT_ZERO(Msrs);
4802
4803 /* If the caller claims VT-x/AMD-V is supported, don't need to recheck it. */
4804 if (!(fCaps & (SUPVTCAPS_VT_X | SUPVTCAPS_AMD_V)))
4805 rc = SUPR0GetVTSupport(&fCaps);
4806 else
4807 rc = VINF_SUCCESS;
4808 if (RT_SUCCESS(rc))
4809 {
4810 if (fCaps & SUPVTCAPS_VT_X)
4811 {
4812 Msrs.u.vmx.u64FeatCtrl = ASMRdMsr(MSR_IA32_FEATURE_CONTROL);
4813 Msrs.u.vmx.u64Basic = ASMRdMsr(MSR_IA32_VMX_BASIC);
4814 Msrs.u.vmx.PinCtls.u = ASMRdMsr(MSR_IA32_VMX_PINBASED_CTLS);
4815 Msrs.u.vmx.ProcCtls.u = ASMRdMsr(MSR_IA32_VMX_PROCBASED_CTLS);
4816 Msrs.u.vmx.ExitCtls.u = ASMRdMsr(MSR_IA32_VMX_EXIT_CTLS);
4817 Msrs.u.vmx.EntryCtls.u = ASMRdMsr(MSR_IA32_VMX_ENTRY_CTLS);
4818 Msrs.u.vmx.u64Misc = ASMRdMsr(MSR_IA32_VMX_MISC);
4819 Msrs.u.vmx.u64Cr0Fixed0 = ASMRdMsr(MSR_IA32_VMX_CR0_FIXED0);
4820 Msrs.u.vmx.u64Cr0Fixed1 = ASMRdMsr(MSR_IA32_VMX_CR0_FIXED1);
4821 Msrs.u.vmx.u64Cr4Fixed0 = ASMRdMsr(MSR_IA32_VMX_CR4_FIXED0);
4822 Msrs.u.vmx.u64Cr4Fixed1 = ASMRdMsr(MSR_IA32_VMX_CR4_FIXED1);
4823 Msrs.u.vmx.u64VmcsEnum = ASMRdMsr(MSR_IA32_VMX_VMCS_ENUM);
4824
4825 if (RT_BF_GET(Msrs.u.vmx.u64Basic, VMX_BF_BASIC_TRUE_CTLS))
4826 {
4827 Msrs.u.vmx.TruePinCtls.u = ASMRdMsr(MSR_IA32_VMX_TRUE_PINBASED_CTLS);
4828 Msrs.u.vmx.TrueProcCtls.u = ASMRdMsr(MSR_IA32_VMX_TRUE_PROCBASED_CTLS);
4829 Msrs.u.vmx.TrueEntryCtls.u = ASMRdMsr(MSR_IA32_VMX_TRUE_ENTRY_CTLS);
4830 Msrs.u.vmx.TrueExitCtls.u = ASMRdMsr(MSR_IA32_VMX_TRUE_EXIT_CTLS);
4831 }
4832
4833 if (Msrs.u.vmx.ProcCtls.n.allowed1 & VMX_PROC_CTLS_USE_SECONDARY_CTLS)
4834 {
4835 Msrs.u.vmx.ProcCtls2.u = ASMRdMsr(MSR_IA32_VMX_PROCBASED_CTLS2);
4836
4837 if (Msrs.u.vmx.ProcCtls2.n.allowed1 & (VMX_PROC_CTLS2_EPT | VMX_PROC_CTLS2_VPID))
4838 Msrs.u.vmx.u64EptVpidCaps = ASMRdMsr(MSR_IA32_VMX_EPT_VPID_CAP);
4839
4840 if (Msrs.u.vmx.ProcCtls2.n.allowed1 & VMX_PROC_CTLS2_VMFUNC)
4841 Msrs.u.vmx.u64VmFunc = ASMRdMsr(MSR_IA32_VMX_VMFUNC);
4842 }
4843
4844 if (Msrs.u.vmx.ProcCtls.n.allowed1 & VMX_PROC_CTLS_USE_TERTIARY_CTLS)
4845 Msrs.u.vmx.u64ProcCtls3 = ASMRdMsr(MSR_IA32_VMX_PROCBASED_CTLS3);
4846
4847 if (Msrs.u.vmx.ExitCtls.n.allowed1 & VMX_EXIT_CTLS_USE_SECONDARY_CTLS)
4848 Msrs.u.vmx.u64ExitCtls2 = ASMRdMsr(MSR_IA32_VMX_EXIT_CTLS2);
4849 }
4850 else if (fCaps & SUPVTCAPS_AMD_V)
4851 {
4852 Msrs.u.svm.u64MsrHwcr = ASMRdMsr(MSR_K8_HWCR);
4853 Msrs.u.svm.u64MsrSmmAddr = ASMRdMsr(MSR_K7_SMM_ADDR);
4854 Msrs.u.svm.u64MsrSmmMask = ASMRdMsr(MSR_K7_SMM_MASK);
4855 }
4856 else
4857 {
4858 RTThreadPreemptRestore(&PreemptState);
4859 AssertMsgFailedReturn(("SUPR0GetVTSupport returns success but neither VT-x nor AMD-V reported!\n"),
4860 VERR_INTERNAL_ERROR_2);
4861 }
4862
4863 /*
4864 * Copy the MSRs out.
4865 */
4866 memcpy(pMsrs, &Msrs, sizeof(*pMsrs));
4867 }
4868
4869 RTThreadPreemptRestore(&PreemptState);
4870
4871 return rc;
4872}
4873SUPR0_EXPORT_SYMBOL(SUPR0GetHwvirtMsrs);
4874
4875
4876/**
4877 * Register a component factory with the support driver.
4878 *
4879 * This is currently restricted to kernel sessions only.
4880 *
4881 * @returns VBox status code.
4882 * @retval VINF_SUCCESS on success.
4883 * @retval VERR_NO_MEMORY if we're out of memory.
4884 * @retval VERR_ALREADY_EXISTS if the factory has already been registered.
4885 * @retval VERR_ACCESS_DENIED if it isn't a kernel session.
4886 * @retval VERR_INVALID_PARAMETER on invalid parameter.
4887 * @retval VERR_INVALID_POINTER on invalid pointer parameter.
4888 *
4889 * @param pSession The SUPDRV session (must be a ring-0 session).
4890 * @param pFactory Pointer to the component factory registration structure.
4891 *
4892 * @remarks This interface is also available via SUPR0IdcComponentRegisterFactory.
4893 */
4894SUPR0DECL(int) SUPR0ComponentRegisterFactory(PSUPDRVSESSION pSession, PCSUPDRVFACTORY pFactory)
4895{
4896 PSUPDRVFACTORYREG pNewReg;
4897 const char *psz;
4898 int rc;
4899
4900 /*
4901 * Validate parameters.
4902 */
4903 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
4904 AssertReturn(pSession->R0Process == NIL_RTR0PROCESS, VERR_ACCESS_DENIED);
4905 AssertPtrReturn(pFactory, VERR_INVALID_POINTER);
4906 AssertPtrReturn(pFactory->pfnQueryFactoryInterface, VERR_INVALID_POINTER);
4907 psz = RTStrEnd(pFactory->szName, sizeof(pFactory->szName));
4908 AssertReturn(psz, VERR_INVALID_PARAMETER);
4909
4910 /*
4911 * Allocate and initialize a new registration structure.
4912 */
4913 pNewReg = (PSUPDRVFACTORYREG)RTMemAlloc(sizeof(SUPDRVFACTORYREG));
4914 if (pNewReg)
4915 {
4916 pNewReg->pNext = NULL;
4917 pNewReg->pFactory = pFactory;
4918 pNewReg->pSession = pSession;
4919 pNewReg->cchName = psz - &pFactory->szName[0];
4920
4921 /*
4922 * Add it to the tail of the list after checking for prior registration.
4923 */
4924 rc = RTSemFastMutexRequest(pSession->pDevExt->mtxComponentFactory);
4925 if (RT_SUCCESS(rc))
4926 {
4927 PSUPDRVFACTORYREG pPrev = NULL;
4928 PSUPDRVFACTORYREG pCur = pSession->pDevExt->pComponentFactoryHead;
4929 while (pCur && pCur->pFactory != pFactory)
4930 {
4931 pPrev = pCur;
4932 pCur = pCur->pNext;
4933 }
4934 if (!pCur)
4935 {
4936 if (pPrev)
4937 pPrev->pNext = pNewReg;
4938 else
4939 pSession->pDevExt->pComponentFactoryHead = pNewReg;
4940 rc = VINF_SUCCESS;
4941 }
4942 else
4943 rc = VERR_ALREADY_EXISTS;
4944
4945 RTSemFastMutexRelease(pSession->pDevExt->mtxComponentFactory);
4946 }
4947
4948 if (RT_FAILURE(rc))
4949 RTMemFree(pNewReg);
4950 }
4951 else
4952 rc = VERR_NO_MEMORY;
4953 return rc;
4954}
4955SUPR0_EXPORT_SYMBOL(SUPR0ComponentRegisterFactory);
4956
4957
4958/**
4959 * Deregister a component factory.
4960 *
4961 * @returns VBox status code.
4962 * @retval VINF_SUCCESS on success.
4963 * @retval VERR_NOT_FOUND if the factory wasn't registered.
4964 * @retval VERR_ACCESS_DENIED if it isn't a kernel session.
4965 * @retval VERR_INVALID_PARAMETER on invalid parameter.
4966 * @retval VERR_INVALID_POINTER on invalid pointer parameter.
4967 *
4968 * @param pSession The SUPDRV session (must be a ring-0 session).
4969 * @param pFactory Pointer to the component factory registration structure
4970 * previously passed SUPR0ComponentRegisterFactory().
4971 *
4972 * @remarks This interface is also available via SUPR0IdcComponentDeregisterFactory.
4973 */
4974SUPR0DECL(int) SUPR0ComponentDeregisterFactory(PSUPDRVSESSION pSession, PCSUPDRVFACTORY pFactory)
4975{
4976 int rc;
4977
4978 /*
4979 * Validate parameters.
4980 */
4981 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
4982 AssertReturn(pSession->R0Process == NIL_RTR0PROCESS, VERR_ACCESS_DENIED);
4983 AssertPtrReturn(pFactory, VERR_INVALID_POINTER);
4984
4985 /*
4986 * Take the lock and look for the registration record.
4987 */
4988 rc = RTSemFastMutexRequest(pSession->pDevExt->mtxComponentFactory);
4989 if (RT_SUCCESS(rc))
4990 {
4991 PSUPDRVFACTORYREG pPrev = NULL;
4992 PSUPDRVFACTORYREG pCur = pSession->pDevExt->pComponentFactoryHead;
4993 while (pCur && pCur->pFactory != pFactory)
4994 {
4995 pPrev = pCur;
4996 pCur = pCur->pNext;
4997 }
4998 if (pCur)
4999 {
5000 if (!pPrev)
5001 pSession->pDevExt->pComponentFactoryHead = pCur->pNext;
5002 else
5003 pPrev->pNext = pCur->pNext;
5004
5005 pCur->pNext = NULL;
5006 pCur->pFactory = NULL;
5007 pCur->pSession = NULL;
5008 rc = VINF_SUCCESS;
5009 }
5010 else
5011 rc = VERR_NOT_FOUND;
5012
5013 RTSemFastMutexRelease(pSession->pDevExt->mtxComponentFactory);
5014
5015 RTMemFree(pCur);
5016 }
5017 return rc;
5018}
5019SUPR0_EXPORT_SYMBOL(SUPR0ComponentDeregisterFactory);
5020
5021
5022/**
5023 * Queries a component factory.
5024 *
5025 * @returns VBox status code.
5026 * @retval VERR_INVALID_PARAMETER on invalid parameter.
5027 * @retval VERR_INVALID_POINTER on invalid pointer parameter.
5028 * @retval VERR_SUPDRV_COMPONENT_NOT_FOUND if the component factory wasn't found.
5029 * @retval VERR_SUPDRV_INTERFACE_NOT_SUPPORTED if the interface wasn't supported.
5030 *
5031 * @param pSession The SUPDRV session.
5032 * @param pszName The name of the component factory.
5033 * @param pszInterfaceUuid The UUID of the factory interface (stringified).
5034 * @param ppvFactoryIf Where to store the factory interface.
5035 */
5036SUPR0DECL(int) SUPR0ComponentQueryFactory(PSUPDRVSESSION pSession, const char *pszName, const char *pszInterfaceUuid, void **ppvFactoryIf)
5037{
5038 const char *pszEnd;
5039 size_t cchName;
5040 int rc;
5041
5042 /*
5043 * Validate parameters.
5044 */
5045 AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
5046
5047 AssertPtrReturn(pszName, VERR_INVALID_POINTER);
5048 pszEnd = RTStrEnd(pszName, RT_SIZEOFMEMB(SUPDRVFACTORY, szName));
5049 AssertReturn(pszEnd, VERR_INVALID_PARAMETER);
5050 cchName = pszEnd - pszName;
5051
5052 AssertPtrReturn(pszInterfaceUuid, VERR_INVALID_POINTER);
5053 pszEnd = RTStrEnd(pszInterfaceUuid, RTUUID_STR_LENGTH);
5054 AssertReturn(pszEnd, VERR_INVALID_PARAMETER);
5055
5056 AssertPtrReturn(ppvFactoryIf, VERR_INVALID_POINTER);
5057 *ppvFactoryIf = NULL;
5058
5059 /*
5060 * Take the lock and try all factories by this name.
5061 */
5062 rc = RTSemFastMutexRequest(pSession->pDevExt->mtxComponentFactory);
5063 if (RT_SUCCESS(rc))
5064 {
5065 PSUPDRVFACTORYREG pCur = pSession->pDevExt->pComponentFactoryHead;
5066 rc = VERR_SUPDRV_COMPONENT_NOT_FOUND;
5067 while (pCur)
5068 {
5069 if ( pCur->cchName == cchName
5070 && !memcmp(pCur->pFactory->szName, pszName, cchName))
5071 {
5072 void *pvFactory = pCur->pFactory->pfnQueryFactoryInterface(pCur->pFactory, pSession, pszInterfaceUuid);
5073 if (pvFactory)
5074 {
5075 *ppvFactoryIf = pvFactory;
5076 rc = VINF_SUCCESS;
5077 break;
5078 }
5079 rc = VERR_SUPDRV_INTERFACE_NOT_SUPPORTED;
5080 }
5081
5082 /* next */
5083 pCur = pCur->pNext;
5084 }
5085
5086 RTSemFastMutexRelease(pSession->pDevExt->mtxComponentFactory);
5087 }
5088 return rc;
5089}
5090SUPR0_EXPORT_SYMBOL(SUPR0ComponentQueryFactory);
5091
5092
5093/**
5094 * Adds a memory object to the session.
5095 *
5096 * @returns IPRT status code.
5097 * @param pMem Memory tracking structure containing the
5098 * information to track.
5099 * @param pSession The session.
5100 */
5101static int supdrvMemAdd(PSUPDRVMEMREF pMem, PSUPDRVSESSION pSession)
5102{
5103 PSUPDRVBUNDLE pBundle;
5104
5105 /*
5106 * Find free entry and record the allocation.
5107 */
5108 RTSpinlockAcquire(pSession->Spinlock);
5109 for (pBundle = &pSession->Bundle; pBundle; pBundle = pBundle->pNext)
5110 {
5111 if (pBundle->cUsed < RT_ELEMENTS(pBundle->aMem))
5112 {
5113 unsigned i;
5114 for (i = 0; i < RT_ELEMENTS(pBundle->aMem); i++)
5115 {
5116 if (pBundle->aMem[i].MemObj == NIL_RTR0MEMOBJ)
5117 {
5118 pBundle->cUsed++;
5119 pBundle->aMem[i] = *pMem;
5120 RTSpinlockRelease(pSession->Spinlock);
5121 return VINF_SUCCESS;
5122 }
5123 }
5124 AssertFailed(); /* !!this can't be happening!!! */
5125 }
5126 }
5127 RTSpinlockRelease(pSession->Spinlock);
5128
5129 /*
5130 * Need to allocate a new bundle.
5131 * Insert into the last entry in the bundle.
5132 */
5133 pBundle = (PSUPDRVBUNDLE)RTMemAllocZ(sizeof(*pBundle));
5134 if (!pBundle)
5135 return VERR_NO_MEMORY;
5136
5137 /* take last entry. */
5138 pBundle->cUsed++;
5139 pBundle->aMem[RT_ELEMENTS(pBundle->aMem) - 1] = *pMem;
5140
5141 /* insert into list. */
5142 RTSpinlockAcquire