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: краткое содержание, описание и аннотация

Предлагаем к чтению аннотацию, описание, краткое содержание или предисловие (зависит от того, что написал сам автор книги «Writing Windows WDM Device Drivers»). Если вы не нашли необходимую информацию о книге — напишите в комментариях, мы постараемся отыскать её.

Writing Windows WDM Device Drivers — читать онлайн бесплатно полную книгу (весь текст) целиком

Ниже представлен текст книги, разбитый по страницам. Система сохранения места последней прочитанной страницы, позволяет с удобством читать онлайн бесплатно книгу «Writing Windows WDM Device Drivers», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

UCHAR MajorFunction;

UCHAR MinorFunction;

// …

union {

struct { … } Create;

struct { … } Read;

struct { … } Write;

struct { … } DeviceIoControl;

} Parameters;

// …

} IO_STACK_LOCATION, *PIO_STACK_LOCATION;

The fact that there is an IRP header and several associated I/O stack locations can be a source of confusion. However, the stack locations are a powerful tool for processing IRPs when several layered drivers have to access an IRP in turn.

The I/O stack location contains most of the important information about the IRP. The MajorFunction is the IRP code (e.g., IRP_MJ_READ for a Read IRP). Some IRPs, such as IRP_ MJ_PNP, use the MinorFunction field to specify which particular Plug and Play function is being requested.

Each common IRP type has a struct within the Parameters union in the IO_STACK_LOCATION structure. For example, for Read IRPs, the Parameters.Read.Length field is the number of bytes to transfer. The parameters that are valid for each common IRP are described in the following text.

The key to understanding I/O stack locations is to realize that each driver needs to look at only one, the "current stack location". The information in the IRP header structure and the information in the current stack location are the parameters that a driver uses to process an IRP.

I/O Stack Locations

Let's go off track slightly to ask why Microsoft provides a set of I/O stack locations. If you have a stack of drivers that process an IRP, the highest might be a network protocol driver that can accept read requests of any length. This driver might know that the underlying transport driver can only cope with read transfers of up to 1024 bytes. Its job is to break up long transfers into a series of blocks, each with a maximum size of 1024 bytes. When the protocol driver calls the transport driver it, sets up the next I/O stack location with the transfer size set to 1024. When the transport driver processes the IRP, its current I/O stack location has this value, and it should proceed happily to process the IRP. When it has finished, the IRP is passed back to the protocol driver. This checks that the transfer worked and — assuming it did — sets up the next transfer and calls the transport driver again.

In this approach, the protocol driver sends the transport driver IRPs one by one. However, a more sophisticated protocol driver could allocate new IRPs, enough to move all the data. It could then issue them all to the transport driver. The protocol driver would have to check carefully that all the IRPs finished correctly. When all the data has been moved, one way or another, the protocol driver can finally complete its own original IRP.

This example reveals a problem. The field that contains the pointer to the data to be transferred is not in the I/O stack location, but in the IRP header. The transfer length is in the stack. Surely the data pointer ought to be in there as well. The fact that the original stack location is not changed by the call to the lower driver is good, as it makes it easier for a driver to remember how many bytes to transfer.

However, this reveals another common difficulty with IRPs — determining where to store a driver's own information about an IRP. Suppose the protocol driver wanted to remember something simple (e.g., how many bytes it had sent so far) [15] If the driver processes IRPs one by one, it could store this information in its device extension. .

The ideal place for some storage for drivers would be the I/O stack location. However, there is no space specifically reserved for drivers. Nonetheless, Read IRPs have a ULONG at Parameters.Read.Key in the current I/O stack location that can be used safely, although the DDK does not specifically say so. Write IRPs have a similar ULONG at Parameters.Write.Key.

There is some room in the IRP header that can be used by drivers — a PVOID DriverContext[4] in Tail.Overlay. Use the following code to access the first of these locations.

PVOID p = Irp->Tail.Overlay.DriverContext[0];

However, it is not safe to use these locations for storing context while an IRP is processed by lower drivers, for the simple reason that these other drivers may use this memory too.

The final point to note about I/O stack locations is that you can use different major function code when you call a lower driver. For example, you might implement a read request by sending the lower driver an IOCTL.

Common IRP Parameters

This section lists the parameters that are set for the common IRPs. In the following discussion, "the stack" means the current I/O stack location.

Create IRP, IRP_MJ_CREATE

The main parameter of interest to the Create IRP handler is the FileObject field in the stack. This is a pointer to a _FILE_OBJECT structure. The FileName field in here is a UNICODE_STRING with any characters after the basic device name. If you appended \file to the symbolic link name found in the GetDeviceViaInterface routine in Wdm1Test, \file would appear in FileName. If no characters are appended, FileName has a length of zero.

Other parameters to the Create IRP are given in the Parameters.Create structure in the stack, such as the FileAttributes and ShareAccess.

Close IRP, IRP_MJ_CLOSE

If need be, you can double-check that the FileObject in the IRP header matches the one you were sent in the create request.

If you have queued up Read or Write IRPs for this file, the I/O Manager will have cancelled them before the close request is received. It does this by calling an IRP's Cancel routine and issuing a Cleanup IRP, as described in Chapter 16.

Read IRP, IRP_MJ_READ

The Parameters.Read structure in the IRP stack has Length and ByteOffset fields that say how many bytes are requested and the file pointer. ByteOffset is a 64-bit integer stored in a LARGE_INTEGER structure. The Microsoft compiler can handle this type directly (i.e., Parameters.Read.ByteOffset.Quad Part is an __int64). If you need to specify 64-bit constant values in your code, append i64 to the constant (e.g., 100i64).

The user buffer can be specified in one of two ways, depending on whether your driver uses Buffered I/O or Direct I/O. See the following text for details of these terms. If using Buffered I/O, a pointer to the user buffer is in the IRP header at AssociatedIrp.SystemBuffer. For Direct I/O, a Memory Descriptor List (MDL) is in the IRP header in the MdlAd-dress field.

The Key field in the IRP stack Parameters.Read structure does not seem to be used for anything, and so could be used by a driver for any purpose.

Write IRP, IRP_MJ_WRITE

The parameters for Write IRPs are identical to Read IRPs, except that the relevant parameters are in the stack Parameters.Write structure.

IOCTL IRP, IRP_MJ_DEVICE_CONTROL

The Parameters.DeviceIoControl structure in the IRP stack has IoControlCode, InputBufferLength, and OutputBufferLength parameters.

The user buffer is specified using one or more of the AssociatedIrp.SystemBuffer, MdlAddress, or stack Parameters.DeviceIoControl.Type3InputBuffer fields. See the next section for details.

User Buffers

As a driver can run in the context of any thread, a plain pointer into the user's address space is not guaranteed to access the correct memory.

Читать дальше
Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

Похожие книги на «Writing Windows WDM Device Drivers»

Представляем Вашему вниманию похожие книги на «Writing Windows WDM Device Drivers» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.


Отзывы о книге «Writing Windows WDM Device Drivers»

Обсуждение, отзывы о книге «Writing Windows WDM Device Drivers» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.

x