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», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.
Интервал:
Закладка:
Refer to the previous chapter if you need to remind yourself of the difference between function and filter drivers, and the different types of device objects that the Wdm2 driver deals with.
When a PnP driver handles an AddDevice message, it means that a new device has be found. Either a bus driver has found the device at power on or when it was inserted, or the user has added it by hand from the Control Panel. As Wdm2 devices are virtual, these have to be added by hand.
The PnP Manager will have worked out which drivers are going to be in the stack. The Physical Device Object (PDO) is created by the bus driver first. Then, going up the stack, each driver's AddDevice routine is called in turn. Chapter 11 describes how the PnP Manager works out which drivers to put in the stack.
If a driver's AddDevice routine fails, any drivers below it (whose AddDevice succeeded) will be sent a Remove Device message. Be prepared to accept a Remove Device message straightaway after your AddDevice routine has completed.
The job of an AddDevice routine is to create and initialize a device object for the current driver to use, and to connect it to the device stack. For function drivers, the device object is called a Functional Device Object (FDO). Filter drivers make a Filter Device Object (Filter DO). As mentioned in the last chapter, PDOs, FDOs, and Filter DOs all use the same DEVICE_OBJECT structure. Microsoft recommends that we use different names to help us remember what sort of driver owns the device object.
When a Wdm2 device is added, the Unknown bus driver makes a PDO for it. The PnP Manager passes the PDO to Wdm2. The Wdm2AddDevice routine, shown later, calls IoCreateDevice to create the Wdm2 Functional Device Object and eventually calls IoAttachDeviceToDeviceStack to attach it to the device stack. In between, the FDO and its device extension are initialized and a device interface for it is set up.
The eventual job of the Remove Device message handler is to stop the device and delete the FDO. In Wdm2, PnpRemoveDeviceHandler , shown later, eventually calls IoDetachDevice to detach the device object from the stack and calls IoDeleteDevice to delete the device object and its device extension memory. Processing Remove Device PnP messages safely is, in fact, a bit more complicated than this, as will be shown. Note that a Remove Device request will be the last IRP a driver receives before it is unloaded.
The Wdm1 driver handles adding a device in its AddDevice routine and its Wdm1Pnp routine handles the remove device minor code IRP_MN_REMOVE_DEVICE.
The AddDevice and IRP_MJ_PNP handlers are called at PASSIVE_LEVEL IRQL in the context of a system thread. Calls to these routines may be issued while other IRPs are running in the same driver. Even in a uniprocessor computer, processing of a Read IRP could have stalled for some reason. A PnP call could then be issued.
AddDevice
In the Wdm2 driver, the code for adding and removing devices is substantially the same as Wdm1. The Wdm2AddDevice routine in Listing 9.1 is exactly the same, apart from new lines initializing some extra fields in the device extension. These all relate to handling PnP and Power IRPs correctly and are explained in due course.
Most of the PnP handling code is in the Wdm2 Pnp.cpp module. Some changes have been made to the Dispatch.cpp code from the Wdm1 version. A new module DeviceIo.cpp handles device starting and stopping.
Listing 9.1 Wdm2 Wdm2AddDevice
NTSTATUS Wdm2AddDevice(IN PDRIVER_OBJECT DriverObject, IN PDEVICE_OBJECT pdo) {
DebugPrint("AddDevice");
NTSTATUS status;
PDEVICE_OBJECT fdo;
// Create our Functional Device Object in fdo
status = IoCreateDevice(DriverObject, sizeof(WDM2_DEVICE_EXTENSION), NULL, FILE_DEVICE_UNKNQWN, 0, FALSE, &fdo);
if (NT_ERROR(status)) return status;
// Initialise device extension
PWDM2_DEVICE_EXTENSION dx = (PWDM2_DEVICE_EXTENSION)fdo->DeviceExtension;
dx->fdo = fdo;
dx->pdo = pdo;
dx->UsageCount = 1;
KeInitializeEvent(&dx->StoppingEvent, NotificationEvent, FALSE);
dx->OpenHandleCount = 0;
dx->GotResources = false;
dx->Paused = false;
dx->IODisabled = true;
dx->Stopping = false;
dx->PowerState = PowerDeviceD3;
dx->PowerIdleCounter = NULL;
DebugPrint("FDO is %x",fdo);
// Initialise device power state
POWER_STATE NewState;
NewState.DeviceState = dx->PowerState;
PoSetPowerState(fdo, DevicePowerState, NewState);
// Register and enable our device interface
status = IoRegisterDevicelnterface(pdo, &WDM2_GUID, NULL, &dx->ifSymLinkName);
if (NT_ERROR(status)) {
IoDeleteDevice(fdo);
return status;
}
IoSetDeviceInterfaceState(&dx->ifSymLinkName, TRUE);
DebugPrint("Symbolic Link Name is %T",&dx->ifSymLinkName);
// Attach to the driver stack below us
dx->NextStackDevice = IoAttachDeviceToDeviceStack(fdo.pdo);
// Set fdo flags appropriately
fdo->Flags &= ~DO_DEVICE_INITIALIZING;
fdo->Flags |= DO_BUFFERED_IO;
dx->PowerIdleCounter = PoRegisterDeviceForIdleDetection(pdo, 30, 60, PowerDeviceD3);
return STATUS_SUCCESS;
}
Remove Device handler
The code that handles removing devices has been moved to PnpRemoveDeviceHandler , as shown in Listing 9.2. This is the same as before, apart from calling the PnpStopDevice routine , which is explained in the following text.
Listing 9.2 Wdm2 PnpRemoveDeviceHandler
NTSTATUS PnpRemoveDeviceHandler(IN PDEVICE_OBJECT fdo, IN PIRP Irp) {
PWDM2_DEVICE_EXTENSION dx=(PWDM2_DEVICE_EXTENSION)fdo->DeviceExtension;
DebugPrintMsg("PnpRemoveDeviceHandler");
// Wait for I/O to complete and stop device
PnpStopDevice(dx);
// Pass down stack and carry on immediately
NTSTATUS status = PnpDefaultHandler(fdo, Irp);
// disable device interface
IoSetDeviceInterfaceState(&dx->ifSymLinkName, FALSE);
RtlFreeUnicodeString(&dx->ifSymLinkName);
// unattach from stack if (dx->NextStackDevice)
IoDetachDevice(dx->NextStackDevice);
// delete our fdo
IoDeleteDevice(fdo);
return status;
}
Main PnP IRP Handler
The main IRP_MJ_PNP dispatch routine, Wdm2Pnp , has changed considerably from Wdm1, as shown in Listing 9.3. The bulk of the code is a switch statement based on the PnP minor function code. Most of the interesting minor function handling is delegated to subsidiary routines, but some are handled inline. All other minor function codes are handled by the PnpDefaultHandler routine. The PnpQueryCapabilitiesHandler routine is described in the chapter on Power Management.
Читать дальшеИнтервал:
Закладка:
Похожие книги на «Writing Windows WDM Device Drivers»
Представляем Вашему вниманию похожие книги на «Writing Windows WDM Device Drivers» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.
Обсуждение, отзывы о книге «Writing Windows WDM Device Drivers» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.