VirtualBox

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

Last change on this file since 80281 was 80281, checked in by vboxsync, 5 years ago

VMM,++: Refactoring code to use VMMC & VMMCPUCC. bugref:9217

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

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette