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», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.
Интервал:
Закладка:
KEVENT StoppingEvent; // Set when all pending I/O complete
DEVICE_POWER_STATE PowerState; // Our device power state
PULONG PowerIdleCounter; // Device idle counter
// Resource allocations
bool GotPortOrMemory;
bool PortInIOSpace;
bool PortNeedsMapping;
PUCHAR PortBase;
PHYSICAL_ADDRESS PortStartAddress;
ULONG PortLength;
bool GotInterrupt;
ULONG Vector;
KIRQL Irql;
KINTERRUPT_MODE Mode;
KAFFINITY Affinity;
PKINTERRUPT InterruptObject;
} WDM2_DEVICE_EXTENSION, *PWDM2_DEVICE_EXTENSION;
The GotResources flag indicates that Wdm2 has been assigned its resources. Wdm2 does not use any hardware resources. However, it still needs this flag to indicate the state it is in.
The Paused flag has no hardware interpretation. It is simply a way of stopping IRPs from starting when in the Stop Pending or Remove Pending states. In a full PnP implementation, IRPs must be queued while the Paused flag is set. Wdm2 should never get in the Stop Pending state, as it has no resources to reallocate. It should only be in the Remove Pending state briefly. For simplicity sake, Wdm2 does not queue IRPs. Chapter 16 gives this subject the full airing it deserves.
The IODisabled flag is provided so that the dispatch routines have to check only one flag quickly, not both GotResources and Paused. Each normal IRP dispatch routine, therefore, has the following code at the top that fails the IRP straightaway with an appropriate error code if the device is disabled.
if (dx->IODisabled) return CompleteIrp(Irp, STATUS_DEVICE_NOT_CONNECTED, 0);
To recap, three flags in the Wdm2 device extension are used to ensure that normal I/O requests are permitted only when the Wdm2 device is fully started. In fact, there will be very few times in the life of a Wdm2 device when I/O requests are not permitted. (Strictly speaking, I could have combined the Paused and IODisabled flags, but it is clearer to have them separate.)
When a device is not fully started, a full PnP implementation ought to queue I/O request IRPs.
Consider the various PnP stop messages. These occur when some new hardware has been added to the system or a new device has been plugged in. The PnP Manager may decide that it can only accommodate the new device by reassigning the resources that an existing device currently uses. It does this by issuing a Query Stop message first. If all devices in the stack agree that a stop can take place, then the PnP Manager issues a Stop Device request. If any of the drivers in the stack do not want the device stopped, the PnP Manager issues a Cancel Stop message. It then probably informs the user that there are not enough resources available currently and so a restart is necessary. When the resources have been reassigned, it sends a StartDevice message with the new resource allocations.
During this entire process, it seems reasonable that I/O requests on existing devices carry on as normal. In practice, this means not starting any new requests and holding them in a queue for processing when the device is started again. A user might therefore notice a slight pause in proceedings while resources are reassigned, but I/O requests should not fail.
The DDK documentation recommends that drivers do not start any new I/O requests after a Query Stop or Query Remove message has been received. This lets any following stop or remove request proceed quickly.
The end result is that IRPs ought to be queued when in the Stop Pending, Remove Pending, and Stopped states. In the Wdm2 driver, this means that IRPs ought to be queued when the IODisabled flag is true. However, as stated before, Wdm2 does not hold IRPs, as this is a complicated subject to be covered in Chapter 16.
As shown in Listing 9.3, Wdm2 handles Query Stop message by setting the Paused and IODisabled flags before passing the IRP down the stack. The Query Remove request does the same job. The Cancel Stop and Cancel Remove messages undo these actions by clearing Paused and IODisabled.
What happens if the user asks to remove the Wdm2 device while there are open handles to it?
The PnP Manager sends a Query Remove request to the driver. The simplest approach is to refuse to let a device be removed while there are any open handles. The DDK documentation says that the Query Remove must be failed if "there are open handles that cannot be closed".
Wdm2 uses the simple approach. It keeps a count of open handles to a device in the OpenHandleCount variable in the device extension. OpenHandleCount is initialized to zero when the device is created in Wdm2AddDevice . The InterlockedIncrement and InterlockedDecrement routines are used in the Wdm2Create and Wdm2Close dispatch routines, respectively, to maintain this count safely.
InterlockedIncrement(&dx->OpenHandleCount);
Listing 9.6 shows the complete Query Remove handler for Wdm2. If OpenHandleCount is greater than zero, PnpQueryRemoveDeviceHandler simply fails the IRP straightaway. Notice that it does not need to pass the PnP IRP down the stack as it is failing it. Instead, it just completes the IRP with the STATUS_UNSUCCESSFUL status code.
If there are no open handles, Wdm2 sets its Paused and IODisabled flags, as discussed before. However, in this case, PnpQueryRemoveDeviceHandler must pass the IRP down the stack in PnpDefaultHandler to give lower devices a chance to reject the Query Remove IRP.
Listing 9.6 Wdm2 PnpQueryRemoveDeviceHandler
NTSTATUS PnpQueryRemoveDeviceHandler(IN PDEVICE_OBJECT fdo, IN PIRP Irp) {
PWDM2_DEVICE_EXTENSION dx=(PWDM2_DEVICE_EXTENSION)fdo->DeviceExtension;
DebugPrintMsg("PnpQueryRemoveDoviceHandler");
if( dx->OpenHandleCount>0) {
DebugPrint("PnpQueryRemoveDeviceHandler: %d handles still open", dx->OpenHandleCount);
return CompleteIrp(Irp, STATUS_UNSUCCESSFUL, 0);
}
dx->Paused = true;
dx->IODisabled = true;
return PnpDefaultHandler(fdo,Irp);
}
You must be careful to process PnP IRPs at the right time. When a Start Device message is received for a USB device, for example, the USB drivers must enable the device at the bus level first. It is only then that the function drivers above can access the device. In fact, when processing the Start Device message, the drivers must process the message in order, going up the device stack.
Similar considerations apply when processing Stop, Remove, and Surprise Removal messages. In these cases, all the drivers in the stack must process the IRP first, in order going down the stack. Each driver must do whatever it needs to do to stop its device before the lower drivers pull the rug out from under its feet.
Handle the Cancel Remove and Cancel Stop requests on the way up the stack so that all the lower devices have restarted. However, the Wdm2 driver enables requests straightaway and then passes the IRP down the stack for processing.
Читать дальшеИнтервал:
Закладка:
Похожие книги на «Writing Windows WDM Device Drivers»
Представляем Вашему вниманию похожие книги на «Writing Windows WDM Device Drivers» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.
Обсуждение, отзывы о книге «Writing Windows WDM Device Drivers» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.