summaryrefslogtreecommitdiff
path: root/usb/kmdf_fx2/exe/testapp.c
blob: 43b6c7a218a93661c365bc1241925652b092672f (plain)
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
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
/*++

Copyright (c) Microsoft Corporation.  All rights reserved.

    THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
    KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
    IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR
    PURPOSE.

Module Name:

    TESTAPP.C

Abstract:

    Console test app for osrusbfx2 driver.

Environment:

    user mode only

--*/


#include <DriverSpecs.h>
_Analysis_mode_(_Analysis_code_type_user_code_)

#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

#include "devioctl.h"
#include "strsafe.h"

#pragma warning(disable:4200)  //
#pragma warning(disable:4201)  // nameless struct/union
#pragma warning(disable:4214)  // bit field types other than int

#include <cfgmgr32.h>
#include <basetyps.h>
#include "usbdi.h"
#include "public.h"

#pragma warning(default:4200)
#pragma warning(default:4201)
#pragma warning(default:4214)

#define WHILE(a) \
while(__pragma(warning(disable:4127)) a __pragma(warning(disable:4127)))

#define MAX_DEVPATH_LENGTH 256
#define NUM_ASYNCH_IO   100
#define BUFFER_SIZE     1024
#define READER_TYPE   1
#define WRITER_TYPE   2

BOOL G_fDumpUsbConfig = FALSE;    // flags set in response to console command line switches
BOOL G_fDumpReadData = FALSE;
BOOL G_fRead = FALSE;
BOOL G_fWrite = FALSE;
BOOL G_fPlayWithDevice = FALSE;
BOOL G_fPerformAsyncIo = FALSE;
ULONG G_IterationCount = 1; //count of iterations of the test we are to perform
ULONG G_WriteLen = 512;         // #bytes to write
ULONG G_ReadLen = 512;          // #bytes to read

BOOL
DumpUsbConfig( // defined in dump.c
    );

typedef enum _INPUT_FUNCTION {
    LIGHT_ONE_BAR = 1,
    CLEAR_ONE_BAR,
    LIGHT_ALL_BARS,
    CLEAR_ALL_BARS,
    GET_BAR_GRAPH_LIGHT_STATE,
    GET_SWITCH_STATE,
    GET_SWITCH_STATE_AS_INTERRUPT_MESSAGE,
    GET_7_SEGEMENT_STATE,
    SET_7_SEGEMENT_STATE,
    RESET_DEVICE,
    REENUMERATE_DEVICE,
} INPUT_FUNCTION;

_Success_(return)
BOOL
GetDevicePath(
    _In_  LPGUID InterfaceGuid,
    _Out_writes_z_(BufLen) PWCHAR DevicePath,
    _In_ size_t BufLen
    )
{
    CONFIGRET cr = CR_SUCCESS;
    PWSTR deviceInterfaceList = NULL;
    ULONG deviceInterfaceListLength = 0;
    PWSTR nextInterface;
    HRESULT hr = E_FAIL;
    BOOL bRet = TRUE;

    cr = CM_Get_Device_Interface_List_Size(
        &deviceInterfaceListLength,
        InterfaceGuid,
        NULL,
        CM_GET_DEVICE_INTERFACE_LIST_PRESENT);
    if (cr != CR_SUCCESS) {
        printf("Error 0x%x retrieving device interface list size.\n", cr);
        goto clean0;
    }

    if (deviceInterfaceListLength <= 1) {
        bRet = FALSE;
        printf("Error: No active device interfaces found.\n"
            " Is the sample driver loaded?");
        goto clean0;
    }

    deviceInterfaceList = (PWSTR)malloc(deviceInterfaceListLength * sizeof(WCHAR));
    if (deviceInterfaceList == NULL) {
        bRet = FALSE;
        printf("Error allocating memory for device interface list.\n");
        goto clean0;
    }
    ZeroMemory(deviceInterfaceList, deviceInterfaceListLength * sizeof(WCHAR));

    cr = CM_Get_Device_Interface_List(
        InterfaceGuid,
        NULL,
        deviceInterfaceList,
        deviceInterfaceListLength,
        CM_GET_DEVICE_INTERFACE_LIST_PRESENT);
    if (cr != CR_SUCCESS) {
        printf("Error 0x%x retrieving device interface list.\n", cr);
        goto clean0;
    }

    nextInterface = deviceInterfaceList + wcslen(deviceInterfaceList) + 1;
    if (*nextInterface != UNICODE_NULL) {
        printf("Warning: More than one device interface instance found. \n"
            "Selecting first matching device.\n\n");
    }

    hr = StringCchCopy(DevicePath, BufLen, deviceInterfaceList);
    if (FAILED(hr)) {
        bRet = FALSE;
        printf("Error: StringCchCopy failed with HRESULT 0x%x", hr);
        goto clean0;
    }

clean0:
    if (deviceInterfaceList != NULL) {
        free(deviceInterfaceList);
    }
    if (CR_SUCCESS != cr) {
        bRet = FALSE;
    }

    return bRet;
}


_Check_return_
_Ret_notnull_
_Success_(return != INVALID_HANDLE_VALUE)
HANDLE
OpenDevice(
    _In_ BOOL Synchronous
    )

/*++
Routine Description:

    Called by main() to open an instance of our device after obtaining its name

Arguments:

    Synchronous - TRUE, if Device is to be opened for synchronous access.
                  FALSE, otherwise.

Return Value:

    Device handle on success else INVALID_HANDLE_VALUE

--*/

{
    HANDLE hDev;
    WCHAR completeDeviceName[MAX_DEVPATH_LENGTH];

    if ( !GetDevicePath(
            (LPGUID) &GUID_DEVINTERFACE_OSRUSBFX2,
            completeDeviceName,
            sizeof(completeDeviceName)/sizeof(completeDeviceName[0])) )
    {
        return  INVALID_HANDLE_VALUE;
    }

    printf("DeviceName = (%S)\n", completeDeviceName);

    if(Synchronous) {
        hDev = CreateFile(completeDeviceName,
                GENERIC_WRITE | GENERIC_READ,
                FILE_SHARE_WRITE | FILE_SHARE_READ,
                NULL, // default security
                OPEN_EXISTING,
                FILE_ATTRIBUTE_NORMAL,
                NULL);
    } else {

        hDev = CreateFile(completeDeviceName,
                GENERIC_WRITE | GENERIC_READ,
                FILE_SHARE_WRITE | FILE_SHARE_READ,
                NULL, // default security
                OPEN_EXISTING,
                FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED,
                NULL);
    }

    if (hDev == INVALID_HANDLE_VALUE) {
        printf("Failed to open the device, error - %d", GetLastError());
    } else {
        printf("Opened the device successfully.\n");
    }

    return hDev;
}



VOID
Usage()

/*++
Routine Description:

    Called by main() to dump usage info to the console when
    the app is called with no parms or with an invalid parm

Arguments:

    None

Return Value:

    None

--*/

{
    printf("Usage for osrusbfx2 testapp:\n");
    printf("-r [n] where n is number of bytes to read\n");
    printf("-w [n] where n is number of bytes to write\n");
    printf("-c [n] where n is number of iterations (default = 1)\n");
    printf("-v verbose -- dumps read data\n");
    printf("-p to control bar LEDs, seven segment, and dip switch\n");
    printf("-a to perform asynchronous I/O\n");
    printf("-u to dump USB configuration and pipe info \n");

    return;
}


void
Parse(
    _In_ int argc,
    _In_reads_(argc) LPSTR  *argv
    )

/*++
Routine Description:

    Called by main() to parse command line parms

Arguments:

    argc and argv that was passed to main()

Return Value:

    Sets global flags as per user function request

--*/

{
    int i;

    if ( argc < 2 ) // give usage if invoked with no parms
        Usage();

    for (i=0; i<argc; i++) {
        if (argv[i][0] == '-' ||
            argv[i][0] == '/') {
            switch(argv[i][1]) {
            case 'r':
            case 'R':
                if (i+1 >= argc) {
                    Usage();
                    exit(1);
                }
                else {
#pragma warning(suppress: 6385)
                    G_ReadLen = atoi(&argv[i+1][0]);
                                    G_fRead = TRUE;
                }
                i++;
                break;
            case 'w':
            case 'W':
                if (i+1 >= argc) {
                    Usage();
                    exit(1);
                }
                else {
                    G_WriteLen = atoi(&argv[i+1][0]);
                                    G_fWrite = TRUE;
                }
                i++;
                break;
            case 'c':
            case 'C':
                if (i+1 >= argc) {
                    Usage();
                    exit(1);
                }
                else {
                    G_IterationCount = atoi(&argv[i+1][0]);
                }
                i++;
                break;
            case 'u':
            case 'U':
                G_fDumpUsbConfig = TRUE;
                break;
            case 'p':
            case 'P':
                G_fPlayWithDevice = TRUE;
                break;
            case 'a':
            case 'A':
                G_fPerformAsyncIo = TRUE;
                break;
            case 'v':
            case 'V':
                G_fDumpReadData = TRUE;
                break;
            default:
                Usage();
            }
        }
    }
}

BOOL
Compare_Buffs(
    _In_reads_bytes_(buff1length) char *buff1,
    _In_ ULONG buff1length,
    _In_reads_bytes_(buff2length) char *buff2,
    _In_ ULONG buff2length
    )
/*++
Routine Description:

    Called to verify read and write buffers match for loopback test

Arguments:

    buffers to compare and length

Return Value:

    TRUE if buffers match, else FALSE

--*/
{
    int ok = 1;

    if (buff1length != buff2length || memcmp(buff1, buff2, buff1length )) {
        // Edi, and Esi point to the mismatching char and ecx indicates the
        // remaining length.
        ok = 0;
    }

    return ok;
}

#define NPERLN 8

VOID
Dump(
   UCHAR *b,
   int len
)

/*++
Routine Description:

    Called to do formatted ascii dump to console of the io buffer

Arguments:

    buffer and length

Return Value:

    none

--*/

{
    ULONG i;
    ULONG longLen = (ULONG)len / sizeof( ULONG );
    PULONG pBuf = (PULONG) b;

    // dump an ordinal ULONG for each sizeof(ULONG)'th byte
    printf("\n****** BEGIN DUMP LEN decimal %d, 0x%x\n", len,len);
    for (i=0; i<longLen; i++) {
        printf("%04X ", *pBuf++);
        if (i % NPERLN == (NPERLN - 1)) {
            printf("\n");
        }
    }
    if (i % NPERLN != 0) {
        printf("\n");
    }
    printf("\n****** END DUMP LEN decimal %d, 0x%x\n", len,len);
}


BOOL
PlayWithDevice()
{
    HANDLE          deviceHandle;
    DWORD           code;
    ULONG           index;
    INPUT_FUNCTION  function;
    BAR_GRAPH_STATE barGraphState;
    ULONG           bar;
    SWITCH_STATE    switchState;
    UCHAR           sevenSegment = 0;
    UCHAR           i;
    BOOL            result = FALSE;

    deviceHandle = OpenDevice(FALSE);

    if (deviceHandle == INVALID_HANDLE_VALUE) {

        printf("Unable to find any OSR FX2 devices!\n");

        return FALSE;

    }

    //
    // Infinitely print out the list of choices, ask for input, process
    // the request
    //
    WHILE(TRUE)  {

        printf ("\nUSBFX TEST -- Functions:\n\n");
        printf ("\t1.  Light Bar\n");
        printf ("\t2.  Clear Bar\n");
        printf ("\t3.  Light entire Bar graph\n");
        printf ("\t4.  Clear entire Bar graph\n");
        printf ("\t5.  Get bar graph state\n");
        printf ("\t6.  Get Switch state\n");
        printf ("\t7.  Get Switch Interrupt Message\n");
        printf ("\t8.  Get 7 segment state\n");
        printf ("\t9.  Set 7 segment state\n");
        printf ("\t10. Reset the device\n");
        printf ("\t11. Reenumerate the device\n");
        printf ("\n\t0. Exit\n");
        printf ("\n\tSelection: ");

        if (scanf_s ("%d", &function) <= 0) {

            printf("Error reading input!\n");
            goto Error;

        }

        switch(function)  {

        case LIGHT_ONE_BAR:

        printf("Which Bar (input number 1 thru 8)?\n");
        if (scanf_s ("%d", &bar) <= 0) {

            printf("Error reading input!\n");
            goto Error;

        }

        if(bar == 0 || bar > 8){
            printf("Invalid bar number!\n");
            goto Error;
        }

        bar--; // normalize to 0 to 7

        barGraphState.BarsAsUChar = 1 << (UCHAR)bar;

        if (!DeviceIoControl(deviceHandle,
                             IOCTL_OSRUSBFX2_SET_BAR_GRAPH_DISPLAY,
                             &barGraphState,           // Ptr to InBuffer
                             sizeof(BAR_GRAPH_STATE),  // Length of InBuffer
                             NULL,         // Ptr to OutBuffer
                             0,            // Length of OutBuffer
                             &index,       // BytesReturned
                             0)) {         // Ptr to Overlapped structure

            code = GetLastError();

            printf("DeviceIoControl failed with error 0x%x\n", code);

            goto Error;
        }

        break;

        case CLEAR_ONE_BAR:


        printf("Which Bar (input number 1 thru 8)?\n");
        if (scanf_s ("%d", &bar) <= 0) {

            printf("Error reading input!\n");
            goto Error;

        }

        if(bar == 0 || bar > 8){
            printf("Invalid bar number!\n");
            goto Error;
        }

        bar--;

        //
        // Read the current state
        //
        if (!DeviceIoControl(deviceHandle,
                             IOCTL_OSRUSBFX2_GET_BAR_GRAPH_DISPLAY,
                             NULL,             // Ptr to InBuffer
                             0,            // Length of InBuffer
                             &barGraphState,           // Ptr to OutBuffer
                             sizeof(BAR_GRAPH_STATE),  // Length of OutBuffer
                             &index,        // BytesReturned
                             0)) {         // Ptr to Overlapped structure

            code = GetLastError();

            printf("DeviceIoControl failed with error 0x%x\n", code);

            goto Error;
        }

        if (barGraphState.BarsAsUChar & (1 << bar)) {

            printf("Bar is set...Clearing it\n");
            barGraphState.BarsAsUChar &= ~(1 << bar);

            if (!DeviceIoControl(deviceHandle,
                                 IOCTL_OSRUSBFX2_SET_BAR_GRAPH_DISPLAY,
                                 &barGraphState,         // Ptr to InBuffer
                                 sizeof(BAR_GRAPH_STATE), // Length of InBuffer
                                 NULL,             // Ptr to OutBuffer
                                 0,            // Length of OutBuffer
                                 &index,        // BytesReturned
                                 0)) {          // Ptr to Overlapped structure

                code = GetLastError();

                printf("DeviceIoControl failed with error 0x%x\n", code);

                goto Error;

            }

        } else {

            printf("Bar not set.\n");

        }

        break;

        case LIGHT_ALL_BARS:

        barGraphState.BarsAsUChar = 0xFF;

        if (!DeviceIoControl(deviceHandle,
                             IOCTL_OSRUSBFX2_SET_BAR_GRAPH_DISPLAY,
                             &barGraphState,         // Ptr to InBuffer
                             sizeof(BAR_GRAPH_STATE),   // Length of InBuffer
                             NULL,         // Ptr to OutBuffer
                             0,            // Length of OutBuffer
                             &index,       // BytesReturned
                             0)) {          // Ptr to Overlapped structure

            code = GetLastError();

            printf("DeviceIoControl failed with error 0x%x\n", code);

            goto Error;
        }

        break;

        case CLEAR_ALL_BARS:

        barGraphState.BarsAsUChar = 0;

        if (!DeviceIoControl(deviceHandle,
                             IOCTL_OSRUSBFX2_SET_BAR_GRAPH_DISPLAY,
                             &barGraphState,                 // Ptr to InBuffer
                             sizeof(BAR_GRAPH_STATE),         // Length of InBuffer
                             NULL,             // Ptr to OutBuffer
                             0,            // Length of OutBuffer
                             &index,         // BytesReturned
                             0)) {        // Ptr to Overlapped structure

            code = GetLastError();

            printf("DeviceIoControl failed with error 0x%x\n", code);

            goto Error;
        }

        break;


        case GET_BAR_GRAPH_LIGHT_STATE:

        barGraphState.BarsAsUChar = 0;

        if (!DeviceIoControl(deviceHandle,
                             IOCTL_OSRUSBFX2_GET_BAR_GRAPH_DISPLAY,
                             NULL,             // Ptr to InBuffer
                             0,            // Length of InBuffer
                             &barGraphState,          // Ptr to OutBuffer
                             sizeof(BAR_GRAPH_STATE), // Length of OutBuffer
                             &index,                  // BytesReturned
                             0)) {                   // Ptr to Overlapped structure

            code = GetLastError();

            printf("DeviceIoControl failed with error 0x%x\n", code);

            goto Error;
        }

        printf("Bar Graph: \n");
        printf("    Bar8 is %s\n", barGraphState.Bar8 ? "ON" : "OFF");
        printf("    Bar7 is %s\n", barGraphState.Bar7 ? "ON" : "OFF");
        printf("    Bar6 is %s\n", barGraphState.Bar6 ? "ON" : "OFF");
        printf("    Bar5 is %s\n", barGraphState.Bar5 ? "ON" : "OFF");
        printf("    Bar4 is %s\n", barGraphState.Bar4 ? "ON" : "OFF");
        printf("    Bar3 is %s\n", barGraphState.Bar3 ? "ON" : "OFF");
        printf("    Bar2 is %s\n", barGraphState.Bar2 ? "ON" : "OFF");
        printf("    Bar1 is %s\n", barGraphState.Bar1 ? "ON" : "OFF");

        break;

        case GET_SWITCH_STATE:

        switchState.SwitchesAsUChar = 0;

        if (!DeviceIoControl(deviceHandle,
                             IOCTL_OSRUSBFX2_READ_SWITCHES,
                             NULL,             // Ptr to InBuffer
                             0,            // Length of InBuffer
                             &switchState,          // Ptr to OutBuffer
                             sizeof(SWITCH_STATE),  // Length of OutBuffer
                             &index,                // BytesReturned
                             0)) {                  // Ptr to Overlapped structure

            code = GetLastError();

            printf("DeviceIoControl failed with error 0x%x\n", code);

            goto Error;
        }

        printf("Switches: \n");
        printf("    Switch8 is %s\n", switchState.Switch8 ? "ON" : "OFF");
        printf("    Switch7 is %s\n", switchState.Switch7 ? "ON" : "OFF");
        printf("    Switch6 is %s\n", switchState.Switch6 ? "ON" : "OFF");
        printf("    Switch5 is %s\n", switchState.Switch5 ? "ON" : "OFF");
        printf("    Switch4 is %s\n", switchState.Switch4 ? "ON" : "OFF");
        printf("    Switch3 is %s\n", switchState.Switch3 ? "ON" : "OFF");
        printf("    Switch2 is %s\n", switchState.Switch2 ? "ON" : "OFF");
        printf("    Switch1 is %s\n", switchState.Switch1 ? "ON" : "OFF");

        break;

        case GET_SWITCH_STATE_AS_INTERRUPT_MESSAGE:

        switchState.SwitchesAsUChar = 0;

        if (!DeviceIoControl(deviceHandle,
                             IOCTL_OSRUSBFX2_GET_INTERRUPT_MESSAGE,
                             NULL,             // Ptr to InBuffer
                             0,            // Length of InBuffer
                             &switchState,           // Ptr to OutBuffer
                             sizeof(switchState),    // Length of OutBuffer
                             &index,                // BytesReturned
                             0)) {                  // Ptr to Overlapped structure

            code = GetLastError();

            printf("DeviceIoControl failed with error 0x%x\n", code);

            goto Error;
        }

        printf("Switches: %d\n",index);
        printf("    Switch8 is %s\n", switchState.Switch8 ? "ON" : "OFF");
        printf("    Switch7 is %s\n", switchState.Switch7 ? "ON" : "OFF");
        printf("    Switch6 is %s\n", switchState.Switch6 ? "ON" : "OFF");
        printf("    Switch5 is %s\n", switchState.Switch5 ? "ON" : "OFF");
        printf("    Switch4 is %s\n", switchState.Switch4 ? "ON" : "OFF");
        printf("    Switch3 is %s\n", switchState.Switch3 ? "ON" : "OFF");
        printf("    Switch2 is %s\n", switchState.Switch2 ? "ON" : "OFF");
        printf("    Switch1 is %s\n", switchState.Switch1 ? "ON" : "OFF");

        break;

        case GET_7_SEGEMENT_STATE:

        sevenSegment = 0;

        if (!DeviceIoControl(deviceHandle,
                             IOCTL_OSRUSBFX2_GET_7_SEGMENT_DISPLAY,
                             NULL,             // Ptr to InBuffer
                             0,            // Length of InBuffer
                             &sevenSegment,                 // Ptr to OutBuffer
                             sizeof(UCHAR),         // Length of OutBuffer
                             &index,                     // BytesReturned
                             0)) {                       // Ptr to Overlapped structure

            code = GetLastError();

            printf("DeviceIoControl failed with error 0x%x\n", code);

            goto Error;
        }

        printf("7 Segment mask:  0x%x\n", sevenSegment);
        break;

        case SET_7_SEGEMENT_STATE:

        for (i = 0; i < 8; i++) {

            sevenSegment = 1 << i;

            if (!DeviceIoControl(deviceHandle,
                                 IOCTL_OSRUSBFX2_SET_7_SEGMENT_DISPLAY,
                                 &sevenSegment,   // Ptr to InBuffer
                                 sizeof(UCHAR),  // Length of InBuffer
                                 NULL,           // Ptr to OutBuffer
                                 0,         // Length of OutBuffer
                                 &index,         // BytesReturned
                                 0)) {           // Ptr to Overlapped structure

                code = GetLastError();

                printf("DeviceIoControl failed with error 0x%x\n", code);

                goto Error;
            }

            printf("This is %d\n", i);
            Sleep(500);

        }

        printf("7 Segment mask:  0x%x\n", sevenSegment);
        break;

        case RESET_DEVICE:

        printf("Reset the device\n");

        if (!DeviceIoControl(deviceHandle,
                             IOCTL_OSRUSBFX2_RESET_DEVICE,
                             NULL,             // Ptr to InBuffer
                             0,            // Length of InBuffer
                             NULL,                 // Ptr to OutBuffer
                             0,         // Length of OutBuffer
                             &index,   // BytesReturned
                             NULL)) {        // Ptr to Overlapped structure

            code = GetLastError();

            printf("DeviceIoControl failed with error 0x%x\n", code);

            goto Error;
        }

        break;

        case REENUMERATE_DEVICE:

        printf("Re-enumerate the device\n");

        if (!DeviceIoControl(deviceHandle,
                             IOCTL_OSRUSBFX2_REENUMERATE_DEVICE,
                             NULL,             // Ptr to InBuffer
                             0,            // Length of InBuffer
                             NULL,                 // Ptr to OutBuffer
                             0,         // Length of OutBuffer
                             &index,   // BytesReturned
                             NULL)) {        // Ptr to Overlapped structure

            code = GetLastError();

            printf("DeviceIoControl failed with error 0x%x\n", code);

            goto Error;
        }

        //
        // Close the handle to the device and exit out so that
        // the driver can unload when the device is surprise-removed
        // and reenumerated.
        //
        default:

        result = TRUE;
        goto Error;

        }

    }   // end of while loop

Error:

    CloseHandle(deviceHandle);
    return result;

}


ULONG
AsyncIo(
    PVOID  ThreadParameter
    )
{
    HANDLE hDevice = INVALID_HANDLE_VALUE;
    HANDLE hCompletionPort = NULL;
    OVERLAPPED *pOvList = NULL;
    PUCHAR      buf = NULL;
    ULONG_PTR    i;
    ULONG   ioType = (ULONG)(ULONG_PTR)ThreadParameter;
    ULONG   error;

    hDevice = OpenDevice(FALSE);

    if (hDevice == INVALID_HANDLE_VALUE) {
        printf("Cannot open device %d\n", GetLastError());
        goto Error;
    }

    hCompletionPort = CreateIoCompletionPort(hDevice, NULL, 1, 0);

    if (hCompletionPort == NULL) {
        printf("Cannot open completion port %d \n",GetLastError());
        goto Error;
    }

    pOvList = (OVERLAPPED *)malloc(NUM_ASYNCH_IO * sizeof(OVERLAPPED));

    if (pOvList == NULL) {
        printf("Cannot allocate overlapped array \n");
        goto Error;
    }

    buf = (PUCHAR)malloc(NUM_ASYNCH_IO * BUFFER_SIZE);

    if (buf == NULL) {
        printf("Cannot allocate buffer \n");
        goto Error;
    }

    ZeroMemory(pOvList, NUM_ASYNCH_IO * sizeof(OVERLAPPED));
    ZeroMemory(buf, NUM_ASYNCH_IO * BUFFER_SIZE);

    //
    // Issue asynch I/O
    //

    for (i = 0; i < NUM_ASYNCH_IO; i++) {
        if (ioType == READER_TYPE) {
            if ( ReadFile( hDevice,
                      buf + (i* BUFFER_SIZE),
                      BUFFER_SIZE,
                      NULL,
                      &pOvList[i]) == 0) {

                error = GetLastError();
                if (error != ERROR_IO_PENDING) {
                    printf(" %Iu th read failed %d \n",i, GetLastError());
                    goto Error;
                }
            }

        } else {
            if ( WriteFile( hDevice,
                      buf + (i* BUFFER_SIZE),
                      BUFFER_SIZE,
                      NULL,
                      &pOvList[i]) == 0) {
                error = GetLastError();
                if (error != ERROR_IO_PENDING) {
                    printf(" %Iu th write failed %d \n",i, GetLastError());
                    goto Error;
                }
            }
        }
    }

    //
    // Wait for the I/Os to complete. If one completes then reissue the I/O
    //

    WHILE (1) {
        OVERLAPPED *completedOv;
        ULONG_PTR   key;
        ULONG     numberOfBytesTransferred;

        if ( GetQueuedCompletionStatus(hCompletionPort, &numberOfBytesTransferred,
                            &key, &completedOv, INFINITE) == 0) {
            printf("GetQueuedCompletionStatus failed %d\n", GetLastError());
            goto Error;
        }

        //
        // Read successfully completed. Issue another one.
        //

        if (ioType == READER_TYPE) {

            i = completedOv - pOvList;

            printf("Number of bytes read by request number %Iu is %d\n",
                                i, numberOfBytesTransferred);

            if ( ReadFile( hDevice,
                      buf + (i * BUFFER_SIZE),
                      BUFFER_SIZE,
                      NULL,
                      completedOv) == 0) {
                error = GetLastError();
                if (error != ERROR_IO_PENDING) {
                    printf("%Iu th Read failed %d \n", i, GetLastError());
                    goto Error;
                }
            }
        } else {

            i = completedOv - pOvList;

            printf("Number of bytes written by request number %Iu is %d\n",
                            i, numberOfBytesTransferred);

            if ( WriteFile( hDevice,
                      buf + (i * BUFFER_SIZE),
                      BUFFER_SIZE,
                      NULL,
                      completedOv) == 0) {
                error = GetLastError();
                if (error != ERROR_IO_PENDING) {
                    printf("%Iu th write failed %d \n", i, GetLastError());
                    goto Error;
                }
            }
        }
    }

Error:
    if (hDevice != INVALID_HANDLE_VALUE) {
        CloseHandle(hDevice);
    }

    if (hCompletionPort) {
        CloseHandle(hCompletionPort);
    }

    if (pOvList) {
        free(pOvList);
    }
    if (buf) {
        free(buf);
    }

    return 1;

}


int
_cdecl
main(
    _In_ int argc,
    _In_reads_(argc) LPSTR  *argv
    )
/*++
Routine Description:

    Entry point to rwbulk.exe
    Parses cmdline, performs user-requested tests

Arguments:

    argc, argv  standard console  'c' app arguments

Return Value:

    Zero

--*/

{
    char * pinBuf = NULL;
    char * poutBuf = NULL;
    ULONG  nBytesRead;
    ULONG  nBytesWrite = 0;
    int    ok;
    int    retValue = 0;
    UINT   success;
    HANDLE hRead = INVALID_HANDLE_VALUE;
    HANDLE hWrite = INVALID_HANDLE_VALUE;
    ULONG  fail = 0L;
    ULONG  i;


    Parse(argc, argv );

    //
    // dump USB configuation and pipe info
    //
    if (G_fDumpUsbConfig) {
        DumpUsbConfig();
    }

    if (G_fPlayWithDevice) {
        PlayWithDevice();
        goto exit;
    }

    if (G_fPerformAsyncIo) {
        HANDLE  th1;

        //
        // Create a reader thread
        //
        th1 = CreateThread( NULL,          // Default Security Attrib.
                            0,             // Initial Stack Size,
                            AsyncIo,       // Thread Func
                            (LPVOID)READER_TYPE,
                            0,             // Creation Flags
                            NULL );        // Don't need the Thread Id.

        if (th1 == NULL) {
            printf("Couldn't create reader thread - error %d\n", GetLastError());
            retValue = 1;
            goto exit;
        }

        //
        // Use this thread for peforming write.
        //
        AsyncIo((PVOID)WRITER_TYPE);

        goto exit;
    }

    //
    // doing a read, write, or both test
    //
    if ((G_fRead) || (G_fWrite)) {

        if (G_fRead) {
            if ( G_fDumpReadData ) { // round size to sizeof ULONG for readable dumping
                while( G_ReadLen % sizeof( ULONG ) ) {
                    G_ReadLen++;
                }
            }

            //
            // open the output file
            //
            hRead = OpenDevice(TRUE);
            if(hRead == INVALID_HANDLE_VALUE) {
                retValue = 1;
                goto exit;
            }

            pinBuf = malloc(G_ReadLen);
        }

        if (G_fWrite) {
            if ( G_fDumpReadData ) { // round size to sizeof ULONG for readable dumping
                while( G_WriteLen % sizeof( ULONG ) ) {
                    G_WriteLen++;
                }
            }

            //
            // open the output file
            //
            hWrite = OpenDevice(TRUE);
            if(hWrite == INVALID_HANDLE_VALUE) {
               retValue = 1;
               goto exit;
            }

            poutBuf = malloc(G_WriteLen);
        }

        for (i = 0; i < G_IterationCount; i++) {
            ULONG  j;

            if (G_fWrite && poutBuf && hWrite != INVALID_HANDLE_VALUE) {

                PULONG pOut = (PULONG) poutBuf;
                ULONG  numLongs = G_WriteLen / sizeof( ULONG );

                //
                // put some data in the output buffer
                //
                for (j=0; j<numLongs; j++) {
                    *(pOut+j) = j;
                }

                //
                // send the write
                //
                success = WriteFile(hWrite, poutBuf, G_WriteLen, &nBytesWrite, NULL);
                if(success == 0) {
                    printf("WriteFile failed - error %d\n", GetLastError());
                    retValue = 1;
                    goto exit;
                }
                printf("Write (%04.4u) : request %06.6u bytes -- %06.6u bytes written\n",
                        i, G_WriteLen, nBytesWrite);

                assert(nBytesWrite == G_WriteLen);
            }

            if (G_fRead && pinBuf) {

                success = ReadFile(hRead, pinBuf, G_ReadLen, &nBytesRead, NULL);
                if(success == 0) {
                    printf("ReadFile failed - error %d\n", GetLastError());
                    retValue = 1;
                    goto exit;
                }

                printf("Read (%04.4u) : request %06.6u bytes -- %06.6u bytes read\n",
                       i, G_ReadLen, nBytesRead);

                if (G_fWrite && poutBuf) {

                    //
                    // validate the input buffer against what
                    // we sent to the 82930 (loopback test)
                    //
                    ok = Compare_Buffs(pinBuf, nBytesRead, poutBuf, nBytesWrite);

                    if( G_fDumpReadData ) {
                        printf("Dumping read buffer\n");
                        Dump( (PUCHAR) pinBuf,  nBytesRead );
                        printf("Dumping write buffer\n");
                        Dump( (PUCHAR) poutBuf, nBytesRead );
                    }
                    assert(ok);

                    if(ok != 1) {
                        fail++;
                    }

                    assert(G_ReadLen == G_WriteLen);
                    assert(nBytesRead == G_ReadLen);
                }
            }
        }

    }

exit:

    if (pinBuf) {
        free(pinBuf);
    }

    if (poutBuf) {
        free(poutBuf);
    }

    // close devices if needed
    if (hRead != INVALID_HANDLE_VALUE) {
        CloseHandle(hRead);
    }

    if (hWrite != INVALID_HANDLE_VALUE) {
        _Analysis_assume_(hWrite != NULL);
        CloseHandle(hWrite);
    }

    return retValue;
}