Chris Cant - Writing Windows WDM Device Drivers
Здесь есть возможность читать онлайн «Chris Cant - Writing Windows WDM Device Drivers» весь текст электронной книги совершенно бесплатно (целиком полную версию без сокращений). В некоторых случаях можно слушать аудио, скачать через торрент в формате fb2 и присутствует краткое содержание. Город: Lawrence, Kansas 66046, ISBN: , Издательство: R & D Books, Жанр: Программирование, на английском языке. Описание произведения, (предисловие) а так же отзывы посетителей доступны на портале библиотеки ЛибКат.
- Название:Writing Windows WDM Device Drivers
- Автор:
- Издательство:R & D Books
- Жанр:
- Год:неизвестен
- Город:Lawrence, Kansas 66046
- ISBN:0-87930-565-7
- Рейтинг книги:5 / 5. Голосов: 1
-
Избранное:Добавить в избранное
- Отзывы:
-
Ваша оценка:
- 100
- 1
- 2
- 3
- 4
- 5
Writing Windows WDM Device Drivers: краткое содержание, описание и аннотация
Предлагаем к чтению аннотацию, описание, краткое содержание или предисловие (зависит от того, что написал сам автор книги «Writing Windows WDM Device Drivers»). Если вы не нашли необходимую информацию о книге — напишите в комментариях, мы постараемся отыскать её.
Writing Windows WDM Device Drivers — читать онлайн бесплатно полную книгу (весь текст) целиком
Ниже представлен текст книги, разбитый по страницам. Система сохранения места последней прочитанной страницы, позволяет с удобством читать онлайн бесплатно книгу «Writing Windows WDM Device Drivers», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.
Интервал:
Закладка:
If StartDevice succeeds, it will have set the GotResources flag. PnpStartDeviceHandler also then clears the Paused and IODisabled flags.
The drivers above Wdm2 in the device stack could fail the Start Device IRP. If this happens, Wdm2 and the other lower drivers will be sent a Remove Device request.
Listing 9.8 Wdm2 PnP start device handler
NTSTATUS PnpStartDeviceHandle(IN PDEVICE_OBJECT fdo, IN PIRP Irp) {
DebugPrintMsg("PnpStartDeviceHandler");
PWDM2_DEVICE_EXTENSION dx=(PWDM2_DEVICE_EXTENSION)fdo->DeviceExtension;
PIO_STACK_LOCATION IrpStack = IoGetCurrentIrpStackLocation(Irp);
NTSTATUS status = ForwardIrpAndWait(fdo, Irp);
if (!NT_SUCCESS(status)) return CompleteIrp(Irp, status, Irp->IoStatus.Information);
DebugPrint("PnpStartDeviceHandler: post-processing");
status = StartDevice(dx, IrpStack->Parameters.StartDevice.AllocatedResourcesTranslated);
if (NT_SUCCESS(status)) {
dx->Paused = false;
dx->IODisabled = false;
}
return Complete Irp(Irp, status, 0);
}
When a user wants to remove a Wdm2 device, the PnP Manager always asks if it is all right to remove it using a Query Remove request. As described previously, Wdm2 agrees to a removal request only if there are no open handles to the device. Therefore, for the main RemoveDevice request, the Wdm2 driver can be certain that there is no I/O in progress on the device.
However, some devices are hot-pluggable (i.e., a user can ruthlessly pull out the plug, or it could be bashed out by mistake). In this case, a PnP driver does not receive a Query Remove message. Instead, in Windows 98, it simply gets a Remove Device message. Windows 2000 sends a Surprise Removal message first and then sends a Remove Device request when all the open handles are closed.
A driver needs to cope with surprise removals in the best way possible. A SurpriseRemoval IRP must succeed. Obviously, the driver needs to stop any further I/O as soon as possible. However, one or more I/O requests may be in progress or queued up. It is fairly straightforward to cancel all the IRPs in a device queue; see Chapter 16 for details. However, the best method to handle I/O IRPs that are in progress is more complicated.
If you cannot somehow fail any I/O requests in progress, the recommended solution is to wait for them to complete. The main IRP processing routines are more than likely to be using the device or device extension, so these structures cannot be deleted until it is certain that they will not be used again. The main IRP processing routines almost certainly encounter some sort of problem. Make sure that they can handle a device being removed. A routine might be expecting an interrupt. Chapter 17 later shows how two different types of timers can be used to provide a time-out for I/O requests.
What is best way to keep track of how many I/O requests are in progress? The answer is to laboriously keep track of the number of open I/O requests in a UsageCount field in the device extension. A call to LockDevice is made at the beginning of each IRP request to increment UsageCount. UnlockDevice is called when each IRP is completed to decrement UsageCount.
UsageCount is set to one when the device is created. To remove or stop a device, an extra call to UnlockDevice is made. If there are no other IRPs in progress, this call should have decremented UsageCount to zero. If there are IRPs in progress, UsageCount will at this stage have a value greater than zero. However, when these IRPs finish, UnlockDevice will be called and so UsageCount will in due course become zero.
The Remove Device or Stop Device PnP IRP needs to know when UnlockDevice decrements UsageCount to zero. Another kernel event, StoppingEvent, is used for this purpose. UnlockDevice sets StoppingEvent into the signalled state when UsageCount drops to zero.
Listing 9.9 shows the PnpStopDevice routine that the Wdm2 driver uses to stop a device. It is called by the Remove Device, Surprise Removal, and Stop Device PnP IRP handlers. PnpStopDevice sets the IODisabled flag straightaway to stop any new requests from starting. The device is already stopped if GotResources is false, so no more processing is required.
PnpStopDevice resets StoppingEvent and then calls UnlockDevice twice. The first undoes the call to LockDevice at the start of the main PnP IRP handler. The second will reduce UsageCount to zero, either straightaway or when all the IRPs in progress complete. PnpStopDevice then waits for StoppingEvent to be set by UnlockDevice.
PnpStopDevice then calls the StopDevice routine, described later. StopDevice resets the GotResources flag. PnpStopDevice's last task is to call LockDevice again to increment UsageCount again. The main PnP IRP handler calls UnlockDevice in due course to get UsageCount down to its correct value of zero.
Listing 9.9 PnpStopDevice routine
void PnpStopDevice(IN PWDM2_DEVICE_EXTENSION dx) {
// Stop I/O ASAP
dx->IODisabled = true;
// Do nothing if we're already stopped
if (!dx->GotResources) return;
// Wait for any pending I/O operations to complete
dx->Stopping = true;
KeResetEvent(&dx->StoppingEvent);
UnlockDevice(dx);
UnlockDevice(dx);
KeWaitForSingleObject(&dx->StoppingEvent, Executive, KernelMode, FALSE, NULL);
DebugPrint("PnpStopDevice: All pending I/O completed");
dx->Stopping = false;
// Stop our device before passing down
StopDevice(dx);
// Bump usage count back up again
LockDevice(dx);
LockDevice(dx);
}
Listing 9.10 shows how a typical I/O IRP dispatch routine fits into the Wdm2 device Plug and Play handling. Initially, it checks the IODisabled flag and then it tries to lock the device using LockDevice . If LockDevice fails, the correct response is to return STATUS_DELETE_PENDING. The Wdm2 PnpStopDevice routine always sets the IODisabled flag first, so the dispatch routine will never return STATUS_DELETE_PENDING. This could be fixed by adding another suitable flag to the device extension.
The dispatch routine ends by completing the IRP and calling UnlockDevice . If the IRP is not completed straightaway, do not call UnlockDevice straightaway. Instead, wait until the IRP is completed or cancelled before calling UnlockDevice.
All dispatch routines should include calls to LockDevice when an IRP arrives and UnlockDevice when an IRP is completed or passed onto another driver. PnP and WMI IRP handlers should also call these routines.
Listing 9.10 Dispatch routine entry and exit code
NTSTATUS Wdm2Read( IN PDEVICE_OBJECT fdo, IN PIRP Irp) {
PWDM2_DEVICE_EXTENSION dx = (PWDM2_DEVICE_EXTENSION)fdo->DeviceExtension;
if (dx->IODisabled) return CompleteIrp(Irp, STATUS_DEVICE_NOT_CONNECTED, 0);
Интервал:
Закладка:
Похожие книги на «Writing Windows WDM Device Drivers»
Представляем Вашему вниманию похожие книги на «Writing Windows WDM Device Drivers» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.
Обсуждение, отзывы о книге «Writing Windows WDM Device Drivers» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.