VirtualBox

source: vbox/trunk/src/VBox/HostDrivers/Support/win/SUPDrv-win.cpp@ 8155

Last change on this file since 8155 was 8155, checked in by vboxsync, 17 years ago

The Big Sun Rebranding Header Change

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 26.9 KB
Line 
1/* $Id: SUPDrv-win.cpp 8155 2008-04-18 15:16:47Z vboxsync $ */
2/** @file
3 * VirtualBox Support Driver - Windows NT specific parts.
4 */
5
6/*
7 * Copyright (C) 2006-2007 Sun Microsystems, Inc.
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 *
17 * The contents of this file may alternatively be used under the terms
18 * of the Common Development and Distribution License Version 1.0
19 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the
20 * VirtualBox OSE distribution, in which case the provisions of the
21 * CDDL are applicable instead of those of the GPL.
22 *
23 * You may elect to license modified versions of this file under the
24 * terms and conditions of either the GPL or the CDDL or both.
25 *
26 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
27 * Clara, CA 95054 USA or visit http://www.sun.com if you need
28 * additional information or have any questions.
29 */
30
31
32
33/*******************************************************************************
34* Header Files *
35*******************************************************************************/
36#include "SUPDRV.h"
37#include <excpt.h>
38#include <iprt/assert.h>
39#include <iprt/process.h>
40
41
42/*******************************************************************************
43* Defined Constants And Macros *
44*******************************************************************************/
45/** The support service name. */
46#define SERVICE_NAME "VBoxDrv"
47/** Win32 Device name. */
48#define DEVICE_NAME "\\\\.\\VBoxDrv"
49/** NT Device name. */
50#define DEVICE_NAME_NT L"\\Device\\VBoxDrv"
51/** Win Symlink name. */
52#define DEVICE_NAME_DOS L"\\DosDevices\\VBoxDrv"
53/** The Pool tag (VBox). */
54#define SUPDRV_NT_POOL_TAG 'xoBV'
55
56
57/*******************************************************************************
58* Structures and Typedefs *
59*******************************************************************************/
60#if 0 //def RT_ARCH_AMD64
61typedef struct SUPDRVEXECMEM
62{
63 PMDL pMdl;
64 void *pvMapping;
65 void *pvAllocation;
66} SUPDRVEXECMEM, *PSUPDRVEXECMEM;
67#endif
68
69
70/*******************************************************************************
71* Internal Functions *
72*******************************************************************************/
73static void _stdcall VBoxDrvNtUnload(PDRIVER_OBJECT pDrvObj);
74static NTSTATUS _stdcall VBoxDrvNtCreate(PDEVICE_OBJECT pDevObj, PIRP pIrp);
75static NTSTATUS _stdcall VBoxDrvNtClose(PDEVICE_OBJECT pDevObj, PIRP pIrp);
76static NTSTATUS _stdcall VBoxDrvNtDeviceControl(PDEVICE_OBJECT pDevObj, PIRP pIrp);
77static int VBoxDrvNtDeviceControlSlow(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PIRP pIrp, PIO_STACK_LOCATION pStack);
78static NTSTATUS _stdcall VBoxDrvNtNotSupportedStub(PDEVICE_OBJECT pDevObj, PIRP pIrp);
79static NTSTATUS VBoxDrvNtErr2NtStatus(int rc);
80static NTSTATUS VBoxDrvNtGipInit(PSUPDRVDEVEXT pDevExt);
81static void VBoxDrvNtGipTerm(PSUPDRVDEVEXT pDevExt);
82static void _stdcall VBoxDrvNtGipTimer(IN PKDPC pDpc, IN PVOID pvUser, IN PVOID SystemArgument1, IN PVOID SystemArgument2);
83static void _stdcall VBoxDrvNtGipPerCpuDpc(IN PKDPC pDpc, IN PVOID pvUser, IN PVOID SystemArgument1, IN PVOID SystemArgument2);
84
85
86/*******************************************************************************
87* Exported Functions *
88*******************************************************************************/
89__BEGIN_DECLS
90ULONG _stdcall DriverEntry(PDRIVER_OBJECT pDrvObj, PUNICODE_STRING pRegPath);
91__END_DECLS
92
93
94/**
95 * Driver entry point.
96 *
97 * @returns appropriate status code.
98 * @param pDrvObj Pointer to driver object.
99 * @param pRegPath Registry base path.
100 */
101ULONG _stdcall DriverEntry(PDRIVER_OBJECT pDrvObj, PUNICODE_STRING pRegPath)
102{
103 NTSTATUS rc;
104 dprintf(("VBoxDrv::DriverEntry\n"));
105
106 /*
107 * Create device.
108 * (That means creating a device object and a symbolic link so the DOS
109 * subsystems (OS/2, win32, ++) can access the device.)
110 */
111 UNICODE_STRING DevName;
112 RtlInitUnicodeString(&DevName, DEVICE_NAME_NT);
113 PDEVICE_OBJECT pDevObj;
114 rc = IoCreateDevice(pDrvObj, sizeof(SUPDRVDEVEXT), &DevName, FILE_DEVICE_UNKNOWN, 0, FALSE, &pDevObj);
115 if (NT_SUCCESS(rc))
116 {
117 UNICODE_STRING DosName;
118 RtlInitUnicodeString(&DosName, DEVICE_NAME_DOS);
119 rc = IoCreateSymbolicLink(&DosName, &DevName);
120 if (NT_SUCCESS(rc))
121 {
122 /*
123 * Initialize the device extension.
124 */
125 PSUPDRVDEVEXT pDevExt = (PSUPDRVDEVEXT)pDevObj->DeviceExtension;
126 memset(pDevExt, 0, sizeof(*pDevExt));
127 int vrc = supdrvInitDevExt(pDevExt);
128 if (!vrc)
129 {
130 /*
131 * Inititalize the GIP.
132 */
133 rc = VBoxDrvNtGipInit(pDevExt);
134 if (NT_SUCCESS(rc))
135 {
136 /*
137 * Setup the driver entry points in pDrvObj.
138 */
139 pDrvObj->DriverUnload = VBoxDrvNtUnload;
140 pDrvObj->MajorFunction[IRP_MJ_CREATE] = VBoxDrvNtCreate;
141 pDrvObj->MajorFunction[IRP_MJ_CLOSE] = VBoxDrvNtClose;
142 pDrvObj->MajorFunction[IRP_MJ_DEVICE_CONTROL] = VBoxDrvNtDeviceControl;
143 pDrvObj->MajorFunction[IRP_MJ_READ] = VBoxDrvNtNotSupportedStub;
144 pDrvObj->MajorFunction[IRP_MJ_WRITE] = VBoxDrvNtNotSupportedStub;
145 /* more? */
146 dprintf(("VBoxDrv::DriverEntry returning STATUS_SUCCESS\n"));
147 return STATUS_SUCCESS;
148 }
149 dprintf(("VBoxDrvNtGipInit failed with rc=%#x!\n", rc));
150
151 supdrvDeleteDevExt(pDevExt);
152 }
153 else
154 {
155 dprintf(("supdrvInitDevExit failed with vrc=%d!\n", vrc));
156 rc = VBoxDrvNtErr2NtStatus(vrc);
157 }
158
159 IoDeleteSymbolicLink(&DosName);
160 }
161 else
162 dprintf(("IoCreateSymbolicLink failed with rc=%#x!\n", rc));
163
164 IoDeleteDevice(pDevObj);
165 }
166 else
167 dprintf(("IoCreateDevice failed with rc=%#x!\n", rc));
168
169 if (NT_SUCCESS(rc))
170 rc = STATUS_INVALID_PARAMETER;
171 dprintf(("VBoxDrv::DriverEntry returning %#x\n", rc));
172 return rc;
173}
174
175
176/**
177 * Unload the driver.
178 *
179 * @param pDrvObj Driver object.
180 */
181void _stdcall VBoxDrvNtUnload(PDRIVER_OBJECT pDrvObj)
182{
183 PSUPDRVDEVEXT pDevExt = (PSUPDRVDEVEXT)pDrvObj->DeviceObject->DeviceExtension;
184
185 dprintf(("VBoxDrvNtUnload at irql %d\n", KeGetCurrentIrql()));
186
187 /*
188 * We ASSUME that it's not possible to unload a driver with open handles.
189 * Start by deleting the symbolic link
190 */
191 UNICODE_STRING DosName;
192 RtlInitUnicodeString(&DosName, DEVICE_NAME_DOS);
193 NTSTATUS rc = IoDeleteSymbolicLink(&DosName);
194
195 /*
196 * Terminate the GIP page and delete the device extension.
197 */
198 VBoxDrvNtGipTerm(pDevExt);
199 supdrvDeleteDevExt(pDevExt);
200 IoDeleteDevice(pDrvObj->DeviceObject);
201}
202
203
204/**
205 * Create (i.e. Open) file entry point.
206 *
207 * @param pDevObj Device object.
208 * @param pIrp Request packet.
209 */
210NTSTATUS _stdcall VBoxDrvNtCreate(PDEVICE_OBJECT pDevObj, PIRP pIrp)
211{
212 dprintf(("VBoxDrvNtCreate\n"));
213 PIO_STACK_LOCATION pStack = IoGetCurrentIrpStackLocation(pIrp);
214 PFILE_OBJECT pFileObj = pStack->FileObject;
215 PSUPDRVDEVEXT pDevExt = (PSUPDRVDEVEXT)pDevObj->DeviceExtension;
216
217 /*
218 * We are not remotely similar to a directory...
219 * (But this is possible.)
220 */
221 if (pStack->Parameters.Create.Options & FILE_DIRECTORY_FILE)
222 {
223 pIrp->IoStatus.Status = STATUS_NOT_A_DIRECTORY;
224 pIrp->IoStatus.Information = 0;
225 IoCompleteRequest(pIrp, IO_NO_INCREMENT);
226 return STATUS_NOT_A_DIRECTORY;
227 }
228
229 /*
230 * Call common code for the rest.
231 */
232 pFileObj->FsContext = NULL;
233 PSUPDRVSESSION pSession;
234 int rc = supdrvCreateSession(pDevExt, &pSession);
235 if (!rc)
236 {
237 pSession->Uid = NIL_RTUID;
238 pSession->Gid = NIL_RTGID;
239 pSession->Process = RTProcSelf();
240 pSession->R0Process = RTR0ProcHandleSelf();
241 pFileObj->FsContext = pSession;
242 }
243
244 NTSTATUS rcNt = pIrp->IoStatus.Status = VBoxDrvNtErr2NtStatus(rc);
245 pIrp->IoStatus.Information = 0;
246 IoCompleteRequest(pIrp, IO_NO_INCREMENT);
247
248 return rcNt;
249}
250
251
252/**
253 * Close file entry point.
254 *
255 * @param pDevObj Device object.
256 * @param pIrp Request packet.
257 */
258NTSTATUS _stdcall VBoxDrvNtClose(PDEVICE_OBJECT pDevObj, PIRP pIrp)
259{
260 PSUPDRVDEVEXT pDevExt = (PSUPDRVDEVEXT)pDevObj->DeviceExtension;
261 PIO_STACK_LOCATION pStack = IoGetCurrentIrpStackLocation(pIrp);
262 PFILE_OBJECT pFileObj = pStack->FileObject;
263 dprintf(("VBoxDrvNtClose: pDevExt=%p pFileObj=%p pSession=%p\n",
264 pDevExt, pFileObj, pFileObj->FsContext));
265 supdrvCloseSession(pDevExt, (PSUPDRVSESSION)pFileObj->FsContext);
266 pFileObj->FsContext = NULL;
267 pIrp->IoStatus.Information = 0;
268 pIrp->IoStatus.Status = STATUS_SUCCESS;
269 IoCompleteRequest(pIrp, IO_NO_INCREMENT);
270
271 return STATUS_SUCCESS;
272}
273
274
275/**
276 * Device I/O Control entry point.
277 *
278 * @param pDevObj Device object.
279 * @param pIrp Request packet.
280 */
281NTSTATUS _stdcall VBoxDrvNtDeviceControl(PDEVICE_OBJECT pDevObj, PIRP pIrp)
282{
283 PSUPDRVDEVEXT pDevExt = (PSUPDRVDEVEXT)pDevObj->DeviceExtension;
284 PIO_STACK_LOCATION pStack = IoGetCurrentIrpStackLocation(pIrp);
285 PSUPDRVSESSION pSession = (PSUPDRVSESSION)pStack->FileObject->FsContext;
286
287 /*
288 * Deal with the two high-speed IOCtl that takes it's arguments from
289 * the session and iCmd, and only returns a VBox status code.
290 */
291 ULONG ulCmd = pStack->Parameters.DeviceIoControl.IoControlCode;
292 if ( ulCmd == SUP_IOCTL_FAST_DO_RAW_RUN
293 || ulCmd == SUP_IOCTL_FAST_DO_HWACC_RUN
294 || ulCmd == SUP_IOCTL_FAST_DO_NOP)
295 {
296 KIRQL oldIrql;
297 int rc;
298
299 /* Raise the IRQL to DISPATCH_LEVEl to prevent Windows from rescheduling us to another CPU/core. */
300 Assert(KeGetCurrentIrql() <= DISPATCH_LEVEL);
301 KeRaiseIrql(DISPATCH_LEVEL, &oldIrql);
302 rc = supdrvIOCtlFast(ulCmd, pDevExt, pSession);
303 KeLowerIrql(oldIrql);
304
305 /* Complete the I/O request. */
306 NTSTATUS rcNt = pIrp->IoStatus.Status = STATUS_SUCCESS;
307 pIrp->IoStatus.Information = sizeof(rc);
308 __try
309 {
310 *(int *)pIrp->UserBuffer = rc;
311 }
312 __except(EXCEPTION_EXECUTE_HANDLER)
313 {
314 rcNt = pIrp->IoStatus.Status = GetExceptionCode();
315 dprintf(("VBoxSupDrvDeviceContorl: Exception Code %#x\n", rcNt));
316 }
317 IoCompleteRequest(pIrp, IO_NO_INCREMENT);
318 return rcNt;
319 }
320
321 return VBoxDrvNtDeviceControlSlow(pDevExt, pSession, pIrp, pStack);
322}
323
324
325/**
326 * Worker for VBoxDrvNtDeviceControl that takes the slow IOCtl functions.
327 *
328 * @returns NT status code.
329 *
330 * @param pDevObj Device object.
331 * @param pSession The session.
332 * @param pIrp Request packet.
333 * @param pStack The stack location containing the DeviceControl parameters.
334 */
335static int VBoxDrvNtDeviceControlSlow(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PIRP pIrp, PIO_STACK_LOCATION pStack)
336{
337 NTSTATUS rcNt;
338 unsigned cbOut = 0;
339 int rc = 0;
340 dprintf2(("VBoxDrvNtDeviceControlSlow(%p,%p): ioctl=%#x pBuf=%p cbIn=%#x cbOut=%#x pSession=%p\n",
341 pDevExt, pIrp, pStack->Parameters.DeviceIoControl.IoControlCode,
342 pIrp->AssociatedIrp.SystemBuffer, pStack->Parameters.DeviceIoControl.InputBufferLength,
343 pStack->Parameters.DeviceIoControl.OutputBufferLength, pSession));
344
345#ifdef RT_ARCH_AMD64
346 /* Don't allow 32-bit processes to do any I/O controls. */
347 if (!IoIs32bitProcess(pIrp))
348#endif
349 {
350 /* Verify that it's a buffered CTL. */
351 if ((pStack->Parameters.DeviceIoControl.IoControlCode & 0x3) == METHOD_BUFFERED)
352 {
353 /* Verify that the sizes in the request header are correct. */
354 PSUPREQHDR pHdr = (PSUPREQHDR)pIrp->AssociatedIrp.SystemBuffer;
355 if ( pStack->Parameters.DeviceIoControl.InputBufferLength >= sizeof(*pHdr)
356 && pStack->Parameters.DeviceIoControl.InputBufferLength == pHdr->cbIn
357 && pStack->Parameters.DeviceIoControl.OutputBufferLength == pHdr->cbOut)
358 {
359 /*
360 * Do the job.
361 */
362 rc = supdrvIOCtl(pStack->Parameters.DeviceIoControl.IoControlCode, pDevExt, pSession, pHdr);
363 if (!rc)
364 {
365 rcNt = STATUS_SUCCESS;
366 cbOut = pHdr->cbOut;
367 if (cbOut > pStack->Parameters.DeviceIoControl.OutputBufferLength)
368 {
369 cbOut = pStack->Parameters.DeviceIoControl.OutputBufferLength;
370 OSDBGPRINT(("VBoxDrvLinuxIOCtl: too much output! %#x > %#x; uCmd=%#x!\n",
371 pHdr->cbOut, cbOut, pStack->Parameters.DeviceIoControl.IoControlCode));
372 }
373 }
374 else
375 rcNt = STATUS_INVALID_PARAMETER;
376 dprintf2(("VBoxDrvNtDeviceControlSlow: returns %#x cbOut=%d rc=%#x\n", rcNt, cbOut, rc));
377 }
378 else
379 {
380 dprintf(("VBoxDrvNtDeviceControlSlow: Mismatching sizes (%#x) - Hdr=%#lx/%#lx Irp=%#lx/%#lx!\n",
381 pStack->Parameters.DeviceIoControl.IoControlCode,
382 pStack->Parameters.DeviceIoControl.InputBufferLength >= sizeof(*pHdr) ? pHdr->cbIn : 0,
383 pStack->Parameters.DeviceIoControl.InputBufferLength >= sizeof(*pHdr) ? pHdr->cbOut : 0,
384 pStack->Parameters.DeviceIoControl.InputBufferLength,
385 pStack->Parameters.DeviceIoControl.OutputBufferLength));
386 rcNt = STATUS_INVALID_PARAMETER;
387 }
388 }
389 else
390 {
391 dprintf(("VBoxDrvNtDeviceControlSlow: not buffered request (%#x) - not supported\n",
392 pStack->Parameters.DeviceIoControl.IoControlCode));
393 rcNt = STATUS_NOT_SUPPORTED;
394 }
395 }
396#ifdef RT_ARCH_AMD64
397 else
398 {
399 dprintf(("VBoxDrvNtDeviceControlSlow: WOW64 req - not supported\n"));
400 rcNt = STATUS_NOT_SUPPORTED;
401 }
402#endif
403
404 /* complete the request. */
405 pIrp->IoStatus.Status = rcNt;
406 pIrp->IoStatus.Information = cbOut;
407 IoCompleteRequest(pIrp, IO_NO_INCREMENT);
408 return rcNt;
409}
410
411
412/**
413 * Stub function for functions we don't implemented.
414 *
415 * @returns STATUS_NOT_SUPPORTED
416 * @param pDevObj Device object.
417 * @param pIrp IRP.
418 */
419NTSTATUS _stdcall VBoxDrvNtNotSupportedStub(PDEVICE_OBJECT pDevObj, PIRP pIrp)
420{
421 dprintf(("VBoxDrvNtNotSupportedStub\n"));
422 pDevObj = pDevObj;
423
424 pIrp->IoStatus.Information = 0;
425 pIrp->IoStatus.Status = STATUS_NOT_SUPPORTED;
426 IoCompleteRequest(pIrp, IO_NO_INCREMENT);
427
428 return STATUS_NOT_SUPPORTED;
429}
430
431
432/**
433 * Initializes any OS specific object creator fields.
434 */
435void VBOXCALL supdrvOSObjInitCreator(PSUPDRVOBJ pObj, PSUPDRVSESSION pSession)
436{
437 NOREF(pObj);
438 NOREF(pSession);
439}
440
441
442/**
443 * Checks if the session can access the object.
444 *
445 * @returns true if a decision has been made.
446 * @returns false if the default access policy should be applied.
447 *
448 * @param pObj The object in question.
449 * @param pSession The session wanting to access the object.
450 * @param pszObjName The object name, can be NULL.
451 * @param prc Where to store the result when returning true.
452 */
453bool VBOXCALL supdrvOSObjCanAccess(PSUPDRVOBJ pObj, PSUPDRVSESSION pSession, const char *pszObjName, int *prc)
454{
455 NOREF(pObj);
456 NOREF(pSession);
457 NOREF(pszObjName);
458 NOREF(prc);
459 return false;
460}
461
462/**
463 * Gets the monotone timestamp (nano seconds).
464 * @returns NanoTS.
465 */
466static inline uint64_t supdrvOSMonotime(void)
467{
468 return (uint64_t)KeQueryInterruptTime() * 100;
469}
470
471
472/**
473 * Initializes the GIP.
474 *
475 * @returns NT status code.
476 * @param pDevExt Instance data. GIP stuff may be updated.
477 */
478static NTSTATUS VBoxDrvNtGipInit(PSUPDRVDEVEXT pDevExt)
479{
480 dprintf2(("VBoxSupDrvTermGip:\n"));
481
482 /*
483 * Try allocate the memory.
484 * Make sure it's below 4GB for 32-bit GC support
485 */
486 NTSTATUS rc;
487 PHYSICAL_ADDRESS Phys;
488 Phys.HighPart = 0;
489 Phys.LowPart = ~0;
490 PSUPGLOBALINFOPAGE pGip = (PSUPGLOBALINFOPAGE)MmAllocateContiguousMemory(PAGE_SIZE, Phys);
491 if (pGip)
492 {
493 if (!((uintptr_t)pGip & (PAGE_SIZE - 1)))
494 {
495 pDevExt->pGipMdl = IoAllocateMdl(pGip, PAGE_SIZE, FALSE, FALSE, NULL);
496 if (pDevExt->pGipMdl)
497 {
498 MmBuildMdlForNonPagedPool(pDevExt->pGipMdl);
499
500 /*
501 * Figure the timer interval and frequency.
502 * It turns out trying 1023Hz doesn't work. So, we'll set the max Hz at 128 for now.
503 */
504 ExSetTimerResolution(156250, TRUE);
505 ULONG ulClockIntervalActual = ExSetTimerResolution(0, FALSE);
506 ULONG ulClockInterval = RT_MAX(ulClockIntervalActual, 78125); /* 1/128 */
507 ULONG ulClockFreq = 10000000 / ulClockInterval;
508 pDevExt->ulGipTimerInterval = ulClockInterval / 10000; /* ms */
509
510 /*
511 * Call common initialization routine.
512 */
513 Phys = MmGetPhysicalAddress(pGip); /* could perhaps use the Mdl, not that it looks much better */
514 supdrvGipInit(pDevExt, pGip, (RTHCPHYS)Phys.QuadPart, supdrvOSMonotime(), ulClockFreq);
515
516 /*
517 * Initialize the timer.
518 */
519 KeInitializeTimerEx(&pDevExt->GipTimer, SynchronizationTimer);
520 KeInitializeDpc(&pDevExt->GipDpc, VBoxDrvNtGipTimer, pDevExt);
521
522 /*
523 * Initialize the DPCs we're using to update the per-cpu GIP data.
524 */
525 for (unsigned i = 0; i < RT_ELEMENTS(pDevExt->aGipCpuDpcs); i++)
526 {
527 KeInitializeDpc(&pDevExt->aGipCpuDpcs[i], VBoxDrvNtGipPerCpuDpc, pGip);
528 KeSetImportanceDpc(&pDevExt->aGipCpuDpcs[i], HighImportance);
529 KeSetTargetProcessorDpc(&pDevExt->aGipCpuDpcs[i], i);
530 }
531
532 dprintf(("VBoxDrvNtGipInit: ulClockFreq=%ld ulClockInterval=%ld ulClockIntervalActual=%ld Phys=%x%08x\n",
533 ulClockFreq, ulClockInterval, ulClockIntervalActual, Phys.HighPart, Phys.LowPart));
534 return STATUS_SUCCESS;
535 }
536
537 dprintf(("VBoxSupDrvInitGip: IoAllocateMdl failed for %p/PAGE_SIZE\n", pGip));
538 rc = STATUS_NO_MEMORY;
539 }
540 else
541 {
542 dprintf(("VBoxSupDrvInitGip: GIP memory is not page aligned! pGip=%p\n", pGip));
543 rc = STATUS_INVALID_ADDRESS;
544 }
545 MmFreeContiguousMemory(pGip);
546 }
547 else
548 {
549 dprintf(("VBoxSupDrvInitGip: no cont memory.\n"));
550 rc = STATUS_NO_MEMORY;
551 }
552 return rc;
553}
554
555
556/**
557 * Terminates the GIP.
558 *
559 * @returns negative errno.
560 * @param pDevExt Instance data. GIP stuff may be updated.
561 */
562static void VBoxDrvNtGipTerm(PSUPDRVDEVEXT pDevExt)
563{
564 dprintf(("VBoxSupDrvTermGip:\n"));
565 PSUPGLOBALINFOPAGE pGip;
566
567 /*
568 * Cancel the timer and wait on DPCs if it was still pending.
569 */
570 if (KeCancelTimer(&pDevExt->GipTimer))
571 {
572 UNICODE_STRING RoutineName;
573 RtlInitUnicodeString(&RoutineName, L"KeFlushQueuedDpcs");
574 VOID (*pfnKeFlushQueuedDpcs)(VOID) = (VOID (*)(VOID))MmGetSystemRoutineAddress(&RoutineName);
575 if (pfnKeFlushQueuedDpcs)
576 {
577 /* KeFlushQueuedDpcs must be run at IRQL PASSIVE_LEVEL */
578 AssertMsg(KeGetCurrentIrql() == PASSIVE_LEVEL, ("%d != %d (PASSIVE_LEVEL)\n", KeGetCurrentIrql(), PASSIVE_LEVEL));
579 pfnKeFlushQueuedDpcs();
580 }
581 }
582
583 /*
584 * Uninitialize the content.
585 */
586 pGip = pDevExt->pGip;
587 pDevExt->pGip = NULL;
588 if (pGip)
589 {
590 supdrvGipTerm(pGip);
591
592 /*
593 * Free the page.
594 */
595 if (pDevExt->pGipMdl)
596 {
597 IoFreeMdl(pDevExt->pGipMdl);
598 pDevExt->pGipMdl = NULL;
599 }
600 MmFreeContiguousMemory(pGip);
601 }
602}
603
604
605/**
606 * Timer callback function.
607 * The pvUser parameter is the pDevExt pointer.
608 */
609static void _stdcall VBoxDrvNtGipTimer(IN PKDPC pDpc, IN PVOID pvUser, IN PVOID SystemArgument1, IN PVOID SystemArgument2)
610{
611 PSUPDRVDEVEXT pDevExt = (PSUPDRVDEVEXT)pvUser;
612 PSUPGLOBALINFOPAGE pGip = pDevExt->pGip;
613 if (pGip)
614 {
615 if (pGip->u32Mode != SUPGIPMODE_ASYNC_TSC)
616 supdrvGipUpdate(pGip, supdrvOSMonotime());
617 else
618 {
619 KIRQL oldIrql;
620
621 /* KeQueryActiveProcessors must be executed at IRQL < DISPATCH_LEVEL */
622 Assert(KeGetCurrentIrql() < DISPATCH_LEVEL);
623 KAFFINITY Mask = KeQueryActiveProcessors();
624
625 /* Raise the IRQL to DISPATCH_LEVEL so we can't be rescheduled to another cpu */
626 KeRaiseIrql(DISPATCH_LEVEL, &oldIrql);
627
628 /*
629 * We cannot do other than assume a 1:1 relationship between the
630 * affinity mask and the process despite the warnings in the docs.
631 * If someone knows a better way to get this done, please let bird know.
632 */
633 unsigned iSelf = KeGetCurrentProcessorNumber();
634
635 for (unsigned i = 0; i < RT_ELEMENTS(pDevExt->aGipCpuDpcs); i++)
636 {
637 if ( i != iSelf
638 && (Mask & RT_BIT_64(i)))
639 KeInsertQueueDpc(&pDevExt->aGipCpuDpcs[i], 0, 0);
640 }
641
642 /* Run the normal update. */
643 supdrvGipUpdate(pGip, supdrvOSMonotime());
644
645 KeLowerIrql(oldIrql);
646 }
647 }
648}
649
650
651/**
652 * Per cpu callback callback function.
653 * The pvUser parameter is the pGip pointer.
654 */
655static void _stdcall VBoxDrvNtGipPerCpuDpc(IN PKDPC pDpc, IN PVOID pvUser, IN PVOID SystemArgument1, IN PVOID SystemArgument2)
656{
657 PSUPGLOBALINFOPAGE pGip = (PSUPGLOBALINFOPAGE)pvUser;
658 supdrvGipUpdatePerCpu(pGip, supdrvOSMonotime(), ASMGetApicId());
659}
660
661
662/**
663 * Maps the GIP into user space.
664 *
665 * @returns negative errno.
666 * @param pDevExt Instance data.
667 */
668int VBOXCALL supdrvOSGipMap(PSUPDRVDEVEXT pDevExt, PSUPGLOBALINFOPAGE *ppGip)
669{
670 dprintf2(("supdrvOSGipMap: ppGip=%p (pDevExt->pGipMdl=%p)\n", ppGip, pDevExt->pGipMdl));
671
672 /*
673 * Map into user space.
674 */
675 int rc = 0;
676 void *pv = NULL;
677 __try
678 {
679 *ppGip = (PSUPGLOBALINFOPAGE)MmMapLockedPagesSpecifyCache(pDevExt->pGipMdl, UserMode, MmCached, NULL, FALSE, NormalPagePriority);
680 }
681 __except(EXCEPTION_EXECUTE_HANDLER)
682 {
683 NTSTATUS rcNt = GetExceptionCode();
684 dprintf(("supdrvOsGipMap: Exception Code %#x\n", rcNt));
685 rc = SUPDRV_ERR_LOCK_FAILED;
686 }
687
688 dprintf2(("supdrvOSGipMap: returns %d, *ppGip=%p\n", rc, *ppGip));
689 return 0;
690}
691
692
693/**
694 * Maps the GIP into user space.
695 *
696 * @returns negative errno.
697 * @param pDevExt Instance data.
698 */
699int VBOXCALL supdrvOSGipUnmap(PSUPDRVDEVEXT pDevExt, PSUPGLOBALINFOPAGE pGip)
700{
701 dprintf2(("supdrvOSGipUnmap: pGip=%p (pGipMdl=%p)\n", pGip, pDevExt->pGipMdl));
702
703 int rc = 0;
704 __try
705 {
706 MmUnmapLockedPages((void *)pGip, pDevExt->pGipMdl);
707 }
708 __except(EXCEPTION_EXECUTE_HANDLER)
709 {
710 NTSTATUS rcNt = GetExceptionCode();
711 dprintf(("supdrvOSGipUnmap: Exception Code %#x\n", rcNt));
712 rc = SUPDRV_ERR_GENERAL_FAILURE;
713 }
714 dprintf2(("supdrvOSGipUnmap: returns %d\n", rc));
715 return rc;
716}
717
718
719/**
720 * Resumes the GIP updating.
721 *
722 * @param pDevExt Instance data.
723 */
724void VBOXCALL supdrvOSGipResume(PSUPDRVDEVEXT pDevExt)
725{
726 dprintf2(("supdrvOSGipResume:\n"));
727 LARGE_INTEGER DueTime;
728 DueTime.QuadPart = -10000; /* 1ms, relative */
729 KeSetTimerEx(&pDevExt->GipTimer, DueTime, pDevExt->ulGipTimerInterval, &pDevExt->GipDpc);
730}
731
732
733/**
734 * Suspends the GIP updating.
735 *
736 * @param pDevExt Instance data.
737 */
738void VBOXCALL supdrvOSGipSuspend(PSUPDRVDEVEXT pDevExt)
739{
740 dprintf2(("supdrvOSGipSuspend:\n"));
741 KeCancelTimer(&pDevExt->GipTimer);
742#ifdef RT_ARCH_AMD64
743 ExSetTimerResolution(0, FALSE);
744#endif
745}
746
747
748/**
749 * Get the current CPU count.
750 * @returns Number of cpus.
751 */
752unsigned VBOXCALL supdrvOSGetCPUCount(void)
753{
754 KAFFINITY Mask = KeQueryActiveProcessors();
755 unsigned cCpus = 0;
756 unsigned iBit;
757 for (iBit = 0; iBit < sizeof(Mask) * 8; iBit++)
758 if (Mask & RT_BIT_64(iBit))
759 cCpus++;
760 if (cCpus == 0) /* paranoia */
761 cCpus = 1;
762 return cCpus;
763}
764
765
766/**
767 * Force async tsc mode (stub).
768 */
769bool VBOXCALL supdrvOSGetForcedAsyncTscMode(void)
770{
771 return false;
772}
773
774
775/**
776 * Converts a supdrv error code to an nt status code.
777 *
778 * @returns corresponding nt status code.
779 * @param rc supdrv error code (SUPDRV_ERR_* defines).
780 */
781static NTSTATUS VBoxDrvNtErr2NtStatus(int rc)
782{
783 switch (rc)
784 {
785 case 0: return STATUS_SUCCESS;
786 case SUPDRV_ERR_GENERAL_FAILURE: return STATUS_NOT_SUPPORTED;
787 case SUPDRV_ERR_INVALID_PARAM: return STATUS_INVALID_PARAMETER;
788 case SUPDRV_ERR_INVALID_MAGIC: return STATUS_UNKNOWN_REVISION;
789 case SUPDRV_ERR_INVALID_HANDLE: return STATUS_INVALID_HANDLE;
790 case SUPDRV_ERR_INVALID_POINTER: return STATUS_INVALID_ADDRESS;
791 case SUPDRV_ERR_LOCK_FAILED: return STATUS_NOT_LOCKED;
792 case SUPDRV_ERR_ALREADY_LOADED: return STATUS_IMAGE_ALREADY_LOADED;
793 case SUPDRV_ERR_PERMISSION_DENIED: return STATUS_ACCESS_DENIED;
794 case SUPDRV_ERR_VERSION_MISMATCH: return STATUS_REVISION_MISMATCH;
795 }
796
797 return STATUS_UNSUCCESSFUL;
798}
799
800
801/** Runtime assert implementation for Native Win32 Ring-0. */
802RTDECL(void) AssertMsg1(const char *pszExpr, unsigned uLine, const char *pszFile, const char *pszFunction)
803{
804 DbgPrint("\n!!Assertion Failed!!\n"
805 "Expression: %s\n"
806 "Location : %s(%d) %s\n",
807 pszExpr, pszFile, uLine, pszFunction);
808}
809
810int VBOXCALL mymemcmp(const void *pv1, const void *pv2, size_t cb)
811{
812 const uint8_t *pb1 = (const uint8_t *)pv1;
813 const uint8_t *pb2 = (const uint8_t *)pv2;
814 for (; cb > 0; cb--, pb1++, pb2++)
815 if (*pb1 != *pb2)
816 return *pb1 - *pb2;
817 return 0;
818}
819
Note: See TracBrowser for help on using the repository browser.

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