Window系统USB驱动提交URB并超时示例代码
2023-01-12
297
0
Windows系统自带的USB驱动URB会设置一个超时,这个时间大概是5秒钟。
源代码可以参考如下实现:
NTSTATUS
USBAudioCancelCompleteSynch(
IN PDEVICE_OBJECT DeviceObject,
IN PIRP Irp,
IN PKEVENT pKevent
)
{
ASSERT(pKevent);
KeSetEvent(pKevent, 0, FALSE);
return STATUS_MORE_PROCESSING_REQUIRED;
}
NTSTATUS
SubmitUrbToUsbdSynch(PDEVICE_OBJECT pNextDeviceObject, PURB pUrb)
{
NTSTATUS ntStatus, status = STATUS_SUCCESS;
PIRP pIrp;
KEVENT Kevent;
IO_STATUS_BLOCK ioStatus;
PIO_STACK_LOCATION nextStack;
// issue a synchronous request
KeInitializeEvent(&Kevent, NotificationEvent, FALSE);
pIrp = IoBuildDeviceIoControlRequest(
IOCTL_INTERNAL_USB_SUBMIT_URB,
pNextDeviceObject,
NULL,
0,
NULL,
0,
TRUE, /* INTERNAL */
&Kevent,
&ioStatus);
if ( !pIrp ) {
return STATUS_INSUFFICIENT_RESOURCES;
}
IoSetCompletionRoutine(
pIrp,
USBAudioCancelCompleteSynch,
&Kevent,
TRUE,
TRUE,
TRUE
);
// Call the class driver to perform the operation. If the returned status
// is PENDING, wait for the request to complete.
nextStack = IoGetNextIrpStackLocation(pIrp);
ASSERT(nextStack != NULL);
// pass the URB to the USB driver stack
nextStack->Parameters.Others.Argument1 = pUrb;
ntStatus = IoCallDriver(pNextDeviceObject, pIrp );
if (ntStatus == STATUS_PENDING) {
// Irp is pending. we have to wait till completion..
LARGE_INTEGER timeout;
// Specify a timeout of 5 seconds to wait for this call to complete.
//
timeout.QuadPart = -10000 * 5000;
status = KeWaitForSingleObject(&Kevent, Executive, KernelMode, FALSE, &timeout);
if (status == STATUS_TIMEOUT) {
//
// We got it to the IRP before it was completed. We can cancel
// the IRP without fear of losing it, as the completion routine
// won't let go of the IRP until we say so.
//
IoCancelIrp(pIrp);
KeWaitForSingleObject(&Kevent, Executive, KernelMode, FALSE, NULL);
// Return STATUS_TIMEOUT
ioStatus.Status = status;
}
} else {
ioStatus.Status = ntStatus;
}
IoCompleteRequest(pIrp, IO_NO_INCREMENT);
ntStatus = ioStatus.Status;
return ntStatus;
}
HID人机交互QQ群:564808376
UAC音频QQ群:218581009
UVC相机QQ群:331552032
BOT&UASP大容量存储QQ群:258159197
STC-USB单片机QQ群:315457461
USB技术交流QQ群2:580684376
USB技术交流QQ群:952873936