本代码演示用IoBuildDeviceIoControlRequest向下层存储设备的DeviceObject发送一个代码为
IOCTL_STORAGE_QUERY_PROPERTY的IRP_MJ_DEVICE_IO_CONTROL的Irp获取到存储设备所在的总线类型。
此代码来源于互联网,所有权归原作者所有。
ULONG GetStorageDeviceBusType(IN PDEVICE_OBJECT DeviceObject)
{
PIRP NewIrp;
PSTORAGE_DEVICE_DESCRIPTOR Descriptor;
STORAGE_PROPERTY_QUERY Query;
CHAR Buffer[BUFFER_SIZE];
KEVENT WaitEvent;
NTSTATUS Status;
IO_STATUS_BLOCK IoStatus;
// first set the query properties
Query.PropertyId = StorageDeviceProperty;
Query.QueryType = PropertyStandardQuery;
// initialize the waitable event
KeInitializeEvent(&WaitEvent, NotificationEvent, FALSE);
// we should build the query irp ourselves
NewIrp = IoBuildDeviceIoControlRequest(IOCTL_STORAGE_QUERY_PROPERTY, DeviceObject,
(PVOID)&Query, sizeof(Query), (PVOID)Buffer, NAME_BUFFER_SIZE, FALSE, &WaitEvent,
&IoStatus);
if (NULL == NewIrp) // can't create new irp
{
DbgPrint("[%s] [%u] I can't create a new irp to query the property of device (%p)!/n",
__FILE__, __LINE__, DeviceObject);
return BusTypeUnknown;
}
// send this irp to the storage device
Status = IoCallDriver(DeviceObject, NewIrp);
if (Status == STATUS_PENDING)
{
Status = KeWaitForSingleObject(&WaitEvent, Executive, KernelMode, FALSE, NULL);
Status = IoStatus.Status;
}
if (!NT_SUCCESS(Status))
{
DbgPrint("[%s] [%u] Query IOCTL_STORAGE_QUERY_PROPERTY of device (%p) failed, Status=0x%
08X!/n",
__FILE__, __LINE__, DeviceObject, Status);
return BusTypeUnknown;
}
Descriptor = (PSTORAGE_DEVICE_DESCRIPTOR)Buffer;
return Descriptor->BusType;
}
若本函数返回BusType=3是一般硬盘,BusType=7是USB接口设备。