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
/*!********************************************************************
libusbK - Multi-driver USB library.
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 "lusbk_private.h"
#include "lusbk_handles.h"
#include "lusbk_stack_collection.h"

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

#ifndef DESCRIPTOR_PARSE_BUILD_STACK___________________________________

typedef struct _DESCRIPTOR_ITERATOR
{
	LONG	Remaining;

	union
	{
		PUCHAR						Offset;

		PUSB_COMMON_DESCRIPTOR		Comn;
		PUSB_INTERFACE_DESCRIPTOR	Intf;
		PUSB_ENDPOINT_DESCRIPTOR	Pipe;
		PUSB_SUPERSPEED_ENDPOINT_COMPANION_DESCRIPTOR	SuperSpeedEndpointCompanion;
	} Ptr;
} DESCRIPTOR_ITERATOR, *PDESCRIPTOR_ITERATOR;

static BOOL u_Desc_Next(PDESCRIPTOR_ITERATOR desc)
{
	if (desc->Remaining < sizeof(USB_COMMON_DESCRIPTOR)) return FALSE;

	desc->Remaining -= desc->Ptr.Comn->bLength;

	if (desc->Remaining >= sizeof(USB_COMMON_DESCRIPTOR))
	{
		desc->Ptr.Offset += desc->Ptr.Comn->bLength;
		return TRUE;
	}
	return FALSE;
}

static void u_Add_Pipe(PKUSB_ALT_INTERFACE_EL altInterfaceEL, PDESCRIPTOR_ITERATOR desc)
{
	PKUSB_PIPE_EL pipeEL;
	DESCRIPTOR_ITERATOR descPrev;
	PKUSB_PIPE_EL prevPipeELForCompanionAttach = NULL;

	memcpy(&descPrev, desc, sizeof(descPrev));

	while (u_Desc_Next(desc))
	{
		if (desc->Ptr.Comn->bDescriptorType == USB_DESCRIPTOR_TYPE_INTERFACE)
		{
			memcpy(desc, &descPrev, sizeof(*desc));
			break;
		}
		else if (desc->Ptr.Comn->bDescriptorType == USB_DESCRIPTOR_TYPE_ENDPOINT)
		{
			FindPipeEL(altInterfaceEL, pipeEL, FALSE, desc->Ptr.Pipe->bEndpointAddress);
			if (!pipeEL)
			{
				pipeEL = Mem_Alloc(sizeof(*pipeEL));
				if (!pipeEL) return;

				pipeEL->Descriptor	= desc->Ptr.Pipe;
				pipeEL->ID			= pipeEL->Descriptor->bEndpointAddress;
				pipeEL->Index		= altInterfaceEL->PipeCount++;

				DL_APPEND(altInterfaceEL->PipeList, pipeEL);
			}
			prevPipeELForCompanionAttach = pipeEL;
		}
		else if (desc->Ptr.Comn->bDescriptorType == USB_SUPERSPEED_ENDPOINT_COMPANION)
		{
			if (prevPipeELForCompanionAttach)
			{
				prevPipeELForCompanionAttach->SuperSpeedCompanionDescriptor = desc->Ptr.SuperSpeedEndpointCompanion;
				prevPipeELForCompanionAttach = NULL;
			}
		}

		memcpy(&descPrev, desc, sizeof(descPrev));
	}
}

static void u_Add_Interface(PKUSB_HANDLE_INTERNAL Handle, PDESCRIPTOR_ITERATOR desc)
{
	PKUSB_INTERFACE_EL interfaceEL;
	PKUSB_ALT_INTERFACE_EL altInterfaceEL;

	FindInterfaceEL(Handle->Device->UsbStack, interfaceEL, FALSE, desc->Ptr.Intf->bInterfaceNumber);
	if (!interfaceEL)
	{
		interfaceEL = Mem_Alloc(sizeof(*interfaceEL));
		if (!interfaceEL) return;

		interfaceEL->ID		= desc->Ptr.Intf->bInterfaceNumber;
		interfaceEL->Index	= Handle->Device->UsbStack->InterfaceCount++;

		interfaceEL->SharedInterface		= &Get_SharedInterface(Handle, interfaceEL->Index);
		interfaceEL->SharedInterface->ID	= interfaceEL->ID;
		interfaceEL->SharedInterface->Index	= interfaceEL->Index;

		DL_APPEND(Handle->Device->UsbStack->InterfaceList,	interfaceEL);
	}

	FindAltInterfaceEL(interfaceEL, altInterfaceEL, FALSE, desc->Ptr.Intf->bAlternateSetting);
	if (!altInterfaceEL)
	{
		altInterfaceEL = Mem_Alloc(sizeof(*altInterfaceEL));
		if (!altInterfaceEL) return;

		altInterfaceEL->Descriptor	= desc->Ptr.Intf;
		altInterfaceEL->ID			= desc->Ptr.Intf->bAlternateSetting;
		altInterfaceEL->Index		= interfaceEL->AltInterfaceCount++;

		DL_APPEND(interfaceEL->AltInterfaceList, altInterfaceEL);
	}

	u_Add_Pipe(altInterfaceEL, desc);
}

static BOOL u_Init_Config(__in PKUSB_HANDLE_INTERNAL Handle)
{
	DWORD errorCode = ERROR_SUCCESS;
	DESCRIPTOR_ITERATOR desc;
	PUSB_CONFIGURATION_DESCRIPTOR cfg = Handle->Device->ConfigDescriptor;

	Mem_Zero(&desc, sizeof(desc));
	desc.Ptr.Offset = (PUCHAR)cfg;
	desc.Remaining = (LONG)cfg->wTotalLength;

	while(u_Desc_Next(&desc))
	{
		if (desc.Ptr.Comn->bDescriptorType == USB_DESCRIPTOR_TYPE_INTERFACE)
			u_Add_Interface(Handle, &desc);
	}

	return LusbwError(errorCode);
}

#endif

static BOOL u_Init_Handle(__out PKUSB_HANDLE_INTERNAL* Handle,
                          __in KUSB_DRVID DriverID,
                          __in_opt PKDEV_HANDLE_INTERNAL SharedDevice,
                          __in_opt PKUSB_STACK_CB Init_BackendCB,
                          __in PKOBJ_CB Cleanup_UsbK,
                          __in PKOBJ_CB Cleanup_DevK)
{
	PKUSB_HANDLE_INTERNAL handle = NULL;

	UNREFERENCED_PARAMETER(DriverID);

	ErrorHandle(!IsHandleValid(Handle), Error, "Handle");

	handle = PoolHandle_Acquire_UsbK(Cleanup_UsbK);
	ErrorNoSet(!IsHandleValid(handle), Error, "->PoolHandle_Acquire_UsbK");

	if (SharedDevice)
	{
		// this is a cloned/associated handle.
		ErrorSet(!PoolHandle_Inc_DevK(SharedDevice), Error, ERROR_RESOURCE_NOT_AVAILABLE, "->PoolHandle_Inc_DevK");
		handle->Device = SharedDevice;
		handle->IsClone = TRUE;
	}
	else
	{
		handle->Device = PoolHandle_Acquire_DevK(Cleanup_DevK);
		ErrorNoSet(!IsHandleValid(handle->Device), Error, "->PoolHandle_Acquire_DevK");

		if (Init_BackendCB)
		{
			ErrorNoSet(!Init_BackendCB(handle), Error, "->Init_BackendCB");
		}
	}

	*Handle = handle;
	return TRUE;

Error:
	if (handle) PoolHandle_Dec_UsbK(handle);
	*Handle = NULL;
	return FALSE;
}

BOOL UsbStack_Init(
    __out		KUSB_HANDLE* Handle,
    __in_opt	KUSB_DRVID DriverID,
    __in		BOOL UsePipeCache,
    __in_opt	HANDLE DeviceHandle,
    __in_opt	KLST_DEVINFO_HANDLE DevInfo,
    __in_opt	PKDEV_HANDLE_INTERNAL SharedDevice,
    __in		PKUSB_STACK_CB Init_ConfigCB,
    __in_opt	PKUSB_STACK_CB Init_BackendCB,
    __in		PKOBJ_CB Cleanup_UsbK,
    __in		PKOBJ_CB Cleanup_DevK)
{
	BOOL success;
	PKUSB_HANDLE_INTERNAL handle = NULL;
	const size_t extraMemAlloc = sizeof(KUSB_INTERFACE_STACK) + sizeof(KUSB_DRIVER_API) + ((sizeof(KDEV_SHARED_INTERFACE) * KDEV_SHARED_INTERFACE_COUNT));
	PUCHAR extraMem;

	success = u_Init_Handle(&handle, DriverID, SharedDevice, Init_BackendCB, Cleanup_UsbK, Cleanup_DevK);
	ErrorNoSetAction(!success, return FALSE, "->u_Init_Handle");

	// if SharedDevice is non-null this handle is an associated handle
	if (!SharedDevice)
	{
		if (!IsHandleValid(DeviceHandle))
		{
			DeviceHandle = CreateDeviceFile(DevInfo->DevicePath);
			ErrorNoSet(!IsHandleValid(DeviceHandle), Error, "CreateDeviceFile failed.");
			DriverID = (KUSB_DRVID)DevInfo->DriverID;
			handle->Device->DevicePath = Str_Dupe(DevInfo->DevicePath);
		}

		handle->Device->MasterDeviceHandle = DeviceHandle;

		extraMem = Mem_Alloc(extraMemAlloc);
		ErrorMemoryAction(!IsHandleValid(extraMem), return FALSE);

		handle->Device->UsbStack = (KUSB_INTERFACE_STACK*)extraMem;
		extraMem += sizeof(KUSB_INTERFACE_STACK);

		handle->Device->DriverAPI = (KUSB_DRIVER_API*)extraMem;
		extraMem += sizeof(KUSB_DRIVER_API);

		handle->Device->SharedInterfaces = (KDEV_SHARED_INTERFACE*)extraMem;
		extraMem += ((sizeof(KDEV_SHARED_INTERFACE) * KDEV_SHARED_INTERFACE_COUNT));

		handle->Device->UsbStack->UsePipeCache = UsePipeCache;

		success = Init_ConfigCB(handle);
		ErrorNoSet(!success, Error, "->Init_ConfigCB");

		handle->Selected_SharedInterface_Index = 0;
		success = u_Init_Config(handle);
		ErrorNoSet(!success, Error, "->u_Init_Config");

		// load a driver API
		LibK_LoadDriverAPI(handle->Device->DriverAPI, DriverID);

		if (handle->Device->UsbStack->UsePipeCache)
			UsbStack_RefreshPipeCache(handle);
	}

	*Handle = (KUSB_HANDLE)handle;
	if (!SharedDevice)
	{
		PoolHandle_Live_DevK(handle->Device);
		PoolHandle_Live_UsbK(handle);
	}
	return TRUE;

Error:
	if (IsHandleValid(handle)) PoolHandle_Dec_UsbK(handle);
	*Handle = NULL;
	return FALSE;
}

BOOL UsbStack_CloneHandle (
    __in KUSB_HANDLE Handle,
    __out KUSB_HANDLE* ClonedHandle)
{
	PKUSB_HANDLE_INTERNAL handle;
	PKUSB_HANDLE_INTERNAL clonedHandle = NULL;
	BOOL success;

	Pub_To_Priv_UsbK(Handle, handle, return FALSE);
	ErrorSetAction(!PoolHandle_Inc_UsbK(handle), ERROR_RESOURCE_NOT_AVAILABLE, return FALSE, "->PoolHandle_Inc_UsbK");

	success = UsbStack_Init(
	              (KUSB_HANDLE*)&clonedHandle,
	              handle->Device->DriverAPI->Info.DriverID,
	              handle->Device->UsbStack->UsePipeCache,
	              NULL,
	              NULL,
	              handle->Device,
	              NULL,
	              NULL,
	              handle->Base.Evt.Cleanup,
	              handle->Device->Base.Evt.Cleanup);

	ErrorNoSet(!success, Error, "->UsbStack_Init");

	clonedHandle->Selected_SharedInterface_Index = handle->Selected_SharedInterface_Index;

	*ClonedHandle = (KUSB_HANDLE)clonedHandle;
	PoolHandle_Dec_UsbK(handle);
	PoolHandle_Live_UsbK(clonedHandle);
	return TRUE;

Error:
	if (IsHandleValid(clonedHandle)) PoolHandle_Dec_UsbK(clonedHandle);
	PoolHandle_Dec_UsbK(handle);
	*ClonedHandle = NULL;
	return FALSE;
}

BOOL UsbStack_GetAssociatedInterface (
    __in KUSB_HANDLE Handle,
    __in UCHAR AssociatedInterfaceIndex,
    __out KUSB_HANDLE* AssociatedHandle)
{
	PKUSB_HANDLE_INTERNAL handle;
	PKUSB_HANDLE_INTERNAL associatedHandle = NULL;
	UCHAR nextIndex;
	PKUSB_INTERFACE_EL interfaceEL;
	BOOL success;

	Pub_To_Priv_UsbK(Handle, handle, return FALSE);
	ErrorSetAction(!PoolHandle_Inc_UsbK(handle), ERROR_RESOURCE_NOT_AVAILABLE, return FALSE, "->PoolHandle_Inc_UsbK");

	nextIndex = ((UCHAR)handle->Selected_SharedInterface_Index) + 1 + AssociatedInterfaceIndex;

	FindInterfaceEL(handle->Device->UsbStack, interfaceEL, TRUE, nextIndex);
	ErrorSet(!interfaceEL, Error, ERROR_NO_MORE_ITEMS, "Interface index %u not found.", nextIndex);

	success = UsbStack_CloneHandle((KUSB_HANDLE)handle, (KUSB_HANDLE*)&associatedHandle);
	ErrorNoSet(!success, Error, "->UsbStack_CloneHandle");

	associatedHandle->Selected_SharedInterface_Index = nextIndex;
	*AssociatedHandle = (KUSB_HANDLE)associatedHandle;
	PoolHandle_Dec_UsbK(handle);

	PoolHandle_Live_UsbK(associatedHandle);
	return TRUE;

Error:
	if (IsHandleValid(associatedHandle)) PoolHandle_Dec_UsbK(associatedHandle);
	PoolHandle_Dec_UsbK(handle);
	*AssociatedHandle = NULL;
	return FALSE;
}

VOID UsbStack_Clear(PKUSB_INTERFACE_STACK UsbStack)
{
	PKUSB_INTERFACE_EL nextInterfaceEL, t0;
	PKUSB_ALT_INTERFACE_EL nextAltInterfaceEL, t1;
	PKUSB_PIPE_EL nextPipeEL, t2;

	if (!IsHandleValid(UsbStack)) return;

	// free the interface list
	DL_FOREACH_SAFE(UsbStack->InterfaceList, nextInterfaceEL, t0)
	{
		// free the stack collection lists
		DL_FOREACH_SAFE(nextInterfaceEL->AltInterfaceList, nextAltInterfaceEL, t1)
		{
			DL_FOREACH_SAFE(nextAltInterfaceEL->PipeList, nextPipeEL, t2)
			{
				DL_DELETE(nextAltInterfaceEL->PipeList, nextPipeEL);
				Mem_Free(&nextPipeEL);
			}

			DL_DELETE(nextInterfaceEL->AltInterfaceList, nextAltInterfaceEL);
			Mem_Free(&nextAltInterfaceEL);
		}

		DL_DELETE(UsbStack->InterfaceList, nextInterfaceEL);
		Mem_Free(&nextInterfaceEL);
	}
}

BOOL UsbStack_Rebuild(
    __in PKUSB_HANDLE_INTERNAL Handle,
    __in PKUSB_STACK_CB Init_ConfigCB)
{
	BOOL success;

	if (DecLock(ALLK_GETREF_HANDLE(Handle->Device)) != 1)
	{
		IncLock(ALLK_GETREF_HANDLE(Handle->Device));
		return LusbwError(ERROR_RESOURCE_NOT_AVAILABLE);
	}

	if (DecLock(ALLK_GETREF_HANDLE(Handle->Device)) != 0)
	{
		IncLock(ALLK_GETREF_HANDLE(Handle->Device));
		IncLock(ALLK_GETREF_HANDLE(Handle->Device));
		return LusbwError(ERROR_RESOURCE_NOT_AVAILABLE);
	}

	UsbStack_Clear(Handle->Device->UsbStack);
	Mem_Free(&Handle->Device->ConfigDescriptor);
	Handle->Selected_SharedInterface_Index = 0;
	memset(Handle->Device->SharedInterfaces, 0, sizeof(Handle->Device->SharedInterfaces));
	memset(&Handle->Move, 0, sizeof(Handle->Move));

	success = Init_ConfigCB(Handle);
	ErrorNoSet(!success, Error, "->Init_ConfigCB");

	success = u_Init_Config(Handle);
	ErrorNoSet(!success, Error, "->u_Init_Config");

	IncLock(ALLK_GETREF_HANDLE(Handle->Device));
	IncLock(ALLK_GETREF_HANDLE(Handle->Device));
	return TRUE;

Error:
	IncLock(ALLK_GETREF_HANDLE(Handle->Device));
	IncLock(ALLK_GETREF_HANDLE(Handle->Device));
	return FALSE;
}

BOOL UsbStack_QueryInterfaceSettings (
    __in KUSB_HANDLE Handle,
    __in UCHAR AltSettingIndex,
    __out PUSB_INTERFACE_DESCRIPTOR UsbAltInterfaceDescriptor)
{
	PKUSB_HANDLE_INTERNAL handle;
	PKUSB_INTERFACE_EL intfEL;
	PKUSB_ALT_INTERFACE_EL altfEL;

	ErrorParamAction(!IsHandleValid(UsbAltInterfaceDescriptor), "UsbAltInterfaceDescriptor", return FALSE);
	ErrorParamAction(AltSettingIndex > 0x7F, "AltSettingIndex", return FALSE);

	Pub_To_Priv_UsbK(Handle, handle, return FALSE);
	ErrorSetAction(!PoolHandle_Inc_UsbK(handle), ERROR_RESOURCE_NOT_AVAILABLE, return FALSE, "->PoolHandle_Inc_UsbK");

	FindInterfaceEL(handle->Device->UsbStack, intfEL, TRUE, handle->Selected_SharedInterface_Index);
	ErrorSet(!intfEL, Error, ERROR_NO_MORE_ITEMS, "Failed locating interface number %u.", handle->Selected_SharedInterface_Index);

	FindAltInterfaceEL(intfEL, altfEL, TRUE, AltSettingIndex);
	ErrorSet(!altfEL, Error, ERROR_NO_MORE_ITEMS, "AltSettingIndex %u does not exists.", AltSettingIndex);

	memcpy(UsbAltInterfaceDescriptor, altfEL->Descriptor, sizeof(*UsbAltInterfaceDescriptor));
	PoolHandle_Dec_UsbK(handle);
	return TRUE;

Error:
	PoolHandle_Dec_UsbK(handle);
	return FALSE;
}

BOOL UsbStack_SelectInterface (
    __in KUSB_HANDLE Handle,
    __in UCHAR IndexOrNumber,
    __in BOOL IsIndex)
{
	PKUSB_HANDLE_INTERNAL handle;
	PKUSB_INTERFACE_EL intfEL;

	ErrorParamAction(IndexOrNumber > 0x7F, "IndexOrNumber", return FALSE);

	Pub_To_Priv_UsbK(Handle, handle, return FALSE);
	ErrorSetAction(!PoolHandle_Inc_UsbK(handle), ERROR_RESOURCE_NOT_AVAILABLE, return FALSE, "->PoolHandle_Inc_UsbK");

	FindInterfaceEL(handle->Device->UsbStack, intfEL, IsIndex, IndexOrNumber);
	ErrorSet(!intfEL, Error, ERROR_NO_MORE_ITEMS, "Failed locating interface %s %u.", IsIndex ? "index" : "number", IndexOrNumber);

	InterlockedExchange(&handle->Selected_SharedInterface_Index, intfEL->Index);

	PoolHandle_Dec_UsbK(handle);
	return TRUE;

Error:
	PoolHandle_Dec_UsbK(handle);
	return FALSE;
}

BOOL UsbStack_QuerySelectedEndpoint(
    __in KUSB_HANDLE Handle,
    __in UCHAR EndpointAddressOrIndex,
    __in BOOL IsIndex,
    __out PUSB_ENDPOINT_DESCRIPTOR EndpointDescriptor)
{
	PKUSB_HANDLE_INTERNAL handle;
	PKUSB_INTERFACE_EL intfEL;
	PKUSB_ALT_INTERFACE_EL altfEL;
	PKUSB_PIPE_EL pipeEL;
	UCHAR altSetting;

	ErrorParamAction(!IsHandleValid(EndpointDescriptor), "EndpointDescriptor", return FALSE);

	Pub_To_Priv_UsbK(Handle, handle, return FALSE);
	ErrorSetAction(!PoolHandle_Inc_UsbK(handle), ERROR_RESOURCE_NOT_AVAILABLE, return FALSE, "->PoolHandle_Inc_UsbK");

	FindInterfaceEL(handle->Device->UsbStack, intfEL, TRUE, handle->Selected_SharedInterface_Index);
	ErrorSet(!intfEL, Error, ERROR_NO_MORE_ITEMS, "Failed locating interface number %u.", handle->Selected_SharedInterface_Index);

	altSetting = (UCHAR)handle->Device->SharedInterfaces[handle->Selected_SharedInterface_Index].CurrentAltSetting;

	FindAltInterfaceEL(intfEL, altfEL, FALSE, altSetting);
	ErrorSet(!altfEL, Error, ERROR_NO_MORE_ITEMS, "AltSettingNumber %u does not exists.", altSetting);

	FindPipeEL(altfEL, pipeEL, IsIndex, EndpointAddressOrIndex);
	ErrorSet(!pipeEL, Error, ERROR_NO_MORE_ITEMS, "Endpoint %s %u does not exists.", IsIndex ? "index" : "address", EndpointAddressOrIndex);

	memcpy(EndpointDescriptor, pipeEL->Descriptor, sizeof(*EndpointDescriptor));

	PoolHandle_Dec_UsbK(handle);
	return TRUE;

Error:
	PoolHandle_Dec_UsbK(handle);
	return FALSE;
}

BOOL UsbStack_QuerySelectedPipe(
	__in KUSB_HANDLE Handle,
	__in UCHAR EndpointAddressOrIndex,
	__in BOOL IsIndex,
	__out PWINUSB_PIPE_INFORMATION_EX PipeInformationEx)
{
	PKUSB_HANDLE_INTERNAL handle;
	PKUSB_INTERFACE_EL intfEL;
	PKUSB_ALT_INTERFACE_EL altfEL;
	PKUSB_PIPE_EL pipeEL;
	UCHAR altSetting;

	ErrorParamAction(!IsHandleValid(PipeInformationEx), "PipeInformationEx", return FALSE);

	Pub_To_Priv_UsbK(Handle, handle, return FALSE);
	ErrorSetAction(!PoolHandle_Inc_UsbK(handle), ERROR_RESOURCE_NOT_AVAILABLE, return FALSE, "->PoolHandle_Inc_UsbK");

	FindInterfaceEL(handle->Device->UsbStack, intfEL, TRUE, handle->Selected_SharedInterface_Index);
	ErrorSet(!intfEL, Error, ERROR_NO_MORE_ITEMS, "Failed locating interface number %u.", handle->Selected_SharedInterface_Index);

	altSetting = (UCHAR)handle->Device->SharedInterfaces[handle->Selected_SharedInterface_Index].CurrentAltSetting;

	FindAltInterfaceEL(intfEL, altfEL, FALSE, altSetting);
	ErrorSet(!altfEL, Error, ERROR_NO_MORE_ITEMS, "AltSettingNumber %u does not exists.", altSetting);

	FindPipeEL(altfEL, pipeEL, IsIndex, EndpointAddressOrIndex);
	ErrorSet(!pipeEL, Error, ERROR_NO_MORE_ITEMS, "Endpoint %s %u does not exists.", IsIndex ? "index" : "address", EndpointAddressOrIndex);

	if (!UsbStack_QueryPipeEx(Handle, altSetting, pipeEL->Index, PipeInformationEx))
	{
		ErrorNoSetAction(TRUE,goto Error, "Endpoint %s %u does not exists.", IsIndex ? "index" : "address", EndpointAddressOrIndex);
	}
	
	PoolHandle_Dec_UsbK(handle);
	return TRUE;

Error:
	PoolHandle_Dec_UsbK(handle);
	return FALSE;
}

BOOL UsbStack_QueryPipe(
    __in KUSB_HANDLE Handle,
    __in UCHAR AltSettingNumber,
    __in UCHAR PipeIndex,
    __out PWINUSB_PIPE_INFORMATION PipeInformation)
{
	PKUSB_HANDLE_INTERNAL handle;
	PKUSB_INTERFACE_EL intfEL;
	PKUSB_ALT_INTERFACE_EL altfEL;
	PKUSB_PIPE_EL pipeEL;

	ErrorParamAction(AltSettingNumber > 0x7F, "AltSettingNumber", return FALSE);
	ErrorParamAction(PipeIndex > 0x1F, "PipeIndex", return FALSE);
	ErrorParamAction(!IsHandleValid(PipeInformation), "PipeInformation", return FALSE);

	Pub_To_Priv_UsbK(Handle, handle, return FALSE);
	ErrorSetAction(!PoolHandle_Inc_UsbK(handle), ERROR_RESOURCE_NOT_AVAILABLE, return FALSE, "->PoolHandle_Inc_UsbK");

	FindInterfaceEL(handle->Device->UsbStack, intfEL, TRUE, handle->Selected_SharedInterface_Index);
	ErrorSet(!intfEL, Error, ERROR_NO_MORE_ITEMS, "Failed locating interface number %u.", handle->Selected_SharedInterface_Index);

	FindAltInterfaceEL(intfEL, altfEL, FALSE, AltSettingNumber);
	ErrorSet(!altfEL, Error, ERROR_NO_MORE_ITEMS, "AltSettingNumber %u does not exists.", AltSettingNumber);

	FindPipeEL(altfEL, pipeEL, TRUE, PipeIndex);
	ErrorSet(!pipeEL, Error, ERROR_NO_MORE_ITEMS, "PipeIndex %u does not exists.", PipeIndex);

	PipeInformation->PipeType			= pipeEL->Descriptor->bmAttributes & 0x03;
	PipeInformation->MaximumPacketSize	= (pipeEL->Descriptor->wMaxPacketSize & 0x7FF) * (((pipeEL->Descriptor->wMaxPacketSize >> 11) & 0x3) + 1);
	PipeInformation->PipeId				= pipeEL->Descriptor->bEndpointAddress;
	PipeInformation->Interval			= pipeEL->Descriptor->bInterval;

	PoolHandle_Dec_UsbK(handle);
	return TRUE;

Error:
	PoolHandle_Dec_UsbK(handle);
	return FALSE;
}

BOOL UsbStack_QueryPipeEx(
	__in KUSB_HANDLE Handle,
	__in UCHAR AltSettingNumber,
	__in UCHAR PipeIndex,
	__out PWINUSB_PIPE_INFORMATION_EX PipeInformationEx)
{
	PKUSB_HANDLE_INTERNAL handle;
	PKUSB_INTERFACE_EL intfEL;
	PKUSB_ALT_INTERFACE_EL altfEL;
	PKUSB_PIPE_EL pipeEL;
	
	ErrorParamAction(AltSettingNumber > 0x7F, "AltSettingNumber", return FALSE);
	ErrorParamAction(PipeIndex > 0x1F, "PipeIndex", return FALSE);
	ErrorParamAction(!IsHandleValid(PipeInformationEx), "PipeInformation", return FALSE);

	Pub_To_Priv_UsbK(Handle, handle, return FALSE);
	ErrorSetAction(!PoolHandle_Inc_UsbK(handle), ERROR_RESOURCE_NOT_AVAILABLE, return FALSE, "->PoolHandle_Inc_UsbK");

	FindInterfaceEL(handle->Device->UsbStack, intfEL, TRUE, handle->Selected_SharedInterface_Index);
	ErrorSet(!intfEL, Error, ERROR_NO_MORE_ITEMS, "Failed locating interface number %u.", handle->Selected_SharedInterface_Index);

	FindAltInterfaceEL(intfEL, altfEL, FALSE, AltSettingNumber);
	ErrorSet(!altfEL, Error, ERROR_NO_MORE_ITEMS, "AltSettingNumber %u does not exists.", AltSettingNumber);

	FindPipeEL(altfEL, pipeEL, TRUE, PipeIndex);
	ErrorSet(!pipeEL, Error, ERROR_NO_MORE_ITEMS, "PipeIndex %u does not exists.", PipeIndex);
	
	PipeInformationEx->PipeType = pipeEL->Descriptor->bmAttributes & 0x03;
	PipeInformationEx->MaximumPacketSize = (pipeEL->Descriptor->wMaxPacketSize & 0x7FF) * (((pipeEL->Descriptor->wMaxPacketSize >> 11) & 0x3) + 1);
	PipeInformationEx->PipeId = pipeEL->Descriptor->bEndpointAddress;
	PipeInformationEx->Interval = pipeEL->Descriptor->bInterval;
	if (pipeEL->SuperSpeedCompanionDescriptor)
	{
		PipeInformationEx->MaximumBytesPerInterval = pipeEL->SuperSpeedCompanionDescriptor->wBytesPerInterval;
		if (PipeInformationEx->MaximumBytesPerInterval == 0)
			PipeInformationEx->MaximumBytesPerInterval = PipeInformationEx->MaximumPacketSize;
	}
	else
	{
		PipeInformationEx->MaximumBytesPerInterval = PipeInformationEx->MaximumPacketSize;
	}
	PoolHandle_Dec_UsbK(handle);
	return TRUE;

Error:
	PoolHandle_Dec_UsbK(handle);
	return FALSE;
}

BOOL UsbStack_GetSuperSpeedPipeCompanionDescriptor(
	__in KUSB_HANDLE Handle,
	__in UCHAR AltSettingNumber,
	__in UCHAR PipeIndex,
	__out PUSB_SUPERSPEED_ENDPOINT_COMPANION_DESCRIPTOR PipeCompanionDescriptor)
{
	PKUSB_HANDLE_INTERNAL handle;
	PKUSB_INTERFACE_EL intfEL;
	PKUSB_ALT_INTERFACE_EL altfEL;
	PKUSB_PIPE_EL pipeEL;
	
	ErrorParamAction(AltSettingNumber > 0x7F, "AltSettingNumber", return FALSE);
	ErrorParamAction(PipeIndex > 0x1F, "PipeIndex", return FALSE);
	ErrorParamAction(!IsHandleValid(PipeCompanionDescriptor), "PipeCompanionDescriptor", return FALSE);

	Pub_To_Priv_UsbK(Handle, handle, return FALSE);
	ErrorSetAction(!PoolHandle_Inc_UsbK(handle), ERROR_RESOURCE_NOT_AVAILABLE, return FALSE, "->PoolHandle_Inc_UsbK");

	FindInterfaceEL(handle->Device->UsbStack, intfEL, TRUE, handle->Selected_SharedInterface_Index);
	ErrorSet(!intfEL, Error, ERROR_NO_MORE_ITEMS, "Failed locating interface number %u.", handle->Selected_SharedInterface_Index);

	FindAltInterfaceEL(intfEL, altfEL, FALSE, AltSettingNumber);
	ErrorSet(!altfEL, Error, ERROR_NO_MORE_ITEMS, "AltSettingNumber %u does not exists.", AltSettingNumber);

	FindPipeEL(altfEL, pipeEL, TRUE, PipeIndex);
	ErrorSet(!pipeEL, Error, ERROR_NO_MORE_ITEMS, "PipeIndex %u does not exists.", PipeIndex);

	ErrorSet(!pipeEL->SuperSpeedCompanionDescriptor, Error, ERROR_NOT_FOUND, "PipeIndex %u does not have a super speed endpoint companion descriptor.", PipeIndex);

	memcpy(PipeCompanionDescriptor, pipeEL->SuperSpeedCompanionDescriptor, sizeof(*PipeCompanionDescriptor));

	PoolHandle_Dec_UsbK(handle);
	return TRUE;

Error:
	PoolHandle_Dec_UsbK(handle);
	return FALSE;
}

BOOL UsbStack_RefreshPipeCache(PKUSB_HANDLE_INTERNAL Handle)
{
	PKUSB_INTERFACE_EL		intfEL;
	PKUSB_ALT_INTERFACE_EL	altfEL;
	PKUSB_PIPE_EL			pipeEL;
	PKDEV_SHARED_INTERFACE	sharedInterface;
	KUSB_PIPE_CACHE*		pipeCacheItem;

	DL_FOREACH(Handle->Device->UsbStack->InterfaceList, intfEL)
	{
		sharedInterface = &Get_SharedInterface(Handle, intfEL->Index);
		DL_FOREACH(intfEL->AltInterfaceList, altfEL)
		{
			DL_FOREACH(altfEL->PipeList, pipeEL)
			{
				pipeCacheItem = &Handle->Device->UsbStack->PipeCache[PIPEID_TO_IDX(pipeEL->ID)];
				if (altfEL->ID == sharedInterface->CurrentAltSetting)
				{
					InterlockedExchangePointer(&pipeCacheItem->InterfaceHandle, sharedInterface->InterfaceHandle);
				}
				else if (pipeCacheItem->InterfaceHandle == NULL)
				{
					if (sharedInterface->InterfaceHandle)
						InterlockedExchangePointer(&pipeCacheItem->InterfaceHandle, sharedInterface->InterfaceHandle);
					else
						InterlockedExchangePointer(&pipeCacheItem->InterfaceHandle, Handle->Device->MasterInterfaceHandle);
				}
			}
		}
	}

	return TRUE;
}