// 2003.09.08, 2003.12.28, 2004.10.15, 2004.12.05, 2004.12.10, 2005.01.20, 2005.02.23, 2005.07.15, 2005.08.17, 2005.08.23, 2005.12.15, 2009.06.05, 2011,02.22
//****************************************
//**  Copyright  (C)  W.ch  1999-2011   **
//**  Web:  http://www.winchiphead.com  **
//****************************************
//**  WDM for USB interface chip CH375  **
//**  C, VC5.0, Windows 98 DDK          **
//****************************************
//
// USB总线接口芯片CH375的WDM驱动程序   V2.6
// 南京沁恒电子有限公司       http://wch.cn
// CH375-WDM  V2.7, Support: Ctrl/Bulk/Int
// 运行环境: Windows 98/ME, Windows 2000/XP/VISTA/7/SERVER2003/SERVER2008
// support USB chip: CH372/CH375
//


#define		mTHIS_VERSION			0x26		// 当前版本
#define		mTHIS_VER_STR			"2.6"		// 当前版本字符串

#include	<wdm.h>
#include	<usbdi.h>
#include	<usbdlib.h>


#include	"CH375WDM.H"

typedef	struct	_LINK_URB_BUF {
	struct	_LINK_URB_BUF	*mNext;
	URB					mUrb;
	KEVENT				mEvent;
	IO_STATUS_BLOCK		mIoStatusBlock;
	NTSTATUS			mStatus;
	ULONG				mLength;
	UCHAR				mBuffer[ mCH375_PACKET_LENGTH * 2 ];
} mLINK_URB_BUF, *mPLINK_URB_BUF;

#define		mTHREAD_MAX_LINK		10

typedef	struct	_DEVICE_EXTENSION {				// 定义设备扩展结构
	UNICODE_STRING		mExtDeviceName;			// 设备名称
	PDEVICE_OBJECT		mExtPhysicalTarget;		// 物理设备对象指针
	PDEVICE_OBJECT		mExtNextLowerDevice;	// 下级设备对象指针
	USBD_PIPE_HANDLE	mExtInterUpPipe;		// USB中断数据上传管道的句柄
	USBD_PIPE_HANDLE	mExtAuxDownPipe;		// USB辅助数据下传管道的句柄
	USBD_PIPE_HANDLE	mExtDataDownPipe;		// USB数据块下传管道的句柄
	USBD_PIPE_HANDLE	mExtDataUpPipe;			// USB数据块上传管道的句柄
	ULONG				mExtIoCount;			// 计数正在进行的操作,以阻止操作中途停止或者移除设备
	ULONG				mExtDeviceOpen;			// 指示设备被打开的次数
	BOOLEAN				mExtDeviceStart;		// 指示设备启动状态
	BOOLEAN				mExtDeviceRemove;		// 指示设备移除状态
	BOOLEAN				mExtDeviceExclusive;	// 指示设备是否独占使用
	ULONG				mExtInterTimeout;		// USB中断数据上传管道的通讯超时
	ULONG				mExtAuxTimeout;			// USB辅助数据下传管道的通讯超时
	ULONG				mExtDownTimeout;		// USB数据块下传管道的通讯超时
	ULONG				mExtUpTimeout;			// USB数据块上传管道的通讯超时
	LARGE_INTEGER		mExtInterWaitTime;
	LARGE_INTEGER		mExtAuxWaitTime;
	LARGE_INTEGER		mExtDownWaitTime;
	LARGE_INTEGER		mExtUpWaitTime;
	KEVENT				mExtThreadToutEvent;
	ULONG				mExtUsbInterCount;
	ULONG				mExtUsbAuxCount;
	ULONG				mExtUsbUpCount;
	ULONG				mExtUsbDownCount;
	LARGE_INTEGER		mExtInterStartTime;
	LARGE_INTEGER		mExtAuxStartTime;
	LARGE_INTEGER		mExtDownStartTime;
	LARGE_INTEGER		mExtUpStartTime;
	PURB				mExtUrbBuffer;			// 指向URB
	URB					mExtPublicUrb;			// 公用URB
	KSPIN_LOCK			mControlLock;
	KEVENT				ThreadStartEvent;
	ULONG				ThreadUsbCount;
	PUCHAR				ThreadBuffer;
	mPLINK_URB_BUF		ThreadQueueFree;
	mPLINK_URB_BUF		ThreadQueueWait;
	ULONG				ThreadBufSize;
	PUCHAR				ThreadInStart;
	PUCHAR				ThreadOutStart;
	ULONG				ThreadInSize;
	KSPIN_LOCK			mControlLockDn;
	KEVENT				DnThreadStartEvent;
	ULONG				DnThreadUsbCount;
	PUCHAR				DnThreadBuffer;
	mPLINK_URB_BUF		DnThreadQueueFree;
	mPLINK_URB_BUF		DnThreadQueueWait;
	ULONG				DnThreadBufSize;
	PUCHAR				DnThreadInStart;
	PUCHAR				DnThreadOutStart;
	ULONG				DnThreadInSize;
	ULONG				mPowerState;
	PIRP				mDevPowerIrp;
	ULONG				mOnDevExist;			// 指示正在调用检查设备存在的子程序
	BOOLEAN				mDeviceGone;		// 指示设备是否存在
	ULONG				mThreadCount;
	KEVENT				ThreadPowerEvent;
} mDEVICE_EXTENSION, *mPDEVICE_EXTENSION;

#define		IO_CH375_INCREMENT		5			// CH375操作后的优先级增量


// 驱动程序说明
UCHAR			mDescription[128] = " CH375 WDM V" mTHIS_VER_STR " "
									" Author : W.ch  "
									"HX.S065  2003.12\xd\xa"
									" www.wch99.com  \xd\xa"
									" Copyright (C) W.ch 1999-2005 \xd\xa\x0";

PDRIVER_OBJECT	mDriverObject = NULL;			// 驱动程序对象,无效则指示系统线程终止


// 子程序说明


NTSTATUS		DriverEntry( PDRIVER_OBJECT iDriverObject, PUNICODE_STRING iRegistryPath );
VOID			mDriverUnload( PDRIVER_OBJECT iDriverObject );
NTSTATUS		mAddDevice( PDRIVER_OBJECT iDriverObject, PDEVICE_OBJECT iPhysicalDeviceObject );
VOID			mRemoveDevice( PDEVICE_OBJECT iDeviceObject );
NTSTATUS		mDispatchCreate( PDEVICE_OBJECT iDeviceObject, PIRP iIrp );
NTSTATUS		mDispatchClose( PDEVICE_OBJECT iDeviceObject, PIRP iIrp );
NTSTATUS		mPipeInterCompletion( PDEVICE_OBJECT iDeviceObject, PIRP iIrp, PVOID iContext );
NTSTATUS		mPipeAuxCompletion( PDEVICE_OBJECT iDeviceObject, PIRP iIrp, PVOID iContext );
NTSTATUS		mPipeUpCompletion( PDEVICE_OBJECT iDeviceObject, PIRP iIrp, PVOID iContext );
NTSTATUS		mPipeDownCompletion( PDEVICE_OBJECT iDeviceObject, PIRP iIrp, PVOID iContext );
NTSTATUS		mDispatchDeviceControl( PDEVICE_OBJECT iDeviceObject, PIRP iIrp );
NTSTATUS		mRequestPipe( PDEVICE_OBJECT iDeviceObject, USHORT iFunction, ULONG iPipe );
VOID			mCancelCurrentInter( PDEVICE_OBJECT iDeviceObject, PIRP iIrp );
VOID			mCancelCurrentAux( PDEVICE_OBJECT iDeviceObject, PIRP iIrp );
VOID			mCancelCurrentUp( PDEVICE_OBJECT iDeviceObject, PIRP iIrp );
VOID			mCancelCurrentDown( PDEVICE_OBJECT iDeviceObject, PIRP iIrp );
NTSTATUS		mDispatchCleanup( PDEVICE_OBJECT iDeviceObject, PIRP iIrp );
NTSTATUS		mDispatchPower( PDEVICE_OBJECT iDeviceObject, PIRP iIrp );
NTSTATUS		mSysPwrCompletRoutine( PDEVICE_OBJECT iDeviceObject, PIRP iIrp, PPOWER_STATE iPowerState );
VOID			mSysPwrReqCompletion( PDEVICE_OBJECT iDeviceObject, UCHAR iMinorFunction, POWER_STATE iPowerState, PIRP iIrp, PIO_STATUS_BLOCK iIoStatus );
NTSTATUS		mDevPwrCompletRoutine( PDEVICE_OBJECT iDeviceObject, PIRP iIrp, PVOID iContext );
VOID			mThreadDevPower( PVOID iContext );
NTSTATUS		mDispatchSystemControl( PDEVICE_OBJECT iDeviceObject, PIRP iIrp );
NTSTATUS		mDispatchPnp( PDEVICE_OBJECT iDeviceObject, PIRP iIrp );
NTSTATUS		mWaitCompletion( PDEVICE_OBJECT iDeviceObject, PIRP iIrp );
NTSTATUS		mCompletionRoutine( PDEVICE_OBJECT iDeviceObject, PIRP iIrp, PVOID iContext );
NTSTATUS		mActiveConfig( PDEVICE_OBJECT iDeviceObject, PIRP iIrp );
NTSTATUS		mDeactiveConfig( PDEVICE_OBJECT iDeviceObject, PIRP iIrp );
NTSTATUS		mUsbSubmitUrb( PDEVICE_OBJECT iDeviceObject, PURB iUrb );
BOOLEAN			mIsDeviceExist( PDEVICE_OBJECT iDeviceObject, NTSTATUS iStatus );
VOID			mAbortAsyncRead( PDEVICE_OBJECT iDeviceObject );
VOID			mThreadRead( PVOID iContext );
NTSTATUS		mExitThreadRead( PDEVICE_OBJECT iDeviceObject );
NTSTATUS		mGetBufferData( PDEVICE_OBJECT iDeviceObject, PUCHAR oBuffer, PULONG ioLength );
VOID			mClearUpBufferData( PDEVICE_OBJECT iDeviceObject );
VOID			mAbortAsyncWrite( PDEVICE_OBJECT iDeviceObject );
VOID			mThreadWrite( PVOID iContext );
NTSTATUS		mExitThreadWrite( PDEVICE_OBJECT iDeviceObject );
NTSTATUS		mPutBufferData( PDEVICE_OBJECT iDeviceObject, PUCHAR iBuffer, ULONG iLength );
VOID			mClearDnBufferData( PDEVICE_OBJECT iDeviceObject );
NTSTATUS		mResetUsbDevice( PDEVICE_OBJECT iDeviceObject );
VOID			mThreadTimeout( PVOID iContext );
VOID			mDelay20mS( void );


// 初始化完成后可丢弃的代码
#ifdef		ALLOC_PRAGMA
#pragma		alloc_text( INIT, DriverEntry )
#endif


NTSTATUS	DriverEntry(  // 驱动程序初始化入口
	PDRIVER_OBJECT	iDriverObject,  // 驱动程序对象
	PUNICODE_STRING	iRegistryPath )
{
	mDriverObject = iDriverObject;  // 保存驱动程序对象
//	while ( mDriverObject );  // 调试
	iDriverObject -> MajorFunction[ IRP_MJ_CREATE ] = mDispatchCreate;  // 创建或者打开设备
	iDriverObject -> MajorFunction[ IRP_MJ_CLOSE ] = mDispatchClose;  // 关闭设备
	iDriverObject -> MajorFunction[ IRP_MJ_DEVICE_CONTROL ] = mDispatchDeviceControl;  // 设备控制
	iDriverObject -> MajorFunction[ IRP_MJ_CLEANUP ] = mDispatchCleanup;  // 取消操作
	iDriverObject -> MajorFunction[ IRP_MJ_POWER ] = mDispatchPower;  // 电源管理
	iDriverObject -> MajorFunction[ IRP_MJ_SYSTEM_CONTROL ] = mDispatchSystemControl;  // 系统WMI接口
	iDriverObject -> MajorFunction[ IRP_MJ_PNP ] = mDispatchPnp;  // 设备PnP操作
	iDriverObject -> DriverUnload = mDriverUnload;  // 卸载驱动程序
	iDriverObject -> DriverExtension -> AddDevice = mAddDevice;  // 检测到新硬件设备
	return( STATUS_SUCCESS );
}

VOID		mDriverUnload(  // 卸载驱动程序
	PDRIVER_OBJECT	iDriverObject )
{
//	mDelay20mS( );
	mDriverObject = NULL;  // 清除驱动程序对象,指示系统线程终止
}

NTSTATUS	mAddDevice(  // 添加新设备的PnP例程
	PDRIVER_OBJECT	iDriverObject,  // 驱动程序对象
	PDEVICE_OBJECT	iPhysicalDeviceObject )
{
	PDEVICE_OBJECT		mDeviceObject = NULL;
	mPDEVICE_EXTENSION	mDeviceExtension;
	HANDLE				mThreadHandle;
	NTSTATUS			mStatus = STATUS_INSUFFICIENT_RESOURCES;
	__try {  // 确保退出前的处理
		mStatus = IoCreateDevice( iDriverObject, sizeof( mDEVICE_EXTENSION ), NULL,  // 创建设备对象
								  FILE_DEVICE_UNKNOWN, 0, FALSE, &mDeviceObject );  // 返回的设备对象
		if ( ! NT_SUCCESS( mStatus ) ) __leave;  // 创建设备失败
		mDeviceExtension = mDeviceObject -> DeviceExtension;  // 设备扩展指针
		RtlZeroMemory( mDeviceExtension, sizeof( mDEVICE_EXTENSION ) );  // 清除内存
		mDeviceExtension -> mExtPhysicalTarget = iPhysicalDeviceObject;  // 物理设备的功能设备对象
		mDeviceExtension -> mExtIoCount = 0;  // 清操作计数
		mDeviceExtension -> mExtUsbInterCount = 0;  // 清操作计数
		mDeviceExtension -> mExtUsbAuxCount = 0;  // 清操作计数
		mDeviceExtension -> mExtUsbUpCount = 0;  // 清操作计数
		mDeviceExtension -> mExtUsbDownCount = 0;  // 清操作计数
		mDeviceExtension -> mExtDeviceOpen = 0;  // 清除设备打开标志
		mDeviceExtension -> mExtDeviceStart = FALSE;  // 清除设备启动标志
		mDeviceExtension -> mExtDeviceRemove = FALSE;  // 清除设备移除标志
		mDeviceExtension -> mExtDeviceExclusive = FALSE;  // 设备共享使用
		mDeviceExtension -> mPowerState = PowerDeviceD0;
		mDeviceExtension -> mDeviceGone = FALSE;
		mDeviceExtension -> mOnDevExist = 0;
		mDeviceExtension -> mThreadCount = 0;
		KeInitializeEvent( & mDeviceExtension -> ThreadPowerEvent, SynchronizationEvent, FALSE );
		KeInitializeEvent( & mDeviceExtension -> mExtThreadToutEvent, SynchronizationEvent, FALSE );
		KeInitializeEvent( & mDeviceExtension -> ThreadStartEvent, SynchronizationEvent, FALSE );
		KeInitializeEvent( & mDeviceExtension -> DnThreadStartEvent, SynchronizationEvent, FALSE );
		KeInitializeSpinLock( & mDeviceExtension -> mControlLock );
		KeInitializeSpinLock( & mDeviceExtension -> mControlLockDn );
		mDeviceExtension -> mExtInterTimeout = 0xFFFFFFFF;  // USB中断数据上传管道的通讯超时
		mDeviceExtension -> mExtAuxTimeout = 2000;  // USB辅助数据下传管道的通讯超时
		mDeviceExtension -> mExtAuxWaitTime.QuadPart = (LONGLONG)( mDeviceExtension -> mExtAuxTimeout ) * -10000;  // 计算超时
		mDeviceExtension -> mExtDownTimeout = 0xFFFFFFFF;  // USB数据块下传管道的通讯超时
		mDeviceExtension -> mExtUpTimeout = 0xFFFFFFFF;  // USB数据块上传管道的通讯超时
		mDeviceExtension -> mExtUrbBuffer = & mDeviceExtension -> mExtPublicUrb;  // 公用URB
		mDeviceExtension -> mExtNextLowerDevice = IoAttachDeviceToDeviceStack( mDeviceObject,  // 挂接设备栈,返回下级设备
																			   iPhysicalDeviceObject );  // 指向物理对象
		if ( mDeviceExtension -> mExtNextLowerDevice == NULL ) {  // 挂接设备栈失败
			mStatus = STATUS_UNSUCCESSFUL;  // 返回错误信息
			__leave;
		}
		mStatus = IoRegisterDeviceInterface( iPhysicalDeviceObject, &CH375Guid,  // 注册设备接口
											 NULL, & mDeviceExtension -> mExtDeviceName );  // 保存符号链接名称
		mDeviceObject -> Flags |= DO_BUFFERED_IO | DO_POWER_PAGABLE;  // 缓冲IO,指示代码可能在分页内存中
		mDeviceObject -> Flags &= ~DO_DEVICE_INITIALIZING;  // 初始化完成
		PsCreateSystemThread( &mThreadHandle, 0, NULL, NULL, NULL, mThreadTimeout, mDeviceObject );  // 新建系统线程
		ZwClose( mThreadHandle );  // 关闭句柄
		PsCreateSystemThread( &mThreadHandle, 0, NULL, NULL, NULL, mThreadDevPower, mDeviceObject );  // 新建系统线程
		ZwClose( mThreadHandle );  // 关闭句柄
	}
	__finally {  // 退出前的处理
		if ( ! NT_SUCCESS( mStatus ) ) {  // 初始化失败
			mRemoveDevice( mDeviceObject );  // 移除设备
		}
	}
	return( STATUS_SUCCESS );
}

VOID		mRemoveDevice(  // 移除设备
	PDEVICE_OBJECT	iDeviceObject )
{
	ULONG				mDeviceInstance;
	mPDEVICE_EXTENSION	mDeviceExtension;
	if ( iDeviceObject == NULL ) return;  // 设备对象无效
	mDeviceExtension = iDeviceObject -> DeviceExtension;  // 设备扩展
	if ( mDeviceExtension -> mExtDeviceName.Buffer != NULL ) {  // 已经注册设备接口
		IoSetDeviceInterfaceState( & mDeviceExtension -> mExtDeviceName, FALSE );  // 禁用设备接口
		RtlFreeUnicodeString( & mDeviceExtension -> mExtDeviceName );  // 释放设备名称缓冲区
		mDeviceExtension -> mExtDeviceName.Buffer = NULL;
	}
	while ( mDeviceExtension -> mThreadCount ) {
		KeSetEvent( & mDeviceExtension -> mExtThreadToutEvent, IO_CH375_INCREMENT, FALSE );  // 置线程启动事件
		KeSetEvent( & mDeviceExtension -> ThreadPowerEvent, IO_CH375_INCREMENT, FALSE );  // 置线程启动事件
		mDelay20mS( );
	}
	if ( mDeviceExtension -> mExtNextLowerDevice != NULL ) {  // 已经挂接到设备栈
		IoDetachDevice( mDeviceExtension -> mExtNextLowerDevice );  // 撤出设备栈
		mDeviceExtension -> mExtNextLowerDevice = NULL;
	}
	IoDeleteDevice( iDeviceObject );  // 删除设备对象
}

NTSTATUS	mDispatchCreate(  // 新建或者打开
	PDEVICE_OBJECT	iDeviceObject,
	PIRP			iIrp )
{
	ULONG	mCount;
	mPDEVICE_EXTENSION	mDeviceExtension = iDeviceObject -> DeviceExtension;  // 设备扩展
	iIrp -> IoStatus.Information = 0;
	mCount = InterlockedIncrement( & mDeviceExtension -> mExtDeviceOpen );  // 打开计数增量
	if ( mDeviceExtension -> mExtDeviceExclusive && mCount > 1 ) {  // 设备独占使用
		InterlockedDecrement( & mDeviceExtension -> mExtDeviceOpen );  // 打开计数减量
		iIrp -> IoStatus.Status = STATUS_ACCESS_DENIED;  // 返回操作状态
		IoCompleteRequest( iIrp, IO_NO_INCREMENT );  // 完成请求
		return( STATUS_ACCESS_DENIED );  // 返回状态
	}
	iIrp -> IoStatus.Status = STATUS_SUCCESS;  // 返回操作状态
	KeSetEvent( & mDeviceExtension -> mExtThreadToutEvent, EVENT_INCREMENT, FALSE );  // 置线程启动事件
	KeSetEvent( & mDeviceExtension -> ThreadStartEvent, EVENT_INCREMENT, FALSE );  // 置线程启动事件
	KeSetEvent( & mDeviceExtension -> DnThreadStartEvent, EVENT_INCREMENT, FALSE );  // 置线程启动事件
	IoCompleteRequest( iIrp, IO_NO_INCREMENT );  // 完成请求
	return( STATUS_SUCCESS );  // 返回状态
}

NTSTATUS	mDispatchClose(  // 关闭
	PDEVICE_OBJECT	iDeviceObject,
	PIRP			iIrp )
{
	mPDEVICE_EXTENSION	mDeviceExtension = iDeviceObject -> DeviceExtension;  // 设备扩展
	if ( mDeviceExtension -> mExtDeviceOpen ) InterlockedDecrement( & mDeviceExtension -> mExtDeviceOpen );  // 关闭则打开计数减量
	iIrp -> IoStatus.Status = STATUS_SUCCESS;  // 返回操作状态
	iIrp -> IoStatus.Information = 0;
	IoCompleteRequest( iIrp, IO_NO_INCREMENT );  // 完成请求
	return( STATUS_SUCCESS );  // 返回状态
}

NTSTATUS	mPipeInterCompletion(
	PDEVICE_OBJECT	iDeviceObject,
	PIRP			iIrp,
	PVOID			iContext )
{
	NTSTATUS			mStatus;
	PURB				mUrb;
	mPWIN32_COMMAND		mWin32Command;
	mPDEVICE_EXTENSION	mDeviceExtension = iDeviceObject -> DeviceExtension;  // 设备扩展
	mUrb = iContext;
	if ( iIrp -> IoStatus.Status == STATUS_CANCELLED ) iIrp -> IoStatus.Status = STATUS_TIMEOUT;  // 被取消
	mStatus = iIrp -> IoStatus.Status;
	mWin32Command = iIrp -> AssociatedIrp.SystemBuffer;  // 命令缓冲区
	mWin32Command -> mStatus = mStatus;  // 返回操作状态
	mWin32Command -> mLength = mUrb -> UrbBulkOrInterruptTransfer.TransferBufferLength;  // 实际传输长度
	if ( mUrb == & mDeviceExtension -> mExtPublicUrb ) mDeviceExtension -> mExtUrbBuffer = mUrb;
	else ExFreePool( mUrb );  // 释放内存
	if ( NT_SUCCESS( mStatus ) ) iIrp -> IoStatus.Information = mWin32Command -> mLength + mWIN32_COMMAND_HEAD;  // 加上头部长度得返回数据的总长度
	if ( InterlockedDecrement( & mDeviceExtension -> mExtUsbInterCount ) == 0 ) mDeviceExtension -> mExtInterStartTime.QuadPart = 0;  // 清超时
	InterlockedDecrement( & mDeviceExtension -> mExtIoCount );  // 操作计数减量
	return( mStatus );
}

NTSTATUS	mPipeAuxCompletion(
	PDEVICE_OBJECT	iDeviceObject,
	PIRP			iIrp,
	PVOID			iContext )
{
	NTSTATUS			mStatus;
	PURB				mUrb;
	mPWIN32_COMMAND		mWin32Command;
	mPDEVICE_EXTENSION	mDeviceExtension = iDeviceObject -> DeviceExtension;  // 设备扩展
	mUrb = iContext;
	if ( iIrp -> IoStatus.Status == STATUS_CANCELLED ) iIrp -> IoStatus.Status = STATUS_TIMEOUT;  // 被取消
	mStatus = iIrp -> IoStatus.Status;
	mWin32Command = iIrp -> AssociatedIrp.SystemBuffer;  // 命令缓冲区
	mWin32Command -> mStatus = mStatus;  // 返回操作状态
	mWin32Command -> mLength = mUrb -> UrbBulkOrInterruptTransfer.TransferBufferLength;  // 实际传输长度
	if ( mUrb == & mDeviceExtension -> mExtPublicUrb ) mDeviceExtension -> mExtUrbBuffer = mUrb;
	else ExFreePool( mUrb );  // 释放内存
	if ( NT_SUCCESS( mStatus ) ) iIrp -> IoStatus.Information = mWin32Command -> mLength + mWIN32_COMMAND_HEAD;  // 加上头部长度得返回数据的总长度
	if ( InterlockedDecrement( & mDeviceExtension -> mExtUsbAuxCount ) == 0 ) mDeviceExtension -> mExtAuxStartTime.QuadPart = 0;  // 清超时
	InterlockedDecrement( & mDeviceExtension -> mExtIoCount );  // 操作计数减量
	return( mStatus );
}

NTSTATUS	mPipeUpCompletion(
	PDEVICE_OBJECT	iDeviceObject,
	PIRP			iIrp,
	PVOID			iContext )
{
	NTSTATUS			mStatus;
	PURB				mUrb;
	mPWIN32_COMMAND		mWin32Command;
	mPDEVICE_EXTENSION	mDeviceExtension = iDeviceObject -> DeviceExtension;  // 设备扩展
	mUrb = iContext;
	if ( iIrp -> IoStatus.Status == STATUS_CANCELLED ) iIrp -> IoStatus.Status = STATUS_TIMEOUT;  // 被取消
	mStatus = iIrp -> IoStatus.Status;
	mWin32Command = iIrp -> AssociatedIrp.SystemBuffer;  // 命令缓冲区
	mWin32Command -> mStatus = mStatus;  // 返回操作状态
	mWin32Command -> mLength = mUrb -> UrbBulkOrInterruptTransfer.TransferBufferLength;  // 实际传输长度
	if ( mUrb == & mDeviceExtension -> mExtPublicUrb ) mDeviceExtension -> mExtUrbBuffer = mUrb;
	else ExFreePool( mUrb );  // 释放内存
	if ( NT_SUCCESS( mStatus ) ) iIrp -> IoStatus.Information = mWin32Command -> mLength + mWIN32_COMMAND_HEAD;  // 加上头部长度得返回数据的总长度
	if ( InterlockedDecrement( & mDeviceExtension -> mExtUsbUpCount ) == 0 ) mDeviceExtension -> mExtUpStartTime.QuadPart = 0;  // 清超时
	InterlockedDecrement( & mDeviceExtension -> mExtIoCount );  // 操作计数减量
	return( mStatus );
}

NTSTATUS	mPipeDownCompletion(
	PDEVICE_OBJECT	iDeviceObject,
	PIRP			iIrp,
	PVOID			iContext )
{
	NTSTATUS			mStatus;
	PURB				mUrb;
	mPWIN32_COMMAND		mWin32Command;
	mPDEVICE_EXTENSION	mDeviceExtension = iDeviceObject -> DeviceExtension;  // 设备扩展
	mUrb = iContext;
	if ( iIrp -> IoStatus.Status == STATUS_CANCELLED ) iIrp -> IoStatus.Status = STATUS_TIMEOUT;  // 被取消
	mStatus = iIrp -> IoStatus.Status;
	mWin32Command = iIrp -> AssociatedIrp.SystemBuffer;  // 命令缓冲区
	mWin32Command -> mStatus = mStatus;  // 返回操作状态
	mWin32Command -> mLength = mUrb -> UrbBulkOrInterruptTransfer.TransferBufferLength;  // 实际传输长度
	if ( mUrb == & mDeviceExtension -> mExtPublicUrb ) mDeviceExtension -> mExtUrbBuffer = mUrb;
	else ExFreePool( mUrb );  // 释放内存
	if ( NT_SUCCESS( mStatus ) ) iIrp -> IoStatus.Information = mWin32Command -> mLength + mWIN32_COMMAND_HEAD;  // 加上头部长度得返回数据的总长度
	if ( InterlockedDecrement( & mDeviceExtension -> mExtUsbDownCount ) == 0 ) mDeviceExtension -> mExtDownStartTime.QuadPart = 0;  // 清超时
	InterlockedDecrement( & mDeviceExtension -> mExtIoCount );  // 操作计数减量
	return( mStatus );
}

NTSTATUS	mDispatchDeviceControl(  // 设备控制
	PDEVICE_OBJECT	iDeviceObject,
	PIRP			iIrp )
{
	UCHAR				mRequestType, mRequestCode;
	USHORT				mRequestValue, mRequestIndex;
	ULONG				mControlCode;
	ULONG				mFunction, mLength, mReturn;
	ULONG				mTransferFlags, mParameter;
	LARGE_INTEGER		mWaitTime;
	PVOID				mBuffer;
	mPWIN32_COMMAND		mWin32Command;
	NTSTATUS			mStatus;
	PURB				mUrb;
	HANDLE				mThreadHandle;
	PIO_STACK_LOCATION	mCurrentIrpStack;
	PIO_STACK_LOCATION	mNextIrpStack;
	mPDEVICE_EXTENSION	mDeviceExtension = iDeviceObject -> DeviceExtension;  // 设备扩展
	if ( mDeviceExtension -> mPowerState == PowerDeviceD3 ) {
		iIrp -> IoStatus.Status = STATUS_INVALID_DEVICE_STATE;
		IoSetCancelRoutine( iIrp, NULL );
		mDelay20mS( );
		IoCompleteRequest( iIrp, IO_NO_INCREMENT );
		return( STATUS_INVALID_DEVICE_STATE );
	}
	InterlockedIncrement( & mDeviceExtension -> mExtIoCount );  // 操作计数增量,阻止中途停止或者移除设备
	mCurrentIrpStack = IoGetCurrentIrpStackLocation( iIrp );  // 当前栈单元指针
	mControlCode = mCurrentIrpStack -> Parameters.DeviceIoControl.IoControlCode;  // 操作命令
	if ( mControlCode == IOCTL_CH375_COMMAND ) {  // 专用接口
		mStatus = STATUS_SUCCESS;  // 返回状态预置为成功
		mReturn = 0;  // 返回数据长度预置为0
		mUrb = InterlockedExchangePointer( & mDeviceExtension -> mExtUrbBuffer, NULL );  // 优先使用公用URB
		if ( mUrb == NULL ) mUrb = ExAllocatePool( NonPagedPool, sizeof( URB ) );  // 分配内存作为URB请求块
		if (  mUrb != NULL && mCurrentIrpStack -> Parameters.DeviceIoControl.InputBufferLength >= mWIN32_COMMAND_HEAD ) {  // 输入缓冲区长度有效
			mWin32Command = iIrp -> AssociatedIrp.SystemBuffer;  // 命令缓冲区
			mFunction = mWin32Command -> mFunction;  // 功能代码
			mLength = mWin32Command -> mLength;  // 存取长度
			mBuffer = & mWin32Command -> mBuffer[0];  // 数据缓冲区
			switch( mFunction ) {  // 分析功能代码
				case mFuncGetVersion:  // 获取版本号
					while ( mLength >= sizeof( ULONG ) && *(PULONG)mBuffer == 'hc.W' );  // 等待调试工具W.ch
					*(PUCHAR)mBuffer = mTHIS_VERSION;  // 驱动程序版本号
					mReturn = sizeof( UCHAR );  // 返回数据长度
					break;
				case mFuncGetConfig:  // 获取USB设备配置描述符
					UsbBuildGetDescriptorRequest( mUrb, sizeof( struct _URB_CONTROL_DESCRIPTOR_REQUEST ),  // 构造获取描述符URB
												  USB_CONFIGURATION_DESCRIPTOR_TYPE, 0, 0, mBuffer, NULL, mLength, NULL );
					mStatus = mUsbSubmitUrb( iDeviceObject, mUrb );  // 提交URB
					mReturn = mUrb -> UrbControlDescriptorRequest.TransferBufferLength;  // 实际传输长度
					break;
				case mPipeDeviceCtrl:  // CH375的综合控制管道
					mRequestType = mWin32Command -> mSetupPkt.mUspReqType;  // 请求类型
					mRequestCode = mWin32Command -> mSetupPkt.mUspRequest;  // 请求码
					mRequestValue = mWin32Command -> mSetupPkt.mUspValue;  // 数值参数
					mRequestIndex = mWin32Command -> mSetupPkt.mUspIndex;  // 索引参数
					mLength = mWin32Command -> mSetupPkt.mLength;  // 后续操作的数据长度
					mTransferFlags = ( ( mRequestType & 0x80 ) != 0 ? USBD_TRANSFER_DIRECTION_IN : 0 ) | USBD_SHORT_TRANSFER_OK;  // 传输标志
					switch( mRequestType >> 5 & 0x03 ) {  // 分析请求类型
						case 0:  // 标准请求
							switch( mRequestCode ) {  // 分析请求码
								case USB_REQUEST_CLEAR_FEATURE:  // 清除特性
									UsbBuildFeatureRequest( mUrb, URB_FUNCTION_CLEAR_FEATURE_TO_DEVICE,  // 构造清除特性URB
															mRequestValue, mRequestIndex, NULL );
									mStatus = mUsbSubmitUrb( iDeviceObject, mUrb );  // 提交URB
									break;
								case USB_REQUEST_SET_FEATURE:  // 设置特性
									UsbBuildFeatureRequest( mUrb, URB_FUNCTION_SET_FEATURE_TO_DEVICE,  // 构造设置特性URB
															mRequestValue, mRequestIndex, NULL );
									mStatus = mUsbSubmitUrb( iDeviceObject, mUrb );  // 提交URB
									break;
								case USB_REQUEST_GET_STATUS:  // 获取状态
									UsbBuildGetStatusRequest( mUrb, URB_FUNCTION_GET_STATUS_FROM_DEVICE,  // 构造获取状态URB
															  mRequestIndex, mBuffer, NULL, NULL );
									mStatus = mUsbSubmitUrb( iDeviceObject, mUrb );  // 提交URB
									mReturn = mUrb -> UrbControlGetStatusRequest.TransferBufferLength;  // 实际传输长度
									break;
								case USB_REQUEST_GET_DESCRIPTOR:  // 获取描述符
									mParameter = ( mRequestValue >> 8 ) == 1 ? USB_DEVICE_DESCRIPTOR_TYPE : USB_CONFIGURATION_DESCRIPTOR_TYPE;  // 描述符类型
									UsbBuildGetDescriptorRequest( mUrb, sizeof( struct _URB_CONTROL_DESCRIPTOR_REQUEST ),  // 构造获取描述符URB
																  (UCHAR)mParameter, 0, 0, mBuffer, NULL, mLength, NULL );
									mStatus = mUsbSubmitUrb( iDeviceObject, mUrb );  // 提交URB
									mReturn = mUrb -> UrbControlDescriptorRequest.TransferBufferLength;  // 实际传输长度
									break;
								default:  // 不支持
									mStatus = STATUS_INVALID_PARAMETER;  // 返回错误
									break;
							}
							break;
						case 2:  // 供应商请求
							switch( mRequestType & 0x03 ) {  // 分析接受器
								case 0:  // 设备
									mParameter = URB_FUNCTION_VENDOR_DEVICE;
									break;
								case 1:  // 接口
									mParameter = URB_FUNCTION_VENDOR_INTERFACE;
									break;
								case 2:  // 端点
									mParameter = URB_FUNCTION_VENDOR_ENDPOINT;
									break;
								default:  // 其它
									mParameter = URB_FUNCTION_VENDOR_OTHER;
									break;
							}
							UsbBuildVendorRequest( mUrb, (USHORT)mParameter,  // 构造USB供应商请求
												   sizeof( struct _URB_CONTROL_VENDOR_OR_CLASS_REQUEST ),  // URB结构长度
												   mTransferFlags, 0, mRequestCode, mRequestValue, mRequestIndex,  // 请求参数
												   mBuffer, NULL, mLength, NULL );  // 缓冲区及长度
							mStatus = mUsbSubmitUrb( iDeviceObject, mUrb );  // 提交URB
							mReturn = mUrb -> UrbControlVendorClassRequest.TransferBufferLength;  // 实际传输长度
							break;
						default:  // 不支持的请求
							mStatus = STATUS_INVALID_PARAMETER;  // 返回错误
							break;
					}
					break;
				case mPipeInterUp:  // CH375的中断数据上传管道
					if ( mDeviceExtension -> mExtInterUpPipe != NULL ) {  // 管道有效
						mTransferFlags = USBD_TRANSFER_DIRECTION_IN | USBD_SHORT_TRANSFER_OK;  // 传输标志
						UsbBuildInterruptOrBulkTransferRequest( mUrb, sizeof( struct _URB_BULK_OR_INTERRUPT_TRANSFER ),  // 构造USB请求
																mDeviceExtension -> mExtInterUpPipe,  // 管道的句柄
																mBuffer, NULL, mLength, mTransferFlags, NULL );  // 操作标志
						mUrb -> UrbBulkOrInterruptTransfer.Hdr.Status = USBD_STATUS_HALTED;
						mNextIrpStack = IoGetNextIrpStackLocation( iIrp );
						mNextIrpStack -> MajorFunction = IRP_MJ_INTERNAL_DEVICE_CONTROL;
						mNextIrpStack -> Parameters.Others.Argument1 = (PVOID) mUrb;  // 将URB作为参数传递给下级设备
						mNextIrpStack -> Parameters.DeviceIoControl.IoControlCode = IOCTL_INTERNAL_USB_SUBMIT_URB;
						IoSetCompletionRoutine( iIrp, mPipeInterCompletion, mUrb, TRUE, TRUE, TRUE );
						IoMarkIrpPending( iIrp );
						InterlockedIncrement( & mDeviceExtension -> mExtUsbInterCount );  // 操作计数
						if ( mDeviceExtension -> mExtInterTimeout < 0x80000000 ) {  // 需要检查超时
							KeQuerySystemTime( & mDeviceExtension -> mExtInterStartTime );
							KeSetEvent( & mDeviceExtension -> mExtThreadToutEvent, EVENT_INCREMENT, FALSE );  // 置线程启动事件
						}
						//IoSetCancelRoutine( iIrp, mCancelCurrentInter );
						mStatus = IoCallDriver( mDeviceExtension -> mExtNextLowerDevice, iIrp );  // 向下级设备发送IO请求
						if ( ! NT_SUCCESS( mStatus ) ) {
							if ( mStatus != STATUS_CANCELLED && mStatus != STATUS_DEVICE_NOT_CONNECTED ) mRequestPipe( iDeviceObject, URB_FUNCTION_RESET_PIPE, mPipeInterUp );
						}
						return( STATUS_PENDING );  // 返回等待
					}
					else mStatus = STATUS_NO_SUCH_DEVICE ;  // 管道无效,设备无效
					break;
				case mPipeAuxDown:  // CH375的辅助数据下传管道
					if ( mDeviceExtension -> mExtAuxDownPipe != NULL ) {  // 管道有效
						mTransferFlags = USBD_SHORT_TRANSFER_OK;  // 传输标志
						UsbBuildInterruptOrBulkTransferRequest( mUrb, sizeof( struct _URB_BULK_OR_INTERRUPT_TRANSFER ),  // 构造USB请求
																mDeviceExtension -> mExtAuxDownPipe,  // 管道的句柄
																mBuffer, NULL, mLength, mTransferFlags, NULL );  // 操作标志
						mUrb -> UrbBulkOrInterruptTransfer.Hdr.Status = USBD_STATUS_HALTED;
						mNextIrpStack = IoGetNextIrpStackLocation( iIrp );
						mNextIrpStack -> MajorFunction = IRP_MJ_INTERNAL_DEVICE_CONTROL;
						mNextIrpStack -> Parameters.Others.Argument1 = (PVOID) mUrb;  // 将URB作为参数传递给下级设备
						mNextIrpStack -> Parameters.DeviceIoControl.IoControlCode = IOCTL_INTERNAL_USB_SUBMIT_URB;
						IoSetCompletionRoutine( iIrp, mPipeAuxCompletion, mUrb, TRUE, TRUE, TRUE );
						IoMarkIrpPending( iIrp );
						InterlockedIncrement( & mDeviceExtension -> mExtUsbAuxCount );  // 操作计数
						if ( mDeviceExtension -> mExtAuxTimeout < 0x80000000 ) {  // 需要检查超时
							KeQuerySystemTime( & mDeviceExtension -> mExtAuxStartTime );
							KeSetEvent( & mDeviceExtension -> mExtThreadToutEvent, EVENT_INCREMENT, FALSE );  // 置线程启动事件
						}
						//IoSetCancelRoutine( iIrp, mCancelCurrentAux );
						mStatus = IoCallDriver( mDeviceExtension -> mExtNextLowerDevice, iIrp );  // 向下级设备发送IO请求
						if ( ! NT_SUCCESS( mStatus ) ) {
							if ( mStatus != STATUS_CANCELLED && mStatus != STATUS_DEVICE_NOT_CONNECTED ) mRequestPipe( iDeviceObject, URB_FUNCTION_RESET_PIPE, mPipeAuxDown );
						}
						return( STATUS_PENDING );  // 返回等待
					}
					else mStatus = STATUS_NO_SUCH_DEVICE ;  // 管道无效,设备无效
					break;
				case mPipeDataUp:  // CH375的数据块上传管道
					if ( mDeviceExtension -> mExtDataUpPipe != NULL ) {  // 管道有效
						if ( mDeviceExtension -> ThreadBuffer ) {  // 线程读取
							mReturn = mLength;
							mStatus = mGetBufferData( iDeviceObject, mBuffer, &mReturn );  // 直接获取线程数据
						}
						else {
							mTransferFlags = USBD_TRANSFER_DIRECTION_IN | USBD_SHORT_TRANSFER_OK;  // 传输标志
							UsbBuildInterruptOrBulkTransferRequest( mUrb, sizeof( struct _URB_BULK_OR_INTERRUPT_TRANSFER ),  // 构造USB请求
																	mDeviceExtension -> mExtDataUpPipe,  // 管道的句柄
																	mBuffer, NULL, mLength, mTransferFlags, NULL );  // 操作标志
							mUrb -> UrbBulkOrInterruptTransfer.Hdr.Status = USBD_STATUS_HALTED;
							mNextIrpStack = IoGetNextIrpStackLocation( iIrp );
							mNextIrpStack -> MajorFunction = IRP_MJ_INTERNAL_DEVICE_CONTROL;
							mNextIrpStack -> Parameters.Others.Argument1 = (PVOID) mUrb;  // 将URB作为参数传递给下级设备
							mNextIrpStack -> Parameters.DeviceIoControl.IoControlCode = IOCTL_INTERNAL_USB_SUBMIT_URB;
							IoSetCompletionRoutine( iIrp, mPipeUpCompletion, mUrb, TRUE, TRUE, TRUE );
							IoMarkIrpPending( iIrp );
							InterlockedIncrement( & mDeviceExtension -> mExtUsbUpCount );  // 操作计数
							if ( mDeviceExtension -> mExtUpTimeout < 0x80000000 ) {  // 需要检查超时
								KeQuerySystemTime( & mDeviceExtension -> mExtUpStartTime );
								KeSetEvent( & mDeviceExtension -> mExtThreadToutEvent, EVENT_INCREMENT, FALSE );  // 置线程启动事件
							}
							//IoSetCancelRoutine( iIrp, mCancelCurrentUp );
							mStatus = IoCallDriver( mDeviceExtension -> mExtNextLowerDevice, iIrp );  // 向下级设备发送IO请求
							if ( ! NT_SUCCESS( mStatus ) ) {
								if ( mStatus != STATUS_CANCELLED && mStatus != STATUS_DEVICE_NOT_CONNECTED ) mRequestPipe( iDeviceObject, URB_FUNCTION_RESET_PIPE, mPipeDataUp );
							}
							return( STATUS_PENDING );  // 返回等待
						}
					}
					else mStatus = STATUS_NO_SUCH_DEVICE ;  // 管道无效,设备无效
					break;
				case mPipeDataDown:  // CH375的数据块下传管道
					if ( mDeviceExtension -> mExtDataDownPipe != NULL ) {  // 管道有效
						if ( mDeviceExtension -> DnThreadBuffer ) {  // 线程读取
							mReturn = mLength;
							mStatus = mPutBufferData( iDeviceObject, mBuffer, mReturn );  // 直接将数据送给线程
						}
						else {
							mTransferFlags = USBD_SHORT_TRANSFER_OK;  // 传输标志
							UsbBuildInterruptOrBulkTransferRequest( mUrb, sizeof( struct _URB_BULK_OR_INTERRUPT_TRANSFER ),  // 构造USB请求
																	mDeviceExtension -> mExtDataDownPipe,  // 管道的句柄
																	mBuffer, NULL, mLength, mTransferFlags, NULL );  // 操作标志
							mUrb -> UrbBulkOrInterruptTransfer.Hdr.Status = USBD_STATUS_HALTED;
							mNextIrpStack = IoGetNextIrpStackLocation( iIrp );
							mNextIrpStack -> MajorFunction = IRP_MJ_INTERNAL_DEVICE_CONTROL;
							mNextIrpStack -> Parameters.Others.Argument1 = (PVOID) mUrb;  // 将URB作为参数传递给下级设备
							mNextIrpStack -> Parameters.DeviceIoControl.IoControlCode = IOCTL_INTERNAL_USB_SUBMIT_URB;
							IoSetCompletionRoutine( iIrp, mPipeDownCompletion, mUrb, TRUE, TRUE, TRUE );
							IoMarkIrpPending( iIrp );
							InterlockedIncrement( & mDeviceExtension -> mExtUsbDownCount );  // 操作计数
							if ( mDeviceExtension -> mExtDownTimeout < 0x80000000 ) {  // 需要检查超时
								KeQuerySystemTime( & mDeviceExtension -> mExtDownStartTime );
								KeSetEvent( & mDeviceExtension -> mExtThreadToutEvent, EVENT_INCREMENT, FALSE );  // 置线程启动事件
							}
							//IoSetCancelRoutine( iIrp, mCancelCurrentDown );
							mStatus = IoCallDriver( mDeviceExtension -> mExtNextLowerDevice, iIrp );  // 向下级设备发送IO请求
							if ( ! NT_SUCCESS( mStatus ) ) {
								if ( mStatus != STATUS_CANCELLED && mStatus != STATUS_DEVICE_NOT_CONNECTED ) mRequestPipe( iDeviceObject, URB_FUNCTION_RESET_PIPE, mPipeDataDown );
							}
							return( STATUS_PENDING );  // 返回等待
						}
					}
					else mStatus = STATUS_NO_SUCH_DEVICE ;  // 管道无效,设备无效
					break;
				case mFuncResetDevice:  // 复位USB设备
					mStatus = mResetUsbDevice( iDeviceObject );
					break;
				case mFuncResetPipe:  // 复位USB管道
					mStatus = mRequestPipe( iDeviceObject, URB_FUNCTION_RESET_PIPE, *(PULONG)mBuffer );  // 在指定管道执行复位请求
					break;
				case mFuncAbortPipe:  // 取消USB管道的数据请求
					mStatus = mRequestPipe( iDeviceObject, URB_FUNCTION_ABORT_PIPE, *(PULONG)mBuffer );  // 在指定管道执行取消请求
					break;
				case mFuncSetTimeout:  // 设置USB通讯超时
					mDeviceExtension -> mExtDownTimeout = *(PULONG)( (PUCHAR)mBuffer + 0 );  // 设置USB数据块下传管道的通讯超时,mS
					if ( mDeviceExtension -> mExtDownTimeout == 0 ) mDeviceExtension -> mExtDownTimeout = 1;
					mDeviceExtension -> mExtDownWaitTime.QuadPart = (LONGLONG)( mDeviceExtension -> mExtDownTimeout ) * 10000;  // 计算超时
					mDeviceExtension -> mExtUpTimeout = *(PULONG)( (PUCHAR)mBuffer + 4 );  // 设置USB数据块上传管道的通讯超时,mS
					if ( mDeviceExtension -> mExtUpTimeout == 0 ) mDeviceExtension -> mExtUpTimeout = 1;
					mDeviceExtension -> mExtUpWaitTime.QuadPart = (LONGLONG)( mDeviceExtension -> mExtUpTimeout ) * 10000;  // 计算超时
					if ( mLength >= sizeof( ULONG ) * 4 ) {
						mDeviceExtension -> mExtAuxTimeout = *(PULONG)( (PUCHAR)mBuffer + 8 );  // 设置USB辅助数据下传管道的通讯超时,mS
						if ( mDeviceExtension -> mExtAuxTimeout == 0 ) mDeviceExtension -> mExtAuxTimeout = 1;
						mDeviceExtension -> mExtAuxWaitTime.QuadPart = (LONGLONG)( mDeviceExtension -> mExtAuxTimeout ) * 10000;  // 计算超时
						mDeviceExtension -> mExtInterTimeout = *(PULONG)( (PUCHAR)mBuffer + 12 );  // 设置USB中断数据上传管道的通讯超时,mS
						if ( mDeviceExtension -> mExtInterTimeout == 0 ) mDeviceExtension -> mExtInterTimeout = 1;
						mDeviceExtension -> mExtInterWaitTime.QuadPart = (LONGLONG)( mDeviceExtension -> mExtInterTimeout ) * 10000;  // 计算超时
					}
					break;
				case mFuncSetExclusive:  // 设置独占使用
					if ( *(PUCHAR)mBuffer ) mDeviceExtension -> mExtDeviceExclusive = TRUE;  // 设备独占使用
					else mDeviceExtension -> mExtDeviceExclusive = FALSE;  // 设备共享使用
					*(PULONG)mBuffer = mDeviceExtension -> mExtDeviceOpen;  // 返回设备已经被打开的次数
					mReturn = sizeof( ULONG );  // 返回数据长度
					break;
				case mFuncBufferMode:  // 设定缓冲上传模式及获取缓冲区中的数据长度
					KeSetEvent( & mDeviceExtension -> ThreadStartEvent, IO_CH375_INCREMENT, FALSE );  // 置线程启动事件
					mReturn = *(PUCHAR)mBuffer;
					*(PULONG)mBuffer = 0;  // 返回缓冲区中已接收到的上传包的个数
					switch ( mReturn ) {
						case 0:  // 关闭缓冲模式
							mStatus = mExitThreadRead( iDeviceObject );  // 退出线程
							break;
						case 1:  // 查询缓冲区
							if ( mDeviceExtension -> ThreadBuffer ) *(PULONG)mBuffer = mDeviceExtension -> ThreadInSize / ( mCH375_PACKET_LENGTH + 1 );
							else mStatus = STATUS_INSUFFICIENT_RESOURCES;  // 尚未启动
							break;
						case 2:  // 启用缓冲模式,清空缓冲区
							if ( mDeviceExtension -> mExtDataUpPipe != NULL ) {  // 管道有效
								if ( mDeviceExtension -> ThreadBuffer == NULL ) {  // 新建
									PsCreateSystemThread( &mThreadHandle, 0, NULL, NULL, NULL, mThreadRead, iDeviceObject );  // 新建系统线程
									ZwClose( mThreadHandle );  // 关闭句柄
									for ( mReturn = 0; mReturn < 50; mReturn ++ ) {
										if ( mDeviceExtension -> ThreadBuffer ) break;
										mDelay20mS( );
									}
									mStatus = mReturn >= 50 ? STATUS_UNSUCCESSFUL : STATUS_SUCCESS;
									mReturn = 0;
								}
								else mClearUpBufferData( iDeviceObject );  // 已打开则清缓冲区
							}
							else mStatus = STATUS_NO_SUCH_DEVICE ;  // 管道无效,设备无效
							break;
						default:
							mStatus = STATUS_INVALID_PARAMETER;  // 返回错误
							break;
					}
					mReturn = sizeof( ULONG );  // 返回数据长度
					break;
				case mFuncBufferModeDn:  // 设定缓冲下传模式及获取缓冲区中的数据长度
					KeSetEvent( & mDeviceExtension -> DnThreadStartEvent, IO_CH375_INCREMENT, FALSE );  // 置线程启动事件
					mReturn = *(PUCHAR)mBuffer;
					*(PULONG)mBuffer = 0;  // 返回缓冲区中已接收到的上传包的个数
					switch ( mReturn ) {
						case 0:  // 关闭缓冲模式
							mStatus = mExitThreadWrite( iDeviceObject );  // 退出线程
							break;
						case 1:  // 查询缓冲区
							if ( mDeviceExtension -> DnThreadBuffer ) *(PULONG)mBuffer = mDeviceExtension -> DnThreadInSize / ( mCH375_PACKET_LENGTH + 1 ) + mDeviceExtension -> DnThreadUsbCount;
							else mStatus = STATUS_INSUFFICIENT_RESOURCES;  // 尚未启动
							break;
						case 2:  // 启用缓冲模式,清空缓冲区
							if ( mDeviceExtension -> mExtDataDownPipe != NULL ) {  // 管道有效
								if ( mDeviceExtension -> DnThreadBuffer == NULL ) {  // 新建
									PsCreateSystemThread( &mThreadHandle, 0, NULL, NULL, NULL, mThreadWrite, iDeviceObject );  // 新建系统线程
									ZwClose( mThreadHandle );  // 关闭句柄
									for ( mReturn = 0; mReturn < 50; mReturn ++ ) {
										if ( mDeviceExtension -> DnThreadBuffer ) break;
										mDelay20mS( );
									}
									mStatus = mReturn >= 50 ? STATUS_UNSUCCESSFUL : STATUS_SUCCESS;
									mReturn = 0;
								}
								else mClearDnBufferData( iDeviceObject );  // 已打开则清缓冲区
							}
							else mStatus = STATUS_NO_SUCH_DEVICE ;  // 管道无效,设备无效
							break;
						default:
							mStatus = STATUS_INVALID_PARAMETER;  // 返回错误
							break;
					}
					mReturn = sizeof( ULONG );  // 返回数据长度
					break;
				default:  // 不支持的请求
					mStatus = STATUS_INVALID_PARAMETER;  // 返回错误
					break;
			}
			mWin32Command -> mStatus = mStatus;  // 返回操作状态
			mWin32Command -> mLength = mReturn;  // 实际传输长度
			mReturn += mWIN32_COMMAND_HEAD;  // 加上头部长度得返回数据的总长度
		}
		else {  // 失败
			if ( mUrb == NULL ) mStatus = STATUS_INSUFFICIENT_RESOURCES;  // 资源不够
			else mStatus = STATUS_BUFFER_TOO_SMALL;  // 缓冲区太小
		}
		if ( mUrb != NULL ) {
			if ( mUrb == & mDeviceExtension -> mExtPublicUrb ) mDeviceExtension -> mExtUrbBuffer = mUrb;
			else ExFreePool( mUrb );  // 释放内存
		}
		if ( mStatus != STATUS_PENDING ) {  // 成功返回或者失败返回
			iIrp -> IoStatus.Status = mStatus;  // 返回状态
			iIrp -> IoStatus.Information = mReturn;  // 返回数据的长度
			IoCompleteRequest( iIrp, IO_CH375_INCREMENT );  // 完成请求,增加优先级
		}
	}
	else {  // 直接传送至下级设备处理
		IoSkipCurrentIrpStackLocation( iIrp );  // 直接传送当前栈
		mStatus = IoCallDriver( mDeviceExtension -> mExtNextLowerDevice, iIrp );  // 传送至下级设备
	}
	InterlockedDecrement( & mDeviceExtension -> mExtIoCount );  // 操作计数减量
	return( mStatus );
}

NTSTATUS	mRequestPipe(  // 在指定管道上执行请求
	PDEVICE_OBJECT	iDeviceObject,
	USHORT			iFunction,
	ULONG			iPipe )
{
	PURB				mUrb;
	NTSTATUS			mStatus;
	mPDEVICE_EXTENSION	mDeviceExtension = iDeviceObject -> DeviceExtension;  // 设备扩展
	mUrb = ExAllocatePool( NonPagedPool, sizeof( URB ) );  // 分配内存作为URB请求块
	if ( mUrb == NULL ) return( STATUS_INSUFFICIENT_RESOURCES );  // 资源不够
	mUrb -> UrbHeader.Length = sizeof( struct _URB_PIPE_REQUEST );
	mUrb -> UrbHeader.Function = iFunction;
	switch( iPipe ) {  // 指定管道
		case mPipeInterUp:  // CH375的中断数据上传管道
			mUrb -> UrbPipeRequest.PipeHandle = mDeviceExtension -> mExtInterUpPipe;
			break;
		case mPipeAuxDown:  // CH375的辅助数据下传管道
			mUrb -> UrbPipeRequest.PipeHandle = mDeviceExtension -> mExtAuxDownPipe;
			break;
		case mPipeDataUp:  // CH375的数据块上传管道
			mUrb -> UrbPipeRequest.PipeHandle = mDeviceExtension -> mExtDataUpPipe;
			break;
		case mPipeDataDown:  // CH375的数据块下传管道
			mUrb -> UrbPipeRequest.PipeHandle = mDeviceExtension -> mExtDataDownPipe;
			break;
		default:  // 不支持
			mUrb -> UrbPipeRequest.PipeHandle = NULL;  // 管道无效
			break;
	}
	if ( mUrb -> UrbPipeRequest.PipeHandle == NULL ) mStatus = STATUS_NO_SUCH_DEVICE ;  // 管道无效
	else {
		mStatus = mUsbSubmitUrb( iDeviceObject, mUrb );  // 提交URB
		if ( ! NT_SUCCESS( mStatus ) ) {
			if ( mStatus != STATUS_CANCELLED && mStatus != STATUS_DEVICE_NOT_CONNECTED ) {
				if ( iFunction != URB_FUNCTION_RESET_PIPE ) {
					mUrb -> UrbHeader.Length = sizeof( struct _URB_PIPE_REQUEST );
					mUrb -> UrbHeader.Function = URB_FUNCTION_RESET_PIPE;
					mStatus = mUsbSubmitUrb( iDeviceObject, mUrb );  // 提交URB
				}
				if ( ! NT_SUCCESS( mStatus ) ) mResetUsbDevice( iDeviceObject );
			}
		}
	}
	ExFreePool( mUrb );  // 释放内存
	return( mStatus );
}

VOID		mCancelCurrentInter(  // 取消当前中断上传IRP
	PDEVICE_OBJECT	iDeviceObject,
	PIRP			iIrp )
{
	mPDEVICE_EXTENSION	mDeviceExtension = iDeviceObject -> DeviceExtension;  // 设备扩展
	mDeviceExtension -> mExtInterStartTime.u.HighPart = 0x87654321;
	KeSetEvent( & mDeviceExtension -> mExtThreadToutEvent, EVENT_INCREMENT, FALSE );  // 置线程启动事件
	IoReleaseCancelSpinLock( iIrp -> CancelIrql );
}

VOID		mCancelCurrentAux(  // 取消当前辅助下传IRP
	PDEVICE_OBJECT	iDeviceObject,
	PIRP			iIrp )
{
	mPDEVICE_EXTENSION	mDeviceExtension = iDeviceObject -> DeviceExtension;  // 设备扩展
	mDeviceExtension -> mExtAuxStartTime.u.HighPart = 0x87654321;
	KeSetEvent( & mDeviceExtension -> mExtThreadToutEvent, EVENT_INCREMENT, FALSE );  // 置线程启动事件
	IoReleaseCancelSpinLock( iIrp -> CancelIrql );
}

VOID		mCancelCurrentUp(  // 取消当前上传IRP
	PDEVICE_OBJECT	iDeviceObject,
	PIRP			iIrp )
{
	mPDEVICE_EXTENSION	mDeviceExtension = iDeviceObject -> DeviceExtension;  // 设备扩展
	mDeviceExtension -> mExtUpStartTime.u.HighPart = 0x87654321;
	KeSetEvent( & mDeviceExtension -> mExtThreadToutEvent, EVENT_INCREMENT, FALSE );  // 置线程启动事件
	IoReleaseCancelSpinLock( iIrp -> CancelIrql );
}

VOID		mCancelCurrentDown(  // 取消当前下传IRP
	PDEVICE_OBJECT	iDeviceObject,
	PIRP			iIrp )
{
	mPDEVICE_EXTENSION	mDeviceExtension = iDeviceObject -> DeviceExtension;  // 设备扩展
	mDeviceExtension -> mExtDownStartTime.u.HighPart = 0x87654321;
	KeSetEvent( & mDeviceExtension -> mExtThreadToutEvent, EVENT_INCREMENT, FALSE );  // 置线程启动事件
	IoReleaseCancelSpinLock( iIrp -> CancelIrql );
}

NTSTATUS	mDispatchCleanup(  // 取消操作
	PDEVICE_OBJECT	iDeviceObject,
	PIRP			iIrp )
{
	ULONG				i;
	mPDEVICE_EXTENSION	mDeviceExtension = iDeviceObject -> DeviceExtension;  // 设备扩展
	if ( mDeviceExtension -> mExtIoCount != 0 && mDeviceExtension -> mExtDeviceOpen <= 1 ) {  // 有未完成的操作请求
		for ( i = 0; i < 10; i ++ ) {  /* 取消未完成USB通讯 */
			PURB			mUrb;
			if ( mDeviceExtension -> mExtIoCount == 0 ) break;  /* 操作完成 */
			mDeviceExtension -> mExtInterStartTime.u.HighPart = 0x87654321;
			mDeviceExtension -> mExtAuxStartTime.u.HighPart = 0x87654321;
			mDeviceExtension -> mExtUpStartTime.u.HighPart = 0x87654321;
			mDeviceExtension -> mExtDownStartTime.u.HighPart = 0x87654321;
			KeSetEvent( & mDeviceExtension -> mExtThreadToutEvent, EVENT_INCREMENT, FALSE );  // 置线程启动事件
			mDelay20mS( );
			if ( mDeviceExtension -> mExtIoCount == 0 ) break;  /* 操作完成 */
			if ( i > 5 ) {  /* 强制取消 */
				if ( mDeviceExtension -> mExtUsbDownCount ) mRequestPipe( iDeviceObject, URB_FUNCTION_ABORT_PIPE, mPipeDataDown );  // 在下传管道执行取消请求
				if ( mDeviceExtension -> mExtUsbUpCount ) mRequestPipe( iDeviceObject, URB_FUNCTION_ABORT_PIPE, mPipeDataUp );  // 在上传管道执行取消请求
				if ( mDeviceExtension -> mExtUsbAuxCount ) mRequestPipe( iDeviceObject, URB_FUNCTION_ABORT_PIPE, mPipeAuxDown );  // 取消请求
				if ( mDeviceExtension -> mExtUsbInterCount ) mRequestPipe( iDeviceObject, URB_FUNCTION_ABORT_PIPE, mPipeInterUp );  // 取消请求
			}
			if ( mIsDeviceExist( iDeviceObject, STATUS_SUCCESS ) == FALSE ) break;  // 设备已经移除
		}
	}
	if ( mDeviceExtension -> mExtUsbDownCount ) mRequestPipe( iDeviceObject, URB_FUNCTION_RESET_PIPE, mPipeDataDown );  // 在下传管道执行取消请求
	if ( mDeviceExtension -> mExtUsbUpCount ) mRequestPipe( iDeviceObject, URB_FUNCTION_RESET_PIPE, mPipeDataUp );  // 在上传管道执行取消请求
	if ( mDeviceExtension -> mExtUsbAuxCount ) mRequestPipe( iDeviceObject, URB_FUNCTION_RESET_PIPE, mPipeAuxDown );  // 取消请求
	if ( mDeviceExtension -> mExtUsbInterCount ) mRequestPipe( iDeviceObject, URB_FUNCTION_RESET_PIPE, mPipeInterUp );  // 取消请求
	iIrp -> IoStatus.Status = STATUS_SUCCESS;  // 返回成功
	iIrp -> IoStatus.Information = 0;
	IoCompleteRequest( iIrp, IO_NO_INCREMENT );  // 完成请求
	return( STATUS_SUCCESS );  // 返回状态
}

NTSTATUS	mDispatchPower(  // 电源管理
	PDEVICE_OBJECT	iDeviceObject,
	PIRP			iIrp )
{
	NTSTATUS				mStatus;
	BOOLEAN					mCompletion;
	POWER_STATE				mPowerState;
	mPDEVICE_EXTENSION		mDeviceExtension;
	PIO_STACK_LOCATION		mCurrentIrpStack;
	mDeviceExtension = iDeviceObject -> DeviceExtension;  // 设备扩展
	mCompletion = FALSE;  // 预置为尚未完成
	mCurrentIrpStack = IoGetCurrentIrpStackLocation( iIrp );  // 当前栈单元指针
	switch ( mCurrentIrpStack -> Parameters.Power.Type ) {  // 电源类型
		case DevicePowerState:
			if ( mCurrentIrpStack -> MinorFunction == IRP_MN_SET_POWER ) {
				switch ( mCurrentIrpStack -> Parameters.Power.State.DeviceState ) {
					case PowerDeviceD0:
						mDeviceExtension -> mPowerState = PowerDeviceD0;
						IoMarkIrpPending( iIrp );
						IoCopyCurrentIrpStackLocationToNext( iIrp );  // 复制当前栈单元
						mDeviceExtension -> mDevPowerIrp = iIrp;
						IoSetCompletionRoutine( iIrp, mDevPwrCompletRoutine, iIrp, TRUE, TRUE, TRUE );  // 设置设定完成例程
						mStatus = PoCallDriver( mDeviceExtension -> mExtNextLowerDevice, iIrp );  // 传送至下级设备
						mCompletion = TRUE;  // 操作已经完成
						break;
					case PowerDeviceD3:
						mDeviceExtension -> mPowerState = PowerDeviceD3;
						mDeviceExtension -> mExtDeviceStart = FALSE;  // 清除设备启动标志
						PoSetPowerState( iDeviceObject, DevicePowerState, mCurrentIrpStack -> Parameters.Power.State );
						IoMarkIrpPending( iIrp );
						mDeviceExtension -> mDevPowerIrp = iIrp;
						KeSetEvent( & mDeviceExtension -> ThreadPowerEvent, EVENT_INCREMENT, FALSE );  // 置线程启动事件
						mCompletion = TRUE;  // 操作已经完成
						break;
					default:
						break;
				}
			}
			break;
		case SystemPowerState:
			switch ( mCurrentIrpStack -> MinorFunction ) {
				case IRP_MN_SET_POWER:
					switch ( mCurrentIrpStack -> Parameters.Power.State.SystemState ) {
						case PowerSystemMaximum:
						case PowerSystemWorking:
							mPowerState.DeviceState = PowerDeviceD0;
//							mDeviceExtension -> mPowerState = PowerDeviceD0;
							IoMarkIrpPending( iIrp );
							IoCopyCurrentIrpStackLocationToNext( iIrp );  // 复制当前栈单元
							IoSetCompletionRoutine( iIrp, mSysPwrCompletRoutine, &mPowerState, TRUE, TRUE, TRUE );  // 设置设定完成例程
							mStatus = PoCallDriver( mDeviceExtension -> mExtNextLowerDevice, iIrp );  // 传送至下级设备
							mCompletion = TRUE;  // 操作已经完成
							break;
						case PowerSystemSleeping1:
						case PowerSystemSleeping2:
						case PowerSystemSleeping3:
						case PowerSystemHibernate:
						case PowerSystemShutdown:
							mPowerState.DeviceState = PowerDeviceD3;
//							mDeviceExtension -> mPowerState = PowerDeviceD3;
							IoMarkIrpPending( iIrp );
							IoCopyCurrentIrpStackLocationToNext( iIrp );  // 复制当前栈单元
							IoSetCompletionRoutine( iIrp, mSysPwrCompletRoutine, &mPowerState, TRUE, TRUE, TRUE );  // 设置设定完成例程
							mStatus = PoCallDriver( mDeviceExtension -> mExtNextLowerDevice, iIrp );  // 传送至下级设备
							mCompletion = TRUE;  // 操作已经完成
							break;
						default:
							break;
					}
					break;
				default:
					break;
			}
			break;
		default:
			break;
	}
	if ( mCompletion == FALSE ) {
		PoStartNextPowerIrp( iIrp );  // 开始下一个操作
		IoSkipCurrentIrpStackLocation( iIrp );  // 直接传送当前栈
		mStatus = PoCallDriver( mDeviceExtension -> mExtNextLowerDevice, iIrp );  // 传送至下级设备
	}
	else {
		mStatus = STATUS_PENDING;
	}
	return( mStatus );
}

NTSTATUS	mSysPwrCompletRoutine(  // 操作完成例程
	PDEVICE_OBJECT	iDeviceObject,
	PIRP			iIrp,
	PPOWER_STATE	iPowerState )  // 输入参数
{
	mPDEVICE_EXTENSION	mDeviceExtension = iDeviceObject -> DeviceExtension;  // 设备扩展
	if ( iIrp -> PendingReturned ) IoMarkIrpPending( iIrp );
	PoRequestPowerIrp( mDeviceExtension -> mExtPhysicalTarget, IRP_MN_SET_POWER, *iPowerState, mSysPwrReqCompletion, iIrp, NULL );
	return( STATUS_MORE_PROCESSING_REQUIRED );  // 阻止继续处理当前IRP
}

VOID		mSysPwrReqCompletion(
	PDEVICE_OBJECT		iDeviceObject,
	UCHAR				iMinorFunction,
	POWER_STATE			iPowerState,
	PIRP				iIrp,
	PIO_STATUS_BLOCK	iIoStatus )
{
	PoStartNextPowerIrp( iIrp );  // 开始下一个操作
	IoCompleteRequest( iIrp, IO_NO_INCREMENT );  // 完成当前IRP
}

NTSTATUS	mDevPwrCompletRoutine(  // 操作完成例程
	PDEVICE_OBJECT	iDeviceObject,
	PIRP			iIrp,
	PVOID			iContext )  // 输入参数
{
	mPDEVICE_EXTENSION	mDeviceExtension = iDeviceObject -> DeviceExtension;  // 设备扩展
	if ( iIrp -> PendingReturned ) IoMarkIrpPending( iIrp );
	if ( iContext ) {
		KeSetEvent( & mDeviceExtension -> ThreadPowerEvent, EVENT_INCREMENT, FALSE );  // 置线程启动事件
	}
	else {
		PoStartNextPowerIrp( iIrp );  // 开始下一个操作
		IoCompleteRequest( iIrp, IO_NO_INCREMENT );  // 完成当前IRP
	}
	return( STATUS_MORE_PROCESSING_REQUIRED );  // 阻止继续处理当前IRP
}

VOID		mThreadDevPower(  // 系统线程
	PVOID	iContext )
{
	ULONG				i;
	PIRP				mIrp;
	NTSTATUS			mStatus;
	POWER_STATE			mPowerState;
	PDEVICE_OBJECT		mDeviceObject;
	mPDEVICE_EXTENSION	mDeviceExtension;
	mDeviceObject = (PDEVICE_OBJECT)iContext;  // 设备对象
	mDeviceExtension = mDeviceObject -> DeviceExtension;  // 设备扩展
	InterlockedIncrement( & mDeviceExtension -> mThreadCount );
	KeSetPriorityThread( KeGetCurrentThread(), LOW_REALTIME_PRIORITY );  // 设定当前线程为低实时优先级
	while ( mDriverObject != NULL && mDeviceExtension -> mExtDeviceRemove == FALSE ) {
		KeWaitForSingleObject( & mDeviceExtension -> ThreadPowerEvent, Executive, KernelMode, FALSE, NULL );
		if ( mDeviceExtension -> mExtDeviceRemove ) break;
		mIrp = InterlockedExchangePointer( & mDeviceExtension -> mDevPowerIrp, NULL );
		if ( mIrp != NULL && mDeviceExtension -> mPowerState == PowerDeviceD3 ) {
//			IoSetDeviceInterfaceState( & mDeviceExtension -> mSymbolicName, FALSE );  // 禁用设备接口
			KeClearEvent( & mDeviceExtension -> ThreadStartEvent );  // 清事件
			KeClearEvent( & mDeviceExtension -> DnThreadStartEvent );  // 清事件
			for ( i = 0; i < 30; i ++ ) {
				if ( mDeviceExtension -> ThreadUsbCount == 0 && mDeviceExtension -> DnThreadUsbCount == 0 ) break;
				if ( mDeviceExtension -> ThreadUsbCount ) mRequestPipe( mDeviceObject, (USHORT)( i > 24 ? URB_FUNCTION_RESET_PIPE : URB_FUNCTION_ABORT_PIPE ), mPipeDataUp );  // 取消请求
				if ( mDeviceExtension -> DnThreadUsbCount ) mRequestPipe( mDeviceObject, (USHORT)( i > 24 ? URB_FUNCTION_RESET_PIPE : URB_FUNCTION_ABORT_PIPE ), mPipeDataDown );  // 取消请求
				if ( i == 10 || i == 20 ) KeSetEvent( & mDeviceExtension -> mExtThreadToutEvent, EVENT_INCREMENT, FALSE );  // 置线程启动事件
				mDelay20mS( );
			}
			mDeactiveConfig( mDeviceObject, NULL );  // 去除配置
			IoCopyCurrentIrpStackLocationToNext( mIrp );  // 复制当前栈单元
			IoSetCompletionRoutine( mIrp, mDevPwrCompletRoutine, NULL, TRUE, TRUE, TRUE );  // 设置设定完成例程
			mStatus = PoCallDriver( mDeviceExtension -> mExtNextLowerDevice, mIrp );  // 传送至下级设备
		}
		else if ( mIrp != NULL && mDeviceExtension -> mPowerState == PowerDeviceD0 ) {
			for ( i = 0; i < 8; i ++ ) {
				if ( i ) {
					mDelay20mS( );
					if ( i == 6 ) { mDelay20mS( ); mDelay20mS( ); mDelay20mS( ); }
				}
				mDeviceExtension -> mDeviceGone = FALSE;
				if ( mIsDeviceExist( mDeviceObject, STATUS_SUCCESS ) ) break;
			}
			mStatus = mActiveConfig( mDeviceObject, NULL );  // 激活配置
			if ( ! NT_SUCCESS( mStatus ) ) {
				mDelay20mS( );
				mStatus = mActiveConfig( mDeviceObject, NULL );  // 重新激活配置
			}
			mDeviceExtension -> mExtDeviceStart = TRUE;
			KeSetEvent( & mDeviceExtension -> mExtThreadToutEvent, EVENT_INCREMENT, FALSE );  // 置线程启动事件
			KeSetEvent( & mDeviceExtension -> ThreadStartEvent, EVENT_INCREMENT, FALSE );  // 置线程启动事件
			KeSetEvent( & mDeviceExtension -> DnThreadStartEvent, EVENT_INCREMENT, FALSE );  // 置线程启动事件
			PoStartNextPowerIrp( mIrp );  // 开始下一个操作
			IoCompleteRequest( mIrp, IO_NO_INCREMENT );  // 完成当前IRP
//			IoSetDeviceInterfaceState( & mDeviceExtension -> mSymbolicName, TRUE );  // 允许设备接口
			mPowerState.DeviceState = PowerDeviceD0;
			PoSetPowerState ( mDeviceObject, DevicePowerState, mPowerState );
		}
	}
	InterlockedDecrement( & mDeviceExtension -> mThreadCount );
	PsTerminateSystemThread( STATUS_SUCCESS );  // 终止系统线程
}

NTSTATUS	mDispatchSystemControl(  // 系统WMI控制
	PDEVICE_OBJECT	iDeviceObject,
	PIRP			iIrp )
{
	mPDEVICE_EXTENSION	mDeviceExtension = iDeviceObject -> DeviceExtension;  // 设备扩展
	IoSkipCurrentIrpStackLocation( iIrp );  // 直接传送当前栈
	return( IoCallDriver( mDeviceExtension -> mExtNextLowerDevice, iIrp ) );  // 传送至下级设备
}

NTSTATUS	mDispatchPnp(  // 即插即用
	PDEVICE_OBJECT	iDeviceObject,
	PIRP			iIrp )
{
	ULONG				i, mCompletion;  // 0:下传, 1:完成, 2:返回状态
	NTSTATUS			mStatus;
	PDEVICE_OBJECT		mNextDeviceObject;
	mPDEVICE_EXTENSION	mDeviceExtension = iDeviceObject -> DeviceExtension;  // 设备扩展
	mNextDeviceObject = mDeviceExtension -> mExtNextLowerDevice ;
	mCompletion = 0;  // 预置为下传
	switch( IoGetCurrentIrpStackLocation( iIrp ) -> MinorFunction ) {  // 检查PnP子功能代码
		case IRP_MN_START_DEVICE:  // 启动设备
			mStatus = mWaitCompletion( iDeviceObject, iIrp );  // 等待IRP完成
			if ( NT_SUCCESS( mStatus ) ) {  // 设备启动完成
				mStatus = mActiveConfig( iDeviceObject, iIrp );  // 设备启动完成则激活配置
				if ( ! NT_SUCCESS( mStatus ) ) mStatus = mActiveConfig( iDeviceObject, iIrp );  // 重新激活配置
				if ( NT_SUCCESS( mStatus ) ) {  // 设备配置完成
					mDeviceExtension -> mPowerState = PowerDeviceD0;
					mDeviceExtension -> mExtDeviceStart = TRUE;  // 置设备启动标志
					mDeviceExtension -> mExtDeviceRemove = FALSE;  // 清设备移除标志
					KeSetEvent( & mDeviceExtension -> mExtThreadToutEvent, EVENT_INCREMENT, FALSE );  // 置线程启动事件
					KeSetEvent( & mDeviceExtension -> ThreadStartEvent, EVENT_INCREMENT, FALSE );  // 置线程启动事件
					KeSetEvent( & mDeviceExtension -> DnThreadStartEvent, EVENT_INCREMENT, FALSE );  // 置线程启动事件
					IoSetDeviceInterfaceState( & mDeviceExtension -> mExtDeviceName, TRUE );  // 允许设备接口
				}
			}
			mCompletion = 1;  // 操作已经完成
			break;
		case IRP_MN_QUERY_STOP_DEVICE:  // 将要停止设备
			if ( mDeviceExtension -> mExtIoCount != 0 ) {  // 当前正在操作
				mStatus = STATUS_UNSUCCESSFUL;  // 无法停止,操作失败
				iIrp -> IoStatus.Information = 0;
				mCompletion = 1;  // 强制操作完成
			}
			else mDeviceExtension -> mExtDeviceStart = FALSE;  // 清除设备启动标志
			break;
		case IRP_MN_CANCEL_STOP_DEVICE:  // 取消停止设备
			mDeviceExtension -> mExtDeviceStart = TRUE;  // 恢复设备启动标志
			KeSetEvent( & mDeviceExtension -> mExtThreadToutEvent, EVENT_INCREMENT, FALSE );  // 置线程启动事件
			KeSetEvent( & mDeviceExtension -> ThreadStartEvent, EVENT_INCREMENT, FALSE );  // 置线程启动事件
			KeSetEvent( & mDeviceExtension -> DnThreadStartEvent, EVENT_INCREMENT, FALSE );  // 置线程启动事件
			break;
		case IRP_MN_STOP_DEVICE:  // 停止设备
			mDeviceExtension -> mExtDeviceStart = FALSE;  // 清除设备启动标志
			mDeactiveConfig( iDeviceObject, iIrp );  // 去除配置
			break;
		case IRP_MN_QUERY_REMOVE_DEVICE:  // 将要移除设备
			if ( mDeviceExtension -> mExtDeviceOpen != 0 ||  // 打开计数不为0则尚未关闭
				 mDeviceExtension -> mExtIoCount != 0 ) {  // 或者当前正在操作
				mStatus = STATUS_UNSUCCESSFUL;  // 无法移除,操作失败
				iIrp -> IoStatus.Information = 0;
				mCompletion = 1;  // 强制操作完成
			}
			else {  // 尚未打开且设备空闲
				mDeviceExtension -> mExtDeviceRemove = TRUE;  // 置设备移除标志
				IoSetDeviceInterfaceState( & mDeviceExtension -> mExtDeviceName, FALSE );  // 禁用设备接口
			}
			break;
		case IRP_MN_CANCEL_REMOVE_DEVICE:  // 取消移除设备
			mDeviceExtension -> mExtDeviceRemove = FALSE;  // 清设备移除标志
			IoSetDeviceInterfaceState( & mDeviceExtension -> mExtDeviceName, TRUE );  // 恢复设备接口
			break;
		case IRP_MN_SURPRISE_REMOVAL:  // 意外地移除设备
			mDeviceExtension -> mExtDeviceRemove = TRUE;  // 置设备移除标志
			IoSetDeviceInterfaceState( & mDeviceExtension -> mExtDeviceName, FALSE );  // 禁用设备接口
			break;
		case IRP_MN_REMOVE_DEVICE:  // 移除设备
			mDeviceExtension -> mExtDeviceRemove = TRUE;  // 置设备移除标志
			IoSetDeviceInterfaceState( & mDeviceExtension -> mExtDeviceName, FALSE );  // 禁用设备接口
			mDeviceExtension -> mExtDeviceStart = FALSE;  // 清除设备启动标志
			mDeviceExtension -> mExtDownStartTime.u.HighPart = 0x87654321;
			mDeviceExtension -> mExtUpStartTime.u.HighPart = 0x87654321;
			mDeviceExtension -> mExtAuxStartTime.u.HighPart = 0x87654321;
			mDeviceExtension -> mExtInterStartTime.u.HighPart = 0x87654321;
			mDeviceExtension -> ThreadBufSize = 0;  // 强制退出
			mDeviceExtension -> DnThreadBufSize = 0;  // 强制退出
			KeSetEvent( & mDeviceExtension -> mExtThreadToutEvent, EVENT_INCREMENT, FALSE );  // 置线程启动事件
			KeSetEvent( & mDeviceExtension -> ThreadStartEvent, IO_CH375_INCREMENT, FALSE );  // 置线程启动事件
			KeSetEvent( & mDeviceExtension -> DnThreadStartEvent, IO_CH375_INCREMENT, FALSE );  // 置线程启动事件
			for ( i = 0; i < 10; i ++ ) {  /* 取消未完成USB通讯 */
				if ( mDeviceExtension -> mExtIoCount == 0 ) break;  /* 操作完成 */
				if ( i >= 5 ) {  /* 强制取消 */
					if ( mDeviceExtension -> mExtUsbDownCount ) mRequestPipe( iDeviceObject, (USHORT)( i >= 8 ? URB_FUNCTION_RESET_PIPE : URB_FUNCTION_ABORT_PIPE ), mPipeDataDown );  // 在下传管道执行取消请求
					if ( mDeviceExtension -> mExtUsbUpCount ) mRequestPipe( iDeviceObject, (USHORT)( i >= 8 ? URB_FUNCTION_RESET_PIPE : URB_FUNCTION_ABORT_PIPE ), mPipeDataUp );  // 在上传管道执行取消请求
					if ( mDeviceExtension -> mExtUsbAuxCount ) mRequestPipe( iDeviceObject, (USHORT)( i >= 8 ? URB_FUNCTION_RESET_PIPE : URB_FUNCTION_ABORT_PIPE ), mPipeAuxDown );  // 在辅助下传管道执行取消请求
					if ( mDeviceExtension -> mExtUsbInterCount ) mRequestPipe( iDeviceObject, (USHORT)( i >= 8 ? URB_FUNCTION_RESET_PIPE : URB_FUNCTION_ABORT_PIPE ), mPipeInterUp );  // 在中断上传管道执行取消请求
				}
				mDelay20mS( );
				if ( mDeviceExtension -> mExtIoCount == 0 ) break;  /* 操作完成 */
			}
			while ( ! NT_SUCCESS( mExitThreadRead( iDeviceObject ) ) );
			while ( ! NT_SUCCESS( mExitThreadWrite( iDeviceObject ) ) );
			for ( i = 0; i < 10; i ++ ) {
				if ( mDeviceExtension -> mThreadCount == 0 ) break;
				KeSetEvent( & mDeviceExtension -> mExtThreadToutEvent, IO_CH375_INCREMENT, FALSE );  // 置线程启动事件
				KeSetEvent( & mDeviceExtension -> ThreadPowerEvent, IO_CH375_INCREMENT, FALSE );  // 置线程启动事件
				if ( mDeviceExtension -> mThreadCount == 0 ) break;
				mDelay20mS( );
			}
			mDeactiveConfig( iDeviceObject, iIrp );  // 去除配置
			if ( i >= 10 ) mResetUsbDevice( iDeviceObject );
			mRemoveDevice( iDeviceObject );  // 移除设备操作
//			IoSkipCurrentIrpStackLocation( iIrp );  // 直接传送当前栈
//			mStatus = IoCallDriver( mNextDeviceObject, iIrp );  // 传送至下级设备
//			mCompletion = 2;  // 操作已经完成,返回状态
			break;
		case IRP_MN_QUERY_CAPABILITIES: {
			/*PDEVICE_CAPABILITIES	DevCap;
			DevCap = IoGetCurrentIrpStackLocation( iIrp ) -> Parameters.DeviceCapabilities.Capabilities;
//			DevCap -> Version = 1;
//			DevCap -> Size = sizeof( DEVICE_CAPABILITIES );
			DevCap -> SystemWake = PowerSystemUnspecified;
			DevCap -> DeviceWake = PowerDeviceUnspecified;
			DevCap -> D1Latency = 0;
			DevCap -> D2Latency = 0;
			DevCap -> D3Latency = 0;
			DevCap -> LockSupported = FALSE;
			DevCap -> EjectSupported = FALSE;
			DevCap -> Removable = TRUE;
			DevCap -> DockDevice = FALSE;
//			DevCap -> UniqueID = TRUE;
			DevCap -> UniqueID = FALSE;
			DevCap -> SilentInstall = TRUE;  //?
			DevCap -> SurpriseRemovalOK = TRUE;  //?
//98			DevCap -> NoDisplayInUI = FALSE ;
//			DevCap -> RawDeviceOK = TRUE;
			mStatus = STATUS_SUCCESS;
			mCompletion = 1;  // 操作已经完成
			break;*/
			PDEVICE_CAPABILITIES DevCap;
                        DevCap = IoGetCurrentIrpStackLocation( iIrp ) -> Parameters.DeviceCapabilities.Capabilities;
                        //   DevCap -> Version = 1;
                        //   DevCap -> Size = sizeof( DEVICE_CAPABILITIES );
                        DevCap -> SystemWake = PowerSystemUnspecified;
                        DevCap -> DeviceWake = PowerDeviceUnspecified;
                        DevCap -> D1Latency = 0;
                        DevCap -> D2Latency = 0;
                        DevCap -> D3Latency = 0;
                        DevCap -> LockSupported = FALSE;
                        DevCap -> EjectSupported = FALSE;
                        DevCap -> Removable = TRUE;
                        DevCap -> DockDevice = FALSE;
                        //   DevCap -> UniqueID = TRUE;
                        DevCap -> UniqueID = FALSE;
                        DevCap -> SilentInstall = TRUE;  //?
                        DevCap -> SurpriseRemovalOK = TRUE;  //?
                        //98  DevCap -> NoDisplayInUI = FALSE ;
                        //   DevCap -> RawDeviceOK = TRUE;
                        mStatus = mWaitCompletion(iDeviceObject,iIrp);
                        //   DevCap -> Version = 1;
                        //   DevCap -> Size = sizeof( DEVICE_CAPABILITIES );
                        DevCap -> SystemWake = PowerSystemUnspecified;
                        DevCap -> DeviceWake = PowerDeviceUnspecified;
                        DevCap -> D1Latency = 0;
                        DevCap -> D2Latency = 0;
                        DevCap -> D3Latency = 0;
                        DevCap -> LockSupported = FALSE;
                        DevCap -> EjectSupported = FALSE;
                        DevCap -> Removable = TRUE;
                        DevCap -> DockDevice = FALSE;
                        //   DevCap -> UniqueID = TRUE;
                        DevCap -> UniqueID = FALSE;
                        DevCap -> SilentInstall = TRUE;  //?
                        DevCap -> SurpriseRemovalOK = TRUE;  //?
                        //98   DevCap -> NoDisplayInUI = FALSE ;
                        //   DevCap -> RawDeviceOK = TRUE;
                        //mStatus = STATUS_SUCCESS;
                        mCompletion = 1;  // 操作已经完成
                        break;
		}
		default:
			break;
	}
	if ( mCompletion == 0 ) {  // 操作尚未完成则继续下传
		IoSkipCurrentIrpStackLocation( iIrp );  // 直接传送当前栈
		mStatus = IoCallDriver( mNextDeviceObject, iIrp );  // 传送至下级设备
	}
	else if ( mCompletion == 1 ) {  // 操作已经完成
		iIrp -> IoStatus.Status = mStatus;  // 置完成状态
		IoCompleteRequest( iIrp, IO_NO_INCREMENT );  // 完成当前IRP
	}
	return( mStatus );
}

NTSTATUS	mWaitCompletion(  // 等待IRP操作完成
	PDEVICE_OBJECT	iDeviceObject,
	PIRP			iIrp )
{
	KEVENT				mEvent;
	NTSTATUS			mStatus;
	mPDEVICE_EXTENSION	mDeviceExtension = iDeviceObject -> DeviceExtension;  // 设备扩展
	KeInitializeEvent( &mEvent, NotificationEvent, FALSE );  // 初始化IRP完成事件为无效
	IoCopyCurrentIrpStackLocationToNext( iIrp );  // 复制当前栈单元
	IoSetCompletionRoutine( iIrp, mCompletionRoutine, &mEvent, TRUE, TRUE, TRUE );  // 设置设定完成例程
	mStatus = IoCallDriver( mDeviceExtension -> mExtNextLowerDevice, iIrp );  // 传送至下级设备
	if ( mStatus == STATUS_PENDING ) {  // 等待被悬挂的IO请求完成
		KeWaitForSingleObject( &mEvent, Executive, KernelMode, FALSE, NULL );  // 挂起等待IRP完成
		mStatus = iIrp -> IoStatus.Status;  // 取完成状态
	}
	return( mStatus );  // 返回状态
}

NTSTATUS	mCompletionRoutine(  // 操作完成例程
	PDEVICE_OBJECT	iDeviceObject,
	PIRP			iIrp,
	PVOID			iContext )  // 输入参数,完成事件
{
	KeSetEvent( (PKEVENT)iContext, IO_NO_INCREMENT, FALSE );  // 置操作完成事件
	return( STATUS_MORE_PROCESSING_REQUIRED );  // 阻止继续处理当前IRP
}

NTSTATUS	mActiveConfig(  // 激活配置
	PDEVICE_OBJECT	iDeviceObject,
	PIRP			iIrp )
{
	ULONG							i;
	PURB							mUrb;
	NTSTATUS						mStatus;
	PUSB_CONFIGURATION_DESCRIPTOR	mConfigDescriptor;
	PUSB_INTERFACE_DESCRIPTOR		mInterfaceDescriptor;
	USBD_INTERFACE_LIST_ENTRY		mInterfaceList[2];
	PUSBD_INTERFACE_INFORMATION		mInterface;
	PUSBD_PIPE_INFORMATION			mPipe;
	mPDEVICE_EXTENSION				mDeviceExtension = iDeviceObject -> DeviceExtension;  // 设备扩展
	mStatus = STATUS_INSUFFICIENT_RESOURCES;  // 预置操作失败
	mDeviceExtension -> mExtInterUpPipe = NULL;
	mDeviceExtension -> mExtAuxDownPipe = NULL;
	mDeviceExtension -> mExtDataUpPipe = NULL;
	mDeviceExtension -> mExtDataDownPipe = NULL;
	mConfigDescriptor = ExAllocatePool( NonPagedPool,  // 分配内存作为配置描述符区域和URB请求块
										256 + sizeof( URB ) );
	if ( mConfigDescriptor != NULL ) {  // 分配了内存
		mUrb = (PURB) ( (PUCHAR)mConfigDescriptor + 256 );  // 指向URB请求块,前256字节保留给配置描述符
		UsbBuildGetDescriptorRequest( mUrb, sizeof( struct _URB_CONTROL_DESCRIPTOR_REQUEST ),  // 构造获取配置描述符的URB
									  USB_CONFIGURATION_DESCRIPTOR_TYPE, 0, 0, mConfigDescriptor, NULL,  // 缓冲区
									  sizeof( USB_CONFIGURATION_DESCRIPTOR ), NULL );  // 配置描述符长度
		mStatus = mUsbSubmitUrb( iDeviceObject, mUrb );  // 提交URB
		if ( NT_SUCCESS( mStatus ) && mConfigDescriptor -> wTotalLength > 255 ) mStatus = STATUS_DEVICE_DATA_ERROR;
		if ( NT_SUCCESS( mStatus ) ) {  // 获取了配置描述符
			UsbBuildGetDescriptorRequest( mUrb, sizeof(struct _URB_CONTROL_DESCRIPTOR_REQUEST ),  // 构造获取配置描述符的URB
										  USB_CONFIGURATION_DESCRIPTOR_TYPE, 0, 0, mConfigDescriptor, NULL,  // 缓冲区
										  (ULONG)( mConfigDescriptor -> wTotalLength ), NULL );  // 配置描述符和配置信息的总长度
			mStatus = mUsbSubmitUrb( iDeviceObject, mUrb );  // 提交URB
			if ( NT_SUCCESS( mStatus ) && mConfigDescriptor -> bNumInterfaces == 0 )  // 获取了配置描述符但是不完整
				mStatus = STATUS_DEVICE_DATA_ERROR;  // 接口描述符无效
			if ( NT_SUCCESS( mStatus ) ) {  // 获取了配置描述符且接口描述符有效
				mInterfaceDescriptor = USBD_ParseConfigurationDescriptorEx( mConfigDescriptor, mConfigDescriptor,
																			-1, -1, -1, -1, -1 );  // 获取第一个接口描述符
				mInterfaceList[0].InterfaceDescriptor = mInterfaceDescriptor;  // 填充需要激活配置的接口列表
				mInterfaceList[0].Interface = NULL;
				mInterfaceList[1].InterfaceDescriptor = NULL;  // 列表结束
				mInterfaceList[1].Interface = NULL;
				mUrb = USBD_CreateConfigurationRequestEx( mConfigDescriptor, mInterfaceList );  // 构造配置请求的URB
				if ( mUrb != NULL ) {  // 生成了URB
					mInterface = & mUrb -> UrbSelectConfiguration.Interface;  // 当前接口的信息
					for ( i = 0; i < mInterface -> NumberOfPipes; ++i ) {  // 检查所有端点/管道
						mPipe = & mInterface -> Pipes[ i ];  // 指向管道
						if ( mPipe -> MaximumTransferSize > mMAX_BUFFER_LENGTH )  // 默认的长度较大
							mPipe -> MaximumTransferSize = mMAX_BUFFER_LENGTH;  // 单个请求的最大长度
					}
					mStatus = mUsbSubmitUrb( iDeviceObject, mUrb );  // 提交URB
					if ( NT_SUCCESS( mStatus ) ) {  // 配置CH375芯片完成
						mInterface = & mUrb -> UrbSelectConfiguration.Interface;  // 当前接口的信息
						for ( i = 0; i < mInterface -> NumberOfPipes; ++i ) {  // 检查所有端点/管道
							mPipe = & mInterface -> Pipes[ i ];  // 指向管道
							if ( mPipe -> MaximumTransferSize > mMAX_BUFFER_LENGTH )  // 默认的长度较大
								mPipe -> MaximumTransferSize = mMAX_BUFFER_LENGTH;  // 单个请求的最大长度
							switch( mPipe -> EndpointAddress ) {  // 比较端点地址,以确定管道功能
								case mCH375_ENDP_INTER_UP:  // 中断数据上传端点的地址
									mDeviceExtension -> mExtInterUpPipe = mPipe -> PipeHandle;  // 保存中断数据上传管道的句柄
									break;
								case mCH375_ENDP_AUX_DOWN:  // 辅助数据下传端点的地址
									mDeviceExtension -> mExtAuxDownPipe = mPipe -> PipeHandle;  // 保存辅助数据下传管道的句柄
									break;
								case mCH375_ENDP_DATA_UP:  // 数据块上传端点的地址
									mDeviceExtension -> mExtDataUpPipe = mPipe -> PipeHandle;  // 保存数据块上传管道的句柄
									if ( mPipe -> MaximumPacketSize <= 8 ) mStatus = STATUS_NO_SUCH_DEVICE;  // 不是CH375芯片,设备无效
									break;
								case mCH375_ENDP_DATA_DOWN:  // 数据块下传端点的地址
									mDeviceExtension -> mExtDataDownPipe = mPipe -> PipeHandle;  // 保存数据块下传管道的句柄
									if ( mPipe -> MaximumPacketSize <= 8 ) mStatus = STATUS_NO_SUCH_DEVICE;  // 不是CH375芯片,设备无效
									break;
							}
						}
					}
					ExFreePool( mUrb );  // 释放URB内存
				}
				else mStatus = STATUS_INSUFFICIENT_RESOURCES;  // 无法构造URB
			}
		}
		ExFreePool( mConfigDescriptor );  // 释放配置描述符内存
	}
	return( mStatus );  // 返回状态
}

NTSTATUS	mDeactiveConfig(  // 去除配置
	PDEVICE_OBJECT	iDeviceObject,
	PIRP			iIrp )
{
	PURB				mUrb;
	mPDEVICE_EXTENSION	mDeviceExtension;
	NTSTATUS			mStatus = STATUS_INSUFFICIENT_RESOURCES;  // 预置操作失败
	if ( mIsDeviceExist( iDeviceObject, STATUS_SUCCESS ) == FALSE ) return( STATUS_NO_SUCH_DEVICE );  // 设备已经移除
	mUrb = ExAllocatePool( NonPagedPool, sizeof( URB ) );  // 分配USB请求块
	if ( mUrb != NULL ) {  // 分配了USB请求块
		UsbBuildSelectConfigurationRequest( mUrb, sizeof( struct _URB_SELECT_CONFIGURATION ), NULL );  // 构造URB请求配置
		mStatus = mUsbSubmitUrb( iDeviceObject, mUrb );  // 提交URB
		ExFreePool( mUrb );  // 释放URB
		mDeviceExtension = iDeviceObject -> DeviceExtension;  // 设备扩展
		mDeviceExtension -> mExtInterUpPipe = NULL;
		mDeviceExtension -> mExtAuxDownPipe = NULL;
		mDeviceExtension -> mExtDataUpPipe = NULL;
		mDeviceExtension -> mExtDataDownPipe = NULL;
	}
	return( mStatus );  // 返回状态
}

NTSTATUS	mUsbSubmitUrb(  // 提交URB请求
	PDEVICE_OBJECT	iDeviceObject,
	PURB			iUrb )
{
	PIRP				mIrp;
	KEVENT				mEvent;
	mPDEVICE_EXTENSION	mDeviceExtension;
	IO_STATUS_BLOCK		mIoStatusBlock;
	NTSTATUS			mStatus = STATUS_INSUFFICIENT_RESOURCES;  // 预置操作失败
	mDeviceExtension = iDeviceObject -> DeviceExtension;  // 设备扩展
	InterlockedIncrement( & mDeviceExtension -> mExtIoCount );  // 操作计数增量,阻止中途停止或者移除设备
	KeInitializeEvent( &mEvent, NotificationEvent, FALSE );  // 初始化IRP完成事件信号为无效
	mIrp = IoBuildDeviceIoControlRequest( IOCTL_INTERNAL_USB_SUBMIT_URB, mDeviceExtension -> mExtNextLowerDevice,
										  NULL, 0, NULL, 0, TRUE, &mEvent, &mIoStatusBlock );  // 构造IRP提交URB
	if ( mIrp != NULL ) {  // IRP有效
		IoGetNextIrpStackLocation( mIrp ) -> Parameters.Others.Argument1 = iUrb;  // 将URB作为参数传递给下级设备
		mStatus = IoCallDriver( mDeviceExtension -> mExtNextLowerDevice, mIrp );  // 向下级设备发送IO请求
		if ( mStatus == STATUS_PENDING ) {  // 等待被悬挂的IO请求完成
			KeWaitForSingleObject( &mEvent, Executive, KernelMode, FALSE, NULL );  // 挂起等待IRP完成
			mStatus = mIoStatusBlock.Status;  // 取完成状态
		}
		if ( mStatus == STATUS_TIMEOUT ) mStatus = STATUS_IO_TIMEOUT;  // 转换出错代码
	}
	InterlockedDecrement( & mDeviceExtension -> mExtIoCount );  // 操作计数减量
	return( mStatus );  // 返回状态
}

BOOLEAN		mIsDeviceExist(  // 查询USB设备是否存在
	PDEVICE_OBJECT	iDeviceObject,
	NTSTATUS		iStatus )
{
	ULONG				mPortStatus;
	PIRP				mIrp;
	KEVENT				mEvent;
	mPDEVICE_EXTENSION	mDeviceExtension;
	IO_STATUS_BLOCK		mIoStatusBlock;
	NTSTATUS			mStatus;  // 预置操作失败
	mDeviceExtension = iDeviceObject -> DeviceExtension;  // 设备扩展
	if ( mDeviceExtension -> mDeviceGone ) return( FALSE );
	if ( iStatus == STATUS_NO_SUCH_DEVICE || iStatus == STATUS_DEVICE_DOES_NOT_EXIST
		|| iStatus == STATUS_DEVICE_NOT_CONNECTED
		|| iStatus == STATUS_NO_SUCH_FILE || iStatus == STATUS_DEVICE_OFF_LINE ) {
			mDeviceExtension -> mDeviceGone = TRUE;  // 设备已经移除
			return( FALSE );  // 设备已经移除
	}
	if ( mDeviceExtension -> mPowerState == PowerDeviceD3 ) {  // 睡眠或者尚未初始化
		return( mDeviceExtension -> mDeviceGone ? FALSE : TRUE );
	}
	if ( InterlockedIncrement( & mDeviceExtension -> mOnDevExist ) != 1 ) {
		if ( mDeviceExtension -> mOnDevExist != 1 ) {
			mDelay20mS( );
			if ( mDeviceExtension -> mOnDevExist != 1 ) {
				mDelay20mS( );
				if ( mDeviceExtension -> mOnDevExist != 1 ) {
					InterlockedDecrement( & mDeviceExtension -> mOnDevExist );
					if ( mDeviceExtension -> mDeviceGone ) return( FALSE );
					return( TRUE );
				}
			}
		}
	}
	KeInitializeEvent( &mEvent, NotificationEvent, FALSE );  // 初始化IRP完成事件信号为无效
	for ( mPortStatus = 0; mPortStatus < 5; mPortStatus ++ ) {
		mIrp = IoBuildDeviceIoControlRequest( IOCTL_INTERNAL_USB_GET_PORT_STATUS,  // 构造IRP查询端口状态
											  mDeviceExtension -> mExtNextLowerDevice,
											  NULL, 0, NULL, 0, TRUE, &mEvent, &mIoStatusBlock );
		if ( mIrp ) break;
		mDelay20mS( );
		mDelay20mS( );
	}
	if ( mIrp == NULL ) {
		InterlockedDecrement( & mDeviceExtension -> mOnDevExist );
		return( FALSE );
	}
	mPortStatus = 0;
	IoGetNextIrpStackLocation( mIrp ) -> Parameters.Others.Argument1 = &mPortStatus;  // 参数传递给下级设备
	mStatus = IoCallDriver( mDeviceExtension -> mExtNextLowerDevice, mIrp );  // 向下级设备发送IO请求
	if ( mStatus == STATUS_PENDING ) {  // 等待被悬挂的IO请求完成
		KeWaitForSingleObject( &mEvent, Executive, KernelMode, FALSE, NULL );  // 挂起等待IRP完成
		mStatus = mIoStatusBlock.Status;  // 取完成状态
	}
	InterlockedDecrement( & mDeviceExtension -> mOnDevExist );
	if ( mStatus == STATUS_NO_SUCH_DEVICE || mStatus == STATUS_DEVICE_DOES_NOT_EXIST
		|| mStatus == STATUS_DEVICE_NOT_CONNECTED
		|| mStatus == STATUS_NO_SUCH_FILE || mStatus == STATUS_DEVICE_OFF_LINE
		|| mStatus == STATUS_UNSUCCESSFUL ) {  // 设备不存在
			mDeviceExtension -> mDeviceGone = TRUE;  // 设备已经移除
			return( FALSE );
	}
	if ( mStatus == STATUS_END_OF_FILE || mStatus == STATUS_DEVICE_NOT_READY
		|| mStatus == STATUS_INVALID_DEVICE_REQUEST || mStatus == STATUS_INVALID_DEVICE_STATE
		|| mStatus == STATUS_IO_TIMEOUT || mStatus == STATUS_TIMEOUT ) {  // 设备不存在
			return( FALSE );
	}
	if ( mStatus == STATUS_SUCCESS ) {
		if ( ( mPortStatus & USBD_PORT_CONNECTED ) == 0 ) mDeviceExtension -> mDeviceGone = TRUE;  // 设备已经移除
	}
	return( mPortStatus & USBD_PORT_CONNECTED ? TRUE : FALSE );  // 返回连接状态
}

VOID		mAbortAsyncRead(
	PDEVICE_OBJECT	iDeviceObject )
{
	mPLINK_URB_BUF		mWait;
	LARGE_INTEGER		mTime;
	mPDEVICE_EXTENSION	mDeviceExtension = iDeviceObject -> DeviceExtension;  // 设备扩展
	while ( mWait = mDeviceExtension -> ThreadQueueWait ) {
		mDeviceExtension -> ThreadQueueWait = mWait -> mNext;
		if ( mWait -> mStatus == STATUS_PENDING ) {  // 等待被悬挂的IO请求完成
			while ( 1 ) {
				mTime.QuadPart = 0 - 10000;
				mWait -> mStatus = KeWaitForSingleObject( & mWait -> mEvent, Executive, KernelMode, FALSE, &mTime );  // 挂起等待IRP完成
				if ( mWait -> mStatus != STATUS_TIMEOUT ) break;
				mRequestPipe( iDeviceObject, URB_FUNCTION_ABORT_PIPE, mPipeDataUp );  // 取消请求
			}
		}
		InterlockedDecrement( & mDeviceExtension -> ThreadUsbCount );
	}
}

VOID		mThreadRead(  // 系统线程
	PVOID	iContext )
{
	PUCHAR				mBuffer;
	KIRQL				mOldIrql;
	ULONG				i, mLength;
	PIRP				mIrp;
	PDEVICE_OBJECT		mDeviceObject;
	mPDEVICE_EXTENSION	mDeviceExtension;
	NTSTATUS			mStatus;
	mPLINK_URB_BUF		mFree, mWait;
	mDeviceObject = (PDEVICE_OBJECT)iContext;  // 设备对象
	mDeviceExtension = mDeviceObject -> DeviceExtension;  // 设备扩展
	InterlockedIncrement( & mDeviceExtension -> mThreadCount );
	KeSetPriorityThread( KeGetCurrentThread(), LOW_REALTIME_PRIORITY + 1 );  // 设定当前线程为低实时优先级
	mLength = 131072;
	mBuffer = ExAllocatePool( NonPagedPool, mLength );
	if ( mBuffer == NULL ) PsTerminateSystemThread( STATUS_INSUFFICIENT_RESOURCES );  // 终止系统线程
	mDeviceExtension -> ThreadInSize = 0;
	mLength = ( mLength - sizeof( mLINK_URB_BUF ) * mTHREAD_MAX_LINK ) / ( mCH375_PACKET_LENGTH + 1 );
	mDeviceExtension -> ThreadBufSize = mLength * ( mCH375_PACKET_LENGTH + 1 );
	mDeviceExtension -> ThreadInStart = mDeviceExtension -> ThreadOutStart = mBuffer;
	mDeviceExtension -> ThreadQueueWait = mDeviceExtension -> ThreadQueueFree = NULL;
	mDeviceExtension -> ThreadBuffer = mBuffer;
	mWait = (PVOID)( mDeviceExtension -> ThreadBuffer + mDeviceExtension -> ThreadBufSize );
	for ( mLength = 0; mLength < mTHREAD_MAX_LINK; mLength ++ ) {
		mWait -> mNext = mDeviceExtension -> ThreadQueueFree;
		KeInitializeEvent( & mWait -> mEvent, NotificationEvent, FALSE );  // 初始化IRP完成事件信号为无效
		mDeviceExtension -> ThreadQueueFree = mWait;
		mWait ++;
	}
	mDeviceExtension -> ThreadUsbCount = 0;
	while ( mDriverObject != NULL && mDeviceExtension -> mExtDeviceRemove == FALSE && mDeviceExtension -> ThreadBufSize != 0 ) {  // 系统未卸载,设备未移除
//		InterlockedIncrement( & mDeviceExtension -> mExtIoCount );  // 操作计数增量,阻止中途停止或者移除设备
		KeWaitForSingleObject( & mDeviceExtension -> ThreadStartEvent, Executive, KernelMode, FALSE, NULL );
		while ( mDriverObject != NULL && mDeviceExtension -> mPowerState == PowerDeviceD0  // 系统未卸载,设备未移除
				&& mDeviceExtension -> mExtDeviceStart != FALSE && mDeviceExtension -> mExtDeviceRemove == FALSE ) {  // 设备已经启动并且尚未移除
			if ( mDeviceExtension -> ThreadBufSize == 0 ) break;  // 强制退出
			while ( mFree = mDeviceExtension -> ThreadQueueFree ) {
				mDeviceExtension -> ThreadQueueFree = mFree -> mNext;
				mFree -> mNext = NULL;
				if ( mWait = mDeviceExtension -> ThreadQueueWait ) {
					while ( mWait -> mNext ) mWait = mWait -> mNext;
					mWait -> mNext = mFree;
				}
				else mDeviceExtension -> ThreadQueueWait = mFree;
				InterlockedIncrement( & mDeviceExtension -> ThreadUsbCount );  // 计数
				UsbBuildInterruptOrBulkTransferRequest( & mFree -> mUrb, sizeof( struct _URB_BULK_OR_INTERRUPT_TRANSFER ),  // 构造USB请求
														mDeviceExtension -> mExtDataUpPipe, mFree -> mBuffer, NULL, mCH375_PACKET_LENGTH,  // 管道的句柄
														USBD_TRANSFER_DIRECTION_IN | USBD_SHORT_TRANSFER_OK, NULL );  // 操作标志
				KeClearEvent( & mFree -> mEvent );  // IRP完成事件信号为无效
				mIrp = IoBuildDeviceIoControlRequest( IOCTL_INTERNAL_USB_SUBMIT_URB, mDeviceExtension -> mExtNextLowerDevice,
													  NULL, 0, NULL, 0, TRUE, & mFree -> mEvent, & mFree -> mIoStatusBlock );  // 构造IRP提交URB
				if ( mIrp != NULL ) {  // IRP有效
					IoGetNextIrpStackLocation( mIrp ) -> Parameters.Others.Argument1 = & mFree -> mUrb;  // 将URB作为参数传递给下级设备
					mFree -> mStatus = IoCallDriver( mDeviceExtension -> mExtNextLowerDevice, mIrp );  // 向下级设备发送IO请求
				}
				else mFree -> mStatus = STATUS_INSUFFICIENT_RESOURCES;  // 操作失败
			}
			mWait = mDeviceExtension -> ThreadQueueWait;
			if ( mWait == NULL ) break;
			mDeviceExtension -> ThreadQueueWait = mWait -> mNext;
			mWait -> mNext = mDeviceExtension -> ThreadQueueFree;
			mDeviceExtension -> ThreadQueueFree = mWait;
			if ( mWait -> mStatus == STATUS_PENDING ) {  // 等待被悬挂的IO请求完成
				KeWaitForSingleObject( & mWait -> mEvent, Executive, KernelMode, FALSE, NULL );  // 挂起等待IRP完成
				mWait -> mStatus = mWait -> mIoStatusBlock.Status;  // 取完成状态
			}
			InterlockedDecrement( & mDeviceExtension -> ThreadUsbCount );
			if ( mDeviceExtension -> ThreadBufSize == 0 ) break;  // 强制退出
			mStatus = mWait -> mStatus;
			mLength = mWait -> mUrb.UrbBulkOrInterruptTransfer.TransferBufferLength;  // 实际传输长度
			if ( NT_SUCCESS( mStatus ) && ( mLength || mWait -> mUrb.UrbBulkOrInterruptTransfer.Hdr.Status != USBD_STATUS_CANCELED ) ) {
				KeAcquireSpinLock( & mDeviceExtension -> mControlLock, &mOldIrql );
				if ( mDeviceExtension -> ThreadBuffer ) {
					if ( mDeviceExtension -> ThreadInStart >= mDeviceExtension -> ThreadBuffer + mDeviceExtension -> ThreadBufSize )
						mDeviceExtension -> ThreadInStart = mDeviceExtension -> ThreadBuffer;
					*( mDeviceExtension -> ThreadInStart ) = (UCHAR)mLength;
					RtlCopyMemory( mDeviceExtension -> ThreadInStart + 1, mWait -> mBuffer, mLength );
					mDeviceExtension -> ThreadInStart += mCH375_PACKET_LENGTH + 1;
					mDeviceExtension -> ThreadInSize += mCH375_PACKET_LENGTH + 1;
					if ( mDeviceExtension -> ThreadInSize > mDeviceExtension -> ThreadBufSize ) {  // 溢出处理
						mDeviceExtension -> ThreadInSize = mDeviceExtension -> ThreadBufSize;
						mDeviceExtension -> ThreadOutStart = mDeviceExtension -> ThreadInStart;
					}
				}
				KeReleaseSpinLock( & mDeviceExtension -> mControlLock, mOldIrql );
			}
			else if ( ! NT_SUCCESS( mStatus ) ) {
				if ( mIsDeviceExist( mDeviceObject, mStatus ) == FALSE ) break;  // 设备已经移除
				if ( mDeviceExtension -> mExtDeviceRemove == FALSE )  // 设备尚未移除
					mRequestPipe( mDeviceObject, URB_FUNCTION_RESET_PIPE, mPipeDataUp );  // 出错则复位管道
			}
		}
		mAbortAsyncRead( mDeviceObject );
//		InterlockedDecrement( & mDeviceExtension -> mExtIoCount );
		if ( mIsDeviceExist( mDeviceObject, STATUS_SUCCESS ) == FALSE ) break;  // 设备已经移除
	}
	mAbortAsyncRead( mDeviceObject );
	ExFreePool( mDeviceExtension -> ThreadBuffer );  // 释放内存
	mDeviceExtension -> ThreadBuffer = NULL;
	InterlockedDecrement( & mDeviceExtension -> mThreadCount );
	PsTerminateSystemThread( STATUS_SUCCESS );  // 终止系统线程
}

NTSTATUS	mExitThreadRead(
	PDEVICE_OBJECT	iDeviceObject )
{
	ULONG				i;
	mPDEVICE_EXTENSION	mDeviceExtension;
	mDeviceExtension = iDeviceObject -> DeviceExtension;  // 设备扩展
	for ( i = 0; i < 50; i ++ ) {
		mDeviceExtension -> ThreadBufSize = 0;  // 强制退出
		KeSetEvent( & mDeviceExtension -> ThreadStartEvent, IO_CH375_INCREMENT, FALSE );  // 置线程启动事件
		if ( mDeviceExtension -> ThreadBuffer == NULL ) break;
		mDelay20mS( );
		if ( mDeviceExtension -> ThreadBuffer == NULL ) break;
		mRequestPipe( iDeviceObject, (USHORT)( i > 30 ? URB_FUNCTION_RESET_PIPE : URB_FUNCTION_ABORT_PIPE ), mPipeDataUp );  // 取消请求
	}
	return( i >= 50 ? STATUS_UNSUCCESSFUL : STATUS_SUCCESS );
}

NTSTATUS	mGetBufferData(
	PDEVICE_OBJECT	iDeviceObject,
	PUCHAR			oBuffer,
	PULONG			ioLength )  // 输入为请求长度,输出为实际返回长度
{
	ULONG				mReqLen, mPktSize;
	KIRQL				mOldIrql;
	mPDEVICE_EXTENSION	mDeviceExtension;
	mDeviceExtension = iDeviceObject -> DeviceExtension;  // 设备扩展
	mReqLen = *ioLength;
	*ioLength = 0;
	if ( mDeviceExtension -> mExtDeviceRemove ) return( STATUS_CANCELLED );
	if ( mReqLen && mDeviceExtension -> ThreadInSize ) {
		KeAcquireSpinLock( & mDeviceExtension -> mControlLock, &mOldIrql );
		while ( mReqLen && mDeviceExtension -> ThreadInSize && mDeviceExtension -> ThreadBuffer ) {
			if ( mDeviceExtension -> ThreadOutStart >= mDeviceExtension -> ThreadBuffer + mDeviceExtension -> ThreadBufSize )
				mDeviceExtension -> ThreadOutStart = mDeviceExtension -> ThreadBuffer;
			mPktSize = *( mDeviceExtension -> ThreadOutStart );
			if ( mPktSize > mReqLen ) {
				if ( mPktSize > mCH375_PACKET_LENGTH ) mReqLen = 0;
				mPktSize = mReqLen;
			}
			RtlCopyMemory( oBuffer, mDeviceExtension -> ThreadOutStart + 1, mPktSize );
			mDeviceExtension -> ThreadOutStart += mCH375_PACKET_LENGTH + 1;
			mDeviceExtension -> ThreadInSize -= mCH375_PACKET_LENGTH + 1;
			oBuffer += mPktSize;
			mReqLen -= mPktSize;
			*ioLength += mPktSize;
		}
		KeReleaseSpinLock( & mDeviceExtension -> mControlLock, mOldIrql );
	}
	return( STATUS_SUCCESS );
}

VOID		mClearUpBufferData(
	PDEVICE_OBJECT	iDeviceObject )
{
	KIRQL				mOldIrql;
	mPDEVICE_EXTENSION	mDeviceExtension;
	mDeviceExtension = iDeviceObject -> DeviceExtension;  // 设备扩展
	KeAcquireSpinLock( & mDeviceExtension -> mControlLock, &mOldIrql );
	if ( mDeviceExtension -> ThreadBuffer ) {
		if ( mDeviceExtension -> ThreadInStart >= mDeviceExtension -> ThreadBuffer + mDeviceExtension -> ThreadBufSize )
			mDeviceExtension -> ThreadInStart = mDeviceExtension -> ThreadBuffer;
		mDeviceExtension -> ThreadOutStart = mDeviceExtension -> ThreadInStart;
		mDeviceExtension -> ThreadInSize = 0;
	}
	KeReleaseSpinLock( & mDeviceExtension -> mControlLock, mOldIrql );
}

VOID		mAbortAsyncWrite(
	PDEVICE_OBJECT	iDeviceObject )
{
	mPLINK_URB_BUF		mWait;
	LARGE_INTEGER		mTime;
	mPDEVICE_EXTENSION	mDeviceExtension = iDeviceObject -> DeviceExtension;  // 设备扩展
	while ( mWait = mDeviceExtension -> DnThreadQueueWait ) {
		mDeviceExtension -> DnThreadQueueWait = mWait -> mNext;
		if ( mWait -> mStatus == STATUS_PENDING ) {  // 等待被悬挂的IO请求完成
			while ( 1 ) {
				mTime.QuadPart = 0 - 10000;
				mWait -> mStatus = KeWaitForSingleObject( & mWait -> mEvent, Executive, KernelMode, FALSE, &mTime );  // 挂起等待IRP完成
				if ( mWait -> mStatus != STATUS_TIMEOUT ) break;
				mRequestPipe( iDeviceObject, URB_FUNCTION_ABORT_PIPE, mPipeDataDown );  // 取消请求
			}
		}
		InterlockedDecrement( & mDeviceExtension -> DnThreadUsbCount );
	}
}

VOID		mThreadWrite(  // 系统线程
	PVOID	iContext )
{
	PUCHAR				mBuffer;
	KIRQL				mOldIrql;
	ULONG				i, mLength;
	PIRP				mIrp;
	PDEVICE_OBJECT		mDeviceObject;
	mPDEVICE_EXTENSION	mDeviceExtension;
	NTSTATUS			mStatus;
	mPLINK_URB_BUF		mFree, mWait;
	mDeviceObject = (PDEVICE_OBJECT)iContext;  // 设备对象
	mDeviceExtension = mDeviceObject -> DeviceExtension;  // 设备扩展
	InterlockedIncrement( & mDeviceExtension -> mThreadCount );
	KeSetPriorityThread( KeGetCurrentThread(), LOW_REALTIME_PRIORITY );  // 设定当前线程为低实时优先级
	mLength = 131072;
	mBuffer = ExAllocatePool( NonPagedPool, mLength );
	if ( mBuffer == NULL ) PsTerminateSystemThread( STATUS_INSUFFICIENT_RESOURCES );  // 终止系统线程
	mDeviceExtension -> DnThreadInSize = 0;
	mLength = ( mLength - sizeof( mLINK_URB_BUF ) * mTHREAD_MAX_LINK ) / ( mCH375_PACKET_LENGTH + 1 );
	mDeviceExtension -> DnThreadBufSize = mLength * ( mCH375_PACKET_LENGTH + 1 );
	mDeviceExtension -> DnThreadInStart = mDeviceExtension -> DnThreadOutStart = mBuffer;
	mDeviceExtension -> DnThreadQueueWait = mDeviceExtension -> DnThreadQueueFree = NULL;
	mDeviceExtension -> DnThreadBuffer = mBuffer;
	mWait = (PVOID)( mDeviceExtension -> DnThreadBuffer + mDeviceExtension -> DnThreadBufSize );
	for ( mLength = 0; mLength < mTHREAD_MAX_LINK; mLength ++ ) {
		mWait -> mNext = mDeviceExtension -> DnThreadQueueFree;
		KeInitializeEvent( & mWait -> mEvent, NotificationEvent, FALSE );  // 初始化IRP完成事件信号为无效
		mDeviceExtension -> DnThreadQueueFree = mWait;
		mWait ++;
	}
	mDeviceExtension -> DnThreadUsbCount = 0;
	while ( mDriverObject != NULL && mDeviceExtension -> mExtDeviceRemove == FALSE && mDeviceExtension -> DnThreadBufSize != 0 ) {  // 系统未卸载,设备未移除
//		InterlockedIncrement( & mDeviceExtension -> mExtIoCount );  // 操作计数增量,阻止中途停止或者移除设备
ThreadWriteWait:
		if ( mDeviceExtension -> mExtDeviceStart == FALSE ) mAbortAsyncWrite( mDeviceObject );
		KeWaitForSingleObject( & mDeviceExtension -> DnThreadStartEvent, Executive, KernelMode, FALSE, NULL );
		while ( mDriverObject != NULL && mDeviceExtension -> mPowerState == PowerDeviceD0  // 系统未卸载,设备未移除
				&& mDeviceExtension -> mExtDeviceStart != FALSE && mDeviceExtension -> mExtDeviceRemove == FALSE ) {  // 设备已经启动并且尚未移除
			if ( mDeviceExtension -> DnThreadBufSize == 0 ) break;  // 强制退出
			while ( mDeviceExtension -> DnThreadInSize && mDeviceExtension -> DnThreadQueueFree ) {
				mFree = NULL;
				KeAcquireSpinLock( & mDeviceExtension -> mControlLockDn, &mOldIrql );
				if ( mDeviceExtension -> DnThreadInSize && mDeviceExtension -> DnThreadBuffer ) {
					if ( mDeviceExtension -> DnThreadOutStart >= mDeviceExtension -> DnThreadBuffer + mDeviceExtension -> DnThreadBufSize )
						mDeviceExtension -> DnThreadOutStart = mDeviceExtension -> DnThreadBuffer;
					if ( mFree = mDeviceExtension -> DnThreadQueueFree ) {
						mDeviceExtension -> DnThreadQueueFree = mFree -> mNext;
						mFree -> mNext = NULL;
						mLength = *( mDeviceExtension -> DnThreadOutStart );
						RtlCopyMemory( mFree -> mBuffer, mDeviceExtension -> DnThreadOutStart + 1, mLength );
						mDeviceExtension -> DnThreadOutStart += mCH375_PACKET_LENGTH + 1;
						mDeviceExtension -> DnThreadInSize -= mCH375_PACKET_LENGTH + 1;
						if ( mWait = mDeviceExtension -> DnThreadQueueWait ) {
							while ( mWait -> mNext ) mWait = mWait -> mNext;
							mWait -> mNext = mFree;
						}
						else mDeviceExtension -> DnThreadQueueWait = mFree;
					}
				}
				KeReleaseSpinLock( & mDeviceExtension -> mControlLockDn, mOldIrql );
				if ( mFree ) {						
					InterlockedIncrement( & mDeviceExtension -> DnThreadUsbCount );  // 计数
					UsbBuildInterruptOrBulkTransferRequest( & mFree -> mUrb, sizeof( struct _URB_BULK_OR_INTERRUPT_TRANSFER ),  // 构造USB请求
															mDeviceExtension -> mExtDataDownPipe, mFree -> mBuffer, NULL, mLength,  // 管道的句柄
															USBD_TRANSFER_DIRECTION_OUT | USBD_SHORT_TRANSFER_OK, NULL );  // 操作标志
					KeClearEvent( & mFree -> mEvent );  // IRP完成事件信号为无效
					mIrp = IoBuildDeviceIoControlRequest( IOCTL_INTERNAL_USB_SUBMIT_URB, mDeviceExtension -> mExtNextLowerDevice,
														  NULL, 0, NULL, 0, TRUE, & mFree -> mEvent, & mFree -> mIoStatusBlock );  // 构造IRP提交URB
					if ( mIrp != NULL ) {  // IRP有效
						IoGetNextIrpStackLocation( mIrp ) -> Parameters.Others.Argument1 = & mFree -> mUrb;  // 将URB作为参数传递给下级设备
						mFree -> mStatus = IoCallDriver( mDeviceExtension -> mExtNextLowerDevice, mIrp );  // 向下级设备发送IO请求
					}
					else mFree -> mStatus = STATUS_INSUFFICIENT_RESOURCES;  // 操作失败
				}
				else break;
			}
			mWait = mDeviceExtension -> DnThreadQueueWait;
			if ( mWait == NULL ) goto ThreadWriteWait;
			mDeviceExtension -> DnThreadQueueWait = mWait -> mNext;
			mWait -> mNext = mDeviceExtension -> DnThreadQueueFree;
			mDeviceExtension -> DnThreadQueueFree = mWait;
			if ( mWait -> mStatus == STATUS_PENDING ) {  // 等待被悬挂的IO请求完成
				KeWaitForSingleObject( & mWait -> mEvent, Executive, KernelMode, FALSE, NULL );  // 挂起等待IRP完成
				mWait -> mStatus = mWait -> mIoStatusBlock.Status;  // 取完成状态
			}
			InterlockedDecrement( & mDeviceExtension -> DnThreadUsbCount );
			if ( mDeviceExtension -> DnThreadBufSize == 0 ) break;  // 强制退出
			mStatus = mWait -> mStatus;
			if ( ! NT_SUCCESS( mStatus ) ) {
				if ( mIsDeviceExist( mDeviceObject, mStatus ) == FALSE ) break;  // 设备已经移除
				if ( mDeviceExtension -> mExtDeviceRemove == FALSE )  // 设备尚未移除
					mRequestPipe( mDeviceObject, URB_FUNCTION_RESET_PIPE, mPipeDataDown );  // 出错则复位管道
			}
		}
		mAbortAsyncWrite( mDeviceObject );
//		InterlockedDecrement( & mDeviceExtension -> mExtIoCount );
		if ( mIsDeviceExist( mDeviceObject, STATUS_SUCCESS ) == FALSE ) break;  // 设备已经移除
	}
	mAbortAsyncWrite( mDeviceObject );
	ExFreePool( mDeviceExtension -> DnThreadBuffer );  // 释放内存
	mDeviceExtension -> DnThreadBuffer = NULL;
	InterlockedDecrement( & mDeviceExtension -> mThreadCount );
	PsTerminateSystemThread( STATUS_SUCCESS );  // 终止系统线程
}

NTSTATUS	mExitThreadWrite(
	PDEVICE_OBJECT	iDeviceObject )
{
	ULONG				i;
	mPDEVICE_EXTENSION	mDeviceExtension;
	mDeviceExtension = iDeviceObject -> DeviceExtension;  // 设备扩展
	for ( i = 0; i < 50; i ++ ) {
		mDeviceExtension -> DnThreadBufSize = 0;  // 强制退出
		KeSetEvent( & mDeviceExtension -> DnThreadStartEvent, IO_CH375_INCREMENT, FALSE );  // 置线程启动事件
		if ( mDeviceExtension -> DnThreadBuffer == NULL ) break;
		mDelay20mS( );
		if ( mDeviceExtension -> DnThreadBuffer == NULL ) break;
		mRequestPipe( iDeviceObject, (USHORT)( i > 30 ? URB_FUNCTION_RESET_PIPE : URB_FUNCTION_ABORT_PIPE ), mPipeDataDown );  // 取消请求
	}
	return( i >= 50 ? STATUS_UNSUCCESSFUL : STATUS_SUCCESS );
}

NTSTATUS	mPutBufferData(
	PDEVICE_OBJECT	iDeviceObject,
	PUCHAR			iBuffer,
	ULONG			iLength )  // 输入为请求长度
{
	ULONG				mReqLen, mPktSize;
	KIRQL				mOldIrql;
	mPDEVICE_EXTENSION	mDeviceExtension;
	mDeviceExtension = iDeviceObject -> DeviceExtension;  // 设备扩展
	if ( mDeviceExtension -> mExtDeviceRemove ) return( STATUS_CANCELLED );
	mReqLen = ( iLength + mCH375_PACKET_LENGTH - 1 ) / mCH375_PACKET_LENGTH;
	mReqLen *= mCH375_PACKET_LENGTH + 1;
	if ( mDeviceExtension -> DnThreadInSize + mReqLen > mDeviceExtension -> DnThreadBufSize ) {
		KeSetEvent( & mDeviceExtension -> DnThreadStartEvent, IO_CH375_INCREMENT, FALSE );  // 置线程启动事件
		return( STATUS_BUFFER_OVERFLOW );  // 溢出处理
	}
	if ( mReqLen ) {
		KeAcquireSpinLock( & mDeviceExtension -> mControlLockDn, &mOldIrql );
		if ( mDeviceExtension -> DnThreadBuffer ) {
			while ( mReqLen ) {
				if ( mDeviceExtension -> DnThreadInStart >= mDeviceExtension -> DnThreadBuffer + mDeviceExtension -> DnThreadBufSize )
					mDeviceExtension -> DnThreadInStart = mDeviceExtension -> DnThreadBuffer;
				if ( mReqLen > mCH375_PACKET_LENGTH + 1 ) mPktSize = mCH375_PACKET_LENGTH;
				else {
					mPktSize = iLength & ( mCH375_PACKET_LENGTH - 1 );
					if ( mPktSize == 0 ) mPktSize = mCH375_PACKET_LENGTH;
				}
				*( mDeviceExtension -> DnThreadInStart ) = (UCHAR)mPktSize;
				RtlCopyMemory( mDeviceExtension -> DnThreadInStart + 1, iBuffer, mPktSize );
				mDeviceExtension -> DnThreadInStart += mCH375_PACKET_LENGTH + 1;
				mDeviceExtension -> DnThreadInSize += mCH375_PACKET_LENGTH + 1;
				if ( mDeviceExtension -> DnThreadInSize > mDeviceExtension -> DnThreadBufSize ) {  // 溢出处理
					mDeviceExtension -> DnThreadInSize = mDeviceExtension -> DnThreadBufSize;
					mDeviceExtension -> DnThreadOutStart = mDeviceExtension -> DnThreadInStart;
				}
				iBuffer += mPktSize;
				mReqLen -= mCH375_PACKET_LENGTH + 1;
			}
		}
		KeReleaseSpinLock( & mDeviceExtension -> mControlLockDn, mOldIrql );
	}
	KeSetEvent( & mDeviceExtension -> DnThreadStartEvent, IO_CH375_INCREMENT, FALSE );  // 置线程启动事件
	return( STATUS_SUCCESS );
}

VOID		mClearDnBufferData(
	PDEVICE_OBJECT	iDeviceObject )
{
	KIRQL				mOldIrql;
	mPDEVICE_EXTENSION	mDeviceExtension;
	mDeviceExtension = iDeviceObject -> DeviceExtension;  // 设备扩展
	KeAcquireSpinLock( & mDeviceExtension -> mControlLockDn, &mOldIrql );
	if ( mDeviceExtension -> DnThreadBuffer ) {
		if ( mDeviceExtension -> DnThreadInStart >= mDeviceExtension -> DnThreadBuffer + mDeviceExtension -> DnThreadBufSize )
			mDeviceExtension -> DnThreadInStart = mDeviceExtension -> DnThreadBuffer;
		mDeviceExtension -> DnThreadOutStart = mDeviceExtension -> DnThreadInStart;
		mDeviceExtension -> DnThreadInSize = 0;
	}
	KeReleaseSpinLock( & mDeviceExtension -> mControlLockDn, mOldIrql );
}

NTSTATUS	mResetUsbDevice(
	PDEVICE_OBJECT	iDeviceObject )
{
	PIRP				mIrp;
	KEVENT				mEvent;
	IO_STATUS_BLOCK		mIoStatusBlock;
	NTSTATUS			mStatus;
	mPDEVICE_EXTENSION	mDeviceExtension;
	mDeviceExtension = iDeviceObject -> DeviceExtension;  // 设备扩展
	InterlockedDecrement( & mDeviceExtension -> mExtIoCount );  // 操作计数减量,以便于关闭或者移除设备
	KeInitializeEvent( &mEvent, NotificationEvent, FALSE );  // 初始化IRP完成事件信号为无效
	mIrp = IoBuildDeviceIoControlRequest( IOCTL_INTERNAL_USB_RESET_PORT,  // 构造IRP复位端口
										  mDeviceExtension -> mExtNextLowerDevice,
										  NULL, 0, NULL, 0, TRUE, &mEvent, &mIoStatusBlock );
	mStatus = IoCallDriver( mDeviceExtension -> mExtNextLowerDevice, mIrp );  // 向下级设备发送IO请求,复位端口
	if ( mStatus == STATUS_PENDING ) {  // 等待被悬挂的IO请求完成
		KeWaitForSingleObject( &mEvent, Executive, KernelMode, FALSE, NULL );  // 挂起等待IRP完成
		mStatus = mIoStatusBlock.Status;  // 取完成状态
	}
	InterlockedIncrement( & mDeviceExtension -> mExtIoCount );  // 操作计数增量
	return( mStatus );
}

VOID		mThreadTimeout(  // 系统线程
	PVOID	iContext )
{
	PDEVICE_OBJECT		mDeviceObject;
	mPDEVICE_EXTENSION	mDeviceExtension;
	LARGE_INTEGER		mWaitTime, mReqTime, mCurrentTime;
	mDeviceObject = (PDEVICE_OBJECT)iContext;  // 设备对象
	mDeviceExtension = mDeviceObject -> DeviceExtension;  // 设备扩展
	InterlockedIncrement( & mDeviceExtension -> mThreadCount );
	KeSetPriorityThread( KeGetCurrentThread(), LOW_REALTIME_PRIORITY );  // 设定当前线程为低实时优先级
	while ( mDriverObject != NULL && mDeviceExtension -> mExtDeviceRemove == FALSE ) {  // 系统未卸载,设备未移除
		mWaitTime.QuadPart = 10000000;  // 1S
		KeQuerySystemTime( & mCurrentTime );
		if ( mDeviceExtension -> mExtDownTimeout < 0x80000000 && mDeviceExtension -> mExtDownStartTime.QuadPart ) {  // 需要检查超时
			mReqTime.QuadPart = mDeviceExtension -> mExtDownStartTime.QuadPart + mDeviceExtension -> mExtDownWaitTime.QuadPart - mCurrentTime.QuadPart;
			if ( mReqTime.QuadPart < mWaitTime.QuadPart ) mWaitTime.QuadPart = mReqTime.QuadPart;
		}
		if ( mDeviceExtension -> mExtUpTimeout < 0x80000000 && mDeviceExtension -> mExtUpStartTime.QuadPart ) {  // 需要检查超时
			mReqTime.QuadPart = mDeviceExtension -> mExtUpStartTime.QuadPart + mDeviceExtension -> mExtUpWaitTime.QuadPart - mCurrentTime.QuadPart;
			if ( mReqTime.QuadPart < mWaitTime.QuadPart ) mWaitTime.QuadPart = mReqTime.QuadPart;
		}
		if ( mDeviceExtension -> mExtAuxTimeout < 0x80000000 && mDeviceExtension -> mExtAuxStartTime.QuadPart ) {  // 需要检查超时
			mReqTime.QuadPart = mDeviceExtension -> mExtAuxStartTime.QuadPart + mDeviceExtension -> mExtAuxWaitTime.QuadPart - mCurrentTime.QuadPart;
			if ( mReqTime.QuadPart < mWaitTime.QuadPart ) mWaitTime.QuadPart = mReqTime.QuadPart;
		}
		if ( mDeviceExtension -> mExtInterTimeout < 0x80000000 && mDeviceExtension -> mExtInterStartTime.QuadPart ) {  // 需要检查超时
			mReqTime.QuadPart = mDeviceExtension -> mExtInterStartTime.QuadPart + mDeviceExtension -> mExtInterWaitTime.QuadPart - mCurrentTime.QuadPart;
			if ( mReqTime.QuadPart < mWaitTime.QuadPart ) mWaitTime.QuadPart = mReqTime.QuadPart;
		}
		mWaitTime.QuadPart = 0 - mWaitTime.QuadPart;
		KeWaitForSingleObject( & mDeviceExtension -> mExtThreadToutEvent, Executive, KernelMode, FALSE, &mWaitTime );
		if ( mDeviceExtension -> mExtDeviceOpen == 0 ) IoSetDeviceInterfaceState( & mDeviceExtension -> mExtDeviceName, TRUE );  // 允许设备接口
		KeQuerySystemTime( & mCurrentTime );
		if ( mDeviceExtension -> mExtUsbDownCount ) {
			if ( mDeviceExtension -> mExtDownStartTime.u.HighPart == 0x87654321 ||  // 取消
				mDeviceExtension -> mExtDownTimeout < 0x80000000 && mDeviceExtension -> mExtDownStartTime.QuadPart &&  // 需要检查超时
				mDeviceExtension -> mExtDownStartTime.QuadPart + mDeviceExtension -> mExtDownWaitTime.QuadPart <= mCurrentTime.QuadPart ) {
				mDeviceExtension -> mExtDownStartTime.QuadPart = 0;
				mRequestPipe( mDeviceObject, URB_FUNCTION_ABORT_PIPE, mPipeDataDown );  // 在指定管道执行取消请求
			}
		}
		if ( mDeviceExtension -> mExtUsbUpCount ) {
			if ( mDeviceExtension -> mExtUpStartTime.u.HighPart == 0x87654321 ||  // 取消
				mDeviceExtension -> mExtUpTimeout < 0x80000000 && mDeviceExtension -> mExtUpStartTime.QuadPart &&  // 需要检查超时
				mDeviceExtension -> mExtUpStartTime.QuadPart + mDeviceExtension -> mExtUpWaitTime.QuadPart <= mCurrentTime.QuadPart ) {
				mDeviceExtension -> mExtUpStartTime.QuadPart = 0;
				mRequestPipe( mDeviceObject, URB_FUNCTION_ABORT_PIPE, mPipeDataUp );  // 在指定管道执行取消请求
			}
		}
		if ( mDeviceExtension -> mExtUsbAuxCount ) {
			if ( mDeviceExtension -> mExtAuxStartTime.u.HighPart == 0x87654321 ||  // 取消
				mDeviceExtension -> mExtAuxTimeout < 0x80000000 && mDeviceExtension -> mExtAuxStartTime.QuadPart &&  // 需要检查超时
				mDeviceExtension -> mExtAuxStartTime.QuadPart + mDeviceExtension -> mExtAuxWaitTime.QuadPart <= mCurrentTime.QuadPart ) {
				mDeviceExtension -> mExtAuxStartTime.QuadPart = 0;
				mRequestPipe( mDeviceObject, URB_FUNCTION_ABORT_PIPE, mPipeAuxDown );  // 在指定管道执行取消请求
			}
		}
		if ( mDeviceExtension -> mExtUsbInterCount ) {
			if ( mDeviceExtension -> mExtInterStartTime.u.HighPart == 0x87654321 ||  // 取消
				mDeviceExtension -> mExtInterTimeout < 0x80000000 && mDeviceExtension -> mExtInterStartTime.QuadPart &&  // 需要检查超时
				mDeviceExtension -> mExtInterStartTime.QuadPart + mDeviceExtension -> mExtInterWaitTime.QuadPart <= mCurrentTime.QuadPart ) {
				mDeviceExtension -> mExtInterStartTime.QuadPart = 0;
				mRequestPipe( mDeviceObject, URB_FUNCTION_ABORT_PIPE, mPipeInterUp );  // 在指定管道执行取消请求
			}
		}
	}
	InterlockedDecrement( & mDeviceExtension -> mThreadCount );
	PsTerminateSystemThread( STATUS_SUCCESS );  // 终止系统线程
}

VOID		mDelay20mS( void )
{
	LARGE_INTEGER		mTime;
	mTime.QuadPart = 0 - 200000;
	KeDelayExecutionThread( KernelMode, FALSE, &mTime );
}


// end
