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

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

Интервал:

Закладка:

Сделать

ULONG WriteCmdsLen; // length

PUCHAR StartReadCmds; // Stored commands for start read IRP

ULONG StartReadCmdsLen; // length

PUCHAR ReadCmds; // Stored commands for read IRP

ULONG ReadCmdsLen; // length

UCHAR SetTimeout; // Timeout stored from script

int Timeout; // Seconds left to go. –1 if not in force

bool StopTimer; // Set to stop timer

ULONG TxTotal; // R/W total transfer size in bytes

ULONG TxLeft; // R/W bytes left to transfer

PUCHAR TxBuffer; // R/W buffer. Moves through current IRP SystemBuffer

bool TxIsWrite; // R/W direction

NTSTATUS TxStatus; // R/W status return

UCHAR TxResult[5]; // R/W output buffer (2 Failcode, 2 Offset, 1 user)

UCHAR TxLastIntReg; // R/W last interrupt register value

ULONG TxCmdOutputCount; // R/W Copy of last CmdOutputCount

Starting Requests

Listing 17.2 shows how WdmIoStartIo initiates a write request. The device extension TxIsWrite field is set true for writes, and false for reads. TxTotal contains the total number of bytes to transfer. TxLeft stores the number of bytes left to transfer, and so counts from TxTotal down to zero. TxBuffer points to the next byte to transfer in the IRP buffer, so it moves through the buffer as each byte is written. The IRP buffer is always accessible, as long as the IRP is being processed, so there is no need to make a copy of it. The TxStatus field contains the IRP's eventual completion status, which is initially assumed to be successful.

The TxResult array is used to contain the output from running the stored write commands. This 5-byte array is, therefore, zeroed before the write begins in earnest. TxLastIntReg stores the last value read by the interrupt handler from its status register. The contents of TxResult and TxLastIntReg can eventually be obtained using the IOCTL_WDMIO_GET_RW_ RESULTS call, as shown in Listing 15.4.

The "one-second interval" timer is now started to detect time-outs.

WdmIo is now finally ready to output the first data byte by running the stored write data commands. As interrupts have been enabled, they must be run in the context of a Critical Section routine to avoid being interrupted. Listing 17.2 shows how RunWriteCmdsSynch does this job, calling ProcessCmds to run the commands in dx->WriteCmds with the output going to dx->TxResult. If ProcessCmds fails or if there are bytes left to transfer, RunWriteCmdsSynch returns TRUE and WdmIoStartIo completes the Write IRP straight away with status STATUS_UNSUCCESSFUL.

Listing 17.2 also shows the code in ProcessCmds that handles the PHDIO_WRITE_NEXT command. Basically, it retrieves the next byte from TxBuffer and writes it to the Data register. It increments the TxBuffer pointer and decrements the count of bytes left to process, TxLeft.

Listing 17.2 How WdmIoStartIo starts write requests

case IRP_MJ_WRITE:

if (dx->WriteCmds==NULL || !dx->ConnectedToInterrupt) {

status = STATUS_INVALID_DEVICE_REQUEST;

break;

}

// Store transfer details dx->TxIsWrite = true;

dx->TxTotal = IrpStack->Parameters.Write.Length;

dx->TxLeft = dx->TxTotal;

dx->TxBuffer = (PUCHAR)Buffer;

dx->TxStatus = STATUS_SUCCESS;

RtlZeroMemory(dx->TxResult, sizeof(dx->TxResult));

DebugPrint("WdmIoStartIo: Write %d bytes: %*s", dx->TxTotal, dx->TxTotal, dx->TxBuffer);

// Start timeout timer

dx->Timeout = dx->SetTimeout+1;

IoStartTimer(fdo);

// Send first value

if (KeSynchronizeExecution(dx->InterruptObject, (PKSYNCHRONIZE_ROUTINE)RunWriteCmdsSynch, (PVOID)dx)) {

status = STATUS_UNSUCCESSFUL;

break;

}

return;

// …

BOOLEAN RunWriteCmdsSynch(IN PWDMIO_DEVICE_EXTENSION dx) {

if (dx->TxLeft==0) return TRUE;

dx->CmdOutputCount = 0;

BOOLEAN rv = ProcessCmds(dx, dx->WriteCmds, dx->WriteCmds_en, dx->TxResult, sizeof(dx->TxResult), false);

dx->TxCmdOutputCount = dx->CmdOutputCount;

if (!rv) {

dx->TxStatus = STATUS_UNSUCCESSFUL;

return TRUE;

}

return FALSE;

}

//In ProcessCmds…

case PHDIO_WRITE_NEXT:

{

if (dx->Timeout==-1) {

FailCode = PHDIO_CANNOT_RW_NEXT;

goto fail;

}

if (dx->TxLeft==0) {

FailCode = PHDIO_NO_DATA_LEFT_TO_TRANSFER;

goto fail;

}

GetUChar(reg);

WriteByte(dx, reg, *dx->TxBuffer++);

dx->TxLeft--;

break;

}

Read requests are processed in a very similar way. As Chapter 15 mentioned, one set of stored commands, in StartReadCmds, is used to start read requests. A different set, in ReadCmds, is used to process read interrupts. RunStartReadCmdsSynch and RunReadCmdsSynch are run as Critical Section routines to process these two sets of commands. The PHDIO_READ_NEXT command is run in a very similar way to PHDIO_WRITE_NEXT, except that it stores the byte that it reads in the next location in the IRP buffer.

Interrupt Handler

Listing 17.3 shows the interrupt service routine for WdmIo, InterruptHandler . Remember that this is a general-purpose service routine. If the user mode controlling application has set up its control fields or commands wrongly, things could go horribly wrong.

An interrupt handler should complete its job as quickly as possible. It is run at Device IRQL (DIRQL), so do not make DebugPrint calls. Remember that your device could interrupt at any time, not just when you have started a write request.

The first job of an interrupt handler is to see if the interrupt was generated by the correct device. If it was not, the routine should return FALSE as quickly as possible to let any other chained interrupt service routines have their go. Otherwise it should process the interrupt (at the very least, stop the device from interrupting) and return TRUE.

InterruptHandler reads the device register at InterruptReg. As described in Chapter 15, it then ANDs this value with InterruptRegMask and compares it with InterruptRegValue. If they are equal, the interrupt is valid and the handler can continue.

If the device extension Timeout flag is –1, no transfer is in progress and so TRUE is returned straight away. If your device requires further processing to cancel such "spurious" interrupts, you need to amend WdmIo so that it does what you want.

Next, WdmIo's interrupt handler gets the current IRP for this device. I double-check that there is a current IRP and then see if the I/O Manager has signalled that it should be cancelled by setting its Cancel flag.

If the IRP is still in progress, the TxIsWrite flag indicates whether the Read or Write stored commands should be run. The RunWriteCmdsSynch and RunReadCmdsSynch routines return TRUE if the transfer is now complete (i.e., if all the bytes have been transferred or there has been some error).

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

Интервал:

Закладка:

Сделать

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

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


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

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

x