VirtualBox

source: vbox/trunk/src/VBox/Additions/common/VBoxGuest/VBoxGuest-win.cpp@ 69993

Last change on this file since 69993 was 69500, checked in by vboxsync, 7 years ago

*: scm --update-copyright-year

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 56.0 KB
Line 
1/* $Id: VBoxGuest-win.cpp 69500 2017-10-28 15:14:05Z vboxsync $ */
2/** @file
3 * VBoxGuest - Windows specifics.
4 */
5
6/*
7 * Copyright (C) 2010-2017 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#include "VBoxGuest-win.h"
33#include "VBoxGuestInternal.h"
34
35#include <iprt/asm.h>
36#include <iprt/asm-amd64-x86.h>
37
38#include <VBox/log.h>
39#include <VBox/VBoxGuestLib.h>
40#include <iprt/string.h>
41
42/*
43 * XP DDK #defines ExFreePool to ExFreePoolWithTag. The latter does not exist
44 * on NT4, so... The same for ExAllocatePool.
45 */
46#ifdef TARGET_NT4
47# undef ExAllocatePool
48# undef ExFreePool
49#endif
50
51
52/*********************************************************************************************************************************
53* Internal Functions *
54*********************************************************************************************************************************/
55RT_C_DECLS_BEGIN
56static NTSTATUS vgdrvNtAddDevice(PDRIVER_OBJECT pDrvObj, PDEVICE_OBJECT pDevObj);
57static void vgdrvNtUnload(PDRIVER_OBJECT pDrvObj);
58static NTSTATUS vgdrvNtCreate(PDEVICE_OBJECT pDevObj, PIRP pIrp);
59static NTSTATUS vgdrvNtClose(PDEVICE_OBJECT pDevObj, PIRP pIrp);
60static NTSTATUS vgdrvNtDeviceControl(PDEVICE_OBJECT pDevObj, PIRP pIrp);
61static NTSTATUS vgdrvNtDeviceControlSlow(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession, PIRP pIrp, PIO_STACK_LOCATION pStack);
62static NTSTATUS vgdrvNtInternalIOCtl(PDEVICE_OBJECT pDevObj, PIRP pIrp);
63static NTSTATUS vgdrvNtRegistryReadDWORD(ULONG ulRoot, PCWSTR pwszPath, PWSTR pwszName, PULONG puValue);
64static NTSTATUS vgdrvNtSystemControl(PDEVICE_OBJECT pDevObj, PIRP pIrp);
65static NTSTATUS vgdrvNtShutdown(PDEVICE_OBJECT pDevObj, PIRP pIrp);
66static NTSTATUS vgdrvNtNotSupportedStub(PDEVICE_OBJECT pDevObj, PIRP pIrp);
67#ifdef VBOX_STRICT
68static void vgdrvNtDoTests(void);
69#endif
70static VOID vgdrvNtDpcHandler(PKDPC pDPC, PDEVICE_OBJECT pDevObj, PIRP pIrp, PVOID pContext);
71static BOOLEAN vgdrvNtIsrHandler(PKINTERRUPT interrupt, PVOID serviceContext);
72static NTSTATUS vgdrvNtScanPCIResourceList(PCM_RESOURCE_LIST pResList, PVBOXGUESTDEVEXTWIN pDevExt);
73static NTSTATUS vgdrvNtMapVMMDevMemory(PVBOXGUESTDEVEXTWIN pDevExt, PHYSICAL_ADDRESS PhysAddr, ULONG cbToMap,
74 void **ppvMMIOBase, uint32_t *pcbMMIO);
75RT_C_DECLS_END
76
77
78/*********************************************************************************************************************************
79* Exported Functions *
80*********************************************************************************************************************************/
81RT_C_DECLS_BEGIN
82ULONG DriverEntry(PDRIVER_OBJECT pDrvObj, PUNICODE_STRING pRegPath);
83RT_C_DECLS_END
84
85#ifdef ALLOC_PRAGMA
86# pragma alloc_text(INIT, DriverEntry)
87# pragma alloc_text(PAGE, vgdrvNtAddDevice)
88# pragma alloc_text(PAGE, vgdrvNtUnload)
89# pragma alloc_text(PAGE, vgdrvNtCreate)
90# pragma alloc_text(PAGE, vgdrvNtClose)
91# pragma alloc_text(PAGE, vgdrvNtShutdown)
92# pragma alloc_text(PAGE, vgdrvNtNotSupportedStub)
93# pragma alloc_text(PAGE, vgdrvNtScanPCIResourceList)
94#endif
95
96
97/*********************************************************************************************************************************
98* Global Variables *
99*********************************************************************************************************************************/
100/** The detected NT (windows) version. */
101VGDRVNTVER g_enmVGDrvNtVer = VGDRVNTVER_INVALID;
102
103
104
105/**
106 * Driver entry point.
107 *
108 * @returns appropriate status code.
109 * @param pDrvObj Pointer to driver object.
110 * @param pRegPath Registry base path.
111 */
112ULONG DriverEntry(PDRIVER_OBJECT pDrvObj, PUNICODE_STRING pRegPath)
113{
114 RT_NOREF1(pRegPath);
115 NTSTATUS rc = STATUS_SUCCESS;
116
117 LogFunc(("Driver built: %s %s\n", __DATE__, __TIME__));
118
119 /*
120 * Check if the NT version is supported and initialize g_enmVGDrvNtVer.
121 */
122 ULONG ulMajorVer;
123 ULONG ulMinorVer;
124 ULONG ulBuildNo;
125 BOOLEAN fCheckedBuild = PsGetVersion(&ulMajorVer, &ulMinorVer, &ulBuildNo, NULL);
126
127 /* Use RTLogBackdoorPrintf to make sure that this goes to VBox.log */
128 RTLogBackdoorPrintf("VBoxGuest: Windows version %u.%u, build %u\n", ulMajorVer, ulMinorVer, ulBuildNo);
129 if (fCheckedBuild)
130 RTLogBackdoorPrintf("VBoxGuest: Windows checked build\n");
131
132#ifdef VBOX_STRICT
133 vgdrvNtDoTests();
134#endif
135 switch (ulMajorVer)
136 {
137 case 10:
138 switch (ulMinorVer)
139 {
140 case 0:
141 /* Windows 10 Preview builds starting with 9926. */
142 default:
143 /* Also everything newer. */
144 g_enmVGDrvNtVer = VGDRVNTVER_WIN10;
145 break;
146 }
147 break;
148 case 6: /* Windows Vista or Windows 7 (based on minor ver) */
149 switch (ulMinorVer)
150 {
151 case 0: /* Note: Also could be Windows 2008 Server! */
152 g_enmVGDrvNtVer = VGDRVNTVER_WINVISTA;
153 break;
154 case 1: /* Note: Also could be Windows 2008 Server R2! */
155 g_enmVGDrvNtVer = VGDRVNTVER_WIN7;
156 break;
157 case 2:
158 g_enmVGDrvNtVer = VGDRVNTVER_WIN8;
159 break;
160 case 3:
161 g_enmVGDrvNtVer = VGDRVNTVER_WIN81;
162 break;
163 case 4:
164 /* Windows 10 Preview builds. */
165 default:
166 /* Also everything newer. */
167 g_enmVGDrvNtVer = VGDRVNTVER_WIN10;
168 break;
169 }
170 break;
171 case 5:
172 switch (ulMinorVer)
173 {
174 default:
175 case 2:
176 g_enmVGDrvNtVer = VGDRVNTVER_WIN2K3;
177 break;
178 case 1:
179 g_enmVGDrvNtVer = VGDRVNTVER_WINXP;
180 break;
181 case 0:
182 g_enmVGDrvNtVer = VGDRVNTVER_WIN2K;
183 break;
184 }
185 break;
186 case 4:
187 g_enmVGDrvNtVer = VGDRVNTVER_WINNT4;
188 break;
189 default:
190 if (ulMajorVer > 6)
191 {
192 /* "Windows 10 mode" for Windows 8.1+. */
193 g_enmVGDrvNtVer = VGDRVNTVER_WIN10;
194 }
195 else
196 {
197 if (ulMajorVer < 4)
198 LogRelFunc(("At least Windows NT4 required! (%u.%u)\n", ulMajorVer, ulMinorVer));
199 else
200 LogRelFunc(("Unknown version %u.%u!\n", ulMajorVer, ulMinorVer));
201 rc = STATUS_DRIVER_UNABLE_TO_LOAD;
202 }
203 break;
204 }
205
206 if (NT_SUCCESS(rc))
207 {
208 /*
209 * Setup the driver entry points in pDrvObj.
210 */
211 pDrvObj->DriverUnload = vgdrvNtUnload;
212 pDrvObj->MajorFunction[IRP_MJ_CREATE] = vgdrvNtCreate;
213 pDrvObj->MajorFunction[IRP_MJ_CLOSE] = vgdrvNtClose;
214 pDrvObj->MajorFunction[IRP_MJ_DEVICE_CONTROL] = vgdrvNtDeviceControl;
215 pDrvObj->MajorFunction[IRP_MJ_INTERNAL_DEVICE_CONTROL] = vgdrvNtInternalIOCtl;
216 pDrvObj->MajorFunction[IRP_MJ_SHUTDOWN] = vgdrvNtShutdown;
217 pDrvObj->MajorFunction[IRP_MJ_READ] = vgdrvNtNotSupportedStub;
218 pDrvObj->MajorFunction[IRP_MJ_WRITE] = vgdrvNtNotSupportedStub;
219#ifdef TARGET_NT4
220 rc = vgdrvNt4CreateDevice(pDrvObj, pRegPath);
221#else
222 pDrvObj->MajorFunction[IRP_MJ_PNP] = vgdrvNtPnP;
223 pDrvObj->MajorFunction[IRP_MJ_POWER] = vgdrvNtPower;
224 pDrvObj->MajorFunction[IRP_MJ_SYSTEM_CONTROL] = vgdrvNtSystemControl;
225 pDrvObj->DriverExtension->AddDevice = (PDRIVER_ADD_DEVICE)vgdrvNtAddDevice;
226#endif
227 }
228
229 LogFlowFunc(("Returning %#x\n", rc));
230 return rc;
231}
232
233
234#ifndef TARGET_NT4
235/**
236 * Handle request from the Plug & Play subsystem.
237 *
238 * @returns NT status code
239 * @param pDrvObj Driver object
240 * @param pDevObj Device object
241 *
242 * @remarks Parts of this is duplicated in VBoxGuest-win-legacy.cpp.
243 */
244static NTSTATUS vgdrvNtAddDevice(PDRIVER_OBJECT pDrvObj, PDEVICE_OBJECT pDevObj)
245{
246 NTSTATUS rc;
247 LogFlowFuncEnter();
248
249 /*
250 * Create device.
251 */
252 UNICODE_STRING DevName;
253 RtlInitUnicodeString(&DevName, VBOXGUEST_DEVICE_NAME_NT);
254 PDEVICE_OBJECT pDeviceObject = NULL;
255 rc = IoCreateDevice(pDrvObj, sizeof(VBOXGUESTDEVEXTWIN), &DevName, FILE_DEVICE_UNKNOWN, 0, FALSE, &pDeviceObject);
256 if (NT_SUCCESS(rc))
257 {
258 /*
259 * Create symbolic link (DOS devices).
260 */
261 UNICODE_STRING DosName;
262 RtlInitUnicodeString(&DosName, VBOXGUEST_DEVICE_NAME_DOS);
263 rc = IoCreateSymbolicLink(&DosName, &DevName);
264 if (NT_SUCCESS(rc))
265 {
266 /*
267 * Setup the device extension.
268 */
269 PVBOXGUESTDEVEXTWIN pDevExt = (PVBOXGUESTDEVEXTWIN)pDeviceObject->DeviceExtension;
270 RT_ZERO(*pDevExt);
271
272 KeInitializeSpinLock(&pDevExt->MouseEventAccessLock);
273
274 pDevExt->pDeviceObject = pDeviceObject;
275 pDevExt->enmPrevDevState = VGDRVNTDEVSTATE_STOPPED;
276 pDevExt->enmDevState = VGDRVNTDEVSTATE_STOPPED;
277
278 pDevExt->pNextLowerDriver = IoAttachDeviceToDeviceStack(pDeviceObject, pDevObj);
279 if (pDevExt->pNextLowerDriver != NULL)
280 {
281 /*
282 * If we reached this point we're fine with the basic driver setup,
283 * so continue to init our own things.
284 */
285# ifdef VBOX_WITH_GUEST_BUGCHECK_DETECTION
286 vgdrvNtBugCheckCallback(pDevExt); /* Ignore failure! */
287# endif
288 if (NT_SUCCESS(rc))
289 {
290 /* VBoxGuestPower is pageable; ensure we are not called at elevated IRQL */
291 pDeviceObject->Flags |= DO_POWER_PAGABLE;
292
293 /* Driver is ready now. */
294 pDeviceObject->Flags &= ~DO_DEVICE_INITIALIZING;
295 LogFlowFunc(("Returning with rc=%#x (success)\n", rc));
296 return rc;
297 }
298
299 IoDetachDevice(pDevExt->pNextLowerDriver);
300 }
301 else
302 {
303 LogFunc(("IoAttachDeviceToDeviceStack did not give a nextLowerDriver!\n"));
304 rc = STATUS_DEVICE_NOT_CONNECTED;
305 }
306
307 /* bail out */
308 IoDeleteSymbolicLink(&DosName);
309 }
310 else
311 LogFunc(("IoCreateSymbolicLink failed with rc=%#x!\n", rc));
312 IoDeleteDevice(pDeviceObject);
313 }
314 else
315 LogFunc(("IoCreateDevice failed with rc=%#x!\n", rc));
316
317 LogFunc(("Returning with rc=%#x\n", rc));
318 return rc;
319}
320#endif /* !TARGET_NT4 */
321
322
323#ifdef LOG_ENABLED
324/**
325 * Debug helper to dump a device resource list.
326 *
327 * @param pResourceList list of device resources.
328 */
329static void vgdrvNtShowDeviceResources(PCM_PARTIAL_RESOURCE_LIST pResourceList)
330{
331 PCM_PARTIAL_RESOURCE_DESCRIPTOR pResource = pResourceList->PartialDescriptors;
332 ULONG cResources = pResourceList->Count;
333
334 for (ULONG i = 0; i < cResources; ++i, ++pResource)
335 {
336 ULONG uType = pResource->Type;
337 static char const * const s_apszName[] =
338 {
339 "CmResourceTypeNull",
340 "CmResourceTypePort",
341 "CmResourceTypeInterrupt",
342 "CmResourceTypeMemory",
343 "CmResourceTypeDma",
344 "CmResourceTypeDeviceSpecific",
345 "CmResourceTypeBusNumber",
346 "CmResourceTypeDevicePrivate",
347 "CmResourceTypeAssignedResource",
348 "CmResourceTypeSubAllocateFrom",
349 };
350
351 LogFunc(("Type=%s", uType < RT_ELEMENTS(s_apszName) ? s_apszName[uType] : "Unknown"));
352
353 switch (uType)
354 {
355 case CmResourceTypePort:
356 case CmResourceTypeMemory:
357 LogFunc(("Start %8X%8.8lX, length=%X\n",
358 pResource->u.Port.Start.HighPart, pResource->u.Port.Start.LowPart, pResource->u.Port.Length));
359 break;
360
361 case CmResourceTypeInterrupt:
362 LogFunc(("Level=%X, vector=%X, affinity=%X\n",
363 pResource->u.Interrupt.Level, pResource->u.Interrupt.Vector, pResource->u.Interrupt.Affinity));
364 break;
365
366 case CmResourceTypeDma:
367 LogFunc(("Channel %d, Port %X\n", pResource->u.Dma.Channel, pResource->u.Dma.Port));
368 break;
369
370 default:
371 LogFunc(("\n"));
372 break;
373 }
374 }
375}
376#endif /* LOG_ENABLED */
377
378
379/**
380 * Global initialisation stuff (PnP + NT4 legacy).
381 *
382 * @param pDevObj Device object.
383 * @param pIrp Request packet.
384 */
385#ifndef TARGET_NT4
386NTSTATUS vgdrvNtInit(PDEVICE_OBJECT pDevObj, PIRP pIrp)
387#else
388NTSTATUS vgdrvNtInit(PDRIVER_OBJECT pDrvObj, PDEVICE_OBJECT pDevObj, PUNICODE_STRING pRegPath)
389#endif
390{
391 PVBOXGUESTDEVEXTWIN pDevExt = (PVBOXGUESTDEVEXTWIN)pDevObj->DeviceExtension;
392#ifndef TARGET_NT4
393 PIO_STACK_LOCATION pStack = IoGetCurrentIrpStackLocation(pIrp);
394 LogFlowFunc(("ENTER: pDevObj=%p pIrp=%p\n", pDevObj, pIrp));
395#else
396 LogFlowFunc(("ENTER: pDrvObj=%p pDevObj=%p pRegPath=%p\n", pDrvObj, pDevObj, pRegPath));
397#endif
398
399 NTSTATUS rcNt;
400#ifdef TARGET_NT4
401 /*
402 * Let's have a look at what our PCI adapter offers.
403 */
404 LogFlowFunc(("Starting to scan PCI resources of VBoxGuest ...\n"));
405
406 /* Assign the PCI resources. */
407 PCM_RESOURCE_LIST pResourceList = NULL;
408 UNICODE_STRING classNameString;
409 RtlInitUnicodeString(&classNameString, L"VBoxGuestAdapter");
410 rcNt = HalAssignSlotResources(pRegPath, &classNameString, pDrvObj, pDevObj,
411 PCIBus, pDevExt->busNumber, pDevExt->slotNumber, &pResourceList);
412# ifdef LOG_ENABLED
413 if (pResourceList && pResourceList->Count > 0)
414 vgdrvNtShowDeviceResources(&pResourceList->List[0].PartialResourceList);
415# endif
416 if (NT_SUCCESS(rcNt))
417 rcNt = vgdrvNtScanPCIResourceList(pResourceList, pDevExt);
418#else
419# ifdef LOG_ENABLED
420 if (pStack->Parameters.StartDevice.AllocatedResources->Count > 0)
421 vgdrvNtShowDeviceResources(&pStack->Parameters.StartDevice.AllocatedResources->List[0].PartialResourceList);
422# endif
423 rcNt = vgdrvNtScanPCIResourceList(pStack->Parameters.StartDevice.AllocatedResourcesTranslated, pDevExt);
424#endif
425 if (NT_SUCCESS(rcNt))
426 {
427 /*
428 * Map physical address of VMMDev memory into MMIO region
429 * and init the common device extension bits.
430 */
431 void *pvMMIOBase = NULL;
432 uint32_t cbMMIO = 0;
433 rcNt = vgdrvNtMapVMMDevMemory(pDevExt,
434 pDevExt->vmmDevPhysMemoryAddress,
435 pDevExt->vmmDevPhysMemoryLength,
436 &pvMMIOBase,
437 &cbMMIO);
438 if (NT_SUCCESS(rcNt))
439 {
440 pDevExt->Core.pVMMDevMemory = (VMMDevMemory *)pvMMIOBase;
441
442 LogFunc(("pvMMIOBase=0x%p, pDevExt=0x%p, pDevExt->Core.pVMMDevMemory=0x%p\n",
443 pvMMIOBase, pDevExt, pDevExt ? pDevExt->Core.pVMMDevMemory : NULL));
444
445 int vrc = VGDrvCommonInitDevExt(&pDevExt->Core,
446 pDevExt->Core.IOPortBase,
447 pvMMIOBase, cbMMIO,
448 vgdrvNtVersionToOSType(g_enmVGDrvNtVer),
449 VMMDEV_EVENT_MOUSE_POSITION_CHANGED);
450 if (RT_FAILURE(vrc))
451 {
452 LogFunc(("Could not init device extension, vrc=%Rrc\n", vrc));
453 rcNt = STATUS_DEVICE_CONFIGURATION_ERROR;
454 }
455 }
456 else
457 LogFunc(("Could not map physical address of VMMDev, rcNt=%#x\n", rcNt));
458 }
459
460 if (NT_SUCCESS(rcNt))
461 {
462 int vrc = VbglR0GRAlloc((VMMDevRequestHeader **)&pDevExt->pPowerStateRequest,
463 sizeof(VMMDevPowerStateRequest), VMMDevReq_SetPowerStatus);
464 if (RT_FAILURE(vrc))
465 {
466 LogFunc(("Alloc for pPowerStateRequest failed, vrc=%Rrc\n", vrc));
467 rcNt = STATUS_UNSUCCESSFUL;
468 }
469 }
470
471 if (NT_SUCCESS(rcNt))
472 {
473 /*
474 * Register DPC and ISR.
475 */
476 LogFlowFunc(("Initializing DPC/ISR (pDevObj=%p)...\n", pDevExt->pDeviceObject));
477
478 IoInitializeDpcRequest(pDevExt->pDeviceObject, vgdrvNtDpcHandler);
479#ifdef TARGET_NT4
480 ULONG uInterruptVector = UINT32_MAX;
481 KIRQL irqLevel = UINT8_MAX;
482 /* Get an interrupt vector. */
483 /* Only proceed if the device provides an interrupt. */
484 if ( pDevExt->interruptLevel
485 || pDevExt->interruptVector)
486 {
487 LogFlowFunc(("Getting interrupt vector (HAL): Bus=%u, IRQL=%u, Vector=%u\n",
488 pDevExt->busNumber, pDevExt->interruptLevel, pDevExt->interruptVector));
489
490 uInterruptVector = HalGetInterruptVector(PCIBus,
491 pDevExt->busNumber,
492 pDevExt->interruptLevel,
493 pDevExt->interruptVector,
494 &irqLevel,
495 &pDevExt->interruptAffinity);
496 LogFlowFunc(("HalGetInterruptVector returns vector=%u\n", uInterruptVector));
497 if (uInterruptVector == 0)
498 LogFunc(("No interrupt vector found!\n"));
499 }
500 else
501 LogFunc(("Device does not provide an interrupt!\n"));
502#endif
503 if (pDevExt->interruptVector)
504 {
505#ifdef TARGET_NT4
506 LogFlowFunc(("Connecting interrupt (IntVector=%#u), IrqLevel=%u) ...\n", uInterruptVector, irqLevel));
507#else
508 LogFlowFunc(("Connecting interrupt (IntVector=%#u), IrqLevel=%u) ...\n", pDevExt->interruptVector, pDevExt->interruptLevel));
509#endif
510
511 rcNt = IoConnectInterrupt(&pDevExt->pInterruptObject, /* Out: interrupt object. */
512 (PKSERVICE_ROUTINE)vgdrvNtIsrHandler, /* Our ISR handler. */
513 pDevExt, /* Device context. */
514 NULL, /* Optional spinlock. */
515#ifdef TARGET_NT4
516 uInterruptVector, /* Interrupt vector. */
517 irqLevel, /* Interrupt level. */
518 irqLevel, /* Interrupt level. */
519#else
520 pDevExt->interruptVector, /* Interrupt vector. */
521 (KIRQL)pDevExt->interruptLevel, /* Interrupt level. */
522 (KIRQL)pDevExt->interruptLevel, /* Interrupt level. */
523#endif
524 pDevExt->interruptMode, /* LevelSensitive or Latched. */
525 TRUE, /* Shareable interrupt. */
526 pDevExt->interruptAffinity, /* CPU affinity. */
527 FALSE); /* Don't save FPU stack. */
528 if (NT_ERROR(rcNt))
529 LogFunc(("Could not connect interrupt: rcNt=%#x!\n", rcNt));
530 }
531 else
532 LogFunc(("No interrupt vector found!\n"));
533 }
534
535 if (NT_SUCCESS(rcNt))
536 {
537 ULONG uValue = 0;
538 NTSTATUS rcNt2 = vgdrvNtRegistryReadDWORD(RTL_REGISTRY_SERVICES, L"VBoxGuest", L"LoggingEnabled", &uValue);
539 if (NT_SUCCESS(rcNt2))
540 {
541 pDevExt->Core.fLoggingEnabled = uValue >= 0xFF;
542 if (pDevExt->Core.fLoggingEnabled)
543 LogRelFunc(("Logging to host log enabled (%#x)", uValue));
544 }
545
546 /* Ready to rumble! */
547 LogRelFunc(("Device is ready!\n"));
548 VBOXGUEST_UPDATE_DEVSTATE(pDevExt, VGDRVNTDEVSTATE_WORKING);
549 }
550 else
551 pDevExt->pInterruptObject = NULL;
552
553 /** @todo r=bird: The error cleanup here is completely missing. We'll leak a
554 * whole bunch of things... */
555
556 LogFunc(("Returned with rcNt=%#x\n", rcNt));
557 return rcNt;
558}
559
560
561/**
562 * Cleans up hardware resources.
563 * Do not delete DevExt here.
564 *
565 * @todo r=bird: HC SVNT DRACONES!
566 *
567 * This code leaves clients hung when vgdrvNtInit is called afterwards.
568 * This happens when for instance hotplugging a CPU. Problem is
569 * vgdrvNtInit doing a full VGDrvCommonInitDevExt, orphaning all pDevExt
570 * members, like session lists and stuff.
571 *
572 * @param pDevObj Device object.
573 */
574NTSTATUS vgdrvNtCleanup(PDEVICE_OBJECT pDevObj)
575{
576 LogFlowFuncEnter();
577
578 PVBOXGUESTDEVEXTWIN pDevExt = (PVBOXGUESTDEVEXTWIN)pDevObj->DeviceExtension;
579 if (pDevExt)
580 {
581
582#if 0 /** @todo test & enable cleaning global session data */
583#ifdef VBOX_WITH_HGCM
584 if (pDevExt->pKernelSession)
585 {
586 VGDrvCommonCloseSession(pDevExt, pDevExt->pKernelSession);
587 pDevExt->pKernelSession = NULL;
588 }
589#endif
590#endif
591
592 if (pDevExt->pInterruptObject)
593 {
594 IoDisconnectInterrupt(pDevExt->pInterruptObject);
595 pDevExt->pInterruptObject = NULL;
596 }
597
598 /** @todo cleanup the rest stuff */
599
600
601#ifdef VBOX_WITH_GUEST_BUGCHECK_DETECTION
602 hlpDeregisterBugCheckCallback(pDevExt); /* ignore failure! */
603#endif
604 /* According to MSDN we have to unmap previously mapped memory. */
605 vgdrvNtUnmapVMMDevMemory(pDevExt);
606 }
607
608 return STATUS_SUCCESS;
609}
610
611
612/**
613 * Unload the driver.
614 *
615 * @param pDrvObj Driver object.
616 */
617static void vgdrvNtUnload(PDRIVER_OBJECT pDrvObj)
618{
619 LogFlowFuncEnter();
620
621#ifdef TARGET_NT4
622 vgdrvNtCleanup(pDrvObj->DeviceObject);
623
624 /* Destroy device extension and clean up everything else. */
625 if (pDrvObj->DeviceObject && pDrvObj->DeviceObject->DeviceExtension)
626 VGDrvCommonDeleteDevExt((PVBOXGUESTDEVEXT)pDrvObj->DeviceObject->DeviceExtension);
627
628 /*
629 * I don't think it's possible to unload a driver which processes have
630 * opened, at least we'll blindly assume that here.
631 */
632 UNICODE_STRING DosName;
633 RtlInitUnicodeString(&DosName, VBOXGUEST_DEVICE_NAME_DOS);
634 IoDeleteSymbolicLink(&DosName);
635
636 IoDeleteDevice(pDrvObj->DeviceObject);
637#else /* !TARGET_NT4 */
638 /* On a PnP driver this routine will be called after
639 * IRP_MN_REMOVE_DEVICE (where we already did the cleanup),
640 * so don't do anything here (yet). */
641 RT_NOREF1(pDrvObj);
642#endif /* !TARGET_NT4 */
643
644 LogFlowFunc(("Returning\n"));
645}
646
647
648/**
649 * For simplifying request completion into a simple return statement, extended
650 * version.
651 *
652 * @returns rcNt
653 * @param rcNt The status code.
654 * @param uInfo Extra info value.
655 * @param pIrp The IRP.
656 */
657DECLINLINE(NTSTATUS) vgdrvNtCompleteRequestEx(NTSTATUS rcNt, ULONG_PTR uInfo, PIRP pIrp)
658{
659 pIrp->IoStatus.Status = rcNt;
660 pIrp->IoStatus.Information = uInfo;
661 IoCompleteRequest(pIrp, IO_NO_INCREMENT);
662 return rcNt;
663}
664
665
666/**
667 * For simplifying request completion into a simple return statement.
668 *
669 * @returns rcNt
670 * @param rcNt The status code.
671 * @param pIrp The IRP.
672 */
673DECLINLINE(NTSTATUS) vgdrvNtCompleteRequest(NTSTATUS rcNt, PIRP pIrp)
674{
675 return vgdrvNtCompleteRequestEx(rcNt, 0 /*uInfo*/, pIrp);
676}
677
678
679/**
680 * Create (i.e. Open) file entry point.
681 *
682 * @param pDevObj Device object.
683 * @param pIrp Request packet.
684 */
685static NTSTATUS vgdrvNtCreate(PDEVICE_OBJECT pDevObj, PIRP pIrp)
686{
687 Log(("vgdrvNtCreate: RequestorMode=%d\n", pIrp->RequestorMode));
688 PIO_STACK_LOCATION pStack = IoGetCurrentIrpStackLocation(pIrp);
689 PFILE_OBJECT pFileObj = pStack->FileObject;
690 PVBOXGUESTDEVEXTWIN pDevExt = (PVBOXGUESTDEVEXTWIN)pDevObj->DeviceExtension;
691
692 Assert(pFileObj->FsContext == NULL);
693
694 /*
695 * We are not remotely similar to a directory...
696 * (But this is possible.)
697 */
698 if (pStack->Parameters.Create.Options & FILE_DIRECTORY_FILE)
699 {
700 LogFlow(("vgdrvNtCreate: Failed. FILE_DIRECTORY_FILE set\n"));
701 return vgdrvNtCompleteRequest(STATUS_NOT_A_DIRECTORY, pIrp);
702 }
703
704 /*
705 * Check the device state.
706 */
707 if (pDevExt->enmDevState != VGDRVNTDEVSTATE_WORKING)
708 {
709 LogFlow(("vgdrvNtCreate: Failed. Device is not in 'working' state: %d\n", pDevExt->enmDevState));
710 return vgdrvNtCompleteRequest(STATUS_DEVICE_NOT_READY, pIrp);
711 }
712
713 /*
714 * Create a client session.
715 */
716 int rc;
717 PVBOXGUESTSESSION pSession;
718 if (pIrp->RequestorMode == KernelMode)
719 rc = VGDrvCommonCreateKernelSession(&pDevExt->Core, &pSession);
720 else
721 rc = VGDrvCommonCreateUserSession(&pDevExt->Core, &pSession);
722 if (RT_SUCCESS(rc))
723 {
724 pFileObj->FsContext = pSession;
725 Log(("vgdrvNtCreate: Successfully created %s session %p\n",
726 pIrp->RequestorMode == KernelMode ? "kernel" : "user", pSession));
727 return vgdrvNtCompleteRequestEx(STATUS_SUCCESS, FILE_OPENED, pIrp);
728 }
729
730 Log(("vgdrvNtCreate: Failed to create session: rc=%Rrc\n", rc));
731 /* Note. the IoStatus is completely ignored on error. */
732 if (rc == VERR_NO_MEMORY)
733 return vgdrvNtCompleteRequest(STATUS_NO_MEMORY, pIrp);
734 return vgdrvNtCompleteRequest(STATUS_UNSUCCESSFUL, pIrp);
735}
736
737
738/**
739 * Close file entry point.
740 *
741 * @param pDevObj Device object.
742 * @param pIrp Request packet.
743 */
744static NTSTATUS vgdrvNtClose(PDEVICE_OBJECT pDevObj, PIRP pIrp)
745{
746 PVBOXGUESTDEVEXTWIN pDevExt = (PVBOXGUESTDEVEXTWIN)pDevObj->DeviceExtension;
747 PIO_STACK_LOCATION pStack = IoGetCurrentIrpStackLocation(pIrp);
748 PFILE_OBJECT pFileObj = pStack->FileObject;
749
750 LogFlowFunc(("pDevExt=0x%p, pFileObj=0x%p, FsContext=0x%p\n", pDevExt, pFileObj, pFileObj->FsContext));
751
752#ifdef VBOX_WITH_HGCM
753 /* Close both, R0 and R3 sessions. */
754 PVBOXGUESTSESSION pSession = (PVBOXGUESTSESSION)pFileObj->FsContext;
755 if (pSession)
756 VGDrvCommonCloseSession(&pDevExt->Core, pSession);
757#endif
758
759 pFileObj->FsContext = NULL;
760 pIrp->IoStatus.Information = 0;
761 pIrp->IoStatus.Status = STATUS_SUCCESS;
762 IoCompleteRequest(pIrp, IO_NO_INCREMENT);
763
764 return STATUS_SUCCESS;
765}
766
767
768/**
769 * Device I/O Control entry point.
770 *
771 * @param pDevObj Device object.
772 * @param pIrp Request packet.
773 */
774NTSTATUS _stdcall vgdrvNtDeviceControl(PDEVICE_OBJECT pDevObj, PIRP pIrp)
775{
776 PVBOXGUESTDEVEXTWIN pDevExt = (PVBOXGUESTDEVEXTWIN)pDevObj->DeviceExtension;
777 PIO_STACK_LOCATION pStack = IoGetCurrentIrpStackLocation(pIrp);
778 PVBOXGUESTSESSION pSession = pStack->FileObject ? (PVBOXGUESTSESSION)pStack->FileObject->FsContext : NULL;
779
780 if (!RT_VALID_PTR(pSession))
781 return vgdrvNtCompleteRequest(STATUS_TRUST_FAILURE, pIrp);
782
783#if 0 /* No fast I/O controls defined yet. */
784 /*
785 * Deal with the 2-3 high-speed IOCtl that takes their arguments from
786 * the session and iCmd, and does not return anything.
787 */
788 if (pSession->fUnrestricted)
789 {
790 ULONG ulCmd = pStack->Parameters.DeviceIoControl.IoControlCode;
791 if ( ulCmd == SUP_IOCTL_FAST_DO_RAW_RUN
792 || ulCmd == SUP_IOCTL_FAST_DO_HM_RUN
793 || ulCmd == SUP_IOCTL_FAST_DO_NOP)
794 {
795 int rc = supdrvIOCtlFast(ulCmd, (unsigned)(uintptr_t)pIrp->UserBuffer /* VMCPU id */, pDevExt, pSession);
796
797 /* Complete the I/O request. */
798 supdrvSessionRelease(pSession);
799 return vgdrvNtCompleteRequest(RT_SUCCESS(rc) ? STATUS_SUCCESS : STATUS_INVALID_PARAMETER, pIrp);
800 }
801 }
802#endif
803
804 return vgdrvNtDeviceControlSlow(&pDevExt->Core, pSession, pIrp, pStack);
805}
806
807
808/**
809 * Device I/O Control entry point.
810 *
811 * @param pDevExt The device extension.
812 * @param pSession The session.
813 * @param pIrp Request packet.
814 * @param pStack The request stack pointer.
815 */
816static NTSTATUS vgdrvNtDeviceControlSlow(PVBOXGUESTDEVEXT pDevExt, PVBOXGUESTSESSION pSession,
817 PIRP pIrp, PIO_STACK_LOCATION pStack)
818{
819 NTSTATUS rcNt;
820 uint32_t cbOut = 0;
821 int rc = 0;
822 Log2(("vgdrvNtDeviceControlSlow(%p,%p): ioctl=%#x pBuf=%p cbIn=%#x cbOut=%#x pSession=%p\n",
823 pDevExt, pIrp, pStack->Parameters.DeviceIoControl.IoControlCode,
824 pIrp->AssociatedIrp.SystemBuffer, pStack->Parameters.DeviceIoControl.InputBufferLength,
825 pStack->Parameters.DeviceIoControl.OutputBufferLength, pSession));
826
827#if 0 /*def RT_ARCH_AMD64*/
828 /* Don't allow 32-bit processes to do any I/O controls. */
829 if (!IoIs32bitProcess(pIrp))
830#endif
831 {
832 /* Verify that it's a buffered CTL. */
833 if ((pStack->Parameters.DeviceIoControl.IoControlCode & 0x3) == METHOD_BUFFERED)
834 {
835 /* Verify that the sizes in the request header are correct. */
836 PVBGLREQHDR pHdr = (PVBGLREQHDR)pIrp->AssociatedIrp.SystemBuffer;
837 if ( pStack->Parameters.DeviceIoControl.InputBufferLength >= sizeof(*pHdr)
838 && pStack->Parameters.DeviceIoControl.InputBufferLength == pHdr->cbIn
839 && pStack->Parameters.DeviceIoControl.OutputBufferLength == pHdr->cbOut)
840 {
841 /* Zero extra output bytes to make sure we don't leak anything. */
842 if (pHdr->cbIn < pHdr->cbOut)
843 RtlZeroMemory((uint8_t *)pHdr + pHdr->cbIn, pHdr->cbOut - pHdr->cbIn);
844
845 /*
846 * Do the job.
847 */
848 rc = VGDrvCommonIoCtl(pStack->Parameters.DeviceIoControl.IoControlCode, pDevExt, pSession, pHdr,
849 RT_MAX(pHdr->cbIn, pHdr->cbOut));
850 if (RT_SUCCESS(rc))
851 {
852 rcNt = STATUS_SUCCESS;
853 cbOut = pHdr->cbOut;
854 if (cbOut > pStack->Parameters.DeviceIoControl.OutputBufferLength)
855 {
856 cbOut = pStack->Parameters.DeviceIoControl.OutputBufferLength;
857 LogRel(("vgdrvNtDeviceControlSlow: too much output! %#x > %#x; uCmd=%#x!\n",
858 pHdr->cbOut, cbOut, pStack->Parameters.DeviceIoControl.IoControlCode));
859 }
860
861 /* If IDC successful disconnect request, we must set the context pointer to NULL. */
862 if ( pStack->Parameters.DeviceIoControl.IoControlCode == VBGL_IOCTL_IDC_DISCONNECT
863 && RT_SUCCESS(pHdr->rc))
864 pStack->FileObject->FsContext = NULL;
865 }
866 else if (rc == VERR_NOT_SUPPORTED)
867 rcNt = STATUS_NOT_SUPPORTED;
868 else
869 rcNt = STATUS_INVALID_PARAMETER;
870 Log2(("vgdrvNtDeviceControlSlow: returns %#x cbOut=%d rc=%#x\n", rcNt, cbOut, rc));
871 }
872 else
873 {
874 Log(("vgdrvNtDeviceControlSlow: Mismatching sizes (%#x) - Hdr=%#lx/%#lx Irp=%#lx/%#lx!\n",
875 pStack->Parameters.DeviceIoControl.IoControlCode,
876 pStack->Parameters.DeviceIoControl.InputBufferLength >= sizeof(*pHdr) ? pHdr->cbIn : 0,
877 pStack->Parameters.DeviceIoControl.InputBufferLength >= sizeof(*pHdr) ? pHdr->cbOut : 0,
878 pStack->Parameters.DeviceIoControl.InputBufferLength,
879 pStack->Parameters.DeviceIoControl.OutputBufferLength));
880 rcNt = STATUS_INVALID_PARAMETER;
881 }
882 }
883 else
884 {
885 Log(("vgdrvNtDeviceControlSlow: not buffered request (%#x) - not supported\n",
886 pStack->Parameters.DeviceIoControl.IoControlCode));
887 rcNt = STATUS_NOT_SUPPORTED;
888 }
889 }
890#if 0 /*def RT_ARCH_AMD64*/
891 else
892 {
893 Log(("VBoxDrvNtDeviceControlSlow: WOW64 req - not supported\n"));
894 rcNt = STATUS_NOT_SUPPORTED;
895 }
896#endif
897
898 return vgdrvNtCompleteRequestEx(rcNt, cbOut, pIrp);
899}
900
901
902/**
903 * Internal Device I/O Control entry point (for IDC).
904 *
905 * @param pDevObj Device object.
906 * @param pIrp Request packet.
907 */
908static NTSTATUS vgdrvNtInternalIOCtl(PDEVICE_OBJECT pDevObj, PIRP pIrp)
909{
910 /* Currently no special code here. */
911 return vgdrvNtDeviceControl(pDevObj, pIrp);
912}
913
914
915/**
916 * IRP_MJ_SYSTEM_CONTROL handler.
917 *
918 * @returns NT status code
919 * @param pDevObj Device object.
920 * @param pIrp IRP.
921 */
922static NTSTATUS vgdrvNtSystemControl(PDEVICE_OBJECT pDevObj, PIRP pIrp)
923{
924 PVBOXGUESTDEVEXTWIN pDevExt = (PVBOXGUESTDEVEXTWIN)pDevObj->DeviceExtension;
925
926 LogFlowFuncEnter();
927
928 /* Always pass it on to the next driver. */
929 IoSkipCurrentIrpStackLocation(pIrp);
930
931 return IoCallDriver(pDevExt->pNextLowerDriver, pIrp);
932}
933
934
935/**
936 * IRP_MJ_SHUTDOWN handler.
937 *
938 * @returns NT status code
939 * @param pDevObj Device object.
940 * @param pIrp IRP.
941 */
942static NTSTATUS vgdrvNtShutdown(PDEVICE_OBJECT pDevObj, PIRP pIrp)
943{
944 PVBOXGUESTDEVEXTWIN pDevExt = (PVBOXGUESTDEVEXTWIN)pDevObj->DeviceExtension;
945 LogFlowFuncEnter();
946
947 VMMDevPowerStateRequest *pReq = pDevExt->pPowerStateRequest;
948 if (pReq)
949 {
950 pReq->header.requestType = VMMDevReq_SetPowerStatus;
951 pReq->powerState = VMMDevPowerState_PowerOff;
952
953 int rc = VbglR0GRPerform(&pReq->header);
954 if (RT_FAILURE(rc))
955 LogFunc(("Error performing request to VMMDev, rc=%Rrc\n", rc));
956 }
957
958 /* just in case, since we shouldn't normally get here. */
959 pIrp->IoStatus.Information = 0;
960 pIrp->IoStatus.Status = STATUS_SUCCESS;
961 IoCompleteRequest(pIrp, IO_NO_INCREMENT);
962 return STATUS_SUCCESS;
963}
964
965
966/**
967 * Stub function for functions we don't implemented.
968 *
969 * @returns STATUS_NOT_SUPPORTED
970 * @param pDevObj Device object.
971 * @param pIrp IRP.
972 */
973static NTSTATUS vgdrvNtNotSupportedStub(PDEVICE_OBJECT pDevObj, PIRP pIrp)
974{
975 RT_NOREF1(pDevObj);
976 LogFlowFuncEnter();
977
978 pIrp->IoStatus.Information = 0;
979 pIrp->IoStatus.Status = STATUS_NOT_SUPPORTED;
980 IoCompleteRequest(pIrp, IO_NO_INCREMENT);
981
982 return STATUS_NOT_SUPPORTED;
983}
984
985
986/**
987 * Sets the mouse notification callback.
988 *
989 * @returns VBox status code.
990 * @param pDevExt Pointer to the device extension.
991 * @param pNotify Pointer to the mouse notify struct.
992 */
993int VGDrvNativeSetMouseNotifyCallback(PVBOXGUESTDEVEXT pDevExt, PVBGLIOCSETMOUSENOTIFYCALLBACK pNotify)
994{
995 PVBOXGUESTDEVEXTWIN pDevExtWin = (PVBOXGUESTDEVEXTWIN)pDevExt;
996 /* we need a lock here to avoid concurrency with the set event functionality */
997 KIRQL OldIrql;
998 KeAcquireSpinLock(&pDevExtWin->MouseEventAccessLock, &OldIrql);
999 pDevExtWin->Core.pfnMouseNotifyCallback = pNotify->u.In.pfnNotify;
1000 pDevExtWin->Core.pvMouseNotifyCallbackArg = pNotify->u.In.pvUser;
1001 KeReleaseSpinLock(&pDevExtWin->MouseEventAccessLock, OldIrql);
1002 return VINF_SUCCESS;
1003}
1004
1005
1006/**
1007 * DPC handler.
1008 *
1009 * @param pDPC DPC descriptor.
1010 * @param pDevObj Device object.
1011 * @param pIrp Interrupt request packet.
1012 * @param pContext Context specific pointer.
1013 */
1014static void vgdrvNtDpcHandler(PKDPC pDPC, PDEVICE_OBJECT pDevObj, PIRP pIrp, PVOID pContext)
1015{
1016 RT_NOREF3(pDPC, pIrp, pContext);
1017 PVBOXGUESTDEVEXTWIN pDevExt = (PVBOXGUESTDEVEXTWIN)pDevObj->DeviceExtension;
1018 Log3Func(("pDevExt=0x%p\n", pDevExt));
1019
1020 /* Test & reset the counter. */
1021 if (ASMAtomicXchgU32(&pDevExt->Core.u32MousePosChangedSeq, 0))
1022 {
1023 /* we need a lock here to avoid concurrency with the set event ioctl handler thread,
1024 * i.e. to prevent the event from destroyed while we're using it */
1025 Assert(KeGetCurrentIrql() == DISPATCH_LEVEL);
1026 KeAcquireSpinLockAtDpcLevel(&pDevExt->MouseEventAccessLock);
1027
1028 if (pDevExt->Core.pfnMouseNotifyCallback)
1029 pDevExt->Core.pfnMouseNotifyCallback(pDevExt->Core.pvMouseNotifyCallbackArg);
1030
1031 KeReleaseSpinLockFromDpcLevel(&pDevExt->MouseEventAccessLock);
1032 }
1033
1034 /* Process the wake-up list we were asked by the scheduling a DPC
1035 * in vgdrvNtIsrHandler(). */
1036 VGDrvCommonWaitDoWakeUps(&pDevExt->Core);
1037}
1038
1039
1040/**
1041 * ISR handler.
1042 *
1043 * @return BOOLEAN Indicates whether the IRQ came from us (TRUE) or not (FALSE).
1044 * @param pInterrupt Interrupt that was triggered.
1045 * @param pServiceContext Context specific pointer.
1046 */
1047static BOOLEAN vgdrvNtIsrHandler(PKINTERRUPT pInterrupt, PVOID pServiceContext)
1048{
1049 RT_NOREF1(pInterrupt);
1050 PVBOXGUESTDEVEXTWIN pDevExt = (PVBOXGUESTDEVEXTWIN)pServiceContext;
1051 if (pDevExt == NULL)
1052 return FALSE;
1053
1054 /*Log3Func(("pDevExt=0x%p, pVMMDevMemory=0x%p\n", pDevExt, pDevExt ? pDevExt->pVMMDevMemory : NULL));*/
1055
1056 /* Enter the common ISR routine and do the actual work. */
1057 BOOLEAN fIRQTaken = VGDrvCommonISR(&pDevExt->Core);
1058
1059 /* If we need to wake up some events we do that in a DPC to make
1060 * sure we're called at the right IRQL. */
1061 if (fIRQTaken)
1062 {
1063 Log3Func(("IRQ was taken! pInterrupt=0x%p, pDevExt=0x%p\n", pInterrupt, pDevExt));
1064 if (ASMAtomicUoReadU32( &pDevExt->Core.u32MousePosChangedSeq)
1065 || !RTListIsEmpty(&pDevExt->Core.WakeUpList))
1066 {
1067 Log3Func(("Requesting DPC ...\n"));
1068 IoRequestDpc(pDevExt->pDeviceObject, pDevExt->pCurrentIrp, NULL);
1069 }
1070 }
1071 return fIRQTaken;
1072}
1073
1074
1075/**
1076 * Overridden routine for mouse polling events.
1077 *
1078 * @param pDevExt Device extension structure.
1079 */
1080void VGDrvNativeISRMousePollEvent(PVBOXGUESTDEVEXT pDevExt)
1081{
1082 NOREF(pDevExt);
1083 /* nothing to do here - i.e. since we can not KeSetEvent from ISR level,
1084 * we rely on the pDevExt->u32MousePosChangedSeq to be set to a non-zero value on a mouse event
1085 * and queue the DPC in our ISR routine in that case doing KeSetEvent from the DPC routine */
1086}
1087
1088
1089/**
1090 * Queries (gets) a DWORD value from the registry.
1091 *
1092 * @return NTSTATUS
1093 * @param ulRoot Relative path root. See RTL_REGISTRY_SERVICES or RTL_REGISTRY_ABSOLUTE.
1094 * @param pwszPath Path inside path root.
1095 * @param pwszName Actual value name to look up.
1096 * @param puValue On input this can specify the default value (if RTL_REGISTRY_OPTIONAL is
1097 * not specified in ulRoot), on output this will retrieve the looked up
1098 * registry value if found.
1099 */
1100static NTSTATUS vgdrvNtRegistryReadDWORD(ULONG ulRoot, PCWSTR pwszPath, PWSTR pwszName, PULONG puValue)
1101{
1102 if (!pwszPath || !pwszName || !puValue)
1103 return STATUS_INVALID_PARAMETER;
1104
1105 ULONG ulDefault = *puValue;
1106
1107 RTL_QUERY_REGISTRY_TABLE tblQuery[2];
1108 RtlZeroMemory(tblQuery, sizeof(tblQuery));
1109 /** @todo Add RTL_QUERY_REGISTRY_TYPECHECK! */
1110 tblQuery[0].Flags = RTL_QUERY_REGISTRY_DIRECT;
1111 tblQuery[0].Name = pwszName;
1112 tblQuery[0].EntryContext = puValue;
1113 tblQuery[0].DefaultType = REG_DWORD;
1114 tblQuery[0].DefaultData = &ulDefault;
1115 tblQuery[0].DefaultLength = sizeof(ULONG);
1116
1117 return RtlQueryRegistryValues(ulRoot,
1118 pwszPath,
1119 &tblQuery[0],
1120 NULL /* Context */,
1121 NULL /* Environment */);
1122}
1123
1124
1125/**
1126 * Helper to scan the PCI resource list and remember stuff.
1127 *
1128 * @param pResList Resource list
1129 * @param pDevExt Device extension
1130 */
1131static NTSTATUS vgdrvNtScanPCIResourceList(PCM_RESOURCE_LIST pResList, PVBOXGUESTDEVEXTWIN pDevExt)
1132{
1133 /* Enumerate the resource list. */
1134 LogFlowFunc(("Found %d resources\n",
1135 pResList->List->PartialResourceList.Count));
1136
1137 NTSTATUS rc = STATUS_SUCCESS;
1138 PCM_PARTIAL_RESOURCE_DESCRIPTOR pPartialData = NULL;
1139 ULONG rangeCount = 0;
1140 ULONG cMMIORange = 0;
1141 PVBOXGUESTWINBASEADDRESS pBaseAddress = pDevExt->pciBaseAddress;
1142 for (ULONG i = 0; i < pResList->List->PartialResourceList.Count; i++)
1143 {
1144 pPartialData = &pResList->List->PartialResourceList.PartialDescriptors[i];
1145 switch (pPartialData->Type)
1146 {
1147 case CmResourceTypePort:
1148 {
1149 /* Overflow protection. */
1150 if (rangeCount < PCI_TYPE0_ADDRESSES)
1151 {
1152 LogFlowFunc(("I/O range: Base=%08x:%08x, length=%08x\n",
1153 pPartialData->u.Port.Start.HighPart,
1154 pPartialData->u.Port.Start.LowPart,
1155 pPartialData->u.Port.Length));
1156
1157 /* Save the IO port base. */
1158 /** @todo Not so good.
1159 * Update/bird: What is not so good? That we just consider the last range? */
1160 pDevExt->Core.IOPortBase = (RTIOPORT)pPartialData->u.Port.Start.LowPart;
1161
1162 /* Save resource information. */
1163 pBaseAddress->RangeStart = pPartialData->u.Port.Start;
1164 pBaseAddress->RangeLength = pPartialData->u.Port.Length;
1165 pBaseAddress->RangeInMemory = FALSE;
1166 pBaseAddress->ResourceMapped = FALSE;
1167
1168 LogFunc(("I/O range for VMMDev found! Base=%08x:%08x, length=%08x\n",
1169 pPartialData->u.Port.Start.HighPart,
1170 pPartialData->u.Port.Start.LowPart,
1171 pPartialData->u.Port.Length));
1172
1173 /* Next item ... */
1174 rangeCount++; pBaseAddress++;
1175 }
1176 break;
1177 }
1178
1179 case CmResourceTypeInterrupt:
1180 {
1181 LogFunc(("Interrupt: Level=%x, vector=%x, mode=%x\n",
1182 pPartialData->u.Interrupt.Level,
1183 pPartialData->u.Interrupt.Vector,
1184 pPartialData->Flags));
1185
1186 /* Save information. */
1187 pDevExt->interruptLevel = pPartialData->u.Interrupt.Level;
1188 pDevExt->interruptVector = pPartialData->u.Interrupt.Vector;
1189 pDevExt->interruptAffinity = pPartialData->u.Interrupt.Affinity;
1190
1191 /* Check interrupt mode. */
1192 if (pPartialData->Flags & CM_RESOURCE_INTERRUPT_LATCHED)
1193 pDevExt->interruptMode = Latched;
1194 else
1195 pDevExt->interruptMode = LevelSensitive;
1196 break;
1197 }
1198
1199 case CmResourceTypeMemory:
1200 {
1201 /* Overflow protection. */
1202 if (rangeCount < PCI_TYPE0_ADDRESSES)
1203 {
1204 LogFlowFunc(("Memory range: Base=%08x:%08x, length=%08x\n",
1205 pPartialData->u.Memory.Start.HighPart,
1206 pPartialData->u.Memory.Start.LowPart,
1207 pPartialData->u.Memory.Length));
1208
1209 /* We only care about read/write memory. */
1210 /** @todo Reconsider memory type. */
1211 if ( cMMIORange == 0 /* Only care about the first MMIO range (!!!). */
1212 && (pPartialData->Flags & VBOX_CM_PRE_VISTA_MASK) == CM_RESOURCE_MEMORY_READ_WRITE)
1213 {
1214 /* Save physical MMIO base + length for VMMDev. */
1215 pDevExt->vmmDevPhysMemoryAddress = pPartialData->u.Memory.Start;
1216 pDevExt->vmmDevPhysMemoryLength = (ULONG)pPartialData->u.Memory.Length;
1217
1218 /* Save resource information. */
1219 pBaseAddress->RangeStart = pPartialData->u.Memory.Start;
1220 pBaseAddress->RangeLength = pPartialData->u.Memory.Length;
1221 pBaseAddress->RangeInMemory = TRUE;
1222 pBaseAddress->ResourceMapped = FALSE;
1223
1224 LogFunc(("Memory range for VMMDev found! Base = %08x:%08x, Length = %08x\n",
1225 pPartialData->u.Memory.Start.HighPart,
1226 pPartialData->u.Memory.Start.LowPart,
1227 pPartialData->u.Memory.Length));
1228
1229 /* Next item ... */
1230 rangeCount++; pBaseAddress++; cMMIORange++;
1231 }
1232 else
1233 LogFunc(("Ignoring memory: Flags=%08x\n", pPartialData->Flags));
1234 }
1235 break;
1236 }
1237
1238 default:
1239 {
1240 LogFunc(("Unhandled resource found, type=%d\n", pPartialData->Type));
1241 break;
1242 }
1243 }
1244 }
1245
1246 /* Memorize the number of resources found. */
1247 pDevExt->pciAddressCount = rangeCount;
1248 return rc;
1249}
1250
1251
1252/**
1253 * Maps the I/O space from VMMDev to virtual kernel address space.
1254 *
1255 * @return NTSTATUS
1256 *
1257 * @param pDevExt The device extension.
1258 * @param PhysAddr Physical address to map.
1259 * @param cbToMap Number of bytes to map.
1260 * @param ppvMMIOBase Pointer of mapped I/O base.
1261 * @param pcbMMIO Length of mapped I/O base.
1262 */
1263static NTSTATUS vgdrvNtMapVMMDevMemory(PVBOXGUESTDEVEXTWIN pDevExt, PHYSICAL_ADDRESS PhysAddr, ULONG cbToMap,
1264 void **ppvMMIOBase, uint32_t *pcbMMIO)
1265{
1266 AssertPtrReturn(pDevExt, VERR_INVALID_POINTER);
1267 AssertPtrReturn(ppvMMIOBase, VERR_INVALID_POINTER);
1268 /* pcbMMIO is optional. */
1269
1270 NTSTATUS rc = STATUS_SUCCESS;
1271 if (PhysAddr.LowPart > 0) /* We're mapping below 4GB. */
1272 {
1273 VMMDevMemory *pVMMDevMemory = (VMMDevMemory *)MmMapIoSpace(PhysAddr, cbToMap, MmNonCached);
1274 LogFlowFunc(("pVMMDevMemory = %#x\n", pVMMDevMemory));
1275 if (pVMMDevMemory)
1276 {
1277 LogFunc(("VMMDevMemory: Version = %#x, Size = %d\n", pVMMDevMemory->u32Version, pVMMDevMemory->u32Size));
1278
1279 /* Check version of the structure; do we have the right memory version? */
1280 if (pVMMDevMemory->u32Version == VMMDEV_MEMORY_VERSION)
1281 {
1282 /* Save results. */
1283 *ppvMMIOBase = pVMMDevMemory;
1284 if (pcbMMIO) /* Optional. */
1285 *pcbMMIO = pVMMDevMemory->u32Size;
1286
1287 LogFlowFunc(("VMMDevMemory found and mapped! pvMMIOBase = 0x%p\n", *ppvMMIOBase));
1288 }
1289 else
1290 {
1291 /* Not our version, refuse operation and unmap the memory. */
1292 LogFunc(("Wrong version (%u), refusing operation!\n", pVMMDevMemory->u32Version));
1293
1294 vgdrvNtUnmapVMMDevMemory(pDevExt);
1295 rc = STATUS_UNSUCCESSFUL;
1296 }
1297 }
1298 else
1299 rc = STATUS_UNSUCCESSFUL;
1300 }
1301 return rc;
1302}
1303
1304
1305/**
1306 * Unmaps the VMMDev I/O range from kernel space.
1307 *
1308 * @param pDevExt The device extension.
1309 */
1310void vgdrvNtUnmapVMMDevMemory(PVBOXGUESTDEVEXTWIN pDevExt)
1311{
1312 LogFlowFunc(("pVMMDevMemory = %#x\n", pDevExt->Core.pVMMDevMemory));
1313 if (pDevExt->Core.pVMMDevMemory)
1314 {
1315 MmUnmapIoSpace((void*)pDevExt->Core.pVMMDevMemory, pDevExt->vmmDevPhysMemoryLength);
1316 pDevExt->Core.pVMMDevMemory = NULL;
1317 }
1318
1319 pDevExt->vmmDevPhysMemoryAddress.QuadPart = 0;
1320 pDevExt->vmmDevPhysMemoryLength = 0;
1321}
1322
1323
1324/**
1325 * Translates NT version to VBox OS.
1326 *
1327 * @returns VBox OS type.
1328 * @param enmNtVer The NT version.
1329 */
1330VBOXOSTYPE vgdrvNtVersionToOSType(VGDRVNTVER enmNtVer)
1331{
1332 VBOXOSTYPE enmOsType;
1333 switch (enmNtVer)
1334 {
1335 case VGDRVNTVER_WINNT4:
1336 enmOsType = VBOXOSTYPE_WinNT4;
1337 break;
1338
1339 case VGDRVNTVER_WIN2K:
1340 enmOsType = VBOXOSTYPE_Win2k;
1341 break;
1342
1343 case VGDRVNTVER_WINXP:
1344#if ARCH_BITS == 64
1345 enmOsType = VBOXOSTYPE_WinXP_x64;
1346#else
1347 enmOsType = VBOXOSTYPE_WinXP;
1348#endif
1349 break;
1350
1351 case VGDRVNTVER_WIN2K3:
1352#if ARCH_BITS == 64
1353 enmOsType = VBOXOSTYPE_Win2k3_x64;
1354#else
1355 enmOsType = VBOXOSTYPE_Win2k3;
1356#endif
1357 break;
1358
1359 case VGDRVNTVER_WINVISTA:
1360#if ARCH_BITS == 64
1361 enmOsType = VBOXOSTYPE_WinVista_x64;
1362#else
1363 enmOsType = VBOXOSTYPE_WinVista;
1364#endif
1365 break;
1366
1367 case VGDRVNTVER_WIN7:
1368#if ARCH_BITS == 64
1369 enmOsType = VBOXOSTYPE_Win7_x64;
1370#else
1371 enmOsType = VBOXOSTYPE_Win7;
1372#endif
1373 break;
1374
1375 case VGDRVNTVER_WIN8:
1376#if ARCH_BITS == 64
1377 enmOsType = VBOXOSTYPE_Win8_x64;
1378#else
1379 enmOsType = VBOXOSTYPE_Win8;
1380#endif
1381 break;
1382
1383 case VGDRVNTVER_WIN81:
1384#if ARCH_BITS == 64
1385 enmOsType = VBOXOSTYPE_Win81_x64;
1386#else
1387 enmOsType = VBOXOSTYPE_Win81;
1388#endif
1389 break;
1390
1391 case VGDRVNTVER_WIN10:
1392#if ARCH_BITS == 64
1393 enmOsType = VBOXOSTYPE_Win10_x64;
1394#else
1395 enmOsType = VBOXOSTYPE_Win10;
1396#endif
1397 break;
1398
1399 default:
1400 /* We don't know, therefore NT family. */
1401 enmOsType = VBOXOSTYPE_WinNT;
1402 break;
1403 }
1404 return enmOsType;
1405}
1406
1407#ifdef VBOX_STRICT
1408
1409/**
1410 * A quick implementation of AtomicTestAndClear for uint32_t and multiple bits.
1411 */
1412static uint32_t vgdrvNtAtomicBitsTestAndClear(void *pu32Bits, uint32_t u32Mask)
1413{
1414 AssertPtrReturn(pu32Bits, 0);
1415 LogFlowFunc(("*pu32Bits=%#x, u32Mask=%#x\n", *(uint32_t *)pu32Bits, u32Mask));
1416 uint32_t u32Result = 0;
1417 uint32_t u32WorkingMask = u32Mask;
1418 int iBitOffset = ASMBitFirstSetU32 (u32WorkingMask);
1419
1420 while (iBitOffset > 0)
1421 {
1422 bool fSet = ASMAtomicBitTestAndClear(pu32Bits, iBitOffset - 1);
1423 if (fSet)
1424 u32Result |= 1 << (iBitOffset - 1);
1425 u32WorkingMask &= ~(1 << (iBitOffset - 1));
1426 iBitOffset = ASMBitFirstSetU32 (u32WorkingMask);
1427 }
1428 LogFlowFunc(("Returning %#x\n", u32Result));
1429 return u32Result;
1430}
1431
1432
1433static void vgdrvNtTestAtomicTestAndClearBitsU32(uint32_t u32Mask, uint32_t u32Bits, uint32_t u32Exp)
1434{
1435 ULONG u32Bits2 = u32Bits;
1436 uint32_t u32Result = vgdrvNtAtomicBitsTestAndClear(&u32Bits2, u32Mask);
1437 if ( u32Result != u32Exp
1438 || (u32Bits2 & u32Mask)
1439 || (u32Bits2 & u32Result)
1440 || ((u32Bits2 | u32Result) != u32Bits)
1441 )
1442 AssertLogRelMsgFailed(("TEST FAILED: u32Mask=%#x, u32Bits (before)=%#x, u32Bits (after)=%#x, u32Result=%#x, u32Exp=%#x\n",
1443 u32Mask, u32Bits, u32Bits2, u32Result));
1444}
1445
1446
1447static void vgdrvNtDoTests(void)
1448{
1449 vgdrvNtTestAtomicTestAndClearBitsU32(0x00, 0x23, 0);
1450 vgdrvNtTestAtomicTestAndClearBitsU32(0x11, 0, 0);
1451 vgdrvNtTestAtomicTestAndClearBitsU32(0x11, 0x22, 0);
1452 vgdrvNtTestAtomicTestAndClearBitsU32(0x11, 0x23, 0x1);
1453 vgdrvNtTestAtomicTestAndClearBitsU32(0x11, 0x32, 0x10);
1454 vgdrvNtTestAtomicTestAndClearBitsU32(0x22, 0x23, 0x22);
1455}
1456
1457#endif /* VBOX_STRICT */
1458
1459#ifdef VBOX_WITH_DPC_LATENCY_CHECKER
1460
1461/*
1462 * DPC latency checker.
1463 */
1464
1465/**
1466 * One DPC latency sample.
1467 */
1468typedef struct DPCSAMPLE
1469{
1470 LARGE_INTEGER PerfDelta;
1471 LARGE_INTEGER PerfCounter;
1472 LARGE_INTEGER PerfFrequency;
1473 uint64_t u64TSC;
1474} DPCSAMPLE;
1475AssertCompileSize(DPCSAMPLE, 4*8);
1476
1477/**
1478 * The DPC latency measurement workset.
1479 */
1480typedef struct DPCDATA
1481{
1482 KDPC Dpc;
1483 KTIMER Timer;
1484 KSPIN_LOCK SpinLock;
1485
1486 ULONG ulTimerRes;
1487
1488 bool volatile fFinished;
1489
1490 /** The timer interval (relative). */
1491 LARGE_INTEGER DueTime;
1492
1493 LARGE_INTEGER PerfCounterPrev;
1494
1495 /** Align the sample array on a 64 byte boundrary just for the off chance
1496 * that we'll get cache line aligned memory backing this structure. */
1497 uint32_t auPadding[ARCH_BITS == 32 ? 5 : 7];
1498
1499 int cSamples;
1500 DPCSAMPLE aSamples[8192];
1501} DPCDATA;
1502
1503AssertCompileMemberAlignment(DPCDATA, aSamples, 64);
1504
1505# define VBOXGUEST_DPC_TAG 'DPCS'
1506
1507
1508/**
1509 * DPC callback routine for the DPC latency measurement code.
1510 *
1511 * @param pDpc The DPC, not used.
1512 * @param pvDeferredContext Pointer to the DPCDATA.
1513 * @param SystemArgument1 System use, ignored.
1514 * @param SystemArgument2 System use, ignored.
1515 */
1516static VOID vgdrvNtDpcLatencyCallback(PKDPC pDpc, PVOID pvDeferredContext, PVOID SystemArgument1, PVOID SystemArgument2)
1517{
1518 DPCDATA *pData = (DPCDATA *)pvDeferredContext;
1519 RT_NOREF(pDpc, SystemArgument1, SystemArgument2);
1520
1521 KeAcquireSpinLockAtDpcLevel(&pData->SpinLock);
1522
1523 if (pData->cSamples >= RT_ELEMENTS(pData->aSamples))
1524 pData->fFinished = true;
1525 else
1526 {
1527 DPCSAMPLE *pSample = &pData->aSamples[pData->cSamples++];
1528
1529 pSample->u64TSC = ASMReadTSC();
1530 pSample->PerfCounter = KeQueryPerformanceCounter(&pSample->PerfFrequency);
1531 pSample->PerfDelta.QuadPart = pSample->PerfCounter.QuadPart - pData->PerfCounterPrev.QuadPart;
1532
1533 pData->PerfCounterPrev.QuadPart = pSample->PerfCounter.QuadPart;
1534
1535 KeSetTimer(&pData->Timer, pData->DueTime, &pData->Dpc);
1536 }
1537
1538 KeReleaseSpinLockFromDpcLevel(&pData->SpinLock);
1539}
1540
1541
1542/**
1543 * Handles the DPC latency checker request.
1544 *
1545 * @returns VBox status code.
1546 */
1547int VGDrvNtIOCtl_DpcLatencyChecker(void)
1548{
1549 /*
1550 * Allocate a block of non paged memory for samples and related data.
1551 */
1552 DPCDATA *pData = (DPCDATA *)ExAllocatePoolWithTag(NonPagedPool, sizeof(DPCDATA), VBOXGUEST_DPC_TAG);
1553 if (!pData)
1554 {
1555 RTLogBackdoorPrintf("VBoxGuest: DPC: DPCDATA allocation failed.\n");
1556 return VERR_NO_MEMORY;
1557 }
1558
1559 /*
1560 * Initialize the data.
1561 */
1562 KeInitializeDpc(&pData->Dpc, vgdrvNtDpcLatencyCallback, pData);
1563 KeInitializeTimer(&pData->Timer);
1564 KeInitializeSpinLock(&pData->SpinLock);
1565
1566 pData->fFinished = false;
1567 pData->cSamples = 0;
1568 pData->PerfCounterPrev.QuadPart = 0;
1569
1570 pData->ulTimerRes = ExSetTimerResolution(1000 * 10, 1);
1571 pData->DueTime.QuadPart = -(int64_t)pData->ulTimerRes / 10;
1572
1573 /*
1574 * Start the DPC measurements and wait for a full set.
1575 */
1576 KeSetTimer(&pData->Timer, pData->DueTime, &pData->Dpc);
1577
1578 while (!pData->fFinished)
1579 {
1580 LARGE_INTEGER Interval;
1581 Interval.QuadPart = -100 * 1000 * 10;
1582 KeDelayExecutionThread(KernelMode, TRUE, &Interval);
1583 }
1584
1585 ExSetTimerResolution(0, 0);
1586
1587 /*
1588 * Log everything to the host.
1589 */
1590 RTLogBackdoorPrintf("DPC: ulTimerRes = %d\n", pData->ulTimerRes);
1591 for (int i = 0; i < pData->cSamples; i++)
1592 {
1593 DPCSAMPLE *pSample = &pData->aSamples[i];
1594
1595 RTLogBackdoorPrintf("[%d] pd %lld pc %lld pf %lld t %lld\n",
1596 i,
1597 pSample->PerfDelta.QuadPart,
1598 pSample->PerfCounter.QuadPart,
1599 pSample->PerfFrequency.QuadPart,
1600 pSample->u64TSC);
1601 }
1602
1603 ExFreePoolWithTag(pData, VBOXGUEST_DPC_TAG);
1604 return VINF_SUCCESS;
1605}
1606
1607#endif /* VBOX_WITH_DPC_LATENCY_CHECKER */
1608
Note: See TracBrowser for help on using the repository browser.

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