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
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
/*!********************************************************************
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"

extern volatile LONG DeviceInstanceNumber;

#if (defined(ALLOC_PRAGMA) && defined(PAGING_ENABLED))
#pragma alloc_text(PAGE, Device_OnAdd)
#pragma alloc_text(PAGE, Device_OnPrepareHardware)
#pragma alloc_text(PAGE, Device_OnFileCreate)
#pragma alloc_text(PAGE, Device_OnFileClose)
#pragma alloc_text(PAGE, Device_Create)
#pragma alloc_text(PAGE, Device_FetchConfigDescriptor)
#pragma alloc_text(PAGE, Device_Configure)
#pragma alloc_text(PAGE, Device_Reset)
#endif

NTSTATUS
Device_OnAdd(
    __in WDFDRIVER        Driver,
    __in PWDFDEVICE_INIT  DeviceInit)
/*++
Routine Description:

    EvtDeviceAdd is called by the framework in response to AddDevice
    call from the PnP manager. We create and initialize a device object to
    represent a new instance of the device. All the software resources
    should be allocated in this callback.

Arguments:

    Driver - Handle to a framework driver object created in DriverEntry

    DeviceInit - Pointer to a framework-allocated WDFDEVICE_INIT structure.

Return Value:

    NTSTATUS

--*/
{
	WDF_FILEOBJECT_CONFIG     fileConfig;
	WDF_PNPPOWER_EVENT_CALLBACKS        pnpPowerCallbacks;
	WDF_OBJECT_ATTRIBUTES               fdoAttributes;
	WDF_OBJECT_ATTRIBUTES               fileObjectAttributes;
	WDF_OBJECT_ATTRIBUTES               requestAttributes;
	NTSTATUS                            status;
	WDFDEVICE                           device;
	WDF_DEVICE_PNP_CAPABILITIES         pnpCaps;
	WDF_IO_QUEUE_CONFIG                 ioQueueConfig;
	PDEVICE_CONTEXT                     deviceContext;
	WDFQUEUE                            queue;
	UNICODE_STRING						symbolicLinkName;
	WCHAR								tmpName[128];
	INT									i;

	UNREFERENCED_PARAMETER(Driver);

	PAGED_CODE();

	//
	// Initialize the pnpPowerCallbacks structure.  Callback events for PNP
	// and Power are specified here.  If you don't supply any callbacks,
	// the Framework will take appropriate default actions based on whether
	// DeviceInit is initialized to be an FDO, a PDO or a filter device
	// object.
	//

	WDF_PNPPOWER_EVENT_CALLBACKS_INIT(&pnpPowerCallbacks);

	pnpPowerCallbacks.EvtDevicePrepareHardware = Device_OnPrepareHardware;
	pnpPowerCallbacks.EvtDeviceD0Entry = Device_OnD0Entry;
	pnpPowerCallbacks.EvtDeviceD0Exit = Device_OnD0Exit;

	WdfDeviceInitSetPnpPowerEventCallbacks(DeviceInit, &pnpPowerCallbacks);

	//
	// Initialize the request attributes to specify the context size and type
	// for every request created by framework for this device.
	//
	WDF_OBJECT_ATTRIBUTES_INIT(&requestAttributes);
	WDF_OBJECT_ATTRIBUTES_SET_CONTEXT_TYPE(&requestAttributes, REQUEST_CONTEXT);

	WdfDeviceInitSetRequestAttributes(DeviceInit, &requestAttributes);

	//
	// Initialize WDF_FILEOBJECT_CONFIG_INIT struct to tell the
	// framework whether you are interested in handle Create, Close and
	// Cleanup requests that gets genereate when an application or another
	// kernel component opens an handle to the device. If you don't register
	// the framework default behaviour would be complete these requests
	// with STATUS_SUCCESS. A driver might be interested in registering these
	// events if it wants to do security validation and also wants to maintain
	// per handle (fileobject) context.
	//

	WDF_FILEOBJECT_CONFIG_INIT(
	    &fileConfig,
	    Device_OnFileCreate,
	    Device_OnFileClose,
	    WDF_NO_EVENT_CALLBACK
	);

	//
	// Specify a context for FileObject. If you register FILE_EVENT callbacks,
	// the framework by default creates a framework FILEOBJECT corresponding
	// to the WDM fileobject. If you want to track any per handle context,
	// use the context for FileObject. Driver that typically use FsContext
	// field should instead use Framework FileObject context.
	//
	WDF_OBJECT_ATTRIBUTES_INIT(&fileObjectAttributes);
	WDF_OBJECT_ATTRIBUTES_SET_CONTEXT_TYPE(&fileObjectAttributes, FILE_CONTEXT);

	WdfDeviceInitSetFileObjectConfig(DeviceInit,
	                                 &fileConfig,
	                                 &fileObjectAttributes);

#if !defined(BUFFERED_READ_WRITE)
	//
	// I/O type is Buffered by default. We want to do direct I/O for Reads
	// and Writes so set it explicitly.
	WdfDeviceInitSetIoType(DeviceInit, WdfDeviceIoDirect);

#endif


	WdfDeviceInitSetIoInCallerContextCallback(DeviceInit, Request_PreIoInitialize);

	//
	// Now specify the size of device extension where we track per device
	// context.DeviceInit is completely initialized. So call the framework
	// to create the device and attach it to the lower stack.
	//
	WDF_OBJECT_ATTRIBUTES_INIT(&fdoAttributes);
	WDF_OBJECT_ATTRIBUTES_SET_CONTEXT_TYPE(&fdoAttributes, DEVICE_CONTEXT);

	status = WdfDeviceCreate(&DeviceInit, &fdoAttributes, &device);
	if (!NT_SUCCESS(status))
	{
		USBERR("WdfDeviceCreate failed. status=%Xh\n", status);
		return status;
	}

	//
	// Get the DeviceObject context by using accessor function specified in
	// the WDF_DECLARE_CONTEXT_TYPE_WITH_NAME macro for DEVICE_CONTEXT.
	//

	deviceContext = GetDeviceContext(device);
	deviceContext->WdfDevice = device;
	deviceContext->InstanceNumber = InterlockedIncrement(&DeviceInstanceNumber);

	status = Registry_ReadAllDeviceKeys(deviceContext);
	if (!NT_SUCCESS(status))
	{
		USBERR("Registry_ReadAllDeviceKeys failed. status=%Xh\n", status);
		goto Error;
	}

	/* create the libusb-win32 legacy symbolic link */
	for (i = LIBUSB_MAX_NUMBER_OF_DEVICES - 1; i > 1; i--)
	{
		RtlZeroMemory(tmpName, sizeof(tmpName));

		/* initialize some unicode strings */
		_snwprintf(tmpName,
		           sizeof(tmpName) / sizeof(WCHAR),
		           L"%s%04d", LIBUSB_SYMBOLIC_LINK_NAME, i);

		RtlInitUnicodeString(&symbolicLinkName, tmpName);

		status = WdfDeviceCreateSymbolicLink(device, &symbolicLinkName);
		if (NT_SUCCESS(status))
		{
			USBMSG("[dev-id=#%d] SymbolicLink=%s%04d\n",
			       deviceContext->InstanceNumber, LIBUSB_SYMBOLIC_LINK_NAMEA, i);
			break;
		}

		/* continue until an unused device name is found */
	}

	if (!NT_SUCCESS(status))
	{
		USBERR("[dev-id=#%d] creating symbolic link failed. status=%Xh\n", deviceContext->InstanceNumber, status);
		goto Error;
	}

	//
	// Tell the framework to set the SurpriseRemovalOK in the DeviceCaps so
	// that you don't get the popup in usermode (on Win2K) when you surprise
	// remove the device.
	//
	WDF_DEVICE_PNP_CAPABILITIES_INIT(&pnpCaps);
	pnpCaps.SurpriseRemovalOK = WdfTrue;

	WdfDeviceSetPnpCapabilities(device, &pnpCaps);

	/*
	Create the default queue. The default queue will be a power managed parallel queue.
	While requests are pending in the default queue the device will not suspend.
	*/
	WDF_IO_QUEUE_CONFIG_INIT_DEFAULT_QUEUE(&ioQueueConfig, WdfIoQueueDispatchParallel);

	ioQueueConfig.EvtIoRead = DefaultQueue_OnRead;
	ioQueueConfig.EvtIoWrite = DefaultQueue_OnWrite;
	ioQueueConfig.EvtIoDeviceControl = DefaultQueue_OnIoControl;

	status = WdfIoQueueCreate(device,
	                          &ioQueueConfig,
	                          WDF_NO_OBJECT_ATTRIBUTES,
	                          &queue);// pointer to default queue
	if (!NT_SUCCESS(status))
	{
		USBERR("WdfIoQueueCreate failed  for Default Queue. status=%Xh\n", status);
		goto Error;
	}

	USBD_GetUSBDIVersion(&deviceContext->UsbVersionInfo);

	//
	// Register the DeviceInterfaceGUIDs set in the devices registry key
	//
	if (deviceContext->DeviceRegSettings.DeviceInterfaceGUIDs != WDF_NO_HANDLE)
	{
		WDFCOLLECTION collection = deviceContext->DeviceRegSettings.DeviceInterfaceGUIDs;
		ULONG count = WdfCollectionGetCount(collection);
		ULONG index;
		for (index = 0; index < count; index++)
		{
			WDFSTRING guidString = WdfCollectionGetItem(collection, index);
			if (guidString != WDF_NO_HANDLE)
			{
				GUID guid = {0};
				if (NT_SUCCESS(GUIDFromWdfString(guidString, &guid)))
				{
					status = WdfDeviceCreateDeviceInterface(device,
					                                        (LPGUID) &guid,
					                                        NULL);// Reference String
					if (!NT_SUCCESS(status))
					{
						USBERR("WdfDeviceCreateDeviceInterface failed. status=%Xh\n", status);
						goto Error;
					}
					else
					{
						USBMSG("[dev-id=#%d] assigned DeviceInterfaceGUID {%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X}.\n",
						       deviceContext->InstanceNumber,
						       guid.Data1,
						       guid.Data2,
						       guid.Data3,
						       guid.Data4[0], guid.Data4[1],
						       guid.Data4[2], guid.Data4[3], guid.Data4[4], guid.Data4[5], guid.Data4[6], guid.Data4[7]);
					}
				}
			}
		}
	}

	return status;

Error:
	if (DeviceInit)
	{
		WdfDeviceInitFree(DeviceInit);
		DeviceInit = NULL;
	}
	return status;

}

NTSTATUS
Device_OnPrepareHardware(
    __in WDFDEVICE Device,
    __in WDFCMRESLIST ResourceList,
    __in WDFCMRESLIST ResourceListTranslated)
/*++

Routine Description:

    In this callback, the driver does whatever is necessary to make the
    hardware ready to use.  In the case of a USB device, this involves
    reading and selecting descriptors.

    //TODO:

Arguments:

    Device - handle to a device

Return Value:

    NT status value

--*/
{
	NTSTATUS                    status = STATUS_SUCCESS;
	PDEVICE_CONTEXT             deviceContext;

	UNREFERENCED_PARAMETER(ResourceList);
	UNREFERENCED_PARAMETER(ResourceListTranslated);

	deviceContext = GetDeviceContext(Device);

	// Hardware is already prepared.
	if (deviceContext->WdfUsbTargetDevice)
	{
		USBMSGN("Hardware is already prepared. Skipping..");
		return STATUS_SUCCESS;
	}

	// Create target device; fetch device descriptior and information.
	status = Device_Create(Device);
	if (!NT_SUCCESS(status))
	{
		USBERRN("Device_Create Failed. Status=%08Xh", status);
		return status;
	}

	// Fetch and store config descriptor to device context.
	status = Device_FetchConfigDescriptor(Device);
	if (!NT_SUCCESS(status))
	{
		USBERRN("Device_FetchConfigDescriptor Failed. Status=%08Xh", status);
		return status;
	}

	// Select configuration and initialize interfaces.
	status = Device_Configure(Device);
	if (!NT_SUCCESS(status))
	{
		USBERRN("Device_Configure Failed. Status=%08Xh", status);
		return status;
	}

	// Apply power policy settings presented in the registry.
	status = Policy_InitPower(deviceContext);
	if (!NT_SUCCESS(status))
	{
		USBWRNN("Policy_InitPower Failed. Status=%08Xh", status);
		status = STATUS_SUCCESS;
	}
	return status;
}

NTSTATUS Device_OnD0Entry(WDFDEVICE Device, WDF_POWER_DEVICE_STATE WdfPowerDeviceState)
{
	UNREFERENCED_PARAMETER(Device);
	UNREFERENCED_PARAMETER(WdfPowerDeviceState);

	USBMSGN("Active. D%u -> D0", WdfPowerDeviceState - 1);

	return STATUS_SUCCESS;
}

NTSTATUS Device_OnD0Exit(WDFDEVICE Device, WDF_POWER_DEVICE_STATE WdfPowerDeviceState)
{
	PDEVICE_CONTEXT             deviceContext;
	PQUEUE_CONTEXT              queueContext;
	PPIPE_CONTEXT               pipeContext;
	int i;

	UNREFERENCED_PARAMETER(WdfPowerDeviceState);

	USBMSGN("Idle.   D0 -> D%u", WdfPowerDeviceState - 1);

	deviceContext = GetDeviceContext(Device);

	/*
	Mark all Bulk/Int/Iso IN/OUT endpoints which have the Policies.ResetPipeOnResume set.
	These pipes are reset in the xfer routines before the next subsequent transfer. (not in D0 entry)
	*/
	for (i = 1; i < LIBUSB_MAX_ENDPOINT_COUNT; i++)
	{
		pipeContext = &deviceContext->PipeContextByID[i];
		if (pipeContext->IsValid && pipeContext->Pipe && pipeContext->Queue && pipeContext->Policies.ResetPipeOnResume && (pipeContext->PipeInformation.EndpointAddress & 0xF))
		{
			queueContext = GetQueueContext(pipeContext->Queue);
			if (!queueContext)
			{
				USBERRN("Invalid queue context. pipeID=%02Xh queue=%p",
					pipeContext->PipeInformation.EndpointAddress, pipeContext->Queue);

				continue;
			}

			if (!queueContext->ResetPipeForResume)
			{
				USBMSGN("Marking pipe for reset on next request. pipeID=%02Xh queue=%p",
					pipeContext->PipeInformation.EndpointAddress, pipeContext->Queue);
				
				queueContext->ResetPipeForResume = TRUE;
			}
		}
	}
	
	return STATUS_SUCCESS;
}

VOID Device_OnFileCreate(__in WDFDEVICE            Device,
                         __in WDFREQUEST           Request,
                         __in WDFFILEOBJECT        FileObject)
/*++

Routine Description:

    The framework calls a driver's EvtDeviceFileCreate callback
    when the framework receives an IRP_MJ_CREATE request.
    The system sends this request when a user application opens the
    device to perform an I/O operation, such as reading or writing a file.
    This callback is called synchronously, in the context of the thread
    that created the IRP_MJ_CREATE request.

Arguments:

    Device - Handle to a framework device object.
    FileObject - Pointer to fileobject that represents the open handle.
    CreateParams - copy of the create IO_STACK_LOCATION

Return Value:

   NT status code

--*/
{
	NTSTATUS                    status = STATUS_UNSUCCESSFUL;
	PUNICODE_STRING             fileName;
	PFILE_CONTEXT               pFileContext;
	PDEVICE_CONTEXT             deviceContext;
	PPIPE_CONTEXT               pipeContext;
	PEPROCESS					pProcess;
	PAGED_CODE();

	USBMSG("begins\n");

	//
	// initialize variables
	//
	deviceContext = GetDeviceContext(Device);
	pFileContext = GetFileContext(FileObject);
	pFileContext->DeviceContext = deviceContext;

	fileName = WdfFileObjectGetFileName(FileObject);

	pProcess = PsGetCurrentProcess();
	if (pProcess != NULL)
	{
		USBMSG("Process ID=%u\n", PsGetProcessId(pProcess));
	}

	if (0 == fileName->Length)
	{
		//
		// opening a device as opposed to pipe.
		//
		status = STATUS_SUCCESS;
	}
	else
	{
		//
		// using direct pipe access.
		//
		pipeContext = Pipe_GetContextFromName(deviceContext, fileName);

		if (pipeContext != NULL)
		{
			//
			// found a match
			//
			pFileContext->PipeID = pipeContext->PipeInformation.EndpointAddress;

			WdfUsbTargetPipeSetNoMaximumPacketSizeCheck(pipeContext->Pipe);

			status = STATUS_SUCCESS;
		}
		else
		{
			status = STATUS_INVALID_DEVICE_REQUEST;
		}
	}

	InterlockedIncrement(&deviceContext->OpenedFileHandleCount);
	WdfRequestComplete(Request, status);

	USBMSG("ends\n");

	return;
}

VOID Device_OnFileClose(__in WDFFILEOBJECT FileObject)
{
	PFILE_CONTEXT               pFileContext;

	PAGED_CODE();

	pFileContext = GetFileContext(FileObject);

	if (pFileContext && pFileContext->DeviceContext)
	{
		Interface_ReleaseAll(pFileContext->DeviceContext, WdfFileObjectWdmGetFileObject(FileObject));
		InterlockedDecrement(&pFileContext->DeviceContext->OpenedFileHandleCount);
		USBDBGN("OpenedFileHandleCount=%u", pFileContext->DeviceContext->OpenedFileHandleCount);
	}
}


NTSTATUS Device_Create(__in WDFDEVICE Device)
/*++

Routine Description:

    This routine configures the USB device.
    In this routines we get the device descriptor,
    the configuration descriptor and select the
    configuration.

Arguments:

    Device - Handle to a framework device

Return Value:

    NTSTATUS - NT status value.

--*/
{
	NTSTATUS               status;
	PDEVICE_CONTEXT        deviceContext;
	WDF_USB_DEVICE_INFORMATION  info;

	PAGED_CODE();

	//
	// initialize variables
	//
	deviceContext = GetDeviceContext(Device);

	//
	// Create a usb handle so that we can communicate with the
	// underlying USB stack. The WDFUSBDEVICE handle is used to query,
	// configure, and manage all aspects of the USB device.
	// These aspects include device properties, bus properties,
	// and I/O creation and synchronization. We only create device the first
	// the PrepareHardware is called. If the device is restarted by pnp manager
	// for resource rebalance, we will use the same device handle but then select
	// the interfaces again because the USB stack could reconfigure the device on
	// restart.
	//
	if (deviceContext->WdfUsbTargetDevice == NULL)
	{
		status = WdfUsbTargetDeviceCreate(Device,
		                                  WDF_NO_OBJECT_ATTRIBUTES,
		                                  &deviceContext->WdfUsbTargetDevice);
		if (!NT_SUCCESS(status))
		{
			USBERR("WdfUsbTargetDeviceCreate failed. status=%08Xh\n", status);
			return status;
		}
	}

	WdfUsbTargetDeviceGetDeviceDescriptor(deviceContext->WdfUsbTargetDevice,
	                                      &deviceContext->UsbDeviceDescriptor);

	ASSERT(deviceContext->UsbDeviceDescriptor.bNumConfigurations);

	WDF_USB_DEVICE_INFORMATION_INIT(&info);

	//
	// Retrieve USBD version information, port driver capabilites and device
	// capabilites such as speed, power, etc.
	//
	deviceContext->DeviceSpeed = UsbLowSpeed;
	deviceContext->RemoteWakeCapable = FALSE;
	deviceContext->SelfPowered = FALSE;

	status = WdfUsbTargetDeviceRetrieveInformation(deviceContext->WdfUsbTargetDevice, &info);
	if (NT_SUCCESS(status))
	{
		if ((info.Traits & WDF_USB_DEVICE_TRAIT_AT_HIGH_SPEED))
		{
			deviceContext->DeviceSpeed = UsbHighSpeed;
		}
		if ((info.Traits & WDF_USB_DEVICE_TRAIT_REMOTE_WAKE_CAPABLE))
		{
			deviceContext->RemoteWakeCapable = TRUE;
		}
		if ((info.Traits & WDF_USB_DEVICE_TRAIT_SELF_POWERED))
		{
			deviceContext->SelfPowered = TRUE;
		}
	}
	else
	{
		USBWRN("WdfUsbTargetDeviceRetrieveInformation failed, status=%Xh. Cannot properly determine device speed.\n", status);
	}

	// The winusb device speed policy is offet by speed+1.
	GetPolicyValue(DEVICE_SPEED, deviceContext->DevicePolicy) = deviceContext->DeviceSpeed + 1;

	USBMSG("DeviceSpeed=%s RemoteWakeCapable=%s SelfPowered=%s\n",
	       GetDeviceSpeedString(deviceContext->DeviceSpeed),
	       GetBoolString(deviceContext->RemoteWakeCapable),
	       GetBoolString(deviceContext->SelfPowered));

	return status;
}

NTSTATUS Device_FetchConfigDescriptor(__in WDFDEVICE Device)
/*++

Routine Description:

    This helper routine reads the configuration descriptor
    for the device in couple of steps.

Arguments:

    Device - Handle to a framework device

Return Value:

    NTSTATUS - NT status value

--*/
{
	USHORT                        size = 0;
	NTSTATUS                      status;
	PDEVICE_CONTEXT               deviceContext;
	PUSB_CONFIGURATION_DESCRIPTOR configurationDescriptor;
	WDF_OBJECT_ATTRIBUTES attributes;
	WDFMEMORY   memory;

	PAGED_CODE();

	//
	// initialize the variables
	//
	configurationDescriptor = NULL;
	deviceContext = GetDeviceContext(Device);

	//
	// Read the first configuration descriptor
	// This requires two steps:
	// 1. Ask the WDFUSBDEVICE how big it is
	// 2. Allocate it and get it from the WDFUSBDEVICE
	//
	status = WdfUsbTargetDeviceRetrieveConfigDescriptor(deviceContext->WdfUsbTargetDevice,
	         NULL,
	         &size);

	if (status != STATUS_BUFFER_TOO_SMALL || size == 0)
	{
		USBERR("WdfUsbTargetDeviceRetrieveConfigDescriptor failed. status=%08Xh\n", status);
		return status;
	}

	//
	// Create a memory object and specify usbdevice as the parent so that
	// it will be freed automatically.
	//
	WDF_OBJECT_ATTRIBUTES_INIT(&attributes);

	attributes.ParentObject = deviceContext->WdfDevice;
	deviceContext->ConfigurationDescriptorSize = 0;

	status = WdfMemoryCreate(&attributes,
	                         NonPagedPool,
	                         POOL_TAG,
	                         size,
	                         &memory,
	                         &configurationDescriptor);
	if (!NT_SUCCESS(status))
	{
		USBERR("WdfMemoryCreate failed. size=%u status=%08Xh\n", size, status);
		return status;
	}

	status = WdfUsbTargetDeviceRetrieveConfigDescriptor(deviceContext->WdfUsbTargetDevice,
	         configurationDescriptor,
	         &size);

	if (!NT_SUCCESS(status))
	{
		USBERR("WdfUsbTargetDeviceRetrieveConfigDescriptor failed. status=%08Xh\n", status);
		return status;
	}

	deviceContext->ConfigurationDescriptorSize = size;
	deviceContext->UsbConfigurationDescriptor = configurationDescriptor;
	deviceContext->ConfigDescriptorIndex = 0;

	return status;
}

NTSTATUS Device_Configure(WDFDEVICE Device)
{
	WDF_USB_DEVICE_SELECT_CONFIG_PARAMS		params;
	PWDF_USB_INTERFACE_SETTING_PAIR			settingPairs = NULL;
	NTSTATUS								status;
	PDEVICE_CONTEXT							deviceContext;
	PINTERFACE_CONTEXT						interfaceContext;
	UCHAR									interfaceIndex;

	PAGED_CODE();

	deviceContext = GetDeviceContext(Device);

	deviceContext->InterfaceCount = WdfUsbTargetDeviceGetNumInterfaces(deviceContext->WdfUsbTargetDevice);

	if (deviceContext->InterfaceCount == 1)
	{
		USBDBG("Using single interface configuration..\n");
		WDF_USB_DEVICE_SELECT_CONFIG_PARAMS_INIT_SINGLE_INTERFACE(&params);
	}
	else
	{
		USBDBG("Using multiple interface configuration..\n");
		settingPairs = ExAllocatePoolWithTag(
		                   PagedPool,
		                   sizeof(WDF_USB_INTERFACE_SETTING_PAIR) * deviceContext->InterfaceCount,
		                   POOL_TAG);

		if (settingPairs == NULL)
		{
			status = STATUS_INSUFFICIENT_RESOURCES;
			USBERR("ExAllocatePoolWithTag failed. size=%u status=%08Xh\n",
			       sizeof(WDF_USB_INTERFACE_SETTING_PAIR) * deviceContext->InterfaceCount,
			       status);
			return status;
		}

		for (interfaceIndex = 0; interfaceIndex < deviceContext->InterfaceCount; interfaceIndex++)
		{
			settingPairs[interfaceIndex].UsbInterface =
			    WdfUsbTargetDeviceGetInterface(deviceContext->WdfUsbTargetDevice, interfaceIndex);

			if (settingPairs[interfaceIndex].UsbInterface == WDF_NO_HANDLE)
			{
				USBDBG("WdfUsbTargetDeviceGetInterface failed. interfaceIndex=%u\n", interfaceIndex);
			}
			// Select alternate setting zero on all interfaces.
			settingPairs[interfaceIndex].SettingIndex = 0;
		}

		WDF_USB_DEVICE_SELECT_CONFIG_PARAMS_INIT_MULTIPLE_INTERFACES(&params, deviceContext->InterfaceCount, settingPairs);
	}
	status = WdfUsbTargetDeviceSelectConfig(deviceContext->WdfUsbTargetDevice, NULL, &params);
	if (!NT_SUCCESS(status))
	{
		USBERR("WdfUsbTargetDeviceSelectConfig failed. status=%Xh", status);
		goto Error;
	}
	else
	{
		// get the interface count again; this should be the same as before since KMDF only supports
		// the first configuration.
		//
		deviceContext->InterfaceCount = WdfUsbTargetDeviceGetNumInterfaces(deviceContext->WdfUsbTargetDevice);
		status = Pipe_InitDefaultContext(deviceContext);
		if (!NT_SUCCESS(status))
		{
			USBERR("failed initializing default pipe! status=%Xh", status);
			goto Error;
		}
		for (interfaceIndex = 0; interfaceIndex < deviceContext->InterfaceCount; interfaceIndex++)
		{
			interfaceContext = &deviceContext->InterfaceContext[interfaceIndex];
			interfaceContext->InterfaceIndex = interfaceIndex;
			
			// get the interface handle
			interfaceContext->Interface = WdfUsbTargetDeviceGetInterface(deviceContext->WdfUsbTargetDevice, interfaceContext->InterfaceIndex);
			
			status = Interface_InitContext(deviceContext, interfaceContext);
			if (!NT_SUCCESS(status))
			{
				USBERR("Interface_InitContext failed. status=%Xh", status);
				deviceContext->InterfaceCount = interfaceIndex;
				goto Error;
			}

			status = Interface_Start(deviceContext, interfaceContext);
			if (!NT_SUCCESS(status))
			{
				USBERR("Interface_Start failed. status=%Xh", status);
				deviceContext->InterfaceCount = interfaceIndex;
				goto Error;
			}
		}
	}

Error:
	if (settingPairs)
	{
		ExFreePoolWithTag(settingPairs, POOL_TAG);
		settingPairs = NULL;
	}
	return status;
}

// This routine calls WdfUsbTargetDeviceResetPortSynchronously to reset the device if it's still connected.
//
NTSTATUS Device_Reset(__in WDFDEVICE Device)
{
	PDEVICE_CONTEXT deviceContext;
	NTSTATUS status;

	PAGED_CODE();

	deviceContext = GetDeviceContext(Device);

	//
	// A reset-device
	// request will be stuck in the USB until the pending transactions
	// have been canceled. Similarly, if there are pending tranasfers on the BULK
	// IN/OUT pipe cancel them.
	// To work around this issue, the driver should stop the continuous reader
	// (by calling WdfIoTargetStop) before resetting the device, and restart the
	// continuous reader (by calling WdfIoTargetStart) after the request completes.
	//
	Pipe_StopAll(deviceContext, TRUE);

	//
	// It may not be necessary to check whether device is connected before
	// resetting the port.
	//
	status = WdfUsbTargetDeviceIsConnectedSynchronous(deviceContext->WdfUsbTargetDevice);

	if(NT_SUCCESS(status))
	{
		status = WdfUsbTargetDeviceResetPortSynchronously(deviceContext->WdfUsbTargetDevice);
		USBMSG("WdfUsbTargetDeviceResetPortSynchronously status=%Xh\n", status);
	}
	else
	{
		USBMSG("WdfUsbTargetDeviceIsConnectedSynchronous status=%Xh\n", status);
	}

	Pipe_StartAll(deviceContext, TRUE);


	return status;
}