libusbk-sys 0.2.0

Rust Windows library for accessing USB devices via libusbK
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
/*!********************************************************************
libusbK - WDF USB driver.
Copyright (C) 2012 Travis Lee Robinson. All Rights Reserved.
libusb-win32.sourceforge.net

Development : Travis Lee Robinson  (libusbdotnet@gmail.com)
Testing     : Xiaofan Chen         (xiaofanc@gmail.com)

At the discretion of the user of this library, this software may be
licensed under the terms of the GNU Public License v3 or a BSD-Style
license as outlined in the following files:
* LICENSE-gpl3.txt
* LICENSE-bsd.txt

License files are located in a license folder at the root of source and
binary distributions.
********************************************************************!*/

#include "drv_common.h"
#include "drv_xfer.h"

// warning C4127: conditional expression is constant.
#pragma warning(disable: 4127)

#if (defined(ALLOC_PRAGMA) && defined(PAGING_ENABLED))
#endif

EVT_WDF_REQUEST_COMPLETION_ROUTINE Xfer_ReadBulkRawComplete;
EVT_WDF_REQUEST_COMPLETION_ROUTINE Xfer_ReadBulkComplete;

EVT_WDF_REQUEST_COMPLETION_ROUTINE Xfer_WriteBulkRawComplete;
EVT_WDF_REQUEST_COMPLETION_ROUTINE Xfer_WriteBulkComplete;

#define mXfer_CopyPartialReadToUserMemory(mStatus,mQueueContext, mTransferBuffer, mTransferLength, ErrorAction)	do {	\

		mStatus = WdfMemoryCopyFromBuffer( 																					\
		          mQueueContext->Xfer.UserMem,   																					\
		          mQueueContext->Xfer.Transferred,   																				\
		          mTransferBuffer,   																								\
		          mTransferLength);  																								\
		\
		if (!NT_SUCCESS(mStatus))  																							\
		{  																													\
			USBERR("WdfMemoryCopyFromBuffer failed. Status=%08Xh\n", mStatus); 												\
			ErrorAction;   																									\
		}  																													\
		\
		mQueueContext->OverOfs.BufferOffset	+= mTransferLength; 															\
		mQueueContext->OverOfs.BufferLength	-= mTransferLength; 															\
		mQueueContext->Xfer.Transferred		+= mTransferLength; 															\
	}while(0)


/*
* Sumbmits a bulk/interrupt read stage transfer.
* REQUIRES:
* - ULONG remainingLength [out]
* - ULONG stageLength [out]
* - ULONG remainderLength [out]
* - WDF_REQUEST_SEND_OPTIONS sendOptions [out]
*/
#define mXfer_SubmitNextRead(mStatus, mQueueContext, mRequestContext, mRequest, mCompletionRoutine, mErrorAction) do { 							\

		/* One or more transfers required  */  																										\
		remainingLength	= mQueueContext->Xfer.Length - mQueueContext->Xfer.Transferred; 															\
		stageLength		= remainingLength > mQueueContext->Info.MaximumTransferSize ? mQueueContext->Info.MaximumTransferSize : remainingLength;	\
		remainderLength = stageLength % mQueueContext->Info.MaximumPacketSize; 																		\
		\
		\
		if (stageLength < mQueueContext->Info.MaximumPacketSize)   																					\
		{  																																			\
			if (!mRequestContext->Policies.AllowPartialReads)  																						\
			{  																																		\
				mStatus = STATUS_INVALID_BUFFER_SIZE;  																								\
				USBERRN("Read buffer is not an interval of MaximumPacketSize. MaximumPacketSize: %u RemainderLength: %u",  							\
				        mQueueContext->Info.MaximumPacketSize, remainderLength);   																	\
				mErrorAction;  																														\
			}  																																		\
			/* Use the over-run buffer; CompletionRoutine must update UserMem */   																	\
			mQueueContext->OverOfs.BufferOffset = 0;   																								\
			mQueueContext->OverOfs.BufferLength = stageLength; 																						\
			\
			mStatus = WdfUsbTargetPipeFormatRequestForRead(mQueueContext->PipeHandle, mRequest, mQueueContext->OverMem, NULL); 						\
		}  																																			\
		else   																																		\
		{  																																			\
			/* One or more whole packets can be read directly into the user buffer. */ 																\
			stageLength -= remainderLength;																											\
			mQueueContext->Xfer.UserOfs.BufferOffset = mQueueContext->Xfer.Transferred;																\
			mQueueContext->Xfer.UserOfs.BufferLength = stageLength;																					\
			\
			mStatus = WdfUsbTargetPipeFormatRequestForRead(mQueueContext->PipeHandle, mRequest, mQueueContext->Xfer.UserMem, &mQueueContext->Xfer.UserOfs); 	\
		}  																																			\
		\
		if (!NT_SUCCESS(mStatus))  																													\
		{  																																			\
			USBERR("WdfIoTargetFormatRequestForRead failed. Status=%08Xh\n", mStatus); 																\
			mErrorAction;  																															\
		}  																																			\
		\
		WDF_REQUEST_SEND_OPTIONS_INIT(&sendOptions, 0);																								\
		mStatus = SetRequestTimeout(mRequestContext, mRequest, &sendOptions);  																		\
		if (!NT_SUCCESS(mStatus))  																													\
		{  																																			\
			USBERR("SetRequestTimeout failed. Status=%08Xh\n", mStatus);   																			\
			mErrorAction;  																															\
		}  																																			\
		\
		USBMSG("PipeID=%02Xh Staging=%u\n",	mQueueContext->Info.EndpointAddress, stageLength);  													\
		mStatus = SubmitAsyncQueueRequest(mQueueContext, mRequest, mCompletionRoutine, &sendOptions, mQueueContext);   								\
		if (!NT_SUCCESS(mStatus))  																													\
		{  																																			\
			USBERR("SubmitAsyncQueueRequest failed. Status=%08Xh\n", mStatus); 																		\
			mErrorAction;  																															\
		}  																																			\
	}while(0)

#define mXfer_SubmitNextWrite(mStatus, mQueueContext, mRequestContext, mRequest, mCompletionRoutine, mErrorAction) do {							\

		/* One or more transfers required  */  																										\
		remainingLength	= mQueueContext->Xfer.Length - mQueueContext->Xfer.Transferred; 															\
		stageLength		= remainingLength > mQueueContext->Info.MaximumTransferSize ? mQueueContext->Info.MaximumTransferSize : remainingLength;	\
		\
		mQueueContext->Xfer.UserOfs.BufferOffset = mQueueContext->Xfer.Transferred;																	\
		mQueueContext->Xfer.UserOfs.BufferLength = stageLength;																						\
		\
		if (stageLength)   																															\
			mStatus = WdfUsbTargetPipeFormatRequestForWrite(mQueueContext->PipeHandle, mRequest, mQueueContext->Xfer.UserMem, &mQueueContext->Xfer.UserOfs); 	\
		else   																																		\
			mStatus = WdfUsbTargetPipeFormatRequestForWrite(mQueueContext->PipeHandle, mRequest, NULL, NULL);  										\
		\
		if (!NT_SUCCESS(mStatus))  																													\
		{  																																			\
			USBERR("WdfIoTargetFormatRequestForWrite failed. Status=%08Xh\n", mStatus);																\
			mErrorAction;  																															\
		}  																																			\
		\
		WDF_REQUEST_SEND_OPTIONS_INIT(&sendOptions, 0);																								\
		mStatus = SetRequestTimeout(mRequestContext, mRequest, &sendOptions);  																		\
		if (!NT_SUCCESS(mStatus))  																													\
		{  																																			\
			USBERR("SetRequestTimeout failed. Status=%08Xh\n", mStatus);   																			\
			mErrorAction;  																															\
		}  																																			\
		\
		USBMSG("PipeID=%02Xh Staging=%u\n",	mQueueContext->Info.EndpointAddress, stageLength);  													\
		mStatus = SubmitAsyncQueueRequest(mQueueContext, mRequest, mCompletionRoutine, &sendOptions, mQueueContext);   								\
		if (!NT_SUCCESS(mStatus))  																													\
		{  																																			\
			USBERR("SubmitAsyncQueueRequest failed. Status=%08Xh\n", mStatus); 																		\
			mErrorAction;  																															\
		}  																																			\
	}while(0)

VOID Xfer_ReadBulk (
    __in WDFQUEUE Queue,
    __in WDFREQUEST Request)
{
	NTSTATUS                status;
	PREQUEST_CONTEXT        requestContext = NULL;
	PQUEUE_CONTEXT			queueContext = NULL;
	PDEVICE_CONTEXT         deviceContext;
	ULONG					remainingLength;
	ULONG					stageLength = 0;
	ULONG					remainderLength = 0;
	WDF_REQUEST_SEND_OPTIONS sendOptions;
	PUCHAR					transferBuffer;


	deviceContext = GetDeviceContext(WdfIoQueueGetDevice(Queue));
	requestContext = GetRequestContext(Request);

	VALIDATE_REQUEST_CONTEXT(requestContext, status);
	if (!NT_SUCCESS(status)) goto Exit;

	if ((queueContext = GetQueueContext(Queue)) == NULL)
	{
		status = STATUS_INVALID_DEVICE_REQUEST;
		USBERRN("Invalid queue context");
		goto Exit;
	}

	queueContext->Xfer.Transferred = 0;
	queueContext->Xfer.Length = requestContext->Length;

	if (!queueContext->OverMem)
	{
		status = STATUS_INVALID_DEVICE_REQUEST;
		USBERRN("Invalid queue context:OverMem");
		goto Exit;
	}

	if (!queueContext->Info.MaximumPacketSize)
	{
		status = STATUS_INVALID_BUFFER_SIZE;
		USBERRN("PipeID=%02Xh MaximumPacketSize=0", queueContext->Info.EndpointAddress);
		goto Exit;
	}

	// handle pipe reset scenarios: ResetPipeOnResume, AutoClearStall
	mXfer_HandlePipeResetScenarios(status, queueContext, requestContext);

	// Handle special case scenario where read length = 0
	if (!queueContext->Xfer.Length)
	{
		// if AllowPartialReads complete successfully for 0 bytes
		status = requestContext->Policies.AllowPartialReads ? STATUS_SUCCESS : STATUS_INVALID_BUFFER_SIZE;
		goto Exit;
	}

	// Init queue user memory
	status = GetTransferMemory(Request, requestContext->ActualRequestType, &queueContext->Xfer.UserMem);
	if (!NT_SUCCESS(status))
	{
		USBERR("GetTransferMemory failed. Status=%08Xh\n", status);
		goto Exit;
	}
	queueContext->Xfer.UserOfs.BufferOffset = 0;
	queueContext->Xfer.UserOfs.BufferLength = queueContext->Xfer.Length;

	// Check if there are bytes left over from a previous transfer.
	if (queueContext->OverOfs.BufferLength > 0)
	{
		// Copy partial read bytes bytes into UserMem
		remainingLength = queueContext->Xfer.Length - queueContext->Xfer.Transferred;
		stageLength = (ULONG)queueContext->OverOfs.BufferLength > remainingLength ? remainingLength : (ULONG)queueContext->OverOfs.BufferLength;
		transferBuffer = &queueContext->OverBuf[queueContext->OverOfs.BufferOffset];

		mXfer_CopyPartialReadToUserMemory(status, queueContext, transferBuffer, stageLength, goto Exit);

		USBDBGN("PipeID=%02Xh Transferred %u bytes from a previous partial read.",
		        queueContext->Info.EndpointAddress, queueContext->Xfer.Transferred);

		if (queueContext->Xfer.Transferred >= queueContext->Xfer.Length)
		{
			if (requestContext->Policies.AutoFlush)
			{
				// discard any extra partial read bytes
				queueContext->OverOfs.BufferLength = 0;
				queueContext->OverOfs.BufferOffset = 0;
			}

			USBMSGN("PipeID=%02Xh DoneReason: Transferred==Requested. Transferred=%u",
			        queueContext->Info.EndpointAddress,	queueContext->Xfer.Transferred);
			status = STATUS_SUCCESS;
			goto Exit;
		}

		/*
		It would seem if IgnoreShortPackets=FALSE we would complete the request here.
		However, WinUSB does not handle it this way and will still submit the request.
		*/
#if 0
		else if (!requestContext->Policies.IgnoreShortPackets)
		{
			USBMSGN("PipeID=%02Xh DoneReason: IgnoreShortPackets=FALSE. Transferred=%u",
			        queueContext->Info.EndpointAddress,	queueContext->Xfer.Transferred);
			status = STATUS_SUCCESS;
			goto Exit;
		}
#endif
	}

	mXfer_SubmitNextRead(status, queueContext, requestContext, Request, Xfer_ReadBulkComplete, goto Exit);
	return;

Exit:
	if (queueContext)
	{
		WdfRequestCompleteWithInformation(Request, status, queueContext->Xfer.Transferred);
		return;
	}
	WdfRequestCompleteWithInformation(Request, status, 0);
}

VOID Xfer_ReadBulkComplete(
    __in WDFREQUEST Request,
    __in WDFIOTARGET Target,
    __in PWDF_REQUEST_COMPLETION_PARAMS CompletionParams,
    __in WDFCONTEXT Context)
{
	NTSTATUS                status;
	PREQUEST_CONTEXT        requestContext = NULL;
	PQUEUE_CONTEXT			queueContext = NULL;
	ULONG					remainingLength;
	ULONG					transferredLength;
	ULONG					stageLength = 0;
	ULONG					remainderLength = 0;
	WDF_REQUEST_SEND_OPTIONS sendOptions;
	PUCHAR					transferBuffer;
	PWDF_USB_REQUEST_COMPLETION_PARAMS usbCompletionParams;

	UNREFERENCED_PARAMETER(Target);

	// Make sure the request context is still valid.
	requestContext	= GetRequestContext(Request);
	queueContext	= (PQUEUE_CONTEXT)Context;

	status				= CompletionParams->IoStatus.Status;
	usbCompletionParams = CompletionParams->Parameters.Usb.Completion;
	transferredLength	= (ULONG)usbCompletionParams->Parameters.PipeRead.Length;

	if (!queueContext || !usbCompletionParams)
	{
		status = STATUS_INVALID_DEVICE_REQUEST;
		USBERRN("Invalid queue context.");
		goto Exit;
	}

	Xfer_CheckPipeStatus(status, queueContext->Info.EndpointAddress);

	mXfer_HandlePipeResetScenariosForComplete(status, queueContext, requestContext);

	if (queueContext->OverOfs.BufferLength)
	{
		// Received data to queue OverMem
		if (transferredLength)
		{
			// Copy partial read bytes bytes into UserMem
			stageLength		= (ULONG)queueContext->OverOfs.BufferLength > transferredLength ? transferredLength : (ULONG)queueContext->OverOfs.BufferLength;
			transferBuffer	= queueContext->OverBuf;
			queueContext->OverOfs.BufferLength = transferredLength;

			mXfer_CopyPartialReadToUserMemory(status, queueContext, transferBuffer, stageLength, goto Exit);

			if (queueContext->Xfer.Transferred >= queueContext->Xfer.Length)
			{
				if (requestContext->Policies.AutoFlush)
				{
					// discard any extra partial read bytes
					queueContext->OverOfs.BufferLength = 0;
					queueContext->OverOfs.BufferOffset = 0;
				}

				// DONE REASON: Transferred==Requested
				USBDBGN("PipeID=%02Xh DoneReason: Transferred==Requested. Staged=%u Total=%u Requested=%u",
				        queueContext->Info.EndpointAddress,	stageLength, queueContext->Xfer.Transferred, queueContext->Xfer.Length);
				goto Exit;
			}
			if (!NT_SUCCESS(status)) goto Exit;

		}
		else
		{
			if (!NT_SUCCESS(status)) goto Exit;

			// Received a ZLP
			USBDBGN("PipeID=%02Xh ZLP received.", queueContext->Info.EndpointAddress);
			queueContext->OverOfs.BufferLength = 0;
		}
		if (!NT_SUCCESS(status)) goto Exit;

		if (!requestContext->Policies.IgnoreShortPackets)
		{
			// DONE REASON: IgnoreShortPackets = 0
			USBDBGN("PipeID=%02Xh DoneReason: IgnoreShortPackets=FALSE. Staged=%u Total=%u Requested=%u",
			        queueContext->Info.EndpointAddress,	stageLength, queueContext->Xfer.Transferred, queueContext->Xfer.Length);

			goto Exit;
		}
	}
	else
	{
		// Received data to UserMem
		queueContext->Xfer.Transferred += transferredLength;
		if (!NT_SUCCESS(status)) goto Exit;

		if (!transferredLength)
		{
			// Received a ZLP
			USBDBGN("PipeID=%02Xh ZLP received.", queueContext->Info.EndpointAddress);
		}

		if (queueContext->Xfer.Transferred >= queueContext->Xfer.Length)
		{
			// DONE REASON: Transferred==Requested
			USBDBGN("PipeID=%02Xh DoneReason: Transferred==Requested. Staged=%u Total=%u Requested=%u",
			        queueContext->Info.EndpointAddress,	transferredLength, queueContext->Xfer.Transferred, queueContext->Xfer.Length);
			goto Exit;
		}
		else if (transferredLength && transferredLength == queueContext->Xfer.UserOfs.BufferLength)
		{
			// bytes transferred equals bytes requested and we have more bytes to go. (split transfers)
			goto NextRead;
		}

		if (!requestContext->Policies.IgnoreShortPackets)
		{
			// DONE REASON: IgnoreShortPackets = 0
			USBDBGN("PipeID=%02Xh DoneReason: IgnoreShortPackets=FALSE. Staged=%u Total=%u Requested=%u",
			        queueContext->Info.EndpointAddress,	transferredLength, queueContext->Xfer.Transferred, queueContext->Xfer.Length);
			goto Exit;
		}
	}

NextRead:
	mXfer_SubmitNextRead(status, queueContext, requestContext, Request, Xfer_ReadBulkComplete, goto Exit);
	return;

Exit:
	WdfRequestCompleteWithInformation(Request, status, queueContext->Xfer.Transferred);

}

VOID Xfer_ReadBulkRaw (
    __in WDFQUEUE Queue,
    __in WDFREQUEST Request)
{
	NTSTATUS                status;
	PREQUEST_CONTEXT        requestContext = NULL;
	PDEVICE_CONTEXT         deviceContext;
	WDFMEMORY				transferMemory;
	PQUEUE_CONTEXT			queueContext = NULL;

	WDF_REQUEST_SEND_OPTIONS sendOptions;

	deviceContext = GetDeviceContext(WdfIoQueueGetDevice(Queue));
	requestContext = GetRequestContext(Request);

	VALIDATE_REQUEST_CONTEXT(requestContext, status);
	if (!NT_SUCCESS(status)) goto Exit;

	if ((queueContext = GetQueueContext(Queue)) == NULL)
	{
		status = STATUS_INVALID_DEVICE_REQUEST;
		USBERRN("Invalid queue context");
		goto Exit;
	}

	if (!queueContext->Info.MaximumPacketSize)
	{
		status = STATUS_INVALID_BUFFER_SIZE;
		USBERRN("PipeID=%02Xh MaximumPacketSize=0", queueContext->Info.EndpointAddress);
		goto Exit;
	}

	if ((requestContext->Length % queueContext->Info.MaximumPacketSize) > 0)
	{
		USBERR("PipeID=%02Xh transfer must be an interval of the MaximumPacketSize (%u bytes)\n",
		       queueContext->Info.EndpointAddress, queueContext->Info.MaximumPacketSize);
		status = STATUS_INVALID_BUFFER_SIZE;
		goto Exit;
	}

	status = GetTransferMemory(Request, requestContext->ActualRequestType, &transferMemory);
	if (!NT_SUCCESS(status))
	{
		USBERR("GetTransferMemory failed. Status=%08Xh\n", status);
		goto Exit;
	}

	status = WdfUsbTargetPipeFormatRequestForRead(
	             queueContext->PipeHandle,
	             Request,
	             transferMemory,
	             NULL);

	if (!NT_SUCCESS(status))
	{
		USBERR("WdfIoTargetFormatRequestForRead failed. Status=%08Xh\n", status);
		goto Exit;
	}

	WDF_REQUEST_SEND_OPTIONS_INIT(&sendOptions, 0);
	status = SetRequestTimeout(requestContext, Request, &sendOptions);
	if (!NT_SUCCESS(status))
	{
		USBERR("SetRequestTimeout failed. Status=%08Xh\n", status);
		goto Exit;
	}

	USBMSG("PipeID=%02Xh Length=%u\n",	queueContext->Info.EndpointAddress,	requestContext->Length);
	status = SubmitAsyncQueueRequest(queueContext, Request, Xfer_ReadBulkRawComplete, &sendOptions, queueContext);
	if (!NT_SUCCESS(status))
	{
		USBERR("SubmitAsyncRequest failed. Status=%08Xh\n", status);
		goto Exit;
	}

	return;

Exit:
	WdfRequestCompleteWithInformation(Request, status, 0);
}

VOID Xfer_ReadBulkRawComplete(
    __in WDFREQUEST Request,
    __in WDFIOTARGET Target,
    __in PWDF_REQUEST_COMPLETION_PARAMS CompletionParams,
    __in WDFCONTEXT Context)
{
	NTSTATUS status;
	PREQUEST_CONTEXT requestContext;
	size_t length = 0;
	PWDF_USB_REQUEST_COMPLETION_PARAMS usbCompletionParams;
	PQUEUE_CONTEXT queueContext;

	UNREFERENCED_PARAMETER(Target);

	// Make sure the request context is still valid.
	requestContext = GetRequestContext(Request);
	queueContext = (PQUEUE_CONTEXT)Context;

	status = CompletionParams->IoStatus.Status;
	usbCompletionParams = CompletionParams->Parameters.Usb.Completion;

	length = usbCompletionParams->Parameters.PipeRead.Length;
	Xfer_CheckPipeStatus(status, queueContext->Info.EndpointAddress);

	mXfer_HandlePipeResetScenariosForComplete(status, queueContext, requestContext);

	if (NT_SUCCESS(status) || length)
	{
		USBMSGN("PipeID=%02Xh Done. Total=%u Requested=%u", queueContext->Info.EndpointAddress,	length, requestContext->Length);
	}
	WdfRequestCompleteWithInformation(Request, status, length);

}

VOID Xfer_WriteBulk (
    __in WDFQUEUE Queue,
    __in WDFREQUEST Request)
{
	NTSTATUS                status;
	PREQUEST_CONTEXT        requestContext = NULL;
	PQUEUE_CONTEXT			queueContext = NULL;
	PDEVICE_CONTEXT         deviceContext;
	ULONG					remainingLength;
	ULONG					stageLength = 0;
	WDF_REQUEST_SEND_OPTIONS sendOptions;

	deviceContext = GetDeviceContext(WdfIoQueueGetDevice(Queue));
	requestContext = GetRequestContext(Request);

	VALIDATE_REQUEST_CONTEXT(requestContext, status);
	if (!NT_SUCCESS(status)) goto Exit;

	if ((queueContext = GetQueueContext(Queue)) == NULL)
	{
		status = STATUS_INVALID_DEVICE_REQUEST;
		USBERRN("Invalid queue context");
		goto Exit;
	}

	queueContext->Xfer.Transferred = 0;
	queueContext->Xfer.Length = requestContext->Length;

	if (!queueContext->Info.MaximumPacketSize && queueContext->Xfer.Length)
	{
		status = STATUS_INVALID_BUFFER_SIZE;
		USBERRN("PipeID=%02Xh MaximumPacketSize=0", queueContext->Info.EndpointAddress);
		goto Exit;
	}

	mXfer_HandlePipeResetScenarios(status, queueContext, requestContext);

	// Handle zlp scenario
	if (queueContext->Xfer.Length)
	{
		// Init queue user memory
		status = GetTransferMemory(Request, requestContext->ActualRequestType, &queueContext->Xfer.UserMem);
		if (!NT_SUCCESS(status))
		{
			USBERR("GetTransferMemory failed. Status=%08Xh\n", status);
			goto Exit;
		}
		queueContext->Xfer.UserOfs.BufferOffset = 0;
		queueContext->Xfer.UserOfs.BufferLength = queueContext->Xfer.Length;
	}
	else
	{
		queueContext->Xfer.UserMem = NULL;
		queueContext->Xfer.UserOfs.BufferOffset = 0;
		queueContext->Xfer.UserOfs.BufferLength = 0;
	}

	queueContext->Xfer.Zlps.Required = (UCHAR)requestContext->Policies.ShortPacketTerminate;
	mXfer_SubmitNextWrite(status, queueContext, requestContext, Request, Xfer_WriteBulkComplete, goto Exit);
	return;

Exit:
	if (queueContext)
	{
		WdfRequestCompleteWithInformation(Request, status, queueContext->Xfer.Transferred);
		return;
	}
	WdfRequestCompleteWithInformation(Request, status, 0);
}

VOID Xfer_WriteBulkComplete(
    __in WDFREQUEST Request,
    __in WDFIOTARGET Target,
    __in PWDF_REQUEST_COMPLETION_PARAMS CompletionParams,
    __in WDFCONTEXT Context)
{
	NTSTATUS                status;
	PREQUEST_CONTEXT        requestContext = NULL;
	PQUEUE_CONTEXT			queueContext = NULL;
	ULONG					remainingLength;
	ULONG					transferredLength;
	ULONG					stageLength = 0;
	WDF_REQUEST_SEND_OPTIONS sendOptions;
	PWDF_USB_REQUEST_COMPLETION_PARAMS usbCompletionParams;

	UNREFERENCED_PARAMETER(Target);

	// Make sure the request context is still valid.
	requestContext	= GetRequestContext(Request);
	queueContext	= (PQUEUE_CONTEXT)Context;

	status				= CompletionParams->IoStatus.Status;
	usbCompletionParams = CompletionParams->Parameters.Usb.Completion;
	transferredLength	= (ULONG)usbCompletionParams->Parameters.PipeWrite.Length;

	if (!queueContext || !usbCompletionParams)
	{
		status = STATUS_INVALID_DEVICE_REQUEST;
		USBERRN("Invalid queue context.");
		goto Exit;
	}

	Xfer_CheckPipeStatus(status, queueContext->Info.EndpointAddress);

	queueContext->Xfer.Transferred += transferredLength;
	if (NT_SUCCESS(status))
	{
		if (queueContext->Xfer.Transferred >= queueContext->Xfer.Length)
		{
			if (queueContext->Xfer.Zlps.Sent >= queueContext->Xfer.Zlps.Required)
			{
				// DONE REASON: Transferred==Requested
				USBDBGN("PipeID=%02Xh DoneReason: Transferred==Requested. Staged=%u Total=%u Requested=%u",
				        queueContext->Info.EndpointAddress,	transferredLength, queueContext->Xfer.Transferred, queueContext->Xfer.Length);
				goto Exit;
			}
			else
			{
				queueContext->Xfer.Zlps.Sent++;
				USBDBGN("PipeID=%02Xh Terminating with ZLP %u of %u..",
				        queueContext->Info.EndpointAddress, queueContext->Xfer.Zlps.Sent, queueContext->Xfer.Zlps.Required);

				goto NextWrite;

			}
		}
	}
	else
	{
		// Cannot continue;
		goto Exit;
	}

	/* More bytes to transfer and no errors have occured. */

NextWrite:
	mXfer_SubmitNextWrite(status, queueContext, requestContext, Request, Xfer_WriteBulkComplete, goto Exit);

	return;

Exit:
	WdfRequestCompleteWithInformation(Request, status, queueContext->Xfer.Transferred);

}

VOID Xfer_WriteBulkRaw (
    __in WDFQUEUE Queue,
    __in WDFREQUEST Request)
{
	NTSTATUS                status;
	PREQUEST_CONTEXT        requestContext = NULL;
	PDEVICE_CONTEXT         deviceContext;
	WDFMEMORY				transferMemory;
	PQUEUE_CONTEXT			queueContext = NULL;

	WDF_REQUEST_SEND_OPTIONS sendOptions;

	deviceContext = GetDeviceContext(WdfIoQueueGetDevice(Queue));
	requestContext = GetRequestContext(Request);

	VALIDATE_REQUEST_CONTEXT(requestContext, status);
	if (!NT_SUCCESS(status)) goto Exit;

	if ((queueContext = GetQueueContext(Queue)) == NULL)
	{
		status = STATUS_INVALID_DEVICE_REQUEST;
		USBERRN("Invalid queue context");
		goto Exit;
	}

	if (!queueContext->Info.MaximumPacketSize && requestContext->Length)
	{
		status = STATUS_INVALID_BUFFER_SIZE;
		USBERRN("PipeID=%02Xh MaximumPacketSize=0", queueContext->Info.EndpointAddress);
		goto Exit;
	}

	if (requestContext->Length)
	{
		status = GetTransferMemory(Request, requestContext->ActualRequestType, &transferMemory);
		if (!NT_SUCCESS(status))
		{
			USBERR("GetTransferMemory failed. Status=%08Xh\n", status);
			goto Exit;
		}
	}
	else
	{
		// Zlp write
		transferMemory = NULL;
	}
	status = WdfUsbTargetPipeFormatRequestForWrite(
	             queueContext->PipeHandle,
	             Request,
	             transferMemory,
	             NULL);

	if (!NT_SUCCESS(status))
	{
		USBERR("WdfIoTargetFormatRequestForWrite failed. Status=%08Xh\n", status);
		goto Exit;
	}

	WDF_REQUEST_SEND_OPTIONS_INIT(&sendOptions, 0);
	status = SetRequestTimeout(requestContext, Request, &sendOptions);
	if (!NT_SUCCESS(status))
	{
		USBERR("SetRequestTimeout failed. Status=%08Xh\n", status);
		goto Exit;
	}

	USBMSG("PipeID=%02Xh Length=%u\n",	queueContext->Info.EndpointAddress,	requestContext->Length);
	status = SubmitAsyncQueueRequest(queueContext, Request, Xfer_WriteBulkRawComplete, &sendOptions, queueContext);
	if (!NT_SUCCESS(status))
	{
		USBERR("SubmitAsyncRequest failed. Status=%08Xh\n", status);
		goto Exit;
	}

	return;

Exit:
	WdfRequestCompleteWithInformation(Request, status, 0);
}

VOID Xfer_WriteBulkRawComplete(
    __in WDFREQUEST Request,
    __in WDFIOTARGET Target,
    __in PWDF_REQUEST_COMPLETION_PARAMS CompletionParams,
    __in WDFCONTEXT Context)
{
	NTSTATUS status;
	PREQUEST_CONTEXT requestContext;
	size_t length = 0;
	PWDF_USB_REQUEST_COMPLETION_PARAMS usbCompletionParams;
	PQUEUE_CONTEXT queueContext;

	UNREFERENCED_PARAMETER(Target);

	// Make sure the request context is still valid.
	requestContext = GetRequestContext(Request);
	queueContext = (PQUEUE_CONTEXT)Context;

	status = CompletionParams->IoStatus.Status;
	usbCompletionParams = CompletionParams->Parameters.Usb.Completion;

	length = usbCompletionParams->Parameters.PipeWrite.Length;
	Xfer_CheckPipeStatus(status, queueContext->Info.EndpointAddress);

	if (NT_SUCCESS(status) || length)
	{
		USBMSGN("PipeID=%02Xh Done. Total=%u Requested=%u", queueContext->Info.EndpointAddress,	length, requestContext->Length);
	}
	WdfRequestCompleteWithInformation(Request, status, length);
}