summaryrefslogtreecommitdiffstats
path: root/private/sdktools/simbad/simbad.c
blob: da3041f0856e6a5570c8d8456999e60730937859 (plain) (blame)
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
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
/*++

Copyright (c) 1991 Microsoft Corporation

Module Name:

    simbad.c (formerly simbad.cxx)

Abstract:

    This module contains the main function of SimBad, which
    allows the user to to ask the device driver to simulate
    bad sectors.

Author:

    Bill McJohn (billmc) 16-Aug-1991
    Lars Opstad (a-larso) 6-Feb-1993

Environment:

    ULIB, User Mode

Revision History:

    4.Apr.92 - BobRi  - Minor fix to list function (device control interface)
    9.Apr.92 - BobRi  - Modified (with BillMc's help) to support the access
                        triggers on when block numbers are to fail.

   29.Jan.93 - LarsOp - Major changes to change to allow redirected console
                        input.  This required lots of changes because of
                        dependencies on cxx libraries -> convert to C.

                        Also added functionality on Sanjay's request for
                        supporting file input with multiple lists of bad
                        sectors.

    5.Feb.93 - Larsop - Added new function - orphan device. Any accesses to
                        the indicated partition will fail with a status of
                        STATUS_IO_DEVICE_ERROR.

   20.May.93 - mglass - Add support for VERIFY access type. This will allow
                        SIMBAD to test the format utiltiy.

   21.Jul.93 - mglass - Define access bit to fail attempt to reassign blocks.
   12.May.94 - Venkat - Added code to drop of writes to DISK (CHKDSK testing)
   22.Nov.94 - kpeery - Added code to force hardware reset (for restarts)
--*/
#include "stdlib.h"
#include "stdio.h"
#include "nt.h"
#include "ntrtl.h"
#include "ntdddisk.h"
#include <simbad.h>

//
// Constants for command line arguments
//
#define HD_SPEC   'h'
#define PART_SPEC 'p'
#define LIST      'l'
#define ZERO_OFF  'z'
#define MAP       'm'
#define ADD_ALL   'a'
#define ADD_READ  'r'
#define ADD_WRITE 'w'
#define ADD_VERIFY 'v'
#define DO_NOT_MAP 'x'
#define ENABLE    'e'
#define DISABLE   'd'
#define ORPHAN    'o'
#define CLEAR     'c'
#define FROM_FILE 'f'
#define RANDOM	  'n'
#define BUGCHECK  'b'
#define FIRMWARE_RESET 't'

#define MAX_DEV_NAME 128


char  devname[MAX_DEV_NAME]="\\Device\\HardDisk0\\Partition1";
char  *filename;
WCHAR whattodo=LIST;
ULONG Seed, accessType=0;
int   hdnum=0, partnum=1;
ULONG sectors[MAXIMUM_SIMBAD_SECTORS];


VOID
InputSectorList (
    OUT PULONG sectors,
    OUT PULONG count
    )
/*++

Routine Description:

    This function reads the sector list from stdin.  The list is
    terminated by end of file (max bad sectors entered).

Arguments:

    sectors -- receives array of sectors
    count   -- receives number of sectors read from stdin

Return value:

    None.

--*/
{
    //
    // loop until end-of-file or count exceeds max sectors
    //
    while (!feof(stdin) && (*count) < MAXIMUM_SIMBAD_SECTORS) {

        fscanf(stdin, "%lx", &(sectors[(*count)++]));

    } // while

    //
    // if count is less than MAX_BAD_SECTORS,
    // the last read was an EOF => decrement count.
    //
    if (*count < MAXIMUM_SIMBAD_SECTORS) {

        (*count)--;

    } // if
} // InputSectorList()

VOID
ShowUsage (
    )
/*++

Routine Description:

    This function displays command line options for Simbad.

Arguments:

    None.

Return value:

    None.

--*/
{
    printf("\nUsage: Simbad DeviceSpecifier /command /options\n"
        "or     Simbad /f file /options\n"
        "\nwhere DeviceSpecifier is in one of the following formats:\n"
        "\t\\Device\\HardDisk#\\Partition#\n"
        "\t\\DosDevices\\C:\n"
        "\t/h <hard disk #> /p <partition #>\n"
        "\nand command is one of the following:\n"
        "\ta Fail all   access (enter sector list)\n"
        "\tr Fail read  access (enter sector list)\n"
        "\tw Fail write access (enter sector list)\n"
        "\tv Fail verify access (enter sector list)\n"
        "\to Orphan entire device (return DEVICE FAILURE)\n"
        "\tn Dropping writes randomly\n"
        "\tb BugChecks the system\n"
        "\tt Reset the system\n"
        "\te Enable  (previously entered) bad sectors\n"
        "\td Disable (previously enabled) bad sectors\n"
        "\tl List bad sectors\n"
        "\tc Clear bad sectors\n"
        "\nand options includes any of the following:\n"
        "\tm Pass block reassignments to lower driver\n"
        "\tz Failures report zero offset\n"
        "\tx Fail block reassignment\n"
        "\nNote: /h and /p have been added.  The following cmd lines are equivalent:\n\n"
        "\tSimbad \\Device\\HardDisk0\\Partition1 /l\n"
        "\tSimbad /h 0 /p 1 /l\n"
        "\nThe format of the file used with the /f option is as follows:\n\n"
        "\\Device\\HardDisk#\\Partition#\n"
        "R:0 8 a ...\n"
        "W:...\n"
        "A:...\n\n"
        "This file can contain lists for multiple devices.\n"
        "The bad sector emulation is not enabled until the /e option is entered.\n"
        );
    exit(-1);
} // ShowUsage();


VOID
ParseCmdArgs (
    IN int argc,
    IN char *argv[]
    )
/*++

Routine Description:

    This function sets some global variables based on the command line
    arguments given to main (and passed here).

    The globals that are set are as follows:

        devname    -- name of device to simulate bad sectors on
        accessType -- fail on READ or WRITE, reassign, zero offset
        whattodo   -- which action (add, list, enable/disable, readfromfile)
        filename   -- which filename to use for FROM_FILE action

Arguments:

    argc -- supplies number of arguments
    argv -- supplies list of arguments

Return value:

    None.

--*/
{
    int i=1;

    //
    // if no arguments, just show usage.
    //
    if (argc==1) {

        ShowUsage();

    } // if

    //
    // check each argument
    //
    while (i<argc) {

        //
        // check first character
        //
        switch (argv[i][0]) {

        //
        // if first character is - or /, it is a switch.
        //
        case '-':
        case '/':

            //
            // switch value is the second character
            //
            switch (tolower(argv[i][1])) {

            //
            // specify harddisk, sprintf devname
            //
            case HD_SPEC:

                hdnum=atoi(argv[++i]);

                sprintf(devname,
                    "\\Device\\HardDisk%d\\Partition%d",
                    hdnum,
                    partnum);

                i++;
                break;

            //
            // specify partition, sprintf devname
            //
            case PART_SPEC:

                partnum=atoi(argv[++i]);

                sprintf(devname,
                    "\\Device\\HardDisk%d\\Partition%d",
                    hdnum,
                    partnum);

                i++;
                break;

            //
            // set action to FROM_FILE and set filename
            //
            case FROM_FILE:

                whattodo=argv[i++][1];
                filename=argv[i++];
                break;

            //
            // set zero offset bit in accessMode
            //
            // This means a failed io will return the beginning
            // of the io instead of the failing sector.
            //
            case ZERO_OFF:

                accessType|=SIMBAD_ACCESS_ERROR_ZERO_OFFSET;
                whattodo=ADD_ALL;
                i++;
                break;

            //
            // set reassign bit in accessMode
            //
            // This allows simbad to reassign sectors on this device.
            // Basically, simbad just removes the sector from the list
            // on a reassign request.
            //
            case MAP:

                accessType|=SIMBAD_ACCESS_CAN_REASSIGN_SECTOR;
                whattodo=ADD_ALL;
                i++;
                break;

            //
            // Fail device control requests to reassign a bad block.
            //
            case DO_NOT_MAP:
                accessType|=SIMBAD_ACCESS_FAIL_REASSIGN_SECTOR;
                whattodo=ADD_ALL;
                i++;
                break;

            //
            // set fail-on-read bit in access mode (action is ADD)
            //
            case ADD_READ:

                accessType|=SIMBAD_ACCESS_READ;
                whattodo=ADD_ALL;
                i++;
                break;

            //
            // set fail-on-write bit in access mode (action is ADD)
            //
            case ADD_WRITE:

                accessType|=SIMBAD_ACCESS_WRITE;
                whattodo=ADD_ALL;
                i++;
                break;

            //
            // set fail-on-verify bit in access mode (action is ADD)
            //
            case ADD_VERIFY:

                accessType|=SIMBAD_ACCESS_VERIFY;
                whattodo=ADD_ALL;
                i++;
                break;

            //
            // set fail-on-read and fail-on-write bit in access mode
            //
            // Since ADD_ALL is the intended action, fall through to
            // the next case which just sets the action to whatever
            // character the switch is.
            //
            case ADD_ALL:

                accessType|=(SIMBAD_ACCESS_READ|SIMBAD_ACCESS_WRITE|SIMBAD_ACCESS_VERIFY);

                //
                // NOTE: break intentionally left out (fall through to next)
                //

            //
            // for list, enable, disable and clear, the action is the
            // switch value
            //
            case LIST:
            case ORPHAN:
            case BUGCHECK:
            case FIRMWARE_RESET:
            case ENABLE:
            case DISABLE:
            case CLEAR:

                whattodo=argv[i++][1];
                break;

            case RANDOM:
                whattodo=argv[i++][1];
                if  ( i< argc ){
                    sscanf( argv[i++],"%lu", &Seed);
                }else{
                    Seed=100;
                }
                break;

            //
            // any other switch, show usage
            //
            default:

                ShowUsage();

            } // switch (second character)
            break;

        //
        // if first char is \, it is a device name
        //
        case '\\':

            strcpy(devname,argv[i++]);
            break;


        //
        // anything else, show usage
        //
        default:

            ShowUsage();

        } // switch (first character)

    } // while

} // ParseCmdArgs()


//
// Some of this code was taken directly from simbad.cxx (older version)
// and PLBN needed to be defined for some of the older routines.
//
#define PLBN PULONG

BOOLEAN
OpenDrive(
    IN  char           *psz_string,
    OUT PHANDLE        _phandle
    )
/*++

Routine Description:

    This routine opens the specified drive and passes back the handle.

Arguments:

    psz_string -- supplies the device name (format "\harddiskX\partitionY")
    _phandle   -- receives the handle to the opened device

Return value:

    Returns whether the open was successful.

--*/
{
    OBJECT_ATTRIBUTES oa;
    IO_STATUS_BLOCK   status_block;
    NTSTATUS          _last_status;
    ANSI_STRING       ans_string;
    UNICODE_STRING    uni_string;

    //
    // Build unicode string
    //
    RtlInitAnsiString(&ans_string, psz_string);
    RtlAnsiStringToUnicodeString(&uni_string, &ans_string, TRUE);


    //
    // setup object attributes for openfile
    //
    InitializeObjectAttributes( &oa,
                                &uni_string,
                                OBJ_CASE_INSENSITIVE,
                                0,
                                0 );

    _last_status = NtOpenFile(_phandle,
                              SYNCHRONIZE | FILE_READ_DATA | FILE_WRITE_DATA,
                              &oa, &status_block,
                              FILE_SHARE_READ | FILE_SHARE_WRITE,
                              FILE_SYNCHRONOUS_IO_ALERT);

    //
    // Deallocate unicode string
    //
    RtlFreeUnicodeString(&uni_string);
    //RtlFreeAnsiString(&ans_string); // BUG BUG This causes access viol, why?

    return NT_SUCCESS(_last_status);
} // OpenDrive()

#ifndef SIMBAD_ORPHAN
#define SIMBAD_ORPHAN      0x00000005
#endif
//
//  Bugchecks the system
//

BOOLEAN
BugCheckOrResetTheSystem(HANDLE _handle, ULONG simbadFunction)

/*++

Routine Description:

    This routine will setup SIMBAD for bug checking or reseting the system.

Arguments:
    _handle       - a device handle
    simbadFunction - the desired function to call in the driver

Return Value:

    TRUE upon successful completion.

--*/
{
    SIMBAD_DATA     SimbadData;
    IO_STATUS_BLOCK StatusBlock;
    NTSTATUS        Status;

    SimbadData.Function = simbadFunction;

    Status= NtDeviceIoControlFile(_handle,
                                  0,
                                  NULL,
                                  NULL,
                                  &StatusBlock,
                                  IOCTL_DISK_SIMBAD,
                                  &SimbadData,
                                  sizeof(SIMBAD_DATA),
                                  NULL,
                                  0);

    if ((BOOLEAN)NT_SUCCESS(Status)){
		return TRUE;
    }else{
        fprintf(stderr,
                "BugCheckOrResetTheSystem(0x%08x) function  %s failed (%lX)\n",
                simbadFunction, devname, Status);
        return FALSE;
    }

} //BugCheckOrRestTheSystem


//
//  Drops of writes to disk. Purpose to corrupt the disk.
//

BOOLEAN
RandomWriteFailure(
    HANDLE  _handle
    )
/*++

Routine Description:

    This routine causes io to the specified device to fail writes randomly.

Arguments:

Return Value:

    TRUE upon successful completion.

--*/
{
    SIMBAD_DATA         SimbadData;
    IO_STATUS_BLOCK     StatusBlock;
    NTSTATUS		Status;
    SimbadData.Count = Seed;
    SimbadData.Function = SIMBAD_RANDOM_WRITE_FAIL;

    Status= NtDeviceIoControlFile(_handle,
                                             0,
                                             NULL,
                                             NULL,
                                             &StatusBlock,
                                             IOCTL_DISK_SIMBAD,
                                             &SimbadData,
                                             sizeof(SIMBAD_DATA),
                                             NULL,
					     0);

	   if ((BOOLEAN)NT_SUCCESS(Status)){
		return TRUE;
	   }else{
		fprintf(stderr,
			"RandomWriteFailure disk on %s failed (%lX)\n",
			devname, Status);
		return FALSE;
	   }



} //RandomWriteFailure


BOOLEAN
OrphanDisk(
    HANDLE  _handle
    )
/*++

Routine Description:

    This routine causes io to the specified device to return DEVICE_FAILURE

Arguments:

Return Value:

    TRUE upon successful completion.

--*/
{
    SIMBAD_DATA         SimbadData;
    IO_STATUS_BLOCK     StatusBlock;

    SimbadData.Count = 0;
    SimbadData.Function = SIMBAD_ORPHAN;

    return (BOOLEAN)
           NT_SUCCESS( NtDeviceIoControlFile(_handle,
                                             0,
                                             NULL,
                                             NULL,
                                             &StatusBlock,
                                             IOCTL_DISK_SIMBAD,
                                             &SimbadData,
                                             sizeof(SIMBAD_DATA),
                                             NULL,
                                             0) );
} // OrphanDisk()

BOOLEAN
EnableBadSectorSimulation(
    HANDLE  _handle,
    BOOLEAN Enable
    )
/*++

Routine Description:

    This routine turns bad sector simulation on or off.

Arguments:

    Enable -- supplies whether to turn simulation on (TRUE) or
                off (FALSE)

Return Value:

    TRUE upon successful completion.

--*/
{
    SIMBAD_DATA         SimbadData;
    IO_STATUS_BLOCK     StatusBlock;

    SimbadData.Count = 0;
    SimbadData.Function = Enable ? SIMBAD_ENABLE : SIMBAD_DISABLE;

    return (BOOLEAN)
           NT_SUCCESS( NtDeviceIoControlFile(_handle,
                                             0,
                                             NULL,
                                             NULL,
                                             &StatusBlock,
                                             IOCTL_DISK_SIMBAD,
                                             &SimbadData,
                                             sizeof(SIMBAD_DATA),
                                             NULL,
                                             0) );
} // EnableBadSectorSimulation()

BOOLEAN
ClearBadSectors(
    HANDLE  _handle
    )
/*++

Routine Description:

    This routine turns bad sector simulation on or off.

Arguments:

    _handle - something with which to grip

Return Value:

    TRUE upon successful completion.

--*/
{
    SIMBAD_DATA         SimbadData;
    IO_STATUS_BLOCK     StatusBlock;

    SimbadData.Count = 0;
    SimbadData.Function = SIMBAD_CLEAR;

    return (BOOLEAN)
           NT_SUCCESS( NtDeviceIoControlFile(_handle,
                                             0,
                                             NULL,
                                             NULL,
                                             &StatusBlock,
                                             IOCTL_DISK_SIMBAD,
                                             &SimbadData,
                                             sizeof(SIMBAD_DATA),
                                             NULL,
                                             0) );
} // ClearBadSectors()

BOOLEAN
SimulateBadSectors(
    HANDLE      _handle,
    BOOLEAN     Add,
    ULONG       Count,
    PLBN        SectorArray,
    NTSTATUS    Status,
    ULONG       AccessType
    )
/*++

Routine Description:

    This function adds sectors to or removes sectors from the
    bad sector simulation list.

Arguments:

    Add         -- supplies a flag indicating whether to add (TRUE)
                    or remove (FALSE) sectors
    Count       -- supplies the number of sectors in the sector array
    SectorArray -- supplies the array of sectors to mark as bad.
                    (May be NULL if Count is zero.)
    Status      -- supplies the status to associate with these sectors.
    AccessType  -- supplies the type of access that will trigger the error
                   for all sectors in the SectorArray.

Return Value:

    TRUE upon successful completion.

--*/
{
    SIMBAD_DATA         SimbadData;
    IO_STATUS_BLOCK     StatusBlock;
    ULONG               i;

    if( Count > MAXIMUM_SIMBAD_SECTORS ) {

        return FALSE;

    } // if

    SimbadData.Function = Add ? SIMBAD_ADD_SECTORS : SIMBAD_REMOVE_SECTORS;
    SimbadData.Count    = Count;

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

        SimbadData.Sector[i].BlockAddress = SectorArray[i];
        SimbadData.Sector[i].AccessType = AccessType;
        SimbadData.Sector[i].Status = Status;

    } // for

    for( i = Count; i < MAXIMUM_SIMBAD_SECTORS; i++ ) {

        SimbadData.Sector[i].BlockAddress = 0;
        SimbadData.Sector[i].AccessType = 0;
        SimbadData.Sector[i].Status = 0;

    } // for

    return (BOOLEAN)
           NT_SUCCESS( NtDeviceIoControlFile(_handle,
                                             0,
                                             NULL,
                                             NULL,
                                             &StatusBlock,
                                             IOCTL_DISK_SIMBAD,
                                             &SimbadData,
                                             sizeof(SIMBAD_DATA),
                                             NULL,
                                             0) );
} // SimulateBadSectors()

BOOLEAN
QuerySimulatedBadSectors(
    IN  HANDLE  _handle,
    OUT PULONG  Count,
    IN  ULONG   MaximumLbnsInBuffer,
    OUT PLBN    SectorArray,
    OUT PULONG  AccessTypeArray
    )
/*++

Routine Description:

    This method retrieves the  sectors in the bad sector simulation list.

Arguments:

    Count               -- receives the number of returned sectors
    MaximumLbnsInBuffer -- supplies the length of the buffer
    SectorArray         -- receives the bad sector list
    AccessTypeArray     -- receives the list of access types that trigger
                           the error.

Return Value:

    TRUE upon successful completion

--*/
{
    SIMBAD_DATA         SimbadData;
    IO_STATUS_BLOCK     StatusBlock;
    ULONG               ReturnedCount;
    ULONG               i;


    SimbadData.Function = SIMBAD_LIST_BAD_SECTORS;

    if( !NT_SUCCESS( NtDeviceIoControlFile(_handle,
                                           0,
                                           NULL,
                                           NULL,
                                           &StatusBlock,
                                           IOCTL_DISK_SIMBAD,
                                           &SimbadData,
                                           sizeof(SIMBAD_DATA),
                                           &SimbadData,
                                           sizeof(SIMBAD_DATA)) ) ) {

        return FALSE;
    } // if

    ReturnedCount = (SimbadData.Count < MaximumLbnsInBuffer) ?
                    SimbadData.Count :
                    MaximumLbnsInBuffer;

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

        SectorArray[i] = SimbadData.Sector[i].BlockAddress;
        AccessTypeArray[i] = SimbadData.Sector[i].AccessType;

    } // for

    *Count = ReturnedCount;

    return TRUE;
} // QuerySimulatedBadSectors()

//
// HEX_DIGITS is a string used to search for hex values in the input string
// in ReadFromFile().
//
#define HEX_DIGITS "0123456789abcdefABCDEF"

VOID
ReadFromFile (
    )
/*++

Routine Description:

    This routine reads the list(s) of bad sectors for 1 or more devices
    and adds the sectors from that file.

Arguments:

    None; filename is set in ParseCmdArgs as a global.

Return value:

    None.

--*/
{
    FILE * thefile;
    HANDLE _handle=0;
    ULONG  count;
    ULONG  access;
    char   Buffer[MAX_DEV_NAME*8],
           *curptr;                  // curptr is current location in buffer

    //
    // if able to open the filename (specified on command line), parse it
    //
    if(thefile=fopen(filename,"r")) {

        //
        // read until file is done
        //
        while (!feof(thefile)) {

            //
            // if able to read a string, parse it.
            //
            if(fgets(Buffer, MAX_DEV_NAME*8, thefile)) {

                curptr=Buffer;

                //
                // Always start with the global access type value in case
                // user specified an option, e.g. -x.
                //

                access = accessType;

                //
                // switch based on the beginning of the buffer
                //
                switch (Buffer[0]) {

                //
                // if \ is first char, Buffer is a device name
                //
                case '\\':

                    //
                    // if there is an open handle, close it.
                    //
                    if(_handle) {

                        NtClose(_handle);
                        _handle=0;

                    } // if(_handle)

                    //
                    // trim Buffer and use as devname for OpenDrive()
                    //
                    sscanf(Buffer, "%s", devname);
                    OpenDrive(devname, &_handle);
                    break;

                //
                // r means Buffer is a list of read-failing sectors
                //
                case 'r':
                case 'R':

                    access |= SIMBAD_ACCESS_READ;
                    goto commonRead;

                //
                // w means Buffer is a list of write-failing sectors
                //
                case 'w':
                case 'W':

                    access |= SIMBAD_ACCESS_WRITE;
                    goto commonRead;

                //
                // v means Buffer is a list of verify-failing sectors
                //
                case 'v':
                case 'V':

                    access |= SIMBAD_ACCESS_VERIFY;
                    goto commonRead;

                //
                // a means Buffer is a list of verify-failing sectors
                //
                case 'a':
                case 'A':

                    access |= SIMBAD_ACCESS_VERIFY |
                              SIMBAD_ACCESS_READ |
                              SIMBAD_ACCESS_WRITE;
commonRead:
                    //
                    // if there is an open drive
                    //
                    if (_handle) {

                        count=0;
                        curptr+=2; // Move past token:

                        //
                        // loop until no more sectors > MAX
                        //
                        while (0 < sscanf(curptr,"%lx", &(sectors[count]))
                               && count<MAXIMUM_SIMBAD_SECTORS) {

                            //
                            // scan to first hex digit
                            //
                            curptr=&(curptr[strcspn(curptr,HEX_DIGITS)]);

                            count++;

                            //
                            // scan to first non hex char
                            //
                            curptr=&(curptr[strspn(curptr,HEX_DIGITS)]);

                            } // while

                        if (!SimulateBadSectors(_handle,
                                                TRUE,
                                                count,
                                                sectors,
                                                STATUS_DEVICE_DATA_ERROR,
                                                access)) {

                                printf("Add failed \n");

                        } // if (!SimulateBadSectors())

                    } // if (_handle)
                    break;

                //
                // any other first character, do nothing
                //
                default:
                    ;
                } // switch
            } // if (fgets())
        } // while (!feof())

        //
        // if there is an open handle at the end, close it
        //
        if(_handle) {

            NtClose(_handle);

        } // if (_handle)
    } // if (fopen())
} // ReadFromFile()

VOID _CRTAPI1
main (
    IN int    argc,
    IN char * argv[]
    )
/*++

Routine Description:

    This routine is the entry point for simbad.  It parses the command
    arguments and then performs the action specified on the command line.
    (The action and accessmode are set in SetCmdArgs()).

Arguments:

    argc -- supplies the number of cmd line arguments
    argv -- supplies the array of cmd line arguments

Return value:

    None.

--*/
{
    ULONG  accarr[MAXIMUM_SIMBAD_SECTORS];
    HANDLE _handle;
    ULONG  count, i;

    //
    // ParseCmdArgs and set whattodo, devname and accessmode
    //
    ParseCmdArgs(argc, argv);

    if (whattodo==FROM_FILE) {

        ReadFromFile();

    } else { // NOT from file, read from stdin

        //
        // if able to open drive, perform action
        //
        if (OpenDrive(devname, &_handle)) {

            //
            // perform an action based on whattodo
            //
            switch (tolower(whattodo)) {

            //
            // LIST calls QuerySimulatedBadSectors and displays on stdout
            //
            case LIST:

                if (!QuerySimulatedBadSectors(_handle,
                    &count,
                    MAXIMUM_SIMBAD_SECTORS,
                    sectors,
                    accarr )) {

                    printf("List failed %lx\n", GetLastError());

                } else {

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

                        printf("Sector: %lx\tAccess: %lx\n",
                            sectors[i],
                            accarr[i] );

                    } // for
                } // if
                break;

            //
            // ADD gets a list of sectors from InputSectorList and adds them
            //
            case ADD_ALL:

                count=0;
                InputSectorList(sectors, &count);

                if (!SimulateBadSectors(_handle,
                    TRUE,
                    count,
                    sectors,
                    STATUS_DEVICE_DATA_ERROR,
                    accessType )) {

                        printf("Unable to add sectors to %s (%lx)\n",
                               devname,
                               GetLastError());

                } // if
                break;

            //
            // ORPHAN causes the partition to return DEVICE_FAILUR
            //
            case ORPHAN:

                if (!OrphanDisk(_handle)) {

                    printf ("Orphan disk on %s failed (%lx)\n",
                            devname,
                            GetLastError());

                } // if
                break;


            //
            // ENABLE turns on the bad sector simulation
            //
            case ENABLE:

                if (!EnableBadSectorSimulation(_handle, TRUE)) {

                    printf("Enable bad sectors on %s failed (%lx)\n",
                           devname,
                           GetLastError());
                } // if
                break;

            //
            // DISABLE turns off the bad sector simulation
            //
            case DISABLE:

                if (!EnableBadSectorSimulation(_handle, FALSE)) {

                    printf("Disable bad sectors on %s failed %lx\n",
                           devname,
                           GetLastError());

                } // if
                break;

            //
            // CLEAR clears bad sector list in driver
            //
            case CLEAR:

                if (!ClearBadSectors(_handle)) {

                    printf("Clear bad sectors on %s failed %lx\n",
                           devname,
                           GetLastError());
                } // if
                break;

            //
            // RANDOM   causes the partition to drop writes randomly
            //
            case RANDOM:

                if (!RandomWriteFailure(_handle )) {

                    printf ("RandomWriteFailure disk on %s failed (%lx)\n",
                            devname, 
                            GetLastError());

                } // if
                break;

	        //
            //  BUGCHECK sets up the system for bug check
            //  

            case BUGCHECK:
                if (!BugCheckOrResetTheSystem(_handle, SIMBAD_BUG_CHECK)){
                    printf ("BugCheckTheSystem function failed.\n");
                } // if
                break;

            //
            //  FIRMWARE_RESET setup for firmware reset when enabled.
            //

            case FIRMWARE_RESET:
                if (!BugCheckOrResetTheSystem(_handle, SIMBAD_FIRMWARE_RESET)){
                    printf ("ResetTheSystem function failed.\n");
                } // if
                break;

            // any other action, just close the handle and show usage
	        //

            default:

                NtClose(_handle);
                ShowUsage();

            } // switch (whattodo)


            NtClose(_handle);
        } else {

            printf("Open %s failed %lx\n", devname, GetLastError());

        } // if (OpenDrive())
    } // if (whattodo==FROM_FILE)
} // main()