VirtualBox

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

Last change on this file since 60526 was 60526, checked in by vboxsync, 8 years ago

bugref:8250: fix

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 52.5 KB
Line 
1/* $Id: VBoxGuest-win.cpp 60526 2016-04-18 09:04:31Z vboxsync $ */
2/** @file
3 * VBoxGuest - Windows specifics.
4 */
5
6/*
7 * Copyright (C) 2010-2015 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 NTSTATUS rc = STATUS_SUCCESS;
105
106 LogFunc(("Driver built: %s %s\n", __DATE__, __TIME__));
107
108 /*
109 * Check if the the NT version is supported and initializing
110 * g_enmVGDrvNtVer in the process.
111 */
112 ULONG ulMajorVer;
113 ULONG ulMinorVer;
114 ULONG ulBuildNo;
115 BOOLEAN fCheckedBuild = PsGetVersion(&ulMajorVer, &ulMinorVer, &ulBuildNo, NULL);
116
117 /* Use RTLogBackdoorPrintf to make sure that this goes to VBox.log */
118 RTLogBackdoorPrintf("VBoxGuest: Windows version %u.%u, build %u\n", ulMajorVer, ulMinorVer, ulBuildNo);
119 if (fCheckedBuild)
120 RTLogBackdoorPrintf("VBoxGuest: Windows checked build\n");
121
122#ifdef VBOX_STRICT
123 vgdrvNtDoTests();
124#endif
125 switch (ulMajorVer)
126 {
127 case 10:
128 switch (ulMinorVer)
129 {
130 case 0:
131 /* Windows 10 Preview builds starting with 9926. */
132 default:
133 /* Also everything newer. */
134 g_enmVGDrvNtVer = VGDRVNTVER_WIN10;
135 break;
136 }
137 break;
138 case 6: /* Windows Vista or Windows 7 (based on minor ver) */
139 switch (ulMinorVer)
140 {
141 case 0: /* Note: Also could be Windows 2008 Server! */
142 g_enmVGDrvNtVer = VGDRVNTVER_WINVISTA;
143 break;
144 case 1: /* Note: Also could be Windows 2008 Server R2! */
145 g_enmVGDrvNtVer = VGDRVNTVER_WIN7;
146 break;
147 case 2:
148 g_enmVGDrvNtVer = VGDRVNTVER_WIN8;
149 break;
150 case 3:
151 g_enmVGDrvNtVer = VGDRVNTVER_WIN81;
152 break;
153 case 4:
154 /* Windows 10 Preview builds. */
155 default:
156 /* Also everything newer. */
157 g_enmVGDrvNtVer = VGDRVNTVER_WIN10;
158 break;
159 }
160 break;
161 case 5:
162 switch (ulMinorVer)
163 {
164 default:
165 case 2:
166 g_enmVGDrvNtVer = VGDRVNTVER_WIN2K3;
167 break;
168 case 1:
169 g_enmVGDrvNtVer = VGDRVNTVER_WINXP;
170 break;
171 case 0:
172 g_enmVGDrvNtVer = VGDRVNTVER_WIN2K;
173 break;
174 }
175 break;
176 case 4:
177 g_enmVGDrvNtVer = VGDRVNTVER_WINNT4;
178 break;
179 default:
180 if (ulMajorVer > 6)
181 {
182 /* "Windows 10 mode" for Windows 8.1+. */
183 g_enmVGDrvNtVer = VGDRVNTVER_WIN10;
184 }
185 else
186 {
187 if (ulMajorVer < 4)
188 LogRelFunc(("At least Windows NT4 required! (%u.%u)\n", ulMajorVer, ulMinorVer));
189 else
190 LogRelFunc(("Unknown version %u.%u!\n", ulMajorVer, ulMinorVer));
191 rc = STATUS_DRIVER_UNABLE_TO_LOAD;
192 }
193 break;
194 }
195
196 if (NT_SUCCESS(rc))
197 {
198 /*
199 * Setup the driver entry points in pDrvObj.
200 */
201 pDrvObj->DriverUnload = vgdrvNtUnload;
202 pDrvObj->MajorFunction[IRP_MJ_CREATE] = vgdrvNtCreate;
203 pDrvObj->MajorFunction[IRP_MJ_CLOSE] = vgdrvNtClose;
204 pDrvObj->MajorFunction[IRP_MJ_DEVICE_CONTROL] = vgdrvNtIOCtl;
205 pDrvObj->MajorFunction[IRP_MJ_INTERNAL_DEVICE_CONTROL] = vgdrvNtInternalIOCtl;
206 pDrvObj->MajorFunction[IRP_MJ_SHUTDOWN] = vgdrvNtShutdown;
207 pDrvObj->MajorFunction[IRP_MJ_READ] = vgdrvNtNotSupportedStub;
208 pDrvObj->MajorFunction[IRP_MJ_WRITE] = vgdrvNtNotSupportedStub;
209#ifdef TARGET_NT4
210 rc = vgdrvNt4CreateDevice(pDrvObj, NULL /* pDevObj */, pRegPath);
211#else
212 pDrvObj->MajorFunction[IRP_MJ_PNP] = vgdrvNtPnP;
213 pDrvObj->MajorFunction[IRP_MJ_POWER] = vgdrvNtPower;
214 pDrvObj->MajorFunction[IRP_MJ_SYSTEM_CONTROL] = vgdrvNtSystemControl;
215 pDrvObj->DriverExtension->AddDevice = (PDRIVER_ADD_DEVICE)vgdrvNtAddDevice;
216#endif
217 }
218
219 LogFlowFunc(("Returning %#x\n", rc));
220 return rc;
221}
222
223
224#ifndef TARGET_NT4
225/**
226 * Handle request from the Plug & Play subsystem.
227 *
228 * @returns NT status code
229 * @param pDrvObj Driver object
230 * @param pDevObj Device object
231 *
232 * @remarks Parts of this is duplicated in VBoxGuest-win-legacy.cpp.
233 */
234static NTSTATUS vgdrvNtAddDevice(PDRIVER_OBJECT pDrvObj, PDEVICE_OBJECT pDevObj)
235{
236 NTSTATUS rc;
237 LogFlowFuncEnter();
238
239 /*
240 * Create device.
241 */
242 UNICODE_STRING DevName;
243 RtlInitUnicodeString(&DevName, VBOXGUEST_DEVICE_NAME_NT);
244 PDEVICE_OBJECT pDeviceObject = NULL;
245 rc = IoCreateDevice(pDrvObj, sizeof(VBOXGUESTDEVEXTWIN), &DevName, FILE_DEVICE_UNKNOWN, 0, FALSE, &pDeviceObject);
246 if (NT_SUCCESS(rc))
247 {
248 /*
249 * Create symbolic link (DOS devices).
250 */
251 UNICODE_STRING DosName;
252 RtlInitUnicodeString(&DosName, VBOXGUEST_DEVICE_NAME_DOS);
253 rc = IoCreateSymbolicLink(&DosName, &DevName);
254 if (NT_SUCCESS(rc))
255 {
256 /*
257 * Setup the device extension.
258 */
259 PVBOXGUESTDEVEXTWIN pDevExt = (PVBOXGUESTDEVEXTWIN)pDeviceObject->DeviceExtension;
260 RT_ZERO(*pDevExt);
261
262 KeInitializeSpinLock(&pDevExt->MouseEventAccessLock);
263
264 pDevExt->pDeviceObject = pDeviceObject;
265 pDevExt->enmPrevDevState = VGDRVNTDEVSTATE_STOPPED;
266 pDevExt->enmDevState = VGDRVNTDEVSTATE_STOPPED;
267
268 pDevExt->pNextLowerDriver = IoAttachDeviceToDeviceStack(pDeviceObject, pDevObj);
269 if (pDevExt->pNextLowerDriver != NULL)
270 {
271 /*
272 * If we reached this point we're fine with the basic driver setup,
273 * so continue to init our own things.
274 */
275#ifdef VBOX_WITH_GUEST_BUGCHECK_DETECTION
276 vgdrvNtBugCheckCallback(pDevExt); /* Ignore failure! */
277#endif
278 if (NT_SUCCESS(rc))
279 {
280 /* VBoxGuestPower is pageable; ensure we are not called at elevated IRQL */
281 pDeviceObject->Flags |= DO_POWER_PAGABLE;
282
283 /* Driver is ready now. */
284 pDeviceObject->Flags &= ~DO_DEVICE_INITIALIZING;
285 LogFlowFunc(("Returning with rc=%#x (success)\n", rc));
286 return rc;
287 }
288
289 IoDetachDevice(pDevExt->pNextLowerDriver);
290 }
291 else
292 {
293 LogFunc(("IoAttachDeviceToDeviceStack did not give a nextLowerDriver!\n"));
294 rc = STATUS_DEVICE_NOT_CONNECTED;
295 }
296
297 /* bail out */
298 IoDeleteSymbolicLink(&DosName);
299 }
300 else
301 LogFunc(("IoCreateSymbolicLink failed with rc=%#x!\n", rc));
302 IoDeleteDevice(pDeviceObject);
303 }
304 else
305 LogFunc(("IoCreateDevice failed with rc=%#x!\n", rc));
306
307 LogFunc(("Returning with rc=%#x\n", rc));
308 return rc;
309}
310#endif /* TARGET_NT4 */
311
312
313#ifdef LOG_ENABLED
314/**
315 * Debug helper to dump a device resource list.
316 *
317 * @param pResourceList list of device resources.
318 */
319static void vgdrvNtShowDeviceResources(PCM_PARTIAL_RESOURCE_LIST pResourceList)
320{
321 PCM_PARTIAL_RESOURCE_DESCRIPTOR pResource = pResourceList->PartialDescriptors;
322 ULONG cResources = pResourceList->Count;
323
324 for (ULONG i = 0; i < cResources; ++i, ++pResource)
325 {
326 ULONG uType = pResource->Type;
327 static char const * const s_apszName[] =
328 {
329 "CmResourceTypeNull",
330 "CmResourceTypePort",
331 "CmResourceTypeInterrupt",
332 "CmResourceTypeMemory",
333 "CmResourceTypeDma",
334 "CmResourceTypeDeviceSpecific",
335 "CmResourceTypeBusNumber",
336 "CmResourceTypeDevicePrivate",
337 "CmResourceTypeAssignedResource",
338 "CmResourceTypeSubAllocateFrom",
339 };
340
341 LogFunc(("Type=%s", uType < RT_ELEMENTS(s_apszName) ? s_apszName[uType] : "Unknown"));
342
343 switch (uType)
344 {
345 case CmResourceTypePort:
346 case CmResourceTypeMemory:
347 LogFunc(("Start %8X%8.8lX, length=%X\n",
348 pResource->u.Port.Start.HighPart, pResource->u.Port.Start.LowPart, pResource->u.Port.Length));
349 break;
350
351 case CmResourceTypeInterrupt:
352 LogFunc(("Level=%X, vector=%X, affinity=%X\n",
353 pResource->u.Interrupt.Level, pResource->u.Interrupt.Vector, pResource->u.Interrupt.Affinity));
354 break;
355
356 case CmResourceTypeDma:
357 LogFunc(("Channel %d, Port %X\n", pResource->u.Dma.Channel, pResource->u.Dma.Port));
358 break;
359
360 default:
361 LogFunc(("\n"));
362 break;
363 }
364 }
365}
366#endif /* LOG_ENABLED */
367
368
369/**
370 * Global initialisation stuff (PnP + NT4 legacy).
371 *
372 * @param pDevObj Device object.
373 * @param pIrp Request packet.
374 */
375#ifndef TARGET_NT4
376NTSTATUS vgdrvNtInit(PDEVICE_OBJECT pDevObj, PIRP pIrp)
377#else
378NTSTATUS vgdrvNtInit(PDRIVER_OBJECT pDrvObj, PDEVICE_OBJECT pDevObj, PUNICODE_STRING pRegPath)
379#endif
380{
381 PVBOXGUESTDEVEXTWIN pDevExt = (PVBOXGUESTDEVEXTWIN)pDevObj->DeviceExtension;
382#ifndef TARGET_NT4
383 PIO_STACK_LOCATION pStack = IoGetCurrentIrpStackLocation(pIrp);
384#endif
385
386 LogFlowFuncEnter();
387
388 NTSTATUS rcNt;
389#ifdef TARGET_NT4
390 /*
391 * Let's have a look at what our PCI adapter offers.
392 */
393 LogFlowFunc(("Starting to scan PCI resources of VBoxGuest ...\n"));
394
395 /* Assign the PCI resources. */
396 PCM_RESOURCE_LIST pResourceList = NULL;
397 UNICODE_STRING classNameString;
398 RtlInitUnicodeString(&classNameString, L"VBoxGuestAdapter");
399 rcNt = HalAssignSlotResources(pRegPath, &classNameString, pDrvObj, pDevObj,
400 PCIBus, pDevExt->busNumber, pDevExt->slotNumber, &pResourceList);
401# ifdef LOG_ENABLED
402 if (pResourceList && pResourceList->Count > 0)
403 vgdrvNtShowDeviceResources(&pResourceList->List[0].PartialResourceList);
404# endif
405 if (NT_SUCCESS(rcNt))
406 rcNt = vgdrvNtScanPCIResourceList(pResourceList, pDevExt);
407#else
408# ifdef LOG_ENABLED
409 if (pStack->Parameters.StartDevice.AllocatedResources->Count > 0)
410 vgdrvNtShowDeviceResources(&pStack->Parameters.StartDevice.AllocatedResources->List[0].PartialResourceList);
411# endif
412 rcNt = vgdrvNtScanPCIResourceList(pStack->Parameters.StartDevice.AllocatedResourcesTranslated, pDevExt);
413#endif
414 if (NT_SUCCESS(rcNt))
415 {
416 /*
417 * Map physical address of VMMDev memory into MMIO region
418 * and init the common device extension bits.
419 */
420 void *pvMMIOBase = NULL;
421 uint32_t cbMMIO = 0;
422 rcNt = vgdrvNtMapVMMDevMemory(pDevExt,
423 pDevExt->vmmDevPhysMemoryAddress,
424 pDevExt->vmmDevPhysMemoryLength,
425 &pvMMIOBase,
426 &cbMMIO);
427 if (NT_SUCCESS(rcNt))
428 {
429 pDevExt->Core.pVMMDevMemory = (VMMDevMemory *)pvMMIOBase;
430
431 LogFunc(("pvMMIOBase=0x%p, pDevExt=0x%p, pDevExt->Core.pVMMDevMemory=0x%p\n",
432 pvMMIOBase, pDevExt, pDevExt ? pDevExt->Core.pVMMDevMemory : NULL));
433
434 int vrc = VGDrvCommonInitDevExt(&pDevExt->Core,
435 pDevExt->Core.IOPortBase,
436 pvMMIOBase, cbMMIO,
437 vgdrvNtVersionToOSType(g_enmVGDrvNtVer),
438 VMMDEV_EVENT_MOUSE_POSITION_CHANGED);
439 if (RT_FAILURE(vrc))
440 {
441 LogFunc(("Could not init device extension, vrc=%Rrc\n", vrc));
442 rcNt = STATUS_DEVICE_CONFIGURATION_ERROR;
443 }
444 }
445 else
446 LogFunc(("Could not map physical address of VMMDev, rcNt=%#x\n", rcNt));
447 }
448
449 if (NT_SUCCESS(rcNt))
450 {
451 int vrc = VbglGRAlloc((VMMDevRequestHeader **)&pDevExt->pPowerStateRequest,
452 sizeof(VMMDevPowerStateRequest), VMMDevReq_SetPowerStatus);
453 if (RT_FAILURE(vrc))
454 {
455 LogFunc(("Alloc for pPowerStateRequest failed, vrc=%Rrc\n", vrc));
456 rcNt = STATUS_UNSUCCESSFUL;
457 }
458 }
459
460 if (NT_SUCCESS(rcNt))
461 {
462 /*
463 * Register DPC and ISR.
464 */
465 LogFlowFunc(("Initializing DPC/ISR ...\n"));
466
467 IoInitializeDpcRequest(pDevExt->pDeviceObject, vgdrvNtDpcHandler);
468#ifdef TARGET_NT4
469 ULONG uInterruptVector;
470 KIRQL irqLevel;
471 /* Get an interrupt vector. */
472 /* Only proceed if the device provides an interrupt. */
473 if ( pDevExt->interruptLevel
474 || pDevExt->interruptVector)
475 {
476 LogFlowFunc(("Getting interrupt vector (HAL): Bus=%u, IRQL=%u, Vector=%u\n",
477 pDevExt->busNumber, pDevExt->interruptLevel, pDevExt->interruptVector));
478
479 uInterruptVector = HalGetInterruptVector(PCIBus,
480 pDevExt->busNumber,
481 pDevExt->interruptLevel,
482 pDevExt->interruptVector,
483 &irqLevel,
484 &pDevExt->interruptAffinity);
485 LogFlowFunc(("HalGetInterruptVector returns vector=%u\n", uInterruptVector));
486 if (uInterruptVector == 0)
487 LogFunc(("No interrupt vector found!\n"));
488 }
489 else
490 LogFunc(("Device does not provide an interrupt!\n"));
491#endif
492 if (pDevExt->interruptVector)
493 {
494 LogFlowFunc(("Connecting interrupt ...\n"));
495
496 rcNt = IoConnectInterrupt(&pDevExt->pInterruptObject, /* Out: interrupt object. */
497 (PKSERVICE_ROUTINE)vgdrvNtIsrHandler, /* Our ISR handler. */
498 pDevExt, /* Device context. */
499 NULL, /* Optional spinlock. */
500#ifdef TARGET_NT4
501 uInterruptVector, /* Interrupt vector. */
502 irqLevel, /* Interrupt level. */
503 irqLevel, /* Interrupt level. */
504#else
505 pDevExt->interruptVector, /* Interrupt vector. */
506 (KIRQL)pDevExt->interruptLevel, /* Interrupt level. */
507 (KIRQL)pDevExt->interruptLevel, /* Interrupt level. */
508#endif
509 pDevExt->interruptMode, /* LevelSensitive or Latched. */
510 TRUE, /* Shareable interrupt. */
511 pDevExt->interruptAffinity, /* CPU affinity. */
512 FALSE); /* Don't save FPU stack. */
513 if (NT_ERROR(rcNt))
514 LogFunc(("Could not connect interrupt, rcNt=%#x\n", rcNt));
515 }
516 else
517 LogFunc(("No interrupt vector found!\n"));
518 }
519
520
521#ifdef VBOX_WITH_HGCM
522 LogFunc(("Allocating kernel session data ...\n"));
523 int vrc = VGDrvCommonCreateKernelSession(&pDevExt->Core, &pDevExt->pKernelSession);
524 if (RT_FAILURE(vrc))
525 {
526 LogFunc(("Failed to allocated kernel session data, vrc=%Rrc\n", vrc));
527 rcNt = STATUS_UNSUCCESSFUL;
528 }
529#endif
530
531 if (NT_SUCCESS(rcNt))
532 {
533 ULONG uValue = 0;
534 NTSTATUS rcNt2 = vgdrvNtRegistryReadDWORD(RTL_REGISTRY_SERVICES, L"VBoxGuest", L"LoggingEnabled", &uValue);
535 if (NT_SUCCESS(rcNt2))
536 {
537 pDevExt->Core.fLoggingEnabled = uValue >= 0xFF;
538 if (pDevExt->Core.fLoggingEnabled)
539 LogRelFunc(("Logging to host log enabled (%#x)", uValue));
540 }
541
542 pDevExt->Core.fLoggingEnabled = true;
543
544 /* Ready to rumble! */
545 LogRelFunc(("Device is ready!\n"));
546 VBOXGUEST_UPDATE_DEVSTATE(pDevExt, VGDRVNTDEVSTATE_WORKING);
547 }
548 else
549 pDevExt->pInterruptObject = NULL;
550
551 /** @todo r=bird: The error cleanup here is completely missing. We'll leak a
552 * whole bunch of things... */
553
554 LogFunc(("Returned with rcNt=%#x\n", rcNt));
555 return rcNt;
556}
557
558
559/**
560 * Cleans up hardware resources.
561 * Do not delete DevExt here.
562 *
563 * @param pDevObj Device object.
564 */
565NTSTATUS vgdrvNtCleanup(PDEVICE_OBJECT pDevObj)
566{
567 LogFlowFuncEnter();
568
569 PVBOXGUESTDEVEXTWIN pDevExt = (PVBOXGUESTDEVEXTWIN)pDevObj->DeviceExtension;
570 if (pDevExt)
571 {
572
573#if 0 /** @todo test & enable cleaning global session data */
574#ifdef VBOX_WITH_HGCM
575 if (pDevExt->pKernelSession)
576 {
577 VGDrvCommonCloseSession(pDevExt, pDevExt->pKernelSession);
578 pDevExt->pKernelSession = NULL;
579 }
580#endif
581#endif
582
583 if (pDevExt->pInterruptObject)
584 {
585 IoDisconnectInterrupt(pDevExt->pInterruptObject);
586 pDevExt->pInterruptObject = NULL;
587 }
588
589 /** @todo cleanup the rest stuff */
590
591
592#ifdef VBOX_WITH_GUEST_BUGCHECK_DETECTION
593 hlpDeregisterBugCheckCallback(pDevExt); /* ignore failure! */
594#endif
595 /* According to MSDN we have to unmap previously mapped memory. */
596 vgdrvNtUnmapVMMDevMemory(pDevExt);
597 }
598
599 return STATUS_SUCCESS;
600}
601
602
603/**
604 * Unload the driver.
605 *
606 * @param pDrvObj Driver object.
607 */
608static void vgdrvNtUnload(PDRIVER_OBJECT pDrvObj)
609{
610 LogFlowFuncEnter();
611
612#ifdef TARGET_NT4
613 vgdrvNtCleanup(pDrvObj->DeviceObject);
614
615 /* Destroy device extension and clean up everything else. */
616 if (pDrvObj->DeviceObject && pDrvObj->DeviceObject->DeviceExtension)
617 VGDrvCommonDeleteDevExt((PVBOXGUESTDEVEXT)pDrvObj->DeviceObject->DeviceExtension);
618
619 /*
620 * I don't think it's possible to unload a driver which processes have
621 * opened, at least we'll blindly assume that here.
622 */
623 UNICODE_STRING DosName;
624 RtlInitUnicodeString(&DosName, VBOXGUEST_DEVICE_NAME_DOS);
625 NTSTATUS rc = IoDeleteSymbolicLink(&DosName);
626
627 IoDeleteDevice(pDrvObj->DeviceObject);
628#else /* !TARGET_NT4 */
629 /* On a PnP driver this routine will be called after
630 * IRP_MN_REMOVE_DEVICE (where we already did the cleanup),
631 * so don't do anything here (yet). */
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
918 LogFlowFuncEnter();
919
920 VMMDevPowerStateRequest *pReq = pDevExt->pPowerStateRequest;
921 if (pReq)
922 {
923 pReq->header.requestType = VMMDevReq_SetPowerStatus;
924 pReq->powerState = VMMDevPowerState_PowerOff;
925
926 int rc = VbglGRPerform(&pReq->header);
927 if (RT_FAILURE(rc))
928 LogFunc(("Error performing request to VMMDev, rc=%Rrc\n", rc));
929 }
930
931 return STATUS_SUCCESS;
932}
933
934
935/**
936 * Stub function for functions we don't implemented.
937 *
938 * @returns STATUS_NOT_SUPPORTED
939 * @param pDevObj Device object.
940 * @param pIrp IRP.
941 */
942static NTSTATUS vgdrvNtNotSupportedStub(PDEVICE_OBJECT pDevObj, PIRP pIrp)
943{
944 LogFlowFuncEnter();
945
946 pIrp->IoStatus.Information = 0;
947 pIrp->IoStatus.Status = STATUS_NOT_SUPPORTED;
948 IoCompleteRequest(pIrp, IO_NO_INCREMENT);
949
950 return STATUS_NOT_SUPPORTED;
951}
952
953
954/**
955 * DPC handler.
956 *
957 * @param pDPC DPC descriptor.
958 * @param pDevObj Device object.
959 * @param pIrp Interrupt request packet.
960 * @param pContext Context specific pointer.
961 */
962static void vgdrvNtDpcHandler(PKDPC pDPC, PDEVICE_OBJECT pDevObj, PIRP pIrp, PVOID pContext)
963{
964 PVBOXGUESTDEVEXTWIN pDevExt = (PVBOXGUESTDEVEXTWIN)pDevObj->DeviceExtension;
965 Log3Func(("pDevExt=0x%p\n", pDevExt));
966
967 /* Test & reset the counter. */
968 if (ASMAtomicXchgU32(&pDevExt->Core.u32MousePosChangedSeq, 0))
969 {
970 /* we need a lock here to avoid concurrency with the set event ioctl handler thread,
971 * i.e. to prevent the event from destroyed while we're using it */
972 Assert(KeGetCurrentIrql() == DISPATCH_LEVEL);
973 KeAcquireSpinLockAtDpcLevel(&pDevExt->MouseEventAccessLock);
974
975 if (pDevExt->Core.MouseNotifyCallback.pfnNotify)
976 pDevExt->Core.MouseNotifyCallback.pfnNotify(pDevExt->Core.MouseNotifyCallback.pvUser);
977
978 KeReleaseSpinLockFromDpcLevel(&pDevExt->MouseEventAccessLock);
979 }
980
981 /* Process the wake-up list we were asked by the scheduling a DPC
982 * in vgdrvNtIsrHandler(). */
983 VGDrvCommonWaitDoWakeUps(&pDevExt->Core);
984}
985
986
987/**
988 * ISR handler.
989 *
990 * @return BOOLEAN Indicates whether the IRQ came from us (TRUE) or not (FALSE).
991 * @param pInterrupt Interrupt that was triggered.
992 * @param pServiceContext Context specific pointer.
993 */
994static BOOLEAN vgdrvNtIsrHandler(PKINTERRUPT pInterrupt, PVOID pServiceContext)
995{
996 PVBOXGUESTDEVEXTWIN pDevExt = (PVBOXGUESTDEVEXTWIN)pServiceContext;
997 if (pDevExt == NULL)
998 return FALSE;
999
1000 /*Log3Func(("pDevExt=0x%p, pVMMDevMemory=0x%p\n", pDevExt, pDevExt ? pDevExt->pVMMDevMemory : NULL));*/
1001
1002 /* Enter the common ISR routine and do the actual work. */
1003 BOOLEAN fIRQTaken = VGDrvCommonISR(&pDevExt->Core);
1004
1005 /* If we need to wake up some events we do that in a DPC to make
1006 * sure we're called at the right IRQL. */
1007 if (fIRQTaken)
1008 {
1009 Log3Func(("IRQ was taken! pInterrupt=0x%p, pDevExt=0x%p\n", pInterrupt, pDevExt));
1010 if (ASMAtomicUoReadU32( &pDevExt->Core.u32MousePosChangedSeq)
1011 || !RTListIsEmpty(&pDevExt->Core.WakeUpList))
1012 {
1013 Log3Func(("Requesting DPC ...\n"));
1014 IoRequestDpc(pDevExt->pDeviceObject, pDevExt->pCurrentIrp, NULL);
1015 }
1016 }
1017 return fIRQTaken;
1018}
1019
1020
1021/**
1022 * Overridden routine for mouse polling events.
1023 *
1024 * @param pDevExt Device extension structure.
1025 */
1026void VGDrvNativeISRMousePollEvent(PVBOXGUESTDEVEXT pDevExt)
1027{
1028 NOREF(pDevExt);
1029 /* nothing to do here - i.e. since we can not KeSetEvent from ISR level,
1030 * we rely on the pDevExt->u32MousePosChangedSeq to be set to a non-zero value on a mouse event
1031 * and queue the DPC in our ISR routine in that case doing KeSetEvent from the DPC routine */
1032}
1033
1034
1035/**
1036 * Queries (gets) a DWORD value from the registry.
1037 *
1038 * @return NTSTATUS
1039 * @param ulRoot Relative path root. See RTL_REGISTRY_SERVICES or RTL_REGISTRY_ABSOLUTE.
1040 * @param pwszPath Path inside path root.
1041 * @param pwszName Actual value name to look up.
1042 * @param puValue On input this can specify the default value (if RTL_REGISTRY_OPTIONAL is
1043 * not specified in ulRoot), on output this will retrieve the looked up
1044 * registry value if found.
1045 */
1046static NTSTATUS vgdrvNtRegistryReadDWORD(ULONG ulRoot, PCWSTR pwszPath, PWSTR pwszName, PULONG puValue)
1047{
1048 if (!pwszPath || !pwszName || !puValue)
1049 return STATUS_INVALID_PARAMETER;
1050
1051 ULONG ulDefault = *puValue;
1052
1053 RTL_QUERY_REGISTRY_TABLE tblQuery[2];
1054 RtlZeroMemory(tblQuery, sizeof(tblQuery));
1055 /** @todo Add RTL_QUERY_REGISTRY_TYPECHECK! */
1056 tblQuery[0].Flags = RTL_QUERY_REGISTRY_DIRECT;
1057 tblQuery[0].Name = pwszName;
1058 tblQuery[0].EntryContext = puValue;
1059 tblQuery[0].DefaultType = REG_DWORD;
1060 tblQuery[0].DefaultData = &ulDefault;
1061 tblQuery[0].DefaultLength = sizeof(ULONG);
1062
1063 return RtlQueryRegistryValues(ulRoot,
1064 pwszPath,
1065 &tblQuery[0],
1066 NULL /* Context */,
1067 NULL /* Environment */);
1068}
1069
1070
1071/**
1072 * Helper to scan the PCI resource list and remember stuff.
1073 *
1074 * @param pResList Resource list
1075 * @param pDevExt Device extension
1076 */
1077static NTSTATUS vgdrvNtScanPCIResourceList(PCM_RESOURCE_LIST pResList, PVBOXGUESTDEVEXTWIN pDevExt)
1078{
1079 /* Enumerate the resource list. */
1080 LogFlowFunc(("Found %d resources\n",
1081 pResList->List->PartialResourceList.Count));
1082
1083 NTSTATUS rc = STATUS_SUCCESS;
1084 PCM_PARTIAL_RESOURCE_DESCRIPTOR pPartialData = NULL;
1085 ULONG rangeCount = 0;
1086 ULONG cMMIORange = 0;
1087 PVBOXGUESTWINBASEADDRESS pBaseAddress = pDevExt->pciBaseAddress;
1088 for (ULONG i = 0; i < pResList->List->PartialResourceList.Count; i++)
1089 {
1090 pPartialData = &pResList->List->PartialResourceList.PartialDescriptors[i];
1091 switch (pPartialData->Type)
1092 {
1093 case CmResourceTypePort:
1094 {
1095 /* Overflow protection. */
1096 if (rangeCount < PCI_TYPE0_ADDRESSES)
1097 {
1098 LogFlowFunc(("I/O range: Base=%08x:%08x, length=%08x\n",
1099 pPartialData->u.Port.Start.HighPart,
1100 pPartialData->u.Port.Start.LowPart,
1101 pPartialData->u.Port.Length));
1102
1103 /* Save the IO port base. */
1104 /** @todo Not so good.
1105 * Update/bird: What is not so good? That we just consider the last range? */
1106 pDevExt->Core.IOPortBase = (RTIOPORT)pPartialData->u.Port.Start.LowPart;
1107
1108 /* Save resource information. */
1109 pBaseAddress->RangeStart = pPartialData->u.Port.Start;
1110 pBaseAddress->RangeLength = pPartialData->u.Port.Length;
1111 pBaseAddress->RangeInMemory = FALSE;
1112 pBaseAddress->ResourceMapped = FALSE;
1113
1114 LogFunc(("I/O range for VMMDev found! Base=%08x:%08x, length=%08x\n",
1115 pPartialData->u.Port.Start.HighPart,
1116 pPartialData->u.Port.Start.LowPart,
1117 pPartialData->u.Port.Length));
1118
1119 /* Next item ... */
1120 rangeCount++; pBaseAddress++;
1121 }
1122 break;
1123 }
1124
1125 case CmResourceTypeInterrupt:
1126 {
1127 LogFunc(("Interrupt: Level=%x, vector=%x, mode=%x\n",
1128 pPartialData->u.Interrupt.Level,
1129 pPartialData->u.Interrupt.Vector,
1130 pPartialData->Flags));
1131
1132 /* Save information. */
1133 pDevExt->interruptLevel = pPartialData->u.Interrupt.Level;
1134 pDevExt->interruptVector = pPartialData->u.Interrupt.Vector;
1135 pDevExt->interruptAffinity = pPartialData->u.Interrupt.Affinity;
1136
1137 /* Check interrupt mode. */
1138 if (pPartialData->Flags & CM_RESOURCE_INTERRUPT_LATCHED)
1139 pDevExt->interruptMode = Latched;
1140 else
1141 pDevExt->interruptMode = LevelSensitive;
1142 break;
1143 }
1144
1145 case CmResourceTypeMemory:
1146 {
1147 /* Overflow protection. */
1148 if (rangeCount < PCI_TYPE0_ADDRESSES)
1149 {
1150 LogFlowFunc(("Memory range: Base=%08x:%08x, length=%08x\n",
1151 pPartialData->u.Memory.Start.HighPart,
1152 pPartialData->u.Memory.Start.LowPart,
1153 pPartialData->u.Memory.Length));
1154
1155 /* We only care about read/write memory. */
1156 /** @todo Reconsider memory type. */
1157 if ( cMMIORange == 0 /* Only care about the first MMIO range (!!!). */
1158 && (pPartialData->Flags & VBOX_CM_PRE_VISTA_MASK) == CM_RESOURCE_MEMORY_READ_WRITE)
1159 {
1160 /* Save physical MMIO base + length for VMMDev. */
1161 pDevExt->vmmDevPhysMemoryAddress = pPartialData->u.Memory.Start;
1162 pDevExt->vmmDevPhysMemoryLength = (ULONG)pPartialData->u.Memory.Length;
1163
1164 /* Save resource information. */
1165 pBaseAddress->RangeStart = pPartialData->u.Memory.Start;
1166 pBaseAddress->RangeLength = pPartialData->u.Memory.Length;
1167 pBaseAddress->RangeInMemory = TRUE;
1168 pBaseAddress->ResourceMapped = FALSE;
1169
1170 LogFunc(("Memory range for VMMDev found! Base = %08x:%08x, Length = %08x\n",
1171 pPartialData->u.Memory.Start.HighPart,
1172 pPartialData->u.Memory.Start.LowPart,
1173 pPartialData->u.Memory.Length));
1174
1175 /* Next item ... */
1176 rangeCount++; pBaseAddress++; cMMIORange++;
1177 }
1178 else
1179 LogFunc(("Ignoring memory: Flags=%08x\n", pPartialData->Flags));
1180 }
1181 break;
1182 }
1183
1184 default:
1185 {
1186 LogFunc(("Unhandled resource found, type=%d\n", pPartialData->Type));
1187 break;
1188 }
1189 }
1190 }
1191
1192 /* Memorize the number of resources found. */
1193 pDevExt->pciAddressCount = rangeCount;
1194 return rc;
1195}
1196
1197
1198/**
1199 * Maps the I/O space from VMMDev to virtual kernel address space.
1200 *
1201 * @return NTSTATUS
1202 *
1203 * @param pDevExt The device extension.
1204 * @param PhysAddr Physical address to map.
1205 * @param cbToMap Number of bytes to map.
1206 * @param ppvMMIOBase Pointer of mapped I/O base.
1207 * @param pcbMMIO Length of mapped I/O base.
1208 */
1209static NTSTATUS vgdrvNtMapVMMDevMemory(PVBOXGUESTDEVEXTWIN pDevExt, PHYSICAL_ADDRESS PhysAddr, ULONG cbToMap,
1210 void **ppvMMIOBase, uint32_t *pcbMMIO)
1211{
1212 AssertPtrReturn(pDevExt, VERR_INVALID_POINTER);
1213 AssertPtrReturn(ppvMMIOBase, VERR_INVALID_POINTER);
1214 /* pcbMMIO is optional. */
1215
1216 NTSTATUS rc = STATUS_SUCCESS;
1217 if (PhysAddr.LowPart > 0) /* We're mapping below 4GB. */
1218 {
1219 VMMDevMemory *pVMMDevMemory = (VMMDevMemory *)MmMapIoSpace(PhysAddr, cbToMap, MmNonCached);
1220 LogFlowFunc(("pVMMDevMemory = %#x\n", pVMMDevMemory));
1221 if (pVMMDevMemory)
1222 {
1223 LogFunc(("VMMDevMemory: Version = %#x, Size = %d\n", pVMMDevMemory->u32Version, pVMMDevMemory->u32Size));
1224
1225 /* Check version of the structure; do we have the right memory version? */
1226 if (pVMMDevMemory->u32Version == VMMDEV_MEMORY_VERSION)
1227 {
1228 /* Save results. */
1229 *ppvMMIOBase = pVMMDevMemory;
1230 if (pcbMMIO) /* Optional. */
1231 *pcbMMIO = pVMMDevMemory->u32Size;
1232
1233 LogFlowFunc(("VMMDevMemory found and mapped! pvMMIOBase = 0x%p\n", *ppvMMIOBase));
1234 }
1235 else
1236 {
1237 /* Not our version, refuse operation and unmap the memory. */
1238 LogFunc(("Wrong version (%u), refusing operation!\n", pVMMDevMemory->u32Version));
1239
1240 vgdrvNtUnmapVMMDevMemory(pDevExt);
1241 rc = STATUS_UNSUCCESSFUL;
1242 }
1243 }
1244 else
1245 rc = STATUS_UNSUCCESSFUL;
1246 }
1247 return rc;
1248}
1249
1250
1251/**
1252 * Unmaps the VMMDev I/O range from kernel space.
1253 *
1254 * @param pDevExt The device extension.
1255 */
1256void vgdrvNtUnmapVMMDevMemory(PVBOXGUESTDEVEXTWIN pDevExt)
1257{
1258 LogFlowFunc(("pVMMDevMemory = %#x\n", pDevExt->Core.pVMMDevMemory));
1259 if (pDevExt->Core.pVMMDevMemory)
1260 {
1261 MmUnmapIoSpace((void*)pDevExt->Core.pVMMDevMemory, pDevExt->vmmDevPhysMemoryLength);
1262 pDevExt->Core.pVMMDevMemory = NULL;
1263 }
1264
1265 pDevExt->vmmDevPhysMemoryAddress.QuadPart = 0;
1266 pDevExt->vmmDevPhysMemoryLength = 0;
1267}
1268
1269
1270/**
1271 * Translates NT version to VBox OS.
1272 *
1273 * @returns VBox OS type.
1274 * @param enmNtVer The NT version.
1275 */
1276VBOXOSTYPE vgdrvNtVersionToOSType(VGDRVNTVER enmNtVer)
1277{
1278 VBOXOSTYPE enmOsType;
1279 switch (enmNtVer)
1280 {
1281 case VGDRVNTVER_WINNT4:
1282 enmOsType = VBOXOSTYPE_WinNT4;
1283 break;
1284
1285 case VGDRVNTVER_WIN2K:
1286 enmOsType = VBOXOSTYPE_Win2k;
1287 break;
1288
1289 case VGDRVNTVER_WINXP:
1290#if ARCH_BITS == 64
1291 enmOsType = VBOXOSTYPE_WinXP_x64;
1292#else
1293 enmOsType = VBOXOSTYPE_WinXP;
1294#endif
1295 break;
1296
1297 case VGDRVNTVER_WIN2K3:
1298#if ARCH_BITS == 64
1299 enmOsType = VBOXOSTYPE_Win2k3_x64;
1300#else
1301 enmOsType = VBOXOSTYPE_Win2k3;
1302#endif
1303 break;
1304
1305 case VGDRVNTVER_WINVISTA:
1306#if ARCH_BITS == 64
1307 enmOsType = VBOXOSTYPE_WinVista_x64;
1308#else
1309 enmOsType = VBOXOSTYPE_WinVista;
1310#endif
1311 break;
1312
1313 case VGDRVNTVER_WIN7:
1314#if ARCH_BITS == 64
1315 enmOsType = VBOXOSTYPE_Win7_x64;
1316#else
1317 enmOsType = VBOXOSTYPE_Win7;
1318#endif
1319 break;
1320
1321 case VGDRVNTVER_WIN8:
1322#if ARCH_BITS == 64
1323 enmOsType = VBOXOSTYPE_Win8_x64;
1324#else
1325 enmOsType = VBOXOSTYPE_Win8;
1326#endif
1327 break;
1328
1329 case VGDRVNTVER_WIN81:
1330#if ARCH_BITS == 64
1331 enmOsType = VBOXOSTYPE_Win81_x64;
1332#else
1333 enmOsType = VBOXOSTYPE_Win81;
1334#endif
1335 break;
1336
1337 case VGDRVNTVER_WIN10:
1338#if ARCH_BITS == 64
1339 enmOsType = VBOXOSTYPE_Win10_x64;
1340#else
1341 enmOsType = VBOXOSTYPE_Win10;
1342#endif
1343 break;
1344
1345 default:
1346 /* We don't know, therefore NT family. */
1347 enmOsType = VBOXOSTYPE_WinNT;
1348 break;
1349 }
1350 return enmOsType;
1351}
1352
1353#ifdef VBOX_STRICT
1354
1355/**
1356 * A quick implementation of AtomicTestAndClear for uint32_t and multiple bits.
1357 */
1358static uint32_t vgdrvNtAtomicBitsTestAndClear(void *pu32Bits, uint32_t u32Mask)
1359{
1360 AssertPtrReturn(pu32Bits, 0);
1361 LogFlowFunc(("*pu32Bits=%#x, u32Mask=%#x\n", *(uint32_t *)pu32Bits, u32Mask));
1362 uint32_t u32Result = 0;
1363 uint32_t u32WorkingMask = u32Mask;
1364 int iBitOffset = ASMBitFirstSetU32 (u32WorkingMask);
1365
1366 while (iBitOffset > 0)
1367 {
1368 bool fSet = ASMAtomicBitTestAndClear(pu32Bits, iBitOffset - 1);
1369 if (fSet)
1370 u32Result |= 1 << (iBitOffset - 1);
1371 u32WorkingMask &= ~(1 << (iBitOffset - 1));
1372 iBitOffset = ASMBitFirstSetU32 (u32WorkingMask);
1373 }
1374 LogFlowFunc(("Returning %#x\n", u32Result));
1375 return u32Result;
1376}
1377
1378
1379static void vgdrvNtTestAtomicTestAndClearBitsU32(uint32_t u32Mask, uint32_t u32Bits, uint32_t u32Exp)
1380{
1381 ULONG u32Bits2 = u32Bits;
1382 uint32_t u32Result = vgdrvNtAtomicBitsTestAndClear(&u32Bits2, u32Mask);
1383 if ( u32Result != u32Exp
1384 || (u32Bits2 & u32Mask)
1385 || (u32Bits2 & u32Result)
1386 || ((u32Bits2 | u32Result) != u32Bits)
1387 )
1388 AssertLogRelMsgFailed(("TEST FAILED: u32Mask=%#x, u32Bits (before)=%#x, u32Bits (after)=%#x, u32Result=%#x, u32Exp=%#x\n",
1389 u32Mask, u32Bits, u32Bits2, u32Result));
1390}
1391
1392
1393static void vgdrvNtDoTests(void)
1394{
1395 vgdrvNtTestAtomicTestAndClearBitsU32(0x00, 0x23, 0);
1396 vgdrvNtTestAtomicTestAndClearBitsU32(0x11, 0, 0);
1397 vgdrvNtTestAtomicTestAndClearBitsU32(0x11, 0x22, 0);
1398 vgdrvNtTestAtomicTestAndClearBitsU32(0x11, 0x23, 0x1);
1399 vgdrvNtTestAtomicTestAndClearBitsU32(0x11, 0x32, 0x10);
1400 vgdrvNtTestAtomicTestAndClearBitsU32(0x22, 0x23, 0x22);
1401}
1402
1403#endif /* VBOX_STRICT */
1404
1405#ifdef VBOX_WITH_DPC_LATENCY_CHECKER
1406
1407/*
1408 * DPC latency checker.
1409 */
1410
1411/**
1412 * One DPC latency sample.
1413 */
1414typedef struct DPCSAMPLE
1415{
1416 LARGE_INTEGER PerfDelta;
1417 LARGE_INTEGER PerfCounter;
1418 LARGE_INTEGER PerfFrequency;
1419 uint64_t u64TSC;
1420} DPCSAMPLE;
1421AssertCompileSize(DPCSAMPLE, 4*8);
1422
1423/**
1424 * The DPC latency measurement workset.
1425 */
1426typedef struct DPCDATA
1427{
1428 KDPC Dpc;
1429 KTIMER Timer;
1430 KSPIN_LOCK SpinLock;
1431
1432 ULONG ulTimerRes;
1433
1434 bool volatile fFinished;
1435
1436 /** The timer interval (relative). */
1437 LARGE_INTEGER DueTime;
1438
1439 LARGE_INTEGER PerfCounterPrev;
1440
1441 /** Align the sample array on a 64 byte boundrary just for the off chance
1442 * that we'll get cache line aligned memory backing this structure. */
1443 uint32_t auPadding[ARCH_BITS == 32 ? 5 : 7];
1444
1445 int cSamples;
1446 DPCSAMPLE aSamples[8192];
1447} DPCDATA;
1448
1449AssertCompileMemberAlignment(DPCDATA, aSamples, 64);
1450
1451# define VBOXGUEST_DPC_TAG 'DPCS'
1452
1453
1454/**
1455 * DPC callback routine for the DPC latency measurement code.
1456 *
1457 * @param pDpc The DPC, not used.
1458 * @param pvDeferredContext Pointer to the DPCDATA.
1459 * @param SystemArgument1 System use, ignored.
1460 * @param SystemArgument2 System use, ignored.
1461 */
1462static VOID vgdrvNtDpcLatencyCallback(PKDPC pDpc, PVOID pvDeferredContext, PVOID SystemArgument1, PVOID SystemArgument2)
1463{
1464 DPCDATA *pData = (DPCDATA *)pvDeferredContext;
1465
1466 KeAcquireSpinLockAtDpcLevel(&pData->SpinLock);
1467
1468 if (pData->cSamples >= RT_ELEMENTS(pData->aSamples))
1469 pData->fFinished = true;
1470 else
1471 {
1472 DPCSAMPLE *pSample = &pData->aSamples[pData->cSamples++];
1473
1474 pSample->u64TSC = ASMReadTSC();
1475 pSample->PerfCounter = KeQueryPerformanceCounter(&pSample->PerfFrequency);
1476 pSample->PerfDelta.QuadPart = pSample->PerfCounter.QuadPart - pData->PerfCounterPrev.QuadPart;
1477
1478 pData->PerfCounterPrev.QuadPart = pSample->PerfCounter.QuadPart;
1479
1480 KeSetTimer(&pData->Timer, pData->DueTime, &pData->Dpc);
1481 }
1482
1483 KeReleaseSpinLockFromDpcLevel(&pData->SpinLock);
1484}
1485
1486
1487/**
1488 * Handles the DPC latency checker request.
1489 *
1490 * @returns VBox status code.
1491 */
1492int VGDrvNtIOCtl_DpcLatencyChecker(void)
1493{
1494 /*
1495 * Allocate a block of non paged memory for samples and related data.
1496 */
1497 DPCDATA *pData = (DPCDATA *)ExAllocatePoolWithTag(NonPagedPool, sizeof(DPCDATA), VBOXGUEST_DPC_TAG);
1498 if (!pData)
1499 {
1500 RTLogBackdoorPrintf("VBoxGuest: DPC: DPCDATA allocation failed.\n");
1501 return VERR_NO_MEMORY;
1502 }
1503
1504 /*
1505 * Initialize the data.
1506 */
1507 KeInitializeDpc(&pData->Dpc, vgdrvNtDpcLatencyCallback, pData);
1508 KeInitializeTimer(&pData->Timer);
1509 KeInitializeSpinLock(&pData->SpinLock);
1510
1511 pData->fFinished = false;
1512 pData->cSamples = 0;
1513 pData->PerfCounterPrev.QuadPart = 0;
1514
1515 pData->ulTimerRes = ExSetTimerResolution(1000 * 10, 1);
1516 pData->DueTime.QuadPart = -(int64_t)pData->ulTimerRes / 10;
1517
1518 /*
1519 * Start the DPC measurements and wait for a full set.
1520 */
1521 KeSetTimer(&pData->Timer, pData->DueTime, &pData->Dpc);
1522
1523 while (!pData->fFinished)
1524 {
1525 LARGE_INTEGER Interval;
1526 Interval.QuadPart = -100 * 1000 * 10;
1527 KeDelayExecutionThread(KernelMode, TRUE, &Interval);
1528 }
1529
1530 ExSetTimerResolution(0, 0);
1531
1532 /*
1533 * Log everything to the host.
1534 */
1535 RTLogBackdoorPrintf("DPC: ulTimerRes = %d\n", pData->ulTimerRes);
1536 for (int i = 0; i < pData->cSamples; i++)
1537 {
1538 DPCSAMPLE *pSample = &pData->aSamples[i];
1539
1540 RTLogBackdoorPrintf("[%d] pd %lld pc %lld pf %lld t %lld\n",
1541 i,
1542 pSample->PerfDelta.QuadPart,
1543 pSample->PerfCounter.QuadPart,
1544 pSample->PerfFrequency.QuadPart,
1545 pSample->u64TSC);
1546 }
1547
1548 ExFreePoolWithTag(pData, VBOXGUEST_DPC_TAG);
1549 return VINF_SUCCESS;
1550}
1551
1552#endif /* VBOX_WITH_DPC_LATENCY_CHECKER */
1553
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