Sample Code

windows driver samples/ cdfs file system driver/ C++/ cddata.c/

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
/*++
 
Copyright (c) 1989-2000 Microsoft Corporation
 
Module Name:
 
    CdData.c
 
Abstract:
 
    This module declares the global data used by the Cdfs file system.
 
    This module also handles the dispath routines in the Fsd threads as well as
    handling the IrpContext and Irp through the exception path.
 
 
--*/
 
#include "CdProcs.h"
 
#ifdef CD_SANITY
BOOLEAN CdTestTopLevel = TRUE;
BOOLEAN CdTestRaisedStatus = TRUE;
BOOLEAN CdBreakOnAnyRaise = FALSE;
BOOLEAN CdTraceRaises = FALSE;
NTSTATUS CdInterestingExceptionCodes[] = { STATUS_DISK_CORRUPT_ERROR,
                                           STATUS_FILE_CORRUPT_ERROR,
                                           0, 0, 0, 0, 0, 0, 0, 0 };
#endif
 
//
//  The Bug check file id for this module
//
 
#define BugCheckFileId                   (CDFS_BUG_CHECK_CDDATA)
 
//
//  Global data structures
//
 
CD_DATA CdData;
FAST_IO_DISPATCH CdFastIoDispatch;
 
//
//  Reserved directory strings.
//
 
WCHAR CdUnicodeSelfArray[] = { L'.' };
WCHAR CdUnicodeParentArray[] = { L'.', L'.' };
 
UNICODE_STRING CdUnicodeDirectoryNames[] = {
    { 2, 2, CdUnicodeSelfArray},
    { 4, 4, CdUnicodeParentArray}
};
 
//
//  Volume descriptor identifier strings.
//
 
CHAR CdHsgId[] = { 'C', 'D', 'R', 'O', 'M' };
CHAR CdIsoId[] = { 'C', 'D', '0', '0', '1' };
CHAR CdXaId[] = { 'C', 'D', '-', 'X', 'A', '0', '0', '1' };
 
//
//  Volume label for audio disks.
//
 
WCHAR CdAudioLabel[] = { L'A', L'u', L'd', L'i', L'o', L' ', L'C', L'D' };
USHORT CdAudioLabelLength = sizeof( CdAudioLabel );
 
//
//  Pseudo file names for audio disks.
//
 
CHAR CdAudioFileName[] = { 'T', 'r', 'a', 'c', 'k', '0', '0', '.', 'c', 'd', 'a' };
UCHAR CdAudioFileNameLength = sizeof( CdAudioFileName );
ULONG CdAudioDirentSize = FIELD_OFFSET( RAW_DIRENT, FileId ) + sizeof( CdAudioFileName ) + sizeof( SYSTEM_USE_XA );
ULONG CdAudioDirentsPerSector = SECTOR_SIZE / (FIELD_OFFSET( RAW_DIRENT, FileId ) + sizeof( CdAudioFileName ) + sizeof( SYSTEM_USE_XA ));
ULONG CdAudioSystemUseOffset = FIELD_OFFSET( RAW_DIRENT, FileId ) + sizeof( CdAudioFileName );
 
//
//  Escape sequences for mounting Unicode volumes.
//
 
PCHAR CdJolietEscape[] = { "%/@", "%/C", "%/E" };
 
//
//  Audio Play Files consist completely of this header block.  These
//  files are readable in the root of any audio disc regardless of
//  the capabilities of the drive.
//
//  The "Unique Disk ID Number" is a calculated value consisting of
//  a combination of parameters, including the number of tracks and
//  the starting locations of those tracks.
//
//  Applications interpreting CDDA RIFF files should be advised that
//  additional RIFF file chunks may be added to this header in the
//  future in order to add information, such as the disk and song title.
//
 
LONG CdAudioPlayHeader[] = {
    0x46464952,                         // Chunk ID = 'RIFF'
    4 * 11 - 8,                         // Chunk Size = (file size - 8)
    0x41444443,                         // 'CDDA'
    0x20746d66,                         // 'fmt '
    24,                                 // Chunk Size (of 'fmt ' subchunk) = 24
    0x00000001,                         // WORD Format Tag, WORD Track Number
    0x00000000,                         // DWORD Unique Disk ID Number
    0x00000000,                         // DWORD Track Starting Sector (LBN)
    0x00000000,                         // DWORD Track Length (LBN count)
    0x00000000,                         // DWORD Track Starting Sector (MSF)
    0x00000000                          // DWORD Track Length (MSF)
};
 
//  Audio Philes begin with this header block to identify the data as a
//  PCM waveform.  AudioPhileHeader is coded as if it has no data included
//  in the waveform.  Data must be added in 2352-byte multiples.
//
//  Fields marked 'ADJUST' need to be adjusted based on the size of the
//  data: Add (nSectors*2352) to the DWORDs at offsets 1*4 and 10*4.
//
//  File Size of TRACK??.WAV = nSectors*2352 + sizeof(AudioPhileHeader)
//  RIFF('WAVE' fmt(1, 2, 44100, 176400, 16, 4) data( <CD Audio Raw Data> )
//
//  The number of sectors in a CD-XA CD-DA file is (DataLen/2048).
//  CDFS will expose these files to applications as if they were just
//  'WAVE' files, adjusting the file size so that the RIFF file is valid.
//
//  NT NOTE: We do not do any fidelity adjustment. These are presented as raw
//  2352 byte sectors - 95 has the glimmer of an idea to allow CDFS to expose
//  the CDXA CDDA data at different sampling rates in a virtual directory
//  structure, but we will never do that.
//
 
LONG CdXAAudioPhileHeader[] = {
    0x46464952,                         // Chunk ID = 'RIFF'
    -8,                                 // Chunk Size = (file size - 8) ADJUST1
    0x45564157,                         // 'WAVE'
    0x20746d66,                         // 'fmt '
    16,                                 // Chunk Size (of 'fmt ' subchunk) = 16
    0x00020001,                         // WORD Format Tag WORD nChannels
    44100,                              // DWORD nSamplesPerSecond
    2352 * 75,                          // DWORD nAvgBytesPerSec
    0x00100004,                         // WORD nBlockAlign WORD nBitsPerSample
    0x61746164,                         // 'data'
    -44                                 // <CD Audio Raw Data>          ADJUST2
};
 
//
//  XA Files begin with this RIFF header block to identify the data as
//  raw CD-XA sectors.  Data must be added in 2352-byte multiples.
//
//  This header is added to all CD-XA files which are marked as having
//  mode2form2 sectors.
//
//  Fields marked 'ADJUST' need to be adjusted based on the size of the
//  data: Add file size to the marked DWORDS.
//
//  File Size of TRACK??.WAV = nSectors*2352 + sizeof(XAFileHeader)
//
//  RIFF('CDXA' FMT(Owner, Attr, 'X', 'A', FileNum, 0) data ( <CDXA Raw Data> )
//
 
LONG CdXAFileHeader[] = {
    0x46464952,                         // Chunk ID = 'RIFF'
    -8,                                 // Chunk Size = (file size - 8) ADJUST
    0x41584443,                         // 'CDXA'
    0x20746d66,                         // 'fmt '
    16,                                 // Chunk Size (of CDXA chunk) = 16
    0,                                  // DWORD Owner ID
    0x41580000,                         // WORD Attributes
                                        // BYTE Signature byte 1 'X'
                                        // BYTE Signature byte 2 'A'
    0,                                  // BYTE File Number
    0,                                  // BYTE Reserved[7]
    0x61746164,                         // 'data'
    -44                                 // <CD-XA Raw Sectors>          ADJUST
};
 
#ifdef ALLOC_PRAGMA
#pragma alloc_text(PAGE, CdFastIoCheckIfPossible)
#pragma alloc_text(PAGE, CdSerial32)
#pragma alloc_text(PAGE, CdSetThreadContext)
#endif
 
 
NTSTATUS
CdFsdDispatch (
    _In_ PDEVICE_OBJECT DeviceObject,
    _Inout_ PIRP Irp
    )
 
/*++
 
Routine Description:
 
    This is the driver entry to all of the Fsd dispatch points.
 
    Conceptually the Io routine will call this routine on all requests
    to the file system.  We case on the type of request and invoke the
    correct handler for this type of request.  There is an exception filter
    to catch any exceptions in the CDFS code as well as the CDFS process
    exception routine.
 
    This routine allocates and initializes the IrpContext for this request as
    well as updating the top-level thread context as necessary.  We may loop
    in this routine if we need to retry the request for any reason.  The
    status code STATUS_CANT_WAIT is used to indicate this.  Suppose the disk
    in the drive has changed.  An Fsd request will proceed normally until it
    recognizes this condition.  STATUS_VERIFY_REQUIRED is raised at that point
    and the exception code will handle the verify and either return
    STATUS_CANT_WAIT or STATUS_PENDING depending on whether the request was
    posted.
 
Arguments:
 
    DeviceObject - Supplies the volume device object for this request
 
    Irp - Supplies the Irp being processed
 
Return Value:
 
    NTSTATUS - The FSD status for the IRP
 
--*/
 
{
    THREAD_CONTEXT ThreadContext = {0};
    PIRP_CONTEXT IrpContext = NULL;
    BOOLEAN Wait;
 
#ifdef CD_SANITY
    PVOID PreviousTopLevel;
#endif
 
    NTSTATUS Status;
 
#if DBG
 
    KIRQL SaveIrql = KeGetCurrentIrql();
 
#endif
 
    ASSERT_OPTIONAL_IRP( Irp );
 
    UNREFERENCED_PARAMETER( DeviceObject );
 
    FsRtlEnterFileSystem();
 
#ifdef CD_SANITY
    PreviousTopLevel = IoGetTopLevelIrp();
#endif
 
    //
    //  Loop until this request has been completed or posted.
    //
 
    do {
 
        //
        //  Use a try-except to handle the exception cases.
        //
 
        try {
 
            //
            //  If the IrpContext is NULL then this is the first pass through
            //  this loop.
            //
 
            if (IrpContext == NULL) {
 
                //
                //  Decide if this request is waitable an allocate the IrpContext.
                //  If the file object in the stack location is NULL then this
                //  is a mount which is always waitable.  Otherwise we look at
                //  the file object flags.
                //
 
                if (IoGetCurrentIrpStackLocation( Irp )->FileObject == NULL) {
 
                    Wait = TRUE;
 
                } else {
 
                    Wait = CanFsdWait( Irp );
                }
 
                IrpContext = CdCreateIrpContext( Irp, Wait );
 
                //
                //  Update the thread context information.
                //
 
                CdSetThreadContext( IrpContext, &ThreadContext );
 
#ifdef CD_SANITY
                NT_ASSERT( !CdTestTopLevel ||
                        SafeNodeType( IrpContext->TopLevel ) == CDFS_NTC_IRP_CONTEXT );
#endif
 
            //
            //  Otherwise cleanup the IrpContext for the retry.
            //
 
            } else {
 
                //
                //  Set the MORE_PROCESSING flag to make sure the IrpContext
                //  isn't inadvertently deleted here.  Then cleanup the
                //  IrpContext to perform the retry.
                //
 
                SetFlag( IrpContext->Flags, IRP_CONTEXT_FLAG_MORE_PROCESSING );
                CdCleanupIrpContext( IrpContext, FALSE );
            }
 
            //
            //  Case on the major irp code.
            //
 
            switch (IrpContext->MajorFunction) {
 
            case IRP_MJ_CREATE :
 
                Status = CdCommonCreate( IrpContext, Irp );
                break;
 
            case IRP_MJ_CLOSE :
 
                Status = CdCommonClose( IrpContext, Irp );
                break;
 
            case IRP_MJ_READ :
 
                //
                //  If this is an Mdl complete request, don't go through
                //  common read.
                //
 
                if (FlagOn( IrpContext->MinorFunction, IRP_MN_COMPLETE )) {
 
                    Status = CdCompleteMdl( IrpContext, Irp );
 
                } else {
 
                    Status = CdCommonRead( IrpContext, Irp );
                }
 
                break;
 
            case IRP_MJ_WRITE :
 
                Status = CdCommonWrite( IrpContext, Irp );
                break;
 
            case IRP_MJ_QUERY_INFORMATION :
 
                Status = CdCommonQueryInfo( IrpContext, Irp );
                break;
 
            case IRP_MJ_SET_INFORMATION :
 
                Status = CdCommonSetInfo( IrpContext, Irp );
                break;
 
            case IRP_MJ_QUERY_VOLUME_INFORMATION :
 
                Status = CdCommonQueryVolInfo( IrpContext, Irp );
                break;
 
            case IRP_MJ_DIRECTORY_CONTROL :
 
                Status = CdCommonDirControl( IrpContext, Irp );
                break;
 
            case IRP_MJ_FILE_SYSTEM_CONTROL :
 
                Status = CdCommonFsControl( IrpContext, Irp );
                break;
 
            case IRP_MJ_DEVICE_CONTROL :
 
                Status = CdCommonDevControl( IrpContext, Irp );
                break;
 
            case IRP_MJ_LOCK_CONTROL :
 
                Status = CdCommonLockControl( IrpContext, Irp );
                break;
 
            case IRP_MJ_CLEANUP :
 
                Status = CdCommonCleanup( IrpContext, Irp );
                break;
 
            case IRP_MJ_PNP :
 
                Status = CdCommonPnp( IrpContext, Irp );
                break;
 
            case IRP_MJ_SHUTDOWN :
             
                Status = CdCommonShutdown( IrpContext, Irp );
                break;
 
            default :
 
                Status = STATUS_INVALID_DEVICE_REQUEST;
                CdCompleteRequest( IrpContext, Irp, Status );
            }
 
        } except( CdExceptionFilter( IrpContext, GetExceptionInformation() )) {
 
            Status = CdProcessException( IrpContext, Irp, GetExceptionCode() );
        }
 
    } while (Status == STATUS_CANT_WAIT);
 
#ifdef CD_SANITY
    NT_ASSERT( !CdTestTopLevel ||
            (PreviousTopLevel == IoGetTopLevelIrp()) );
#endif
 
    FsRtlExitFileSystem();
 
    NT_ASSERT( SaveIrql == KeGetCurrentIrql( ));
 
    return Status;
}
 
 
#ifdef CD_SANITY
 
VOID
CdRaiseStatusEx (
    _In_ PIRP_CONTEXT IrpContext,
    _In_ NTSTATUS Status,
    _In_ BOOLEAN NormalizeStatus,
    _In_opt_ ULONG FileId,
    _In_opt_ ULONG Line
    )
{
    BOOLEAN BreakIn = FALSE;
     
    AssertVerifyDevice( IrpContext, Status);
 
    if (CdTraceRaises)  {
 
        DbgPrint( "%p CdRaiseStatusEx 0x%x @ fid %d, line %d\n", PsGetCurrentThread(), Status, FileId, Line);
    }
 
    if (CdTestRaisedStatus && !CdBreakOnAnyRaise)  {
 
        ULONG Index;
 
        for (Index = 0;
             Index < (sizeof( CdInterestingExceptionCodes) / sizeof( CdInterestingExceptionCodes[0]));
             Index++)  {
 
            if ((STATUS_SUCCESS != CdInterestingExceptionCodes[Index]) &&
                (CdInterestingExceptionCodes[Index] == Status))  {
 
                BreakIn = TRUE;
                break;
            }
        }
    }
 
    if (BreakIn || CdBreakOnAnyRaise)  {
         
        DbgPrint( "CDFS: Breaking on raised status %08x  (BI=%d,BA=%d)\n", Status, BreakIn, CdBreakOnAnyRaise);
        DbgPrint( "CDFS: (FILEID %d LINE %d)\n", FileId, Line);
        DbgPrint( "CDFS: Contact CDFS.SYS component owner for triage.\n");
        DbgPrint( "CDFS: 'eb %p 0;eb %p 0' to disable this alert.\n", &CdTestRaisedStatus, &CdBreakOnAnyRaise);
 
        NT_ASSERT(FALSE);
    }
     
    if (NormalizeStatus)  {
 
        IrpContext->ExceptionStatus = FsRtlNormalizeNtstatus( Status, STATUS_UNEXPECTED_IO_ERROR);
    }
    else {
 
        IrpContext->ExceptionStatus = Status;
    }
 
    IrpContext->RaisedAtLineFile = (FileId << 16) | Line;
     
    ExRaiseStatus( IrpContext->ExceptionStatus);
}
 
#endif
 
 
LONG
CdExceptionFilter (
    _Inout_ PIRP_CONTEXT IrpContext,
    _In_ PEXCEPTION_POINTERS ExceptionPointer
    )
 
/*++
 
Routine Description:
 
    This routine is used to decide whether we will handle a raised exception
    status.  If CDFS explicitly raised an error then this status is already
    in the IrpContext.  We choose which is the correct status code and
    either indicate that we will handle the exception or bug-check the system.
 
Arguments:
 
    ExceptionCode - Supplies the exception code to being checked.
 
Return Value:
 
    ULONG - returns EXCEPTION_EXECUTE_HANDLER or bugchecks
 
--*/
 
{
    NTSTATUS ExceptionCode;
    BOOLEAN TestStatus = TRUE;
 
    ASSERT_OPTIONAL_IRP_CONTEXT( IrpContext );
 
    ExceptionCode = ExceptionPointer->ExceptionRecord->ExceptionCode;
 
    //
    // If the exception is STATUS_IN_PAGE_ERROR, get the I/O error code
    // from the exception record.
    //
 
    if ((ExceptionCode == STATUS_IN_PAGE_ERROR) &&
        (ExceptionPointer->ExceptionRecord->NumberParameters >= 3)) {
 
        ExceptionCode =
            (NTSTATUS)ExceptionPointer->ExceptionRecord->ExceptionInformation[2];
    }
 
    //
    //  If there is an Irp context then check which status code to use.
    //
 
    if (ARGUMENT_PRESENT( IrpContext )) {
 
        if (IrpContext->ExceptionStatus == STATUS_SUCCESS) {
 
            //
            //  Store the real status into the IrpContext.
            //
 
            IrpContext->ExceptionStatus = ExceptionCode;
 
        } else {
 
            //
            //  No need to test the status code if we raised it ourselves.
            //
 
            TestStatus = FALSE;
        }
    }
 
    AssertVerifyDevice( IrpContext, IrpContext->ExceptionStatus );
     
    //
    //  Bug check if this status is not supported.
    //
 
    if (TestStatus && !FsRtlIsNtstatusExpected( ExceptionCode )) {
 
#pragma prefast( suppress: __WARNING_USE_OTHER_FUNCTION, "We're corrupted." )   
        CdBugCheck( (ULONG_PTR) ExceptionPointer->ExceptionRecord,
                    (ULONG_PTR) ExceptionPointer->ContextRecord,
                    (ULONG_PTR) ExceptionPointer->ExceptionRecord->ExceptionAddress );
 
    }
 
    return EXCEPTION_EXECUTE_HANDLER;
}
 
 
_Requires_lock_held_(_Global_critical_region_)
NTSTATUS
CdProcessException (
    _In_opt_ PIRP_CONTEXT IrpContext,
    _Inout_ PIRP Irp,
    _In_ NTSTATUS ExceptionCode
    )
 
/*++
 
Routine Description:
 
    This routine processes an exception.  It either completes the request
    with the exception status in the IrpContext, sends this off to the Fsp
    workque or causes it to be retried in the current thread if a verification
    is needed.
 
    If the volume needs to be verified (STATUS_VERIFY_REQUIRED) and we can
    do the work in the current thread we will translate the status code
    to STATUS_CANT_WAIT to indicate that we need to retry the request.
 
Arguments:
 
    Irp - Supplies the Irp being processed
 
    ExceptionCode - Supplies the normalized exception status being handled
 
Return Value:
 
    NTSTATUS - Returns the results of either posting the Irp or the
        saved completion status.
 
--*/
 
{
    PDEVICE_OBJECT Device = NULL;
    PVPB Vpb;
    PETHREAD Thread;
 
    ASSERT_OPTIONAL_IRP_CONTEXT( IrpContext );
    ASSERT_IRP( Irp );
     
    //
    //  If there is not an irp context, then complete the request with the
    //  current status code.
    //
 
    if (!ARGUMENT_PRESENT( IrpContext )) {
 
        CdCompleteRequest( NULL, Irp, ExceptionCode );
        return ExceptionCode;
    }
 
    //
    //  Get the real exception status from the IrpContext.
    //
 
    ExceptionCode = IrpContext->ExceptionStatus;
 
    //
    //  Check if we are posting this request.  One of the following must be true
    //  if we are to post a request.
    //
    //      - Status code is STATUS_CANT_WAIT and the request is asynchronous
    //          or we are forcing this to be posted.
    //
    //      - Status code is STATUS_VERIFY_REQUIRED and we are at APC level
    //          or higher, or within a guarded region.  Can't wait for IO in
    //          the verify path in this case.
    //
    //  Set the MORE_PROCESSING flag in the IrpContext to keep if from being
    //  deleted if this is a retryable condition.
    //
    //
    //  Note that (children of) CdFsdPostRequest can raise (Mdl allocation).
    //
 
    try {
 
        if (ExceptionCode == STATUS_CANT_WAIT) {
 
            if (FlagOn( IrpContext->Flags, IRP_CONTEXT_FLAG_FORCE_POST )) {
 
                ExceptionCode = CdFsdPostRequest( IrpContext, Irp );
            }
        }
        else if ((ExceptionCode == STATUS_VERIFY_REQUIRED) &&
                 FlagOn( IrpContext->Flags, IRP_CONTEXT_FLAG_TOP_LEVEL ) &&
                 KeAreAllApcsDisabled()) {
                  
            ExceptionCode = CdFsdPostRequest( IrpContext, Irp );
        }
    }
    except( CdExceptionFilter( IrpContext, GetExceptionInformation() ))  {
     
        ExceptionCode = GetExceptionCode();       
    }
     
    //
    //  If we posted the request or our caller will retry then just return here.
    //
 
    if ((ExceptionCode == STATUS_PENDING) ||
        (ExceptionCode == STATUS_CANT_WAIT)) {
 
        return ExceptionCode;
    }
 
    ClearFlag( IrpContext->Flags, IRP_CONTEXT_FLAG_MORE_PROCESSING );
 
    //
    //  If we are not a top level request then we just complete the request
    //  with the current status code.
    //
 
    if (!FlagOn( IrpContext->Flags, IRP_CONTEXT_FLAG_TOP_LEVEL )) {
 
        CdCompleteRequest( IrpContext, Irp, ExceptionCode );
        return ExceptionCode;
    }
 
    //
    //  Store this error into the Irp for posting back to the Io system.
    //
 
    Irp->IoStatus.Status = ExceptionCode;
 
    if (IoIsErrorUserInduced( ExceptionCode )) {
 
        //
        //  Check for the various error conditions that can be caused by,
        //  and possibly resolved my the user.
        //
 
        if (ExceptionCode == STATUS_VERIFY_REQUIRED) {
 
            //
            //  Now we are at the top level file system entry point.
            //
            //  If we have already posted this request then the device to
            //  verify is in the original thread.  Find this via the Irp.
            //
 
            Device = IoGetDeviceToVerify( Irp->Tail.Overlay.Thread );
            IoSetDeviceToVerify( Irp->Tail.Overlay.Thread, NULL );
             
            //
            //  If there is no device in that location then check in the
            //  current thread.
            //
 
            if (Device == NULL) {
 
                Device = IoGetDeviceToVerify( PsGetCurrentThread() );
                IoSetDeviceToVerify( PsGetCurrentThread(), NULL );
 
                NT_ASSERT( Device != NULL );
 
            }
 
            //
            //  It turns out some storage drivers really do set invalid non-NULL device
            //  objects to verify.
            //
            //  To work around this, completely ignore the device to verify in the thread,
            //  and just use our real device object instead.
            //
 
            if (IrpContext->Vcb) {
 
                Device = IrpContext->Vcb->Vpb->RealDevice;
            }
 
            //
            //  Let's not BugCheck just because the device to verify is somehow still NULL.
            //
 
            if (Device == NULL) {
 
                ExceptionCode = STATUS_DRIVER_INTERNAL_ERROR;
 
                CdCompleteRequest( IrpContext, Irp, ExceptionCode );
 
                return ExceptionCode;
            }
 
            //
            //  CdPerformVerify() will do the right thing with the Irp.
            //  If we return STATUS_CANT_WAIT then the current thread
            //  can retry the request.
            //
 
            return CdPerformVerify( IrpContext, Irp, Device );
        }
 
        //
        //  The other user induced conditions generate an error unless
        //  they have been disabled for this request.
        //
 
        if (FlagOn( IrpContext->Flags, IRP_CONTEXT_FLAG_DISABLE_POPUPS )) {
 
            CdCompleteRequest( IrpContext, Irp, ExceptionCode );
 
            return ExceptionCode;
 
        }
        //
        //  Generate a pop-up.
        //
        else {
 
            if (IoGetCurrentIrpStackLocation( Irp )->FileObject != NULL) {
 
                Vpb = IoGetCurrentIrpStackLocation( Irp )->FileObject->Vpb;
 
            } else {
 
                Vpb = NULL;
            }
 
 
            //
            //  The device to verify is either in my thread local storage
            //  or that of the thread that owns the Irp.
            //
 
            Thread = Irp->Tail.Overlay.Thread;
            Device = IoGetDeviceToVerify( Thread );
 
            if (Device == NULL) {
 
                Thread = PsGetCurrentThread();
                Device = IoGetDeviceToVerify( Thread );
 
                NT_ASSERT( Device != NULL );
            }
 
            //
            //  It turns out some storage drivers really do set invalid non-NULL device
            //  objects to verify.
            //
            //  To work around this, completely ignore the device to verify in the thread,
            //  and just use our real device object instead.
            //
 
            if (IrpContext->Vcb) {
 
                Device = IrpContext->Vcb->Vpb->RealDevice;
            }
 
            //
            //  Let's not BugCheck just because the device to verify is somehow still NULL.
            //
 
            if (Device == NULL) {
 
                CdCompleteRequest( IrpContext, Irp, ExceptionCode );
 
                return ExceptionCode;
            }
 
            //
            //  This routine actually causes the pop-up.  It usually
            //  does this by queuing an APC to the callers thread,
            //  but in some cases it will complete the request immediately,
            //  so it is very important to IoMarkIrpPending() first.
            //
 
            IoMarkIrpPending( Irp );
            IoRaiseHardError( Irp, Vpb, Device );
 
            //
            //  We will be handing control back to the caller here, so
            //  reset the saved device object.
            //
 
            IoSetDeviceToVerify( Thread, NULL );
 
            //
            //  The Irp will be completed by Io or resubmitted.  In either
            //  case we must clean up the IrpContext here.
            //
 
            CdCompleteRequest( IrpContext, NULL, STATUS_SUCCESS );
            return STATUS_PENDING;
        }
    }
 
    //
    //  This is just a run of the mill error.
    //
 
    CdCompleteRequest( IrpContext, Irp, ExceptionCode );
 
    return ExceptionCode;
}
 
VOID
CdCompleteRequest (
    _Inout_opt_ PIRP_CONTEXT IrpContext,
    _Inout_opt_ PIRP Irp,
    _In_ NTSTATUS Status
    )
 
/*++
 
Routine Description:
 
    This routine completes a Irp and cleans up the IrpContext.  Either or
    both of these may not be specified.
 
Arguments:
 
    Irp - Supplies the Irp being processed.
 
    Status - Supplies the status to complete the Irp with
 
Return Value:
 
    None.
 
--*/
 
{
    ASSERT_OPTIONAL_IRP_CONTEXT( IrpContext );
    ASSERT_OPTIONAL_IRP( Irp );
 
    //
    //  Cleanup the IrpContext if passed in here.
    //
 
    if (ARGUMENT_PRESENT( IrpContext )) {
 
        CdCleanupIrpContext( IrpContext, FALSE );
    }
 
    //
    //  If we have an Irp then complete the irp.
    //
 
    if (ARGUMENT_PRESENT( Irp )) {
 
        //
        //  Clear the information field in case we have used this Irp
        //  internally.
        //
 
        if (NT_ERROR( Status ) &&
            FlagOn( Irp->Flags, IRP_INPUT_OPERATION )) {
 
            Irp->IoStatus.Information = 0;
        }
 
        Irp->IoStatus.Status = Status;
 
        AssertVerifyDeviceIrp( Irp );
         
        IoCompleteRequest( Irp, IO_CD_ROM_INCREMENT );
    }
 
    return;
}
 
VOID
CdSetThreadContext (
    _Inout_ PIRP_CONTEXT IrpContext,
    _In_ PTHREAD_CONTEXT ThreadContext
    )
 
/*++
 
Routine Description:
 
    This routine is called at each Fsd/Fsp entry point set up the IrpContext
    and thread local storage to track top level requests.  If there is
    not a Cdfs context in the thread local storage then we use the input one.
    Otherwise we use the one already there.  This routine also updates the
    IrpContext based on the state of the top-level context.
 
    If the TOP_LEVEL flag in the IrpContext is already set when we are called
    then we force this request to appear top level.
 
Arguments:
 
    ThreadContext - Address on stack for local storage if not already present.
 
    ForceTopLevel - We force this request to appear top level regardless of
        any previous stack value.
 
Return Value:
 
    None
 
--*/
 
{
    PTHREAD_CONTEXT CurrentThreadContext;
 
    PAGED_CODE();
 
    ASSERT_IRP_CONTEXT( IrpContext );
 
    //
    //  Get the current top-level irp out of the thread storage.
    //  If NULL then this is the top-level request.
    //
 
    CurrentThreadContext = (PTHREAD_CONTEXT) IoGetTopLevelIrp();
 
    if (CurrentThreadContext == NULL) {
 
        SetFlag( IrpContext->Flags, IRP_CONTEXT_FLAG_TOP_LEVEL );
    }
 
    //
    //  Initialize the input context unless we are using the current
    //  thread context block.  We use the new block if our caller
    //  specified this or the existing block is invalid.
    //
    //  The following must be true for the current to be a valid Cdfs context.
    //
    //      Structure must lie within current stack.
    //      Address must be ULONG aligned.
    //      Cdfs signature must be present.
    //
    //  If this is not a valid Cdfs context then use the input thread
    //  context and store it in the top level context.
    //
#pragma warning(suppress: 6011) // Bug in PREFast around bitflag operations
    if (FlagOn( IrpContext->Flags, IRP_CONTEXT_FLAG_TOP_LEVEL ) ||
        (!IoWithinStackLimits( (ULONG_PTR)CurrentThreadContext, sizeof( THREAD_CONTEXT ) ) ||
         FlagOn( (ULONG_PTR) CurrentThreadContext, 0x3 ) ||
         (CurrentThreadContext->Cdfs != 0x53464443))) {
 
        ThreadContext->Cdfs = 0x53464443;
        ThreadContext->SavedTopLevelIrp = (PIRP) CurrentThreadContext;
        ThreadContext->TopLevelIrpContext = IrpContext;
        IoSetTopLevelIrp( (PIRP) ThreadContext );
 
        IrpContext->TopLevel = IrpContext;
        IrpContext->ThreadContext = ThreadContext;
 
        SetFlag( IrpContext->Flags, IRP_CONTEXT_FLAG_TOP_LEVEL_CDFS );
 
    //
    //  Otherwise use the IrpContext in the thread context.
    //
 
    } else {
 
        IrpContext->TopLevel = CurrentThreadContext->TopLevelIrpContext;
    }
 
    return;
}
 
 
_Function_class_(FAST_IO_CHECK_IF_POSSIBLE)
_IRQL_requires_same_
_Success_(return != FALSE)
BOOLEAN
CdFastIoCheckIfPossible (
    _In_ PFILE_OBJECT FileObject,
    _In_ PLARGE_INTEGER FileOffset,
    _In_ ULONG Length,
    _In_ BOOLEAN Wait,
    _In_ ULONG LockKey,
    _In_ BOOLEAN CheckForReadOperation,
    _Pre_notnull_
    _When_(return != FALSE, _Post_equal_to_(_Old_(IoStatus)))
    _When_(return == FALSE, _Post_valid_)
    PIO_STATUS_BLOCK IoStatus,
    _In_ PDEVICE_OBJECT DeviceObject
    )
 
/*++
 
Routine Description:
 
    This routine checks if fast i/o is possible for a read/write operation
 
Arguments:
 
    FileObject - Supplies the file object used in the query
 
    FileOffset - Supplies the starting byte offset for the read/write operation
 
    Length - Supplies the length, in bytes, of the read/write operation
 
    Wait - Indicates if we can wait
 
    LockKey - Supplies the lock key
 
    CheckForReadOperation - Indicates if this is a check for a read or write
        operation
 
    IoStatus - Receives the status of the operation if our return value is
        FastIoReturnError
 
Return Value:
 
    BOOLEAN - TRUE if fast I/O is possible and FALSE if the caller needs
        to take the long route.
 
--*/
 
{
    PFCB Fcb;
    TYPE_OF_OPEN TypeOfOpen;
    LARGE_INTEGER LargeLength;
 
    PAGED_CODE();
 
    UNREFERENCED_PARAMETER( Wait );
    UNREFERENCED_PARAMETER( DeviceObject );
 
    //
    //  Decode the type of file object we're being asked to process and
    //  make sure that is is only a user file open.
    //
 
    TypeOfOpen = CdFastDecodeFileObject( FileObject, &Fcb );
 
    if ((TypeOfOpen != UserFileOpen) || !CheckForReadOperation) {
 
        IoStatus->Status = STATUS_INVALID_PARAMETER;
        return TRUE;
    }
 
    LargeLength.QuadPart = Length;
 
    //
    //  Check whether the file locks will allow for fast io.
    //
 
    if ((Fcb->FileLock == NULL) ||
        FsRtlFastCheckLockForRead( Fcb->FileLock,
                                   FileOffset,
                                   &LargeLength,
                                   LockKey,
                                   FileObject,
                                   PsGetCurrentProcess() )) {
 
        return TRUE;
    }
 
    return FALSE;
}
 
ULONG
CdSerial32 (
    _In_reads_bytes_(ByteCount) PCHAR Buffer,
    _In_ ULONG ByteCount
    )
/*++
 
Routine Description:
 
    This routine is called to generate a 32 bit serial number.  This is
    done by doing four separate checksums into an array of bytes and
    then treating the bytes as a ULONG.
 
Arguments:
 
    Buffer - Pointer to the buffer to generate the ID for.
 
    ByteCount - Number of bytes in the buffer.
 
Return Value:
 
    ULONG - The 32 bit serial number.
 
--*/
 
{
    union {
        UCHAR   Bytes[4];
        ULONG   SerialId;
    } Checksum;
 
    PAGED_CODE();
 
    //
    //  Initialize the serial number.
    //
 
    Checksum.SerialId = 0;
 
    //
    //  Continue while there are more bytes to use.
    //
 
    while (ByteCount--) {
 
        //
        //  Increment this sub-checksum.
        //
 
        Checksum.Bytes[ByteCount & 0x3] += *(Buffer++);
    }
 
    //
    //  Return the checksums as a ULONG.
    //
 
    return Checksum.SerialId;
}

Our Services

  • What our customers say about us?

© 2011-2025 All Rights Reserved. Joya Systems. 4425 South Mopac Building II Suite 101 Austin, TX 78735 Tel: 800-DEV-KERNEL

Privacy Policy. Terms of use. Valid XHTML & CSS