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», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

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

Интервал:

Закладка:

Сделать

if (!LockDevice(dx)) return CompleteIrp(Irp, STATUS_DELETE_PENDING, 0);

// …

// Complete IRP

CompleteIrp(Irp,status,BytesTxd);

UnlockDevice(dx);

return status;

}

PnpStopDevice also sets another flag in the device extension, Stopping, to true while it is waiting for all pending I/O to complete. Although not strictly necessary in Wdm2, it is another way of forcing an IRP routine to see if it is OK to start during the call to LockDevice .

Listing 9.11 shows the LockDevice and UnlockDevice routines. They use InterlockedIncrement and InterlockedDecrement calls to ensure that UsageCount is maintained safely in multiprocessor systems. If UnlockDevice finds that UsageCount has decremented to zero, it sets the StoppingEvent flag. LockDevice also checks the Stopping flag. If it is set, a PnP IRP is trying to stop the device and so the caller should not continue. In this case, UsageCount is decremented and StoppingEvent is set, if appropriate, before false is returned.

Listing 9.11 LockDevice and UnlockDevice routines

bool LockDevice(IN PWDM2_DEVICE_EXTENSION dx) {

InterlockedIncrement(&dx->UsageCount);

if (dx->Stopping) {

if (InterlockedDecrement(&dx->UsageCount)==0) KeSetEvent(&dx->StoppingEvent, 0, FALSE);

return false;

}

return true;

}

void UnlockDevice(IN PWDM2_DEVICE_EXTENSION dx) {

LONG UsageCount = InterlockedDecrement(&dx->UsageCount);

if (UsageCount==0) {

DebugPrintMsg("UnlockDevice: setting StoppingEvent flag");

KeSetEvent(&dx->StoppingEvent, 0, FALSE);

}

}

To wrap up the last loose ends, the handlers for the Stop Device and Surprise Removal messages are exactly the same, as shown in Listing 9.12. They both simply call PnpStopDevice and call PnpDefaultHandler to pass the IRP down the stack.

Listing 9.12 Stop device handler

NTSTATUS PnpStopDeviceHandler(IN PDEVICE_OBJECT fdo, IN PIRP Irp) {

DebugPrintMsg("PnpStopDeviceHandler");

PWDM2_DEVICE_EXTENSION dx=(PWDM2_DEVICE_EXTENSI0N)fdo->DeviceExtension;

// Wait for I/O to complete and stop device

PnpStopDevice(dx);

return PnpDefaultHandler(fdo, Irp);

}

W2000 Device Locking

W2000 provides standard routines to replace our LockDevice and UnlockDevice routines, and the associated variables. You must provide an IO_REMOVE_LOCK field in your device extension. Initialise this field using IoInitializeRemoveLock function in your AddDevice routine. Replace all calls to LockDevice with IoAcquireRemoveLock and calls to UnlockDevice with IoReleaseRemoveLock . In the PnpStopDevice routine above, replace the code that waits for all pending I/O to complete with a call to IoReleaseRemoveLockAndWait .

The DDK recommended that you call IoAcquireRemoveLock whenever you pass out a reference to your code, e.g., a timer, DPC, or any other call-back routine. Call IoReleaseRemoveLock when these call-backs are disabled, i.e., usually in your Remove Device handler.

Getting Resource Assignments

A Start Device PnP IRP passes a list of the resources that have been assigned to the device. Although the Wdm2 driver never gets any resources, the code in DeviceIo.cpp goes through the steps to find these out. In addition, there is a lot of commented out code that shows how to use the resources. The WdmIo driver described in Chapters 15-17 show how hardware resources are actually used.

DeviceIo.cpp primarily contains the StartDevice and StopDevice routines. StartDevice must get the list of assigned resources, check that the resources are suitable, allocate them, and do any hardware-related initialization for the driver. If that all goes well, it should set the GotResources flag to true. StopDevice must release any hardware resources and reset the GotResources flag.

StartDevice calls RetrieveResources to find out which resources have been assigned to it by the PnP Configuration Manager. The Start Device PnP message passes two fields in the IRP stack Parameters.StartDevice structure, AllocatedResources, and AllocatedResourcesTranslated. AllocatedResources lists the resources in "raw form". This is how the device itself will see addresses, etc. Use AllocatedResources to program the device itself. Usually the "translated form" of the resource list, AllocatedResourcesTranslated, is of more interest to the driver. Use the AllocatedResourcesTranslated to connect to interrupt vectors, map I/O space, and memory.

If there are no resources assigned, W2000 sets these fields to NULL. In W98, a resource list is allocated but the "partial resource" count is zero.

Table 9.1 shows the raw and translated resource assignments for an I/O Port and two different interrupts in Windows 98 and Windows 2000.

Table 9.1 Resource assignments

I/O Port Address
AllocatedResources 378
AllocatedResourcesTranslated 378
Interrupt (W98) Vector IRQL Affinity Mode
AllocatedResources 7 7 1 Latched
AllocatedResourcesTranslated 37 20 1 Latched
Interrupt (W2000) Vector IRQL Affinity Mode
AllocatedResources 3 3 -1 Latched
AllocatedResourcesTranslated 33 24 1 Latched

Partial Resource Descriptors

A resource list is an array of full resource descriptors. A full resource descriptor has a partial resource list, an array of partial resource descriptors. The relevant structures (CM_RESOURCE_ LIST, CM_FULL_RESOURCE_DESCRIPTOR, CM_PARTIAL_RESOURCE_LIST, and CM_PARTIAL_ RESOURCE_DESCRIPTOR) are also covered in Chapter 18.

WDM drivers have only one full resource descriptor [21] Non-WDM NT style drivers may use more than one full resource descriptor. . Therefore, inspect the array of partial resource descriptors to see what resources have been assigned. The resource descriptors are given in no particular order.

Table 9.2 shows the different types of resource information that can be found in a partial resource descriptor. The Type field specifies what resource is described. There is also a ShareDisposition field that specifies how the resource can be shared. One of the following values can be found: CmResourceShareDeviceExclusive , CmResourceShareDriverExclusive , or CmResourceShareShared .

Table 9.2 Partial resource descriptors

I/O Port (Type==CmResourceTypePort)
PHYSICAL_ADDRESS u.Port.Start Port Bus specific start address
ULONG u.Port.Length Number of addresses
USHORT Flags CM_RESOURCE_PORT_IOor CM_RESOURCE_PORT_MEMORYif you need to map the port into memory with MmMapIoSpace
Memory (Type==CmResourceTypeMemory)
PHYSICAL_ADDRESS u.Memory.Start Bus specific start address
ULONG u.Memory.Length Number of addresses
USHORT Flags CM_RESOURCE_MEMORY_READ_WRITE CM_RESOURCE_MEMORY_READ_ONLY CM_RESOURCE_MEMORY_WRITE_ONLY
Interrupt (Type==CmResourceTypeInterrupt)
ULONG u.Interrupt.Level The interrupt IRQL
ULONG u.Interrupt.Vector The interrupt vector
ULONG u.Interrupt.Affinity The set of processors to which the interrupt is dispatched.
USHORT Flags CM_RESOURCE_INTERRUPT_LEVEL_SENSITIVE CM_RESOURCE_INTERRUPT_LATCHED
DMA (Type==CmResourceTypeDma)
ULONG u.Dma.Channel System DMA controller channel
ULONG u.Dma.Port MCA type device port
USHORT Flags See the DDK
Other resource types
UCHAR Type CmResourceTypeDeviceSpecific CmResourceTypeBusNumber CmResourceTypeDevicePrivateCmResourceTypePcCardConfig

The RetrieveResources code shown in Listing 9.13 extracts and checks the resources that have been assigned for this device. It first checks whether any resources have been assigned. As Wdm2 does not need any resources, it simply returns STATUS_SUCCESS if there are no resources.

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

Интервал:

Закладка:

Сделать

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

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


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

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

x