VirtualBox

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

Last change on this file since 63803 was 63065, checked in by vboxsync, 9 years ago

Additions/common: warnings

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