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», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.
Интервал:
Закладка:
dx->UsageCount = 1;
KeInitializeEvent(&dx->StoppingEvent, NotificationEvent, FALSE);
dx->Stopping = false;
dx->GotPortOrMemory = false;
dx->GotInterrupt = false;
dx->ConnectedToInterrupt = false;
dx->SetTimeout = 10;
dx->Timeout = –1;
dx->StopTimer = false;
dx->WriteCmds = NULL;
dx->ReadCmds = NULL;
dx->StartReadCmds = NULL;
// Initialise timer for this device (but do not start)
status = IoInitializeTimer(phddo, (PIO_TIMER_ROUTINE)Timeout1s, dx);
if (!NT_SUCCESS(status)) {
DebugPrintMsg("Could not initialise timer");
IoDeleteDevice(phddo);
return status;
}
// Create a symbolic link so our device is visible to Win32…
DebugPrint("Creating symbolic link %T", &linkName);
status = IoCreateSymbolicLink(&linkName, &deviceName);
if (!NT_SUCCESS(status)) {
DebugPrintMsg("Could not create symbolic link");
IoDeleteDevice(phddo);
return status;
}
// Initialise our DPC for IRQ completion processing
IoInitializeDpcRequest(phddo, PHDIoDpcForIsr);
return status;
}
When PHDIo is unloaded, its PHDIoUnload routine is called. This runs PHDIoDeleteDevice to stop the PHDIo device, remove its symbolic link, and delete its device object.
If a driver makes a variable number of devices, the unload routine could use the following technique to find all the devices to remove. The kernel sets the driver object DeviceObject field to point to the first device that belongs to the driver. The NextDevice field in each device object points to the next device. It is, therefore, a simple task to traverse this chain of device objects and delete them. The only catch is that you still have to generate the correct symbolic link name for each device so the symbolic link can be removed.
Claiming Resources
This section looks at how to allocate resources. The crucial kernel function is IoReportResourceUsage . This checks to see if any other devices are using the resources. If the resources are free, they are reserved so no other device can use them.
The PHDIo driver only finds out which resources are needed when the user calls CreateFile , passing the resource description in the filename string. The Create IRP arrives in the PHDIoCreate routine. All the previous Create IRP handlers have not done very much. However, PHDIoCreate has these jobs to do.
1. Get the resource details from the filename.
2. Check for resource conflicts and reserve the resources.
3. Translate and map the resources.
Getting the resource details is handled by the GetResourcesFromFilename routine. I will not go into the details of this code here, apart from saying that it uses three support routines that work with the UNICODE_STRING structure: usStrCmpN, usGetHex, and usGetDec. In the end, the GotPortOrMemory device extension field is true if an I/O port specifier has been found, GotInterrupt is true if an interrupt has been found and ResourceOverride is true if the \override specifier was used.
PHDIoCreate checks that an I/O port was specified. It then calls ClaimResources to check for resource conflicts and reserve the resources. Finally, TranslateAndMapResources is used to translate resource information and map memory. PHDIoCreate carefully ensures that all the resource bool fields are reset to false at the fail label if any error occurs.
Listing 18.2 PHDIoCreate routine
NTSTATUS PHDIoCreate(IN PDEVICE_OBJECT phddo, IN PIRP Irp) {
PPHDIO_DEVICE_EXTENSION dx = (PPHDIO_DEVICE_EXTENSION)phddo->DeviceExtension;
PIO_STACK_LOCATION IrpStack = IoGetCurrentIrpStackLocation(Irp);
DebugPrint("Create File is %T", &(IrpStack->FileObject->FileName));
dx->GotPortOrMemory = false;
dx->GotInterrupt = false;
dx->PortNeedsMapping = false;
dx->ConnectedToInterrupt = false;
dx->ResourceOverride = FALSE;
// Get resources from filename string
PUNICODE_STRING usfilename = &(IrpStack->FileObject->FileName);
NTSTATUS status = *(usfilename,dx);
if (!NT_SUCCESS(status)) goto fail;
// We must have IO port resource
if (!dx->GotPortOrMemory) {
DebugPrintMsg("No IO Port resource in filename");
status = STATUS_INVALID_PARAMETER:
goto fail;
}
// Claim resources
status = ClaimResources(phddo);
if (!NT_SUCCESS(status)) {
DebugPrintMsg("Could not ClaimResources");
goto fail;
}
// Translate and map resources
status = TranslateAndMapResources(phddo);
if (!NT_SUCCESS(status)) {
UnclaimResources(phddo);
goto fail;
}
// Complete
return CompleteIrp(Irp,status);
// On error, make sure everything's off fail:
dx->GotPortOrMemory = false;
dx->GotInterrupt = false;
dx->PortNeedsMapping = false;
dx->ConnectedToInterrupt = false;
return CompleteIrp(Irp,status);
}
Claiming resources means working with Full and Partial Resource Descriptors. Chapter 9 showed that a device's resource assignments are given in these structures when the Plug and Play Start Device is received. The WdmIo driver obtains its resource assignments in this way.
NT style drivers have to build a resource list of these descriptors to pass to the IoReportResourceUsage routine. Note carefully that the raw resource details must be passed to IoReportResourceUsage , not the translated values. The kernel resource list structures are sufficiently intricate that it is worth showing them in Listing 1 8.3.
A resource list consists of one Full Resource Descriptor for each bus instance. Note carefully that this is an expandable structure. Although it is declared with only one Full Resource Descriptor, it may in fact contain one or more such descriptors.
A Full Resource Descriptor specifies the bus type and instance number. It also contains a Partial Resource List structure.
A Partial Resource List primarily contains an array of Partial Resource Descriptors. Again, note that a Partial Resource List is a structure that expands as more Partial Resource Descriptors are used.
A Partial Resource Descriptor finally contains the details of an individual resource. Table 9.2 in Chapter 9 gives full details of Partial Resource Descriptors.
Listing 18.3 Kernel resource list structures
typedef struct _CM_RESOURCE_LIST {
ULONG Count;
CM_FULL_RESOURCE_DESCRIPTOR List[1];
} CM_RESOURCE_LIST, *PCM_RESOURCE_LIST;
typedef struct _CM_FULL_RESOURCE_DESCRIPTOR {
Интервал:
Закладка:
Похожие книги на «Writing Windows WDM Device Drivers»
Представляем Вашему вниманию похожие книги на «Writing Windows WDM Device Drivers» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.
Обсуждение, отзывы о книге «Writing Windows WDM Device Drivers» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.