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», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.
Интервал:
Закладка:
RetrieveResources then goes through the partial resource descriptor list checking for I/O Port, Memory, and Interrupt resource types. The assigned information is stored in the device extension and printed out using DebugPrint . Other resource types result in an error.
Listing 9.13 RetrievereSources routine
NTSTATUS RetrieveResources(IN PWDM2_DEVICE_EXTENSION dx, IN PCM_RESOURCE_LIST AllocatedResourcesTranslated) {
if (AllocatedResourcesTranslated==NULL || AllocatedResourcesTranslated->Count==0) {
DebugPrintMsg("RetrieveResources: No allocated translated resources");
return STATUS_SUCCESS; // or whatever
}
// Get to actual resources
PCM_PARTIAL_RESOURCE_LIST list = &AllocatedResourcesTranslated->List[0].PartialResourceList;
PCM_PARTIAL_RESOURCE_DESCRIPTOR resource = list->PartialDescriptors;
ULONG NumResources = list->Count;
DebugPrint("RetrieveResources: %d resource lists %d resources", AllocatedResourcesTranslated->Count, NumResources);
bool GotError = false;
// Clear dx
dx->GotInterrupt = false;
dx->GotPortOrMemory = false;
dx->PortInIOSpace = false;
dx->PortNeedsMapping = false;
// Go through each allocated resource
for (ULONG i=0; i
switch (resource->Type) {
case CmResourceTypePort:
if (dx->GotPortOrMemory) {
GotError = true;
break;
}
dx->GotPortOrMemory = true;
dx->PortStartAddress = resource->u.Port.Start;
dx->PortLength = resource->u.Port.Length;
dx->PortNeedsMapping = (resource->Flags & CM_RESOURCE_PORT_IO)==0;
dx->PortInIOSpace = !dx->PortNeedsMapping;
DebugPrint("RetrieveResources: Port %x%x Length %d NeedsMapping %c",
dx->PortStartAddress.HighPart, dx->PortStartAddress.LowPart, dx->PortLength, dx->PortNeedsMapping);
break;
case CmResourceTypeInterrupt:
dx->GotInterrupt = true;
dx->Irql = (KIRQL)resource->u.Interrupt.Level;
dx->Vector = resource->u.Interrupt.Vector;
dx->Affinity = resource->u.Interrupt.Affinity;
dx->Mode = (resource->Flags = CM_RESOURCE_INTERRUPT_LATCHED) ? Latched : LevelSensitive;
DebugPrint("RetrieveResources: Interrupt vector %x IRQL %d Affinity %d Mode %d",
dx->Vector, dx->Irql, dx->Affinity, dx->Mode);
break;
case CmResourceTypeMemory:
if (dx->GotPortOrMemory) { GotError = true; break; }
dx->GotPortOrMemory = true;
dx->PortStartAddress = resource->u.Memory.Start;
dx->PortLength = resource->u.Memory.Length;
dx->PortNeedsMapping = true;
DebugPrint("RetrieveResources: Memory %x%x Length %d",
dx->PortStartAddress.HighPart, dx->PortStartAddress.LowPart, dx->PortLength);
break;
case CmResourceTypeDma:
case CmResourceTypeDeviceSpecific:
case CmResourceTypeBusNumber:
default:
DebugPrint("RetrieveResources: Unrecognised resource type %d", resource->Type);
GotFrror = true;
break;
}
}
// Check we've got the resources we need
if (GotError /*|| !GotPortOrMemory || !GotInterrupt*/)
return STATUS_DEVICE_CONFIGURATION_ERROR;
return STATUS_SUCCESS;
}
Allocating Resources
The StartDevice routine now allocates the system resources it requires. The Wdm2 driver does not need or expect any resources, so this code is commented out. The WdmIo driver covered in Chapters 15-17 does use system resources. These chapters cover Critical section routines and Interrupts in detail. However, I will briefly introduce these topics now.
For memory mapped I/O ports (with the CM_RESOURCE_PORT_MEMORY flag bit set) you must call MmMapIoSpace to get a pointer that can be used by a driver. Do not forget to call MmUnmapIoSpace when the device is stopped.
dx->PortBase = (PUCHAR)MmMapIoSpace(dx->PortStartAddress, dx->PortLength, MmNonCached);
For ordinary I/O ports and memory, simply use the low 32 bits of the PortStartAddress [22] Obviously, this may well change in 64-bit systems.
.
dx->PortBase = (PUCHAR)dx->PortStartAddress.LowPart;
For interrupts, IoConnectInterrupt is called to install an interrupt handler. You must be ready to handle an interrupt straightaway, so make sure that everything is set up correctly. It is common to be able to disable interrupts by writing some value to a device register. Write a DisableDeviceInterrupts routine to disable interrupts before calling IoConnectInterrupt and call your EnableDeviceInterrupts routine when you are ready to receive interrupts.
Any code that tries to access some real hardware must synchronize its activities with the interrupt handler. It is no good having an interrupt during a complicated device access procedure. Critical section routines solve this problem. You call KeSynchronizeExecution passing the name of the function you want called. KeSynchronizeExecution raises the IRQL to the correct interrupt level and calls your routine. When it has completed, the IRQL is lowered again. Critical section routines obviously need to be in nonpaged memory and cannot access paged memory.
EnableDeviceInterrupts and DisableDeviceInterrupts are usually Critical section routines and will usually need to be called via KeSynchronizeExecution .
Finally, StartDevice powers up its device, as described in the next chapter.
Port and Memory I/O
There are several standard kernel routines to access I/O ports and memory, as this code snippet shows.
void WriteByte(IN PWDM2_DEVICE_EXTENSION dx, IN ULONG offset, IN UCHAR byte) {
if (dx->PortInIOSpace) WRITE_PORT_UCHAR(dx->PortBase+offset, byte);
else WRITE_REGISTER_UCHAR(dx->PortBase+offset, byte);
}
Read data using the routines with READ in their name and write data with WRITE routines. PORT routines access I/O registers in I/O port space, while REGISTER routines access registers in memory space. Each type has UCHAR, USHORT, and ULONG variants. Finally, BUFFER variants transfer more than one data value. For example, use the following code to read a set of ULONG values from I/O port space into a buffer.
READ_PORT_BUFFER_ULONG( PortBase, Buffer, Count);
As mentioned previously, synchronize all your hardware accesses with any interrupt routines using Critical section routines and KeSynchronizeExecution . Chapter 16 covers Critical section routines.
Device Access
Most WDM drivers do not, in fact, need to access I/O ports and memory or handle interrupts. Instead, they access their devices using the facilities provided by class drivers. For example, a USB client driver uses the oft-mentioned USB Request Blocks (URBs) to access its device.
Читать дальшеИнтервал:
Закладка:
Похожие книги на «Writing Windows WDM Device Drivers»
Представляем Вашему вниманию похожие книги на «Writing Windows WDM Device Drivers» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.
Обсуждение, отзывы о книге «Writing Windows WDM Device Drivers» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.