3 Copyright (c) 1989-2000 Microsoft Corporation
11 This module implements the low lever disk read/write support for Cdfs.
19 // The Bug check file id for this module
22 #define BugCheckFileId (CDFS_BUG_CHECK_DEVIOSUP)
25 // Local structure definitions
29 // An array of these structures is passed to CdMultipleAsync describing
30 // a set of runs to execute in parallel.
33 typedef struct _IO_RUN
{
36 // Disk offset to read from and number of bytes to read. These
37 // must be a multiple of 2048 and the disk offset is also a
45 // Current position in user buffer. This is the final destination for
46 // this portion of the Io transfer.
52 // Buffer to perform the transfer to. If this is the same as the
53 // user buffer above then we are using the user's buffer. Otherwise
54 // we either allocated a temporary buffer or are using a different portion
55 // of the user's buffer.
57 // TransferBuffer - Read full sectors into this location. This can
58 // be a pointer into the user's buffer at the exact location the
59 // data should go. It can also be an earlier point in the user's
60 // buffer if the complete I/O doesn't start on a sector boundary.
61 // It may also be a pointer into an allocated buffer.
63 // TransferByteCount - Count of bytes to transfer to user's buffer. A
64 // value of zero indicates that we did do the transfer into the
65 // user's buffer directly.
67 // TransferBufferOffset - Offset in this buffer to begin the transfer
68 // to the user's buffer.
72 ULONG TransferByteCount
;
73 ULONG TransferBufferOffset
;
76 // This is the Mdl describing the locked pages in memory. It may
77 // be allocated to describe the allocated buffer. Or it may be
78 // the Mdl in the originating Irp. The MdlOffset is the offset of
79 // the current buffer from the beginning of the buffer described by
80 // the Mdl below. If the TransferMdl is not the same as the Mdl
81 // in the user's Irp then we know we have allocated it.
85 PVOID TransferVirtualAddress
;
88 // Associated Irp used to perform the Io.
94 typedef IO_RUN
*PIO_RUN
;
96 #define MAX_PARALLEL_IOS 5
99 // Local support routines
102 _Requires_lock_held_(_Global_critical_region_
)
105 _In_ PIRP_CONTEXT IrpContext
,
108 _In_reads_bytes_(ByteCount
) PVOID UserBuffer
,
109 _In_ ULONG UserBufferOffset
,
110 _In_ LONGLONG StartingOffset
,
111 _In_ ULONG ByteCount
,
112 _Out_ PIO_RUN IoRuns
,
113 _Out_ PULONG RunCount
,
114 _Out_ PULONG ThisByteCount
117 _Requires_lock_held_(_Global_critical_region_
)
120 _In_ PIRP_CONTEXT IrpContext
,
123 _In_reads_bytes_(ByteCount
) PVOID UserBuffer
,
124 _In_ ULONG UserBufferOffset
,
125 _In_ LONGLONG StartingOffset
,
126 _In_ ULONG ByteCount
,
127 _Out_ PIO_RUN IoRuns
,
128 _Out_ PULONG RunCount
,
129 _Out_ PULONG ThisByteCount
134 _In_ PIRP_CONTEXT IrpContext
,
135 _Inout_ PIO_RUN IoRuns
,
137 _In_ BOOLEAN FinalCleanup
,
138 _In_ BOOLEAN SaveXABuffer
141 _Requires_lock_held_(_Global_critical_region_
)
144 _In_ PIRP_CONTEXT IrpContext
,
147 _Inout_ PIO_RUN IoRuns
152 _In_ PIRP_CONTEXT IrpContext
,
154 _Inout_ PIO_RUN IoRuns
,
155 _In_ PRAW_READ_INFO RawReads
,
156 _In_ TRACK_MODE_TYPE TrackMode
159 _Requires_lock_held_(_Global_critical_region_
)
162 _In_ PIRP_CONTEXT IrpContext
,
169 _In_ PIRP_CONTEXT IrpContext
172 // Tell prefast this is a completion routine.
173 IO_COMPLETION_ROUTINE CdMultiSyncCompletionRoutine
;
175 // Tell prefast this is a completion routine
176 IO_COMPLETION_ROUTINE CdMultiAsyncCompletionRoutine
;
178 // Tell prefast this is a completion routine
179 IO_COMPLETION_ROUTINE CdSingleSyncCompletionRoutine
;
181 // Tell prefast this is a completion routine
182 IO_COMPLETION_ROUTINE CdSingleAsyncCompletionRoutine
;
184 _When_(SafeNodeType(Fcb
) != CDFS_NTC_FCB_PATH_TABLE
&& StartingOffset
== 0, _At_(ByteCount
, _In_range_(>=, CdAudioDirentSize
+ sizeof(RAW_DIRENT
))))
185 _When_(SafeNodeType(Fcb
) != CDFS_NTC_FCB_PATH_TABLE
&& StartingOffset
!= 0, _At_(ByteCount
, _In_range_(>=, CdAudioDirentSize
+ SECTOR_SIZE
)))
187 CdReadAudioSystemFile (
188 _In_ PIRP_CONTEXT IrpContext
,
190 _In_ LONGLONG StartingOffset
,
191 _In_
_In_range_(>=, CdAudioDirentSize
) ULONG ByteCount
,
192 _Out_writes_bytes_(ByteCount
) PVOID SystemBuffer
195 _Requires_lock_held_(_Global_critical_region_
)
197 CdReadDirDataThroughCache (
198 _In_ PIRP_CONTEXT IrpContext
,
203 #pragma alloc_text(PAGE, CdCreateUserMdl)
204 #pragma alloc_text(PAGE, CdMultipleAsync)
205 #pragma alloc_text(PAGE, CdMultipleXAAsync)
206 #pragma alloc_text(PAGE, CdNonCachedRead)
207 #pragma alloc_text(PAGE, CdNonCachedXARead)
208 #pragma alloc_text(PAGE, CdVolumeDasdWrite)
209 #pragma alloc_text(PAGE, CdFinishBuffers)
210 #pragma alloc_text(PAGE, CdPerformDevIoCtrl)
211 #pragma alloc_text(PAGE, CdPerformDevIoCtrlEx)
212 #pragma alloc_text(PAGE, CdPrepareBuffers)
213 #pragma alloc_text(PAGE, CdPrepareXABuffers)
214 #pragma alloc_text(PAGE, CdReadAudioSystemFile)
215 #pragma alloc_text(PAGE, CdReadSectors)
216 #pragma alloc_text(PAGE, CdSingleAsync)
217 #pragma alloc_text(PAGE, CdWaitSync)
218 #pragma alloc_text(PAGE, CdReadDirDataThroughCache)
219 #pragma alloc_text(PAGE, CdFreeDirCache)
220 #pragma alloc_text(PAGE, CdLbnToMmSsFf)
221 #pragma alloc_text(PAGE, CdHijackIrpAndFlushDevice)
228 _Out_writes_(3) PUCHAR Msf
235 Convert Lbn to MSF format.
239 Msf - on output, set to 0xMmSsFf representation of blocks.
246 Blocks
+= 150; // Lbn 0 == 00:02:00, 1sec == 75 frames.
248 Msf
[0] = (UCHAR
)(Blocks
% 75); // Frames
249 Blocks
/= 75; // -> Seconds
250 Msf
[1] = (UCHAR
)(Blocks
% 60); // Seconds
251 Blocks
/= 60; // -> Minutes
252 Msf
[2] = (UCHAR
)Blocks
; // Minutes
266 This routine converts FCB XA file type flags to the track mode
267 used by the device drivers.
271 Fcb - Fcb representing the file to read.
275 TrackMode of the file represented by the Fcb.
279 NT_ASSERT( FlagOn( Fcb
->FcbState
, FCB_STATE_MODE2FORM2_FILE
|
280 FCB_STATE_MODE2_FILE
|
281 FCB_STATE_DA_FILE
));
283 if (FlagOn( Fcb
->FcbState
, FCB_STATE_MODE2FORM2_FILE
)) {
287 } else if (FlagOn( Fcb
->FcbState
, FCB_STATE_DA_FILE
)) {
294 // FCB_STATE_MODE2_FILE
301 _Requires_lock_held_(_Global_critical_region_
)
304 _In_ PIRP_CONTEXT IrpContext
,
306 _In_ LONGLONG StartingOffset
,
314 This routine performs the non-cached reads to 'cooked' sectors (2048 bytes
315 per sector). This is done by performing the following in a loop.
317 Fill in the IoRuns array for the next block of Io.
318 Send the Io to the device.
319 Perform any cleanup on the Io runs array.
321 We will not do async Io to any request that generates non-aligned Io.
322 Also we will not perform async Io if it will exceed the size of our
323 IoRuns array. These should be the unusual cases but we will raise
324 or return CANT_WAIT in this routine if we detect this case.
328 Fcb - Fcb representing the file to read.
330 StartingOffset - Logical offset in the file to read from.
332 ByteCount - Number of bytes to read.
336 NTSTATUS - Status indicating the result of the operation.
341 NTSTATUS Status
= STATUS_SUCCESS
;
343 IO_RUN IoRuns
[MAX_PARALLEL_IOS
];
345 ULONG CleanupRunCount
= 0;
348 ULONG UserBufferOffset
= 0;
349 LONGLONG CurrentOffset
= StartingOffset
;
350 ULONG RemainingByteCount
= ByteCount
;
354 BOOLEAN FlushIoBuffers
= FALSE
;
355 BOOLEAN FirstPass
= TRUE
;
360 // We want to make sure the user's buffer is locked in all cases.
363 if (IrpContext
->Irp
->MdlAddress
== NULL
) {
365 CdCreateUserMdl( IrpContext
, ByteCount
, TRUE
, IoWriteAccess
);
368 CdMapUserBuffer( IrpContext
, &UserBuffer
);
371 // Special case the root directory and path table for a music volume.
374 if (FlagOn( Fcb
->Vcb
->VcbState
, VCB_STATE_AUDIO_DISK
) &&
375 ((SafeNodeType( Fcb
) == CDFS_NTC_FCB_INDEX
) ||
376 (SafeNodeType( Fcb
) == CDFS_NTC_FCB_PATH_TABLE
))) {
378 CdReadAudioSystemFile( IrpContext
,
384 return STATUS_SUCCESS
;
388 // If we're going to use the sector cache for this request, then
389 // mark the request waitable.
392 if ((SafeNodeType( Fcb
) == CDFS_NTC_FCB_INDEX
) &&
393 (NULL
!= Fcb
->Vcb
->SectorCacheBuffer
) &&
394 (VcbMounted
== IrpContext
->Vcb
->VcbCondition
)) {
396 if (!FlagOn( IrpContext
->Flags
, IRP_CONTEXT_FLAG_WAIT
)) {
398 KeInitializeEvent( &IrpContext
->IoContext
->SyncEvent
,
402 SetFlag( IrpContext
->Flags
, IRP_CONTEXT_FLAG_WAIT
);
407 // Use a try-finally to perform the final cleanup.
413 // Loop while there are more bytes to transfer.
419 // Call prepare buffers to set up the next entries
420 // in the IoRuns array. Remember if there are any
421 // unaligned entries. This routine will raise CANT_WAIT
422 // if there are unaligned entries for an async request.
425 RtlZeroMemory( IoRuns
, sizeof( IoRuns
));
427 Unaligned
= CdPrepareBuffers( IrpContext
,
439 RunCount
= CleanupRunCount
;
442 // If this is an async request and there aren't enough entries
443 // in the Io array then post the request.
446 if ((ThisByteCount
< RemainingByteCount
) &&
447 !FlagOn( IrpContext
->Flags
, IRP_CONTEXT_FLAG_WAIT
)) {
449 CdRaiseStatus( IrpContext
, STATUS_CANT_WAIT
);
453 // If the entire Io is contained in a single run then
454 // we can pass the Io down to the driver. Send the driver down
455 // and wait on the result if this is synchronous.
458 if ((RunCount
== 1) && !Unaligned
&& FirstPass
) {
460 CdSingleAsync( IrpContext
,&IoRuns
[0], Fcb
);
463 // No cleanup needed for the IoRuns array here.
469 // Wait if we are synchronous, otherwise return
472 if (FlagOn( IrpContext
->Flags
, IRP_CONTEXT_FLAG_WAIT
)) {
474 CdWaitSync( IrpContext
);
476 Status
= IrpContext
->Irp
->IoStatus
.Status
;
479 // Our completion routine will free the Io context but
480 // we do want to return STATUS_PENDING.
485 ClearFlag( IrpContext
->Flags
, IRP_CONTEXT_FLAG_ALLOC_IO
);
486 Status
= STATUS_PENDING
;
489 try_return( NOTHING
);
493 // Otherwise we will perform multiple Io to read in the data.
496 CdMultipleAsync( IrpContext
, Fcb
, RunCount
, IoRuns
);
499 // If this is a synchronous request then perform any necessary
503 if (FlagOn( IrpContext
->Flags
, IRP_CONTEXT_FLAG_WAIT
)) {
506 // Wait for the request to complete.
509 CdWaitSync( IrpContext
);
511 Status
= IrpContext
->Irp
->IoStatus
.Status
;
514 // Exit this loop if there is an error.
517 if (!NT_SUCCESS( Status
)) {
519 try_return( NOTHING
);
523 // Perform post read operations on the IoRuns if
528 CdFinishBuffers( IrpContext
, IoRuns
, RunCount
, FALSE
, FALSE
)) {
530 FlushIoBuffers
= TRUE
;
536 // Exit this loop if there are no more bytes to transfer
537 // or we have any error.
540 RemainingByteCount
-= ThisByteCount
;
541 CurrentOffset
+= ThisByteCount
;
542 UserBuffer
= Add2Ptr( UserBuffer
, ThisByteCount
, PVOID
);
543 UserBufferOffset
+= ThisByteCount
;
546 // Otherwise this is an asynchronous request. Always return
552 ClearFlag( IrpContext
->Flags
, IRP_CONTEXT_FLAG_ALLOC_IO
);
554 try_return( Status
= STATUS_PENDING
);
559 } while (RemainingByteCount
!= 0);
562 // Flush the hardware cache if we performed any copy operations.
565 if (FlushIoBuffers
) {
567 KeFlushIoBuffers( IrpContext
->Irp
->MdlAddress
, TRUE
, FALSE
);
574 // Perform final cleanup on the IoRuns if necessary.
577 if (CleanupRunCount
!= 0) {
579 CdFinishBuffers( IrpContext
, IoRuns
, CleanupRunCount
, TRUE
, FALSE
);
588 _Requires_lock_held_(_Global_critical_region_
)
591 _In_ PIRP_CONTEXT IrpContext
,
593 _In_ LONGLONG StartingOffset
,
601 This routine performs the non-cached reads for 'raw' sectors (2352 bytes
602 per sector). We also prepend a hard-coded RIFF header of 44 bytes to the file.
603 All of this is already reflected in the file size.
605 We start by checking whether to prepend any portion of the RIFF header. Then we check
606 if the last raw sector read was from the beginning portion of this file, deallocating
607 that buffer if necessary. Finally we do the following in a loop.
609 Fill the IoRuns array for the next block of Io.
610 Send the Io to the device driver.
611 Perform any cleanup necessary on the IoRuns array.
613 We will not do any async request in this path. The request would have been
614 posted to a worker thread before getting to this point.
618 Fcb - Fcb representing the file to read.
620 StartingOffset - Logical offset in the file to read from.
622 ByteCount - Number of bytes to read.
626 NTSTATUS - Status indicating the result of the operation.
631 NTSTATUS Status
= STATUS_SUCCESS
;
633 RIFF_HEADER LocalRiffHeader
;
634 PRIFF_HEADER RiffHeader
;
636 RAW_READ_INFO RawReads
[MAX_PARALLEL_IOS
];
637 IO_RUN IoRuns
[MAX_PARALLEL_IOS
];
639 ULONG CleanupRunCount
= 0;
642 ULONG UserBufferOffset
= 0;
643 LONGLONG CurrentOffset
= StartingOffset
;
644 ULONG RemainingByteCount
= ByteCount
;
645 ULONG ThisByteCount
= 0;
648 BOOLEAN TryingYellowbookMode2
= FALSE
;
650 TRACK_MODE_TYPE TrackMode
;
655 // We want to make sure the user's buffer is locked in all cases.
658 if (IrpContext
->Irp
->MdlAddress
== NULL
) {
660 CdCreateUserMdl( IrpContext
, ByteCount
, TRUE
, IoWriteAccess
);
664 // The byte count was rounded up to a logical sector boundary. It has
665 // nothing to do with the raw sectors on disk. Limit the remaining
666 // byte count to file size.
669 if (CurrentOffset
+ RemainingByteCount
> Fcb
->FileSize
.QuadPart
) {
671 RemainingByteCount
= (ULONG
) (Fcb
->FileSize
.QuadPart
- CurrentOffset
);
674 CdMapUserBuffer( IrpContext
, &UserBuffer
);
677 // Use a try-finally to perform the final cleanup.
683 // If the initial offset lies within the RIFF header then copy the
684 // necessary bytes to the user's buffer.
687 if (CurrentOffset
< sizeof( RIFF_HEADER
)) {
690 // Copy the appropriate RIFF header.
693 if (FlagOn( Fcb
->FcbState
, FCB_STATE_DA_FILE
)) {
696 // Create the pseudo entries for a music disk.
699 if (FlagOn( Fcb
->Vcb
->VcbState
, VCB_STATE_AUDIO_DISK
)) {
701 PAUDIO_PLAY_HEADER AudioPlayHeader
;
702 PTRACK_DATA TrackData
;
704 AudioPlayHeader
= (PAUDIO_PLAY_HEADER
) &LocalRiffHeader
;
705 TrackData
= &Fcb
->Vcb
->CdromToc
->TrackData
[Fcb
->XAFileNumber
];
708 // Copy the data header into our local buffer.
711 RtlCopyMemory( AudioPlayHeader
,
713 sizeof( AUDIO_PLAY_HEADER
));
716 // Copy the serial number into the Id field. Also
717 // the track number in the TOC.
720 AudioPlayHeader
->DiskID
= Fcb
->Vcb
->Vpb
->SerialNumber
;
721 AudioPlayHeader
->TrackNumber
= TrackData
->TrackNumber
;
724 // One frame == One sector.
725 // One second == 75 frames (winds up being a 44.1khz sample)
727 // Note: LBN 0 == 0:2:0 (MSF)
731 // Fill in the address (both MSF and Lbn format) and length fields.
734 SwapCopyUchar4( &Address
, TrackData
->Address
);
735 CdLbnToMmSsFf( Address
, AudioPlayHeader
->TrackAddress
);
737 SwapCopyUchar4( &AudioPlayHeader
->StartingSector
, TrackData
->Address
);
740 // Go to the next track and find the starting point.
743 TrackData
= &Fcb
->Vcb
->CdromToc
->TrackData
[Fcb
->XAFileNumber
+ 1];
745 SwapCopyUchar4( &AudioPlayHeader
->SectorCount
, TrackData
->Address
);
748 // Now compute the difference. If there is an error then use
752 if (AudioPlayHeader
->SectorCount
< AudioPlayHeader
->StartingSector
) {
754 AudioPlayHeader
->SectorCount
= 0;
758 AudioPlayHeader
->SectorCount
-= AudioPlayHeader
->StartingSector
;
762 // Use the sector count to determine the MSF length. Bias by 150 to make
763 // it an "lbn" since the conversion routine corrects for Lbn 0 == 0:2:0;
766 Address
= AudioPlayHeader
->SectorCount
- 150;
767 CdLbnToMmSsFf( Address
, AudioPlayHeader
->TrackLength
);
769 ThisByteCount
= sizeof( RIFF_HEADER
) - (ULONG
) CurrentOffset
;
771 RtlCopyMemory( UserBuffer
,
772 Add2Ptr( AudioPlayHeader
,
773 sizeof( RIFF_HEADER
) - ThisByteCount
,
784 // The WAVE header format is actually much closer to an audio play
785 // header in format but we only need to modify the filesize fields.
788 RiffHeader
= &LocalRiffHeader
;
791 // Copy the data header into our local buffer and add the file size to it.
794 RtlCopyMemory( RiffHeader
,
795 CdXAAudioPhileHeader
,
796 sizeof( RIFF_HEADER
));
798 RiffHeader
->ChunkSize
+= Fcb
->FileSize
.LowPart
;
799 RiffHeader
->RawSectors
+= Fcb
->FileSize
.LowPart
;
801 ThisByteCount
= sizeof( RIFF_HEADER
) - (ULONG
) CurrentOffset
;
802 RtlCopyMemory( UserBuffer
,
804 sizeof( RIFF_HEADER
) - ThisByteCount
,
815 NT_ASSERT( FlagOn( Fcb
->FcbState
, FCB_STATE_MODE2_FILE
| FCB_STATE_MODE2FORM2_FILE
));
817 RiffHeader
= &LocalRiffHeader
;
820 // Copy the data header into our local buffer and add the file size to it.
823 RtlCopyMemory( RiffHeader
,
825 sizeof( RIFF_HEADER
));
827 RiffHeader
->ChunkSize
+= Fcb
->FileSize
.LowPart
;
828 RiffHeader
->RawSectors
+= Fcb
->FileSize
.LowPart
;
830 RiffHeader
->Attributes
= (USHORT
) Fcb
->XAAttributes
;
831 RiffHeader
->FileNumber
= (UCHAR
) Fcb
->XAFileNumber
;
833 ThisByteCount
= sizeof( RIFF_HEADER
) - (ULONG
) CurrentOffset
;
834 RtlCopyMemory( UserBuffer
,
836 sizeof( RIFF_HEADER
) - ThisByteCount
,
842 // Adjust the starting offset and byte count to reflect that
843 // we copied over the RIFF bytes.
846 UserBuffer
= Add2Ptr( UserBuffer
, ThisByteCount
, PVOID
);
847 UserBufferOffset
+= ThisByteCount
;
848 CurrentOffset
+= ThisByteCount
;
849 RemainingByteCount
-= ThisByteCount
;
853 // Set up the appropriate trackmode
856 TrackMode
= CdFileTrackMode(Fcb
);
859 // Loop while there are more bytes to transfer.
862 while (RemainingByteCount
!= 0) {
865 // Call prepare buffers to set up the next entries
866 // in the IoRuns array. Remember if there are any
867 // unaligned entries. If we're just retrying the previous
868 // runs with a different track mode, then don't do anything here.
871 if (!TryingYellowbookMode2
) {
873 RtlZeroMemory( IoRuns
, sizeof( IoRuns
));
874 RtlZeroMemory( RawReads
, sizeof( RawReads
));
876 CdPrepareXABuffers( IrpContext
,
889 // Perform multiple Io to read in the data. Note that
890 // there may be no Io to do if we were able to use an
891 // existing buffer from the Vcb.
894 if (CleanupRunCount
!= 0) {
896 RunCount
= CleanupRunCount
;
898 CdMultipleXAAsync( IrpContext
,
904 // Wait for the request to complete.
907 CdWaitSync( IrpContext
);
909 Status
= IrpContext
->Irp
->IoStatus
.Status
;
912 // Exit this loop if there is an error.
915 if (!NT_SUCCESS( Status
)) {
917 if (!TryingYellowbookMode2
&&
918 FlagOn( Fcb
->FcbState
, FCB_STATE_MODE2FORM2_FILE
)) {
921 // There are wacky cases where someone has mastered as CD-XA
922 // but the sectors they claim are Mode2Form2 are really, according
923 // to ATAPI devices, Yellowbook Mode2. We will try once more
924 // with these. Kodak PHOTO-CD has been observed to do this.
927 TryingYellowbookMode2
= TRUE
;
928 TrackMode
= YellowMode2
;
931 // Clear our 'cumulative' error status value
934 IrpContext
->IoContext
->Status
= STATUS_SUCCESS
;
939 try_return( NOTHING
);
944 if (TryingYellowbookMode2
) {
947 // We succesfully got data when we tried switching the trackmode,
948 // so change the state of the FCB to remember that.
951 SetFlag( Fcb
->FcbState
, FCB_STATE_MODE2_FILE
);
952 ClearFlag( Fcb
->FcbState
, FCB_STATE_MODE2FORM2_FILE
);
954 TryingYellowbookMode2
= FALSE
;
958 // Perform post read operations on the IoRuns if
962 CdFinishBuffers( IrpContext
, IoRuns
, RunCount
, FALSE
, TRUE
);
966 // Adjust our loop variants.
969 RemainingByteCount
-= ThisByteCount
;
970 CurrentOffset
+= ThisByteCount
;
971 UserBuffer
= Add2Ptr( UserBuffer
, ThisByteCount
, PVOID
);
972 UserBufferOffset
+= ThisByteCount
;
976 // Always flush the hardware cache.
979 KeFlushIoBuffers( IrpContext
->Irp
->MdlAddress
, TRUE
, FALSE
);
985 // Perform final cleanup on the IoRuns if necessary.
988 if (CleanupRunCount
!= 0) {
990 CdFinishBuffers( IrpContext
, IoRuns
, CleanupRunCount
, TRUE
, FALSE
);
997 _Requires_lock_held_(_Global_critical_region_
)
1000 _In_ PIRP_CONTEXT IrpContext
,
1002 _In_ LONGLONG StartingOffset
,
1003 _In_ ULONG ByteCount
1008 Routine Description:
1010 This routine performs the non-cached writes to 'cooked' sectors (2048 bytes
1011 per sector). This is done by filling the IoRun for the desired request
1012 and send it down to the device.
1016 Fcb - Fcb representing the file to read.
1018 StartingOffset - Logical offset in the file to read from.
1020 ByteCount - Number of bytes to read.
1024 NTSTATUS - Status indicating the result of the operation.
1035 // We want to make sure the user's buffer is locked in all cases.
1038 CdLockUserBuffer( IrpContext
, ByteCount
, IoReadAccess
);
1041 // The entire Io can be contained in a single run, just pass
1042 // the Io down to the driver. Send the driver down
1043 // and wait on the result if this is synchronous.
1046 RtlZeroMemory( &IoRun
, sizeof( IoRun
) );
1048 IoRun
.DiskOffset
= StartingOffset
;
1049 IoRun
.DiskByteCount
= ByteCount
;
1051 CdSingleAsync( IrpContext
, &IoRun
, Fcb
);
1054 // Wait if we are synchronous, otherwise return
1057 if (FlagOn( IrpContext
->Flags
, IRP_CONTEXT_FLAG_WAIT
)) {
1059 CdWaitSync( IrpContext
);
1061 Status
= IrpContext
->Irp
->IoStatus
.Status
;
1064 // Our completion routine will free the Io context but
1065 // we do want to return STATUS_PENDING.
1070 ClearFlag( IrpContext
->Flags
, IRP_CONTEXT_FLAG_ALLOC_IO
);
1071 Status
= STATUS_PENDING
;
1081 _In_ PIRP_CONTEXT IrpContext
,
1082 _In_ LONGLONG StartingOffset
,
1083 _In_ ULONG ByteCount
,
1084 _In_ BOOLEAN ReturnError
,
1085 _Out_writes_bytes_(ByteCount
) PVOID Buffer
,
1086 _In_ PDEVICE_OBJECT TargetDeviceObject
1091 Routine Description:
1093 This routine is called to transfer sectors from the disk to a
1094 specified buffer. It is used for mount and volume verify operations.
1096 This routine is synchronous, it will not return until the operation
1097 is complete or until the operation fails.
1099 The routine allocates an IRP and then passes this IRP to a lower
1100 level driver. Errors may occur in the allocation of this IRP or
1101 in the operation of the lower driver.
1105 StartingOffset - Logical offset on the disk to start the read. This
1106 must be on a sector boundary, no check is made here.
1108 ByteCount - Number of bytes to read. This is an integral number of
1109 2K sectors, no check is made here to confirm this.
1111 ReturnError - Indicates whether we should return TRUE or FALSE
1112 to indicate an error or raise an error condition. This only applies
1113 to the result of the IO. Any other error may cause a raise.
1115 Buffer - Buffer to transfer the disk data into.
1117 TargetDeviceObject - The device object for the volume to be read.
1121 BOOLEAN - Depending on 'RaiseOnError' flag above. TRUE if operation
1122 succeeded, FALSE otherwise.
1134 // Initialize the event.
1137 KeInitializeEvent( &Event
, NotificationEvent
, FALSE
);
1140 // Attempt to allocate the IRP. If unsuccessful, raise
1141 // STATUS_INSUFFICIENT_RESOURCES.
1144 Irp
= IoBuildSynchronousFsdRequest( IRP_MJ_READ
,
1148 (PLARGE_INTEGER
) &StartingOffset
,
1150 &IrpContext
->Irp
->IoStatus
);
1154 CdRaiseStatus( IrpContext
, STATUS_INSUFFICIENT_RESOURCES
);
1158 // Ignore the change line (verify) for mount and verify requests
1161 SetFlag( IoGetNextIrpStackLocation( Irp
)->Flags
, SL_OVERRIDE_VERIFY_VOLUME
);
1164 // Send the request down to the driver. If an error occurs return
1165 // it to the caller.
1168 Status
= IoCallDriver( TargetDeviceObject
, Irp
);
1171 // If the status was STATUS_PENDING then wait on the event.
1174 if (Status
== STATUS_PENDING
) {
1176 Status
= KeWaitForSingleObject( &Event
,
1183 // On a successful wait pull the status out of the IoStatus block.
1186 if (NT_SUCCESS( Status
)) {
1188 Status
= IrpContext
->Irp
->IoStatus
.Status
;
1193 // Check whether we should raise in the error case.
1196 if (!NT_SUCCESS( Status
)) {
1200 CdNormalizeAndRaiseStatus( IrpContext
, Status
);
1204 // We don't raise, but return FALSE to indicate an error.
1210 // The operation completed successfully.
1222 _In_ PIRP_CONTEXT IrpContext
,
1223 _In_ ULONG BufferLength
,
1224 _In_ BOOLEAN RaiseOnError
,
1225 _In_ LOCK_OPERATION Operation
1230 Routine Description:
1232 This routine locks the specified buffer for read access (we only write into
1233 the buffer). The file system requires this routine since it does not
1234 ask the I/O system to lock its buffers for direct I/O. This routine
1235 may only be called from the Fsd while still in the user context.
1237 This routine is only called if there is not already an Mdl.
1241 BufferLength - Length of user buffer.
1243 RaiseOnError - Indicates if our caller wants this routine to raise on
1246 Operation - IoWriteAccess or IoReadAccess
1250 NTSTATUS - Status from this routine. Error status only returned if
1251 RaiseOnError is FALSE.
1256 NTSTATUS Status
= STATUS_INSUFFICIENT_RESOURCES
;
1261 UNREFERENCED_PARAMETER( Operation
);
1262 UNREFERENCED_PARAMETER( IrpContext
);
1264 ASSERT_IRP_CONTEXT( IrpContext
);
1265 ASSERT_IRP( IrpContext
->Irp
);
1266 NT_ASSERT( IrpContext
->Irp
->MdlAddress
== NULL
);
1269 // Allocate the Mdl, and Raise if we fail.
1272 Mdl
= IoAllocateMdl( IrpContext
->Irp
->UserBuffer
,
1281 // Now probe the buffer described by the Irp. If we get an exception,
1282 // deallocate the Mdl and return the appropriate "expected" status.
1287 MmProbeAndLockPages( Mdl
, IrpContext
->Irp
->RequestorMode
, IoWriteAccess
);
1289 Status
= STATUS_SUCCESS
;
1291 #pragma warning(suppress: 6320)
1292 } except(EXCEPTION_EXECUTE_HANDLER
) {
1294 Status
= GetExceptionCode();
1297 IrpContext
->Irp
->MdlAddress
= NULL
;
1299 if (!FsRtlIsNtstatusExpected( Status
)) {
1301 Status
= STATUS_INVALID_USER_BUFFER
;
1307 // Check if we are to raise or return
1310 if (Status
!= STATUS_SUCCESS
) {
1314 CdRaiseStatus( IrpContext
, Status
);
1319 // Return the status code.
1327 CdPerformDevIoCtrlEx (
1328 _In_ PIRP_CONTEXT IrpContext
,
1329 _In_ ULONG IoControlCode
,
1330 _In_ PDEVICE_OBJECT Device
,
1331 _In_reads_bytes_opt_(InputBufferLength
) PVOID InputBuffer
,
1332 _In_ ULONG InputBufferLength
,
1333 _Out_writes_bytes_opt_(OutputBufferLength
) PVOID OutputBuffer
,
1334 _In_ ULONG OutputBufferLength
,
1335 _In_ BOOLEAN InternalDeviceIoControl
,
1336 _In_ BOOLEAN OverrideVerify
,
1337 _Out_opt_ PIO_STATUS_BLOCK Iosb
1342 Routine Description:
1344 This routine is called to perform DevIoCtrl functions internally within
1345 the filesystem. We take the status from the driver and return it to our
1350 IoControlCode - Code to send to driver.
1352 Device - This is the device to send the request to.
1354 OutPutBuffer - Pointer to output buffer.
1356 OutputBufferLength - Length of output buffer above.
1358 InternalDeviceIoControl - Indicates if this is an internal or external
1361 OverrideVerify - Indicates if we should tell the driver not to return
1362 STATUS_VERIFY_REQUIRED for mount and verify.
1364 Iosb - If specified, we return the results of the operation here.
1368 NTSTATUS - Status returned by next lower driver.
1376 IO_STATUS_BLOCK LocalIosb
;
1377 PIO_STATUS_BLOCK IosbToUse
= &LocalIosb
;
1381 UNREFERENCED_PARAMETER( IrpContext
);
1384 // Check if the user gave us an Iosb.
1387 if (ARGUMENT_PRESENT( Iosb
)) {
1392 IosbToUse
->Status
= 0;
1393 IosbToUse
->Information
= 0;
1395 KeInitializeEvent( &Event
, NotificationEvent
, FALSE
);
1397 Irp
= IoBuildDeviceIoControlRequest( IoControlCode
,
1403 InternalDeviceIoControl
,
1409 return STATUS_INSUFFICIENT_RESOURCES
;
1412 if (OverrideVerify
) {
1414 SetFlag( IoGetNextIrpStackLocation( Irp
)->Flags
, SL_OVERRIDE_VERIFY_VOLUME
);
1417 Status
= IoCallDriver( Device
, Irp
);
1420 // We check for device not ready by first checking Status
1421 // and then if status pending was returned, the Iosb status
1425 if (Status
== STATUS_PENDING
) {
1427 (VOID
) KeWaitForSingleObject( &Event
,
1431 (PLARGE_INTEGER
)NULL
);
1433 Status
= IosbToUse
->Status
;
1436 NT_ASSERT( !(OverrideVerify
&& (STATUS_VERIFY_REQUIRED
== Status
)));
1444 CdPerformDevIoCtrl (
1445 _In_ PIRP_CONTEXT IrpContext
,
1446 _In_ ULONG IoControlCode
,
1447 _In_ PDEVICE_OBJECT Device
,
1448 _Out_writes_bytes_opt_(OutputBufferLength
) PVOID OutputBuffer
,
1449 _In_ ULONG OutputBufferLength
,
1450 _In_ BOOLEAN InternalDeviceIoControl
,
1451 _In_ BOOLEAN OverrideVerify
,
1452 _Out_opt_ PIO_STATUS_BLOCK Iosb
1457 return CdPerformDevIoCtrlEx( IrpContext
,
1464 InternalDeviceIoControl
,
1472 // Local support routine
1475 _Requires_lock_held_(_Global_critical_region_
)
1478 _In_ PIRP_CONTEXT IrpContext
,
1481 _In_reads_bytes_(ByteCount
) PVOID UserBuffer
,
1482 _In_ ULONG UserBufferOffset
,
1483 _In_ LONGLONG StartingOffset
,
1484 _In_ ULONG ByteCount
,
1485 _Out_ PIO_RUN IoRuns
,
1486 _Out_ PULONG RunCount
,
1487 _Out_ PULONG ThisByteCount
1492 Routine Description:
1494 This routine is the worker routine which looks up each run of an IO
1495 request and stores an entry for it in the IoRuns array. If the run
1496 begins on an unaligned disk boundary then we will allocate a buffer
1497 and Mdl for the unaligned portion and put it in the IoRuns entry.
1499 This routine will raise CANT_WAIT if an unaligned transfer is encountered
1500 and this request can't wait.
1504 Irp - Originating Irp for this request.
1506 Fcb - This is the Fcb for this data stream. It may be a file, directory,
1507 path table or the volume file.
1509 UserBuffer - Current position in the user's buffer.
1511 UserBufferOffset - Offset from the start of the original user buffer.
1513 StartingOffset - Offset in the stream to begin the read.
1515 ByteCount - Number of bytes to read. We will fill the IoRuns array up
1516 to this point. We will stop early if we exceed the maximum number
1517 of parallel Ios we support.
1519 IoRuns - Pointer to the IoRuns array. The entire array is zeroes when
1520 this routine is called.
1522 RunCount - Number of entries in the IoRuns array filled here.
1524 ThisByteCount - Number of bytes described by the IoRun entries. Will
1525 not exceed the ByteCount passed in.
1529 BOOLEAN - TRUE if one of the entries in an unaligned buffer (provided
1530 this is synchronous). FALSE otherwise.
1535 BOOLEAN FoundUnaligned
= FALSE
;
1536 PIO_RUN ThisIoRun
= IoRuns
;
1539 // Following indicate where we are in the current transfer. Current
1540 // position in the file and number of bytes yet to transfer from
1544 ULONG RemainingByteCount
= ByteCount
;
1545 LONGLONG CurrentFileOffset
= StartingOffset
;
1548 // Following indicate the state of the user's buffer. We have
1549 // the destination of the next transfer and its offset in the
1550 // buffer. We also have the next available position in the buffer
1551 // available for a scratch buffer. We will align this up to a sector
1555 PVOID CurrentUserBuffer
= UserBuffer
;
1556 ULONG CurrentUserBufferOffset
= UserBufferOffset
;
1559 // The following is the next contiguous bytes on the disk to
1560 // transfer. Read from the allocation package.
1563 LONGLONG DiskOffset
= 0;
1564 ULONG CurrentByteCount
= RemainingByteCount
;
1569 // Initialize the RunCount and ByteCount.
1576 // Loop while there are more bytes to process or there are
1577 // available entries in the IoRun array.
1585 // Initialize the current position in the IoRuns array.
1586 // Find the user's buffer for this portion of the transfer.
1589 ThisIoRun
->UserBuffer
= CurrentUserBuffer
;
1592 // Find the allocation information for the current offset in the
1596 CdLookupAllocation( IrpContext
,
1600 &CurrentByteCount
);
1603 // Limit ourselves to the data requested.
1606 if (CurrentByteCount
> RemainingByteCount
) {
1608 CurrentByteCount
= RemainingByteCount
;
1612 // Handle the case where this is an unaligned transfer. The
1613 // following must all be true for this to be an aligned transfer.
1615 // Disk offset on a 2048 byte boundary (Start of transfer)
1617 // Byte count is a multiple of 2048 (Length of transfer)
1619 // If the ByteCount is at least one sector then do the
1620 // unaligned transfer only for the tail. We can use the
1621 // user's buffer for the aligned portion.
1624 if (FlagOn( (ULONG
) DiskOffset
, SECTOR_MASK
) ||
1625 (FlagOn( (ULONG
) CurrentByteCount
, SECTOR_MASK
) &&
1626 (CurrentByteCount
< SECTOR_SIZE
))) {
1628 NT_ASSERT( SafeNodeType(Fcb
) != CDFS_NTC_FCB_INDEX
);
1631 // If we can't wait then raise.
1634 if (!FlagOn( IrpContext
->Flags
, IRP_CONTEXT_FLAG_WAIT
)) {
1636 CdRaiseStatus( IrpContext
, STATUS_CANT_WAIT
);
1640 // Remember the offset and the number of bytes out of
1641 // the transfer buffer to copy into the user's buffer.
1642 // We will truncate the current read to end on a sector
1646 ThisIoRun
->TransferBufferOffset
= SectorOffset( DiskOffset
);
1649 // Make sure this transfer ends on a sector boundary.
1652 ThisIoRun
->DiskOffset
= LlSectorTruncate( DiskOffset
);
1655 // We need to allocate an auxilary buffer for the next sector.
1656 // Read up to a page containing the partial data.
1659 ThisIoRun
->DiskByteCount
= SectorAlign( ThisIoRun
->TransferBufferOffset
+ CurrentByteCount
);
1661 if (ThisIoRun
->DiskByteCount
> PAGE_SIZE
) {
1663 ThisIoRun
->DiskByteCount
= PAGE_SIZE
;
1666 if (ThisIoRun
->TransferBufferOffset
+ CurrentByteCount
> ThisIoRun
->DiskByteCount
) {
1668 CurrentByteCount
= ThisIoRun
->DiskByteCount
- ThisIoRun
->TransferBufferOffset
;
1671 ThisIoRun
->TransferByteCount
= CurrentByteCount
;
1674 // Allocate a buffer for the non-aligned transfer.
1677 ThisIoRun
->TransferBuffer
= FsRtlAllocatePoolWithTag( CdNonPagedPool
, PAGE_SIZE
, TAG_IO_BUFFER
);
1680 // Allocate and build the Mdl to describe this buffer.
1683 ThisIoRun
->TransferMdl
= IoAllocateMdl( ThisIoRun
->TransferBuffer
,
1689 ThisIoRun
->TransferVirtualAddress
= ThisIoRun
->TransferBuffer
;
1691 if (ThisIoRun
->TransferMdl
== NULL
) {
1693 IrpContext
->Irp
->IoStatus
.Information
= 0;
1694 CdRaiseStatus( IrpContext
, STATUS_INSUFFICIENT_RESOURCES
);
1697 MmBuildMdlForNonPagedPool( ThisIoRun
->TransferMdl
);
1700 // Remember we found an unaligned transfer.
1703 FoundUnaligned
= TRUE
;
1706 // Otherwise we use the buffer and Mdl from the original request.
1712 // Truncate the read length to a sector-aligned value. We know
1713 // the length must be at least one sector or we wouldn't be
1717 CurrentByteCount
= SectorTruncate( CurrentByteCount
);
1720 // Read these sectors from the disk.
1723 ThisIoRun
->DiskOffset
= DiskOffset
;
1724 ThisIoRun
->DiskByteCount
= CurrentByteCount
;
1727 // Use the user's buffer and Mdl as our transfer buffer
1731 ThisIoRun
->TransferBuffer
= CurrentUserBuffer
;
1732 ThisIoRun
->TransferMdl
= Irp
->MdlAddress
;
1733 ThisIoRun
->TransferVirtualAddress
= Add2Ptr( Irp
->UserBuffer
,
1734 CurrentUserBufferOffset
,
1739 // Update our position in the transfer and the RunCount and
1740 // ByteCount for the user.
1743 RemainingByteCount
-= CurrentByteCount
;
1746 // Break out if no more positions in the IoRuns array or
1747 // we have all of the bytes accounted for.
1750 *ThisByteCount
+= CurrentByteCount
;
1752 if ((RemainingByteCount
== 0) || (*RunCount
== MAX_PARALLEL_IOS
)) {
1758 // Update our pointers for the user's buffer.
1762 CurrentUserBuffer
= Add2Ptr( CurrentUserBuffer
, CurrentByteCount
, PVOID
);
1763 CurrentUserBufferOffset
+= CurrentByteCount
;
1764 CurrentFileOffset
+= CurrentByteCount
;
1767 return FoundUnaligned
;
1772 // Local support routine
1775 _Requires_lock_held_(_Global_critical_region_
)
1777 CdPrepareXABuffers (
1778 _In_ PIRP_CONTEXT IrpContext
,
1781 _In_reads_bytes_(ByteCount
) PVOID UserBuffer
,
1782 _In_ ULONG UserBufferOffset
,
1783 _In_ LONGLONG StartingOffset
,
1784 _In_ ULONG ByteCount
,
1785 _Out_ PIO_RUN IoRuns
,
1786 _Out_ PULONG RunCount
,
1787 _Out_ PULONG ThisByteCount
1792 Routine Description:
1794 This routine is the worker routine which looks up the individual runs
1795 of an IO request and stores an entry for it in the IoRuns array. The
1796 worker routine is for XA files where we need to convert the raw offset
1797 in the file to logical cooked sectors. We store one raw sector in
1798 the Vcb. If the current read is to that sector then we can simply copy
1799 whatever bytes are needed from that sector.
1803 Irp - Originating Irp for this request.
1805 Fcb - This is the Fcb for this data stream. It must be a data stream.
1807 UserBuffer - Current position in the user's buffer.
1809 UserBufferOffset - Offset of this buffer from the beginning of the user's
1810 buffer for the original request.
1812 StartingOffset - Offset in the stream to begin the read.
1814 ByteCount - Number of bytes to read. We will fill the IoRuns array up
1815 to this point. We will stop early if we exceed the maximum number
1816 of parallel Ios we support.
1818 IoRuns - Pointer to the IoRuns array. The entire array is zeroes when
1819 this routine is called.
1821 RunCount - Number of entries in the IoRuns array filled here.
1823 ThisByteCount - Number of bytes described by the IoRun entries. Will
1824 not exceed the ByteCount passed in.
1833 PIO_RUN ThisIoRun
= IoRuns
;
1834 BOOLEAN PerformedCopy
;
1837 // The following deal with where we are in the range of raw sectors.
1838 // Note that we will bias the input file offset by the RIFF header
1839 // to deal directly with the raw sectors.
1842 ULONG RawSectorOffset
;
1843 ULONG RemainingRawByteCount
= ByteCount
;
1844 LONGLONG CurrentRawOffset
= StartingOffset
- sizeof( RIFF_HEADER
);
1847 // The following is the offset into the cooked sectors for the file.
1850 LONGLONG CurrentCookedOffset
;
1851 ULONG RemainingCookedByteCount
;
1854 // Following indicate the state of the user's buffer. We have
1855 // the destination of the next transfer and its offset in the
1856 // buffer. We also have the next available position in the buffer
1857 // available for a scratch buffer.
1860 PVOID CurrentUserBuffer
= UserBuffer
;
1861 ULONG CurrentUserBufferOffset
= UserBufferOffset
;
1864 // The following is the next contiguous bytes on the disk to
1865 // transfer. These are represented by cooked byte offset and length.
1866 // We also compute the number of raw bytes in the current transfer.
1869 LONGLONG DiskOffset
= 0;
1870 ULONG CurrentCookedByteCount
= 0;
1871 ULONG CurrentRawByteCount
;
1876 // We need to maintain our position as we walk through the sectors on the disk.
1877 // We keep separate values for the cooked offset as well as the raw offset.
1878 // These are initialized on sector boundaries and we move through these
1879 // the file sector-by-sector.
1881 // Try to do 32-bit math.
1884 if (((PLARGE_INTEGER
) &CurrentRawOffset
)->HighPart
== 0) {
1887 // Prefix/fast: Note that the following are safe since we only
1888 // take this path for 32bit offsets.
1891 CurrentRawOffset
= (LONGLONG
) ((ULONG
) CurrentRawOffset
/ RAW_SECTOR_SIZE
);
1893 #pragma prefast( suppress: __WARNING_RESULTOFSHIFTCASTTOLARGERSIZE, "This is fine beacuse raw sector size > sector shift" )
1894 CurrentCookedOffset
= (LONGLONG
) ((ULONG
) CurrentRawOffset
<< SECTOR_SHIFT
);
1896 CurrentRawOffset
= (LONGLONG
) ((ULONG
) CurrentRawOffset
* RAW_SECTOR_SIZE
);
1899 // Otherwise we need to do 64-bit math (sigh).
1904 CurrentRawOffset
/= RAW_SECTOR_SIZE
;
1906 CurrentCookedOffset
= CurrentRawOffset
<< SECTOR_SHIFT
;
1908 CurrentRawOffset
*= RAW_SECTOR_SIZE
;
1912 // Now compute the full number of sectors to be read. Count all of the raw
1913 // sectors that need to be read and convert to cooked bytes.
1916 RawSectorOffset
= (ULONG
) ( StartingOffset
- CurrentRawOffset
) - sizeof( RIFF_HEADER
);
1917 CurrentRawByteCount
= (RawSectorOffset
+ RemainingRawByteCount
+ RAW_SECTOR_SIZE
- 1) / RAW_SECTOR_SIZE
;
1919 RemainingCookedByteCount
= CurrentRawByteCount
<< SECTOR_SHIFT
;
1922 // Initialize the RunCount and ByteCount.
1929 // Loop while there are more bytes to process or there are
1930 // available entries in the IoRun array.
1935 PerformedCopy
= FALSE
;
1939 // Initialize the current position in the IoRuns array. Find the
1940 // eventual destination in the user's buffer for this portion of the transfer.
1943 ThisIoRun
->UserBuffer
= CurrentUserBuffer
;
1946 // Find the allocation information for the current offset in the
1950 CdLookupAllocation( IrpContext
,
1952 CurrentCookedOffset
,
1954 &CurrentCookedByteCount
);
1956 // Maybe we got lucky and this is the same sector as in the
1960 if (DiskOffset
== Fcb
->Vcb
->XADiskOffset
) {
1963 // We will perform safe synchronization. Check again that
1964 // this is the correct sector.
1967 CdLockVcb( IrpContext
, Fcb
->Vcb
);
1969 if ((DiskOffset
== Fcb
->Vcb
->XADiskOffset
) &&
1970 (Fcb
->Vcb
->XASector
!= NULL
)) {
1973 // Copy any bytes we can from the current sector.
1976 CurrentRawByteCount
= RAW_SECTOR_SIZE
- RawSectorOffset
;
1979 // Check whether we don't go to the end of the sector.
1982 if (CurrentRawByteCount
> RemainingRawByteCount
) {
1984 CurrentRawByteCount
= RemainingRawByteCount
;
1987 RtlCopyMemory( CurrentUserBuffer
,
1988 Add2Ptr( Fcb
->Vcb
->XASector
, RawSectorOffset
, PCHAR
),
1989 CurrentRawByteCount
);
1991 CdUnlockVcb( IrpContext
, Fcb
->Vcb
);
1994 // Adjust the run count and pointer in the IoRuns array
1995 // to show that we didn't use a position.
2002 // Remember that we performed a copy operation.
2005 PerformedCopy
= TRUE
;
2007 CurrentCookedByteCount
= SECTOR_SIZE
;
2012 // The safe test showed no available buffer. Drop down to common code to
2016 CdUnlockVcb( IrpContext
, Fcb
->Vcb
);
2021 // No work in this pass if we did a copy operation.
2024 if (!PerformedCopy
) {
2027 // Limit ourselves by the number of remaining cooked bytes.
2030 if (CurrentCookedByteCount
> RemainingCookedByteCount
) {
2032 CurrentCookedByteCount
= RemainingCookedByteCount
;
2035 ThisIoRun
->DiskOffset
= DiskOffset
;
2036 ThisIoRun
->TransferBufferOffset
= RawSectorOffset
;
2039 // We will always need to perform copy operations for XA files.
2040 // We allocate an auxillary buffer to read the start of the
2041 // transfer. Then we can use a range of the user's buffer to
2042 // perform the next range of the transfer. Finally we may
2043 // need to allocate a buffer for the tail of the transfer.
2045 // We can use the user's buffer (at the current scratch buffer) if the
2046 // following are true:
2048 // If we are to store the beginning of the raw sector in the user's buffer.
2049 // The current scratch buffer precedes the destination in the user's buffer
2050 // (and hence also lies within it)
2051 // There are enough bytes remaining in the buffer for at least one
2055 if ((RawSectorOffset
== 0) &&
2056 (RemainingRawByteCount
>= RAW_SECTOR_SIZE
)) {
2059 // We can use the scratch buffer. We must ensure we don't send down reads
2060 // greater than the device can handle, since the driver is unable to split
2064 if (CurrentCookedByteCount
<= Fcb
->Vcb
->MaximumTransferRawSectors
* SECTOR_SIZE
) {
2066 CurrentRawByteCount
= (SectorAlign( CurrentCookedByteCount
) >> SECTOR_SHIFT
) * RAW_SECTOR_SIZE
;
2070 CurrentCookedByteCount
= Fcb
->Vcb
->MaximumTransferRawSectors
* SECTOR_SIZE
;
2071 CurrentRawByteCount
= Fcb
->Vcb
->MaximumTransferRawSectors
* RAW_SECTOR_SIZE
;
2075 // Now make sure we are within the page transfer limit.
2078 while (ADDRESS_AND_SIZE_TO_SPAN_PAGES(CurrentUserBuffer
, RawSectorAlign( CurrentRawByteCount
)) >
2079 Fcb
->Vcb
->MaximumPhysicalPages
) {
2081 CurrentRawByteCount
-= RAW_SECTOR_SIZE
;
2082 CurrentCookedByteCount
-= SECTOR_SIZE
;
2086 // Trim the number of bytes to read if it won't fit into the current buffer. Take
2087 // account of the fact that we must read in whole raw sector multiples.
2090 while (RawSectorAlign( CurrentRawByteCount
) > RemainingRawByteCount
) {
2092 CurrentRawByteCount
-= RAW_SECTOR_SIZE
;
2093 CurrentCookedByteCount
-= SECTOR_SIZE
;
2097 // Now trim the maximum number of raw bytes to the remaining bytes.
2100 if (CurrentRawByteCount
> RemainingRawByteCount
) {
2102 CurrentRawByteCount
= RemainingRawByteCount
;
2106 // Update the IO run array. We point to the scratch buffer as
2107 // well as the buffer and Mdl in the original Irp.
2110 ThisIoRun
->DiskByteCount
= SectorAlign( CurrentCookedByteCount
);
2113 // Point to the user's buffer and Mdl for this transfer.
2116 ThisIoRun
->TransferBuffer
= CurrentUserBuffer
;
2117 ThisIoRun
->TransferMdl
= Irp
->MdlAddress
;
2118 ThisIoRun
->TransferVirtualAddress
= Add2Ptr( Irp
->UserBuffer
,
2119 CurrentUserBufferOffset
,
2125 // We need to determine the number of bytes to transfer and the
2126 // offset into this page to begin the transfer.
2128 // We will transfer only one raw sector.
2131 ThisIoRun
->DiskByteCount
= SECTOR_SIZE
;
2133 CurrentCookedByteCount
= SECTOR_SIZE
;
2135 ThisIoRun
->TransferByteCount
= RAW_SECTOR_SIZE
- RawSectorOffset
;
2136 ThisIoRun
->TransferBufferOffset
= RawSectorOffset
;
2138 if (ThisIoRun
->TransferByteCount
> RemainingRawByteCount
) {
2140 ThisIoRun
->TransferByteCount
= RemainingRawByteCount
;
2143 CurrentRawByteCount
= ThisIoRun
->TransferByteCount
;
2146 // We need to allocate an auxillary buffer. We will allocate
2147 // a single page. Then we will build an Mdl to describe the buffer.
2150 ThisIoRun
->TransferBuffer
= FsRtlAllocatePoolWithTag( CdNonPagedPool
, PAGE_SIZE
, TAG_IO_BUFFER
);
2153 // Allocate and build the Mdl to describe this buffer.
2156 ThisIoRun
->TransferMdl
= IoAllocateMdl( ThisIoRun
->TransferBuffer
,
2162 ThisIoRun
->TransferVirtualAddress
= ThisIoRun
->TransferBuffer
;
2164 if (ThisIoRun
->TransferMdl
== NULL
) {
2166 IrpContext
->Irp
->IoStatus
.Information
= 0;
2167 CdRaiseStatus( IrpContext
, STATUS_INSUFFICIENT_RESOURCES
);
2170 MmBuildMdlForNonPagedPool( ThisIoRun
->TransferMdl
);
2175 // Update the byte count for our caller.
2178 RemainingRawByteCount
-= CurrentRawByteCount
;
2179 *ThisByteCount
+= CurrentRawByteCount
;
2182 // Break out if no more positions in the IoRuns array or
2183 // we have all of the bytes accounted for.
2186 if ((RemainingRawByteCount
== 0) || (*RunCount
== MAX_PARALLEL_IOS
)) {
2192 // Update our local pointers to allow for the current range of bytes.
2197 CurrentUserBuffer
= Add2Ptr( CurrentUserBuffer
, CurrentRawByteCount
, PVOID
);
2198 CurrentUserBufferOffset
+= CurrentRawByteCount
;
2200 RawSectorOffset
= 0;
2202 CurrentCookedOffset
+= CurrentCookedByteCount
;
2203 RemainingCookedByteCount
-= CurrentCookedByteCount
;
2211 // Local support routine
2216 _In_ PIRP_CONTEXT IrpContext
,
2217 _Inout_ PIO_RUN IoRuns
,
2218 _In_ ULONG RunCount
,
2219 _In_ BOOLEAN FinalCleanup
,
2220 _In_ BOOLEAN SaveXABuffer
2225 Routine Description:
2227 This routine is called to perform any data transferred required for
2228 unaligned Io or to perform the final cleanup of the IoRuns array.
2230 In all cases this is where we will deallocate any buffer and mdl
2231 allocated to perform the unaligned transfer. If this is not the
2232 final cleanup then we also transfer the bytes to the user buffer
2233 and flush the hardware cache.
2235 We walk backwards through the run array because we may be shifting data
2236 in the user's buffer. Typical case is where we allocated a buffer for
2237 the first part of a read and then used the user's buffer for the
2238 next section (but stored it at the beginning of the buffer.
2242 IoRuns - Pointer to the IoRuns array.
2244 RunCount - Number of entries in the IoRuns array filled here.
2246 FinalCleanup - Indicates if we should be deallocating temporary buffers
2247 (TRUE) or transferring bytes for a unaligned transfers and
2248 deallocating the buffers (FALSE). Flush the system cache if
2251 SaveXABuffer - TRUE if we should try to save an XA buffer, FALSE otherwise
2255 BOOLEAN - TRUE if this request needs the Io buffers to be flushed, FALSE otherwise.
2260 BOOLEAN FlushIoBuffers
= FALSE
;
2262 ULONG RemainingEntries
= RunCount
;
2263 PIO_RUN ThisIoRun
= &IoRuns
[RunCount
- 1];
2269 // Walk through each entry in the IoRun array.
2272 while (RemainingEntries
!= 0) {
2275 // We only need to deal with the case of an unaligned transfer.
2278 if (ThisIoRun
->TransferByteCount
!= 0) {
2281 // If not the final cleanup then transfer the data to the
2282 // user's buffer and remember that we will need to flush
2283 // the user's buffer to memory.
2286 if (!FinalCleanup
) {
2288 RtlCopyMemory( ThisIoRun
->UserBuffer
,
2289 Add2Ptr( ThisIoRun
->TransferBuffer
,
2290 ThisIoRun
->TransferBufferOffset
,
2292 ThisIoRun
->TransferByteCount
);
2294 FlushIoBuffers
= TRUE
;
2298 // Free any Mdl we may have allocated. If the Mdl isn't
2299 // present then we must have failed during the allocation
2303 if (ThisIoRun
->TransferMdl
!= IrpContext
->Irp
->MdlAddress
) {
2305 if (ThisIoRun
->TransferMdl
!= NULL
) {
2307 IoFreeMdl( ThisIoRun
->TransferMdl
);
2311 // Now free any buffer we may have allocated. If the Mdl
2312 // doesn't match the original Mdl then free the buffer.
2315 if (ThisIoRun
->TransferBuffer
!= NULL
) {
2318 // If this is the final buffer for an XA read then store this buffer
2319 // into the Vcb so that we will have it when reading any remaining
2320 // portion of this buffer.
2325 Vcb
= IrpContext
->Vcb
;
2327 CdLockVcb( IrpContext
, Vcb
);
2329 if (Vcb
->XASector
!= NULL
) {
2331 CdFreePool( &Vcb
->XASector
);
2334 Vcb
->XASector
= ThisIoRun
->TransferBuffer
;
2335 Vcb
->XADiskOffset
= ThisIoRun
->DiskOffset
;
2337 SaveXABuffer
= FALSE
;
2339 CdUnlockVcb( IrpContext
, Vcb
);
2342 // Otherwise just free the buffer.
2347 CdFreePool( &ThisIoRun
->TransferBuffer
);
2354 // Now handle the case where we failed in the process
2355 // of allocating associated Irps and Mdls.
2358 if (ThisIoRun
->SavedIrp
!= NULL
) {
2360 if (ThisIoRun
->SavedIrp
->MdlAddress
!= NULL
) {
2362 IoFreeMdl( ThisIoRun
->SavedIrp
->MdlAddress
);
2365 IoFreeIrp( ThisIoRun
->SavedIrp
);
2369 // Move to the previous IoRun entry.
2373 RemainingEntries
-= 1;
2377 // If we copied any data then flush the Io buffers.
2380 return FlushIoBuffers
;
2383 // Tell prefast this is a completion routine.
2384 IO_COMPLETION_ROUTINE CdSyncCompletionRoutine
;
2387 CdSyncCompletionRoutine (
2388 PDEVICE_OBJECT DeviceObject
,
2395 Routine Description:
2397 Completion routine for synchronizing back to dispatch.
2401 Contxt - pointer to KEVENT.
2405 STATUS_MORE_PROCESSING_REQUIRED
2410 PKEVENT Event
= (PKEVENT
)Contxt
;
2411 _Analysis_assume_(Contxt
!= NULL
);
2413 UNREFERENCED_PARAMETER( Irp
);
2414 UNREFERENCED_PARAMETER( DeviceObject
);
2416 KeSetEvent( Event
, 0, FALSE
);
2419 // We don't want IO to get our IRP and free it.
2422 return STATUS_MORE_PROCESSING_REQUIRED
;
2426 _Requires_lock_held_(_Global_critical_region_
)
2429 _In_ PIRP_CONTEXT IrpContext
2434 Routine Description:
2436 Safely frees the sector cache buffer.
2449 if (NULL
!= IrpContext
->Vcb
->SectorCacheBuffer
) {
2451 CdAcquireCacheForUpdate( IrpContext
);
2452 CdFreePool( &IrpContext
->Vcb
->SectorCacheBuffer
);
2453 CdReleaseCache( IrpContext
);
2457 _Requires_lock_held_(_Global_critical_region_
)
2459 CdReadDirDataThroughCache (
2460 _In_ PIRP_CONTEXT IrpContext
,
2466 Routine Description:
2468 Reads blocks through the sector cache. If the data is present, then it
2469 is copied from memory. If not present, one of the cache chunks will be
2470 replaced with a chunk containing the requested region, and the data
2473 Only intended for reading *directory* blocks, for the purpose of pre-caching
2474 directory information, by reading a chunk of blocks which hopefully contains
2475 other directory blocks, rather than just the (usually) single block requested.
2479 Run - description of extent required, and buffer to read into.
2483 None. Raises on error.
2488 PVCB Vcb
= IrpContext
->Vcb
;
2489 ULONG Lbn
= SectorsFromLlBytes( Run
->DiskOffset
);
2490 ULONG Remaining
= SectorsFromBytes( Run
->DiskByteCount
);
2491 PUCHAR UserBuffer
= Run
->TransferBuffer
;
2495 ULONG BufferSectorOffset
;
2500 PIO_STACK_LOCATION IrpSp
;
2501 IO_STATUS_BLOCK Iosb
;
2503 PTRACK_DATA TrackData
;
2506 BOOLEAN JustRead
= FALSE
;
2510 PCD_SECTOR_CACHE_CHUNK Buffer
;
2511 BOOLEAN Result
= FALSE
;
2515 CdAcquireCacheForRead( IrpContext
);
2520 // Check the cache hasn't gone away due to volume verify failure (which
2521 // is the *only* reason it'll go away). If this is the case we raise
2522 // the same error any I/O would return if the cache weren't here.
2525 if (NULL
== Vcb
->SectorCacheBuffer
) {
2527 CdRaiseStatus( IrpContext
, STATUS_VERIFY_REQUIRED
);
2535 // Look to see if any portion is currently cached.
2538 for (Index
= 0; Index
< CD_SEC_CACHE_CHUNKS
; Index
++) {
2540 if ((Vcb
->SecCacheChunks
[ Index
].BaseLbn
!= -1) &&
2541 (Vcb
->SecCacheChunks
[ Index
].BaseLbn
<= Lbn
) &&
2542 ((Vcb
->SecCacheChunks
[ Index
].BaseLbn
+ CD_SEC_CHUNK_BLOCKS
) > Lbn
)) {
2544 Buffer
= &Vcb
->SecCacheChunks
[ Index
];
2550 // If we found any, copy it out and continue.
2553 if (NULL
!= Buffer
) {
2555 BufferSectorOffset
= Lbn
- Buffer
->BaseLbn
;
2556 Found
= Min( CD_SEC_CHUNK_BLOCKS
- BufferSectorOffset
, Remaining
);
2558 RtlCopyMemory( UserBuffer
,
2559 Buffer
->Buffer
+ BytesFromSectors( BufferSectorOffset
),
2560 BytesFromSectors( Found
));
2563 UserBuffer
+= BytesFromSectors( Found
);
2567 // Update stats. Don't count a hit if we've just read the data in.
2572 InterlockedIncrement( (LONG
*)&Vcb
->SecCacheHits
);
2581 // Missed the cache, so we need to read a new chunk. Take the cache
2582 // resource exclusive while we do so.
2585 CdReleaseCache( IrpContext
);
2586 CdAcquireCacheForUpdate( IrpContext
);
2588 Vcb
->SecCacheMisses
+= 1;
2591 // Select the chunk to replace and calculate the start block of the
2592 // chunk to cache. We cache blocks which start on Lbns aligned on
2593 // multiples of chunk size, treating block 16 (VRS start) as block
2597 Buffer
= &Vcb
->SecCacheChunks
[ Vcb
->SecCacheLRUChunkIndex
];
2599 StartBlock
= Lbn
- ((Lbn
- 16) % CD_SEC_CHUNK_BLOCKS
);
2602 // Make sure we don't try and read past end of the last track.
2605 TrackData
= &Vcb
->CdromToc
->TrackData
[(Vcb
->CdromToc
->LastTrack
- Vcb
->CdromToc
->FirstTrack
+ 1)];
2607 SwapCopyUchar4( &EndBlock
, &TrackData
->Address
);
2609 Blocks
= EndBlock
- StartBlock
;
2611 if (Blocks
> CD_SEC_CHUNK_BLOCKS
) {
2613 Blocks
= CD_SEC_CHUNK_BLOCKS
;
2616 if ((0 == Blocks
) || (Lbn
< 16)) {
2618 CdRaiseStatus( IrpContext
, STATUS_INVALID_PARAMETER
);
2622 // Now build / send the read request.
2625 IoReuseIrp( Vcb
->SectorCacheIrp
, STATUS_SUCCESS
);
2627 KeClearEvent( &Vcb
->SectorCacheEvent
);
2628 Vcb
->SectorCacheIrp
->Tail
.Overlay
.Thread
= PsGetCurrentThread();
2631 // Get a pointer to the stack location of the first driver which will be
2632 // invoked. This is where the function codes and the parameters are set.
2635 IrpSp
= IoGetNextIrpStackLocation( Vcb
->SectorCacheIrp
);
2636 IrpSp
->MajorFunction
= (UCHAR
) IRP_MJ_READ
;
2639 // Build an MDL to describe the buffer.
2642 IoAllocateMdl( Buffer
->Buffer
,
2643 BytesFromSectors( Blocks
),
2646 Vcb
->SectorCacheIrp
);
2648 if (NULL
== Vcb
->SectorCacheIrp
->MdlAddress
) {
2650 IrpContext
->Irp
->IoStatus
.Information
= 0;
2651 CdRaiseStatus( IrpContext
, STATUS_INSUFFICIENT_RESOURCES
);
2655 // We're reading/writing into the block cache (paged pool). Lock the
2656 // pages and update the MDL with physical page information.
2661 MmProbeAndLockPages( Vcb
->SectorCacheIrp
->MdlAddress
,
2663 (LOCK_OPERATION
) IoWriteAccess
);
2665 #pragma warning(suppress: 6320)
2666 except(EXCEPTION_EXECUTE_HANDLER
) {
2668 IoFreeMdl( Vcb
->SectorCacheIrp
->MdlAddress
);
2669 Vcb
->SectorCacheIrp
->MdlAddress
= NULL
;
2672 if (NULL
== Vcb
->SectorCacheIrp
->MdlAddress
) {
2674 CdRaiseStatus( IrpContext
, STATUS_INSUFFICIENT_RESOURCES
);
2678 // Reset the BaseLbn as we can't trust this Buffer's data until the request
2679 // is successfully completed.
2682 Buffer
->BaseLbn
= (ULONG
)-1;
2684 IrpSp
->Parameters
.Read
.Length
= BytesFromSectors( Blocks
);
2685 IrpSp
->Parameters
.Read
.ByteOffset
.QuadPart
= LlBytesFromSectors( StartBlock
);
2687 IoSetCompletionRoutine( Vcb
->SectorCacheIrp
,
2688 CdSyncCompletionRoutine
,
2689 &Vcb
->SectorCacheEvent
,
2694 Vcb
->SectorCacheIrp
->UserIosb
= &Iosb
;
2696 Status
= IoCallDriver( Vcb
->TargetDeviceObject
, Vcb
->SectorCacheIrp
);
2698 if (STATUS_PENDING
== Status
) {
2701 (VOID
)KeWaitForSingleObject( &Vcb
->SectorCacheEvent
,
2707 Status
= Vcb
->SectorCacheIrp
->IoStatus
.Status
;
2710 Vcb
->SectorCacheIrp
->UserIosb
= NULL
;
2713 // Unlock the pages and free the MDL.
2716 MmUnlockPages( Vcb
->SectorCacheIrp
->MdlAddress
);
2717 IoFreeMdl( Vcb
->SectorCacheIrp
->MdlAddress
);
2718 Vcb
->SectorCacheIrp
->MdlAddress
= NULL
;
2720 if (!NT_SUCCESS( Status
)) {
2722 try_leave( Status
);
2726 // Update the buffer information, and drop the cache resource to shared
2727 // to allow in reads.
2730 Buffer
->BaseLbn
= StartBlock
;
2731 Vcb
->SecCacheLRUChunkIndex
= (Vcb
->SecCacheLRUChunkIndex
+ 1) % CD_SEC_CACHE_CHUNKS
;
2733 CdConvertCacheToShared( IrpContext
);
2743 CdReleaseCache( IrpContext
);
2751 // Local support routine
2754 _Requires_lock_held_(_Global_critical_region_
)
2757 _In_ PIRP_CONTEXT IrpContext
,
2759 _In_ ULONG RunCount
,
2760 _Inout_ PIO_RUN IoRuns
2765 Routine Description:
2767 This routine first does the initial setup required of a Master IRP that is
2768 going to be completed using associated IRPs. This routine should not
2769 be used if only one async request is needed, instead the single read
2770 async routines should be called.
2772 A context parameter is initialized, to serve as a communications area
2773 between here and the common completion routine.
2775 Next this routine reads or writes one or more contiguous sectors from
2776 a device asynchronously, and is used if there are multiple reads for a
2777 master IRP. A completion routine is used to synchronize with the
2778 completion of all of the I/O requests started by calls to this routine.
2780 Also, prior to calling this routine the caller must initialize the
2781 IoStatus field in the Context, with the correct success status and byte
2782 count which are expected if all of the parallel transfers complete
2783 successfully. After return this status will be unchanged if all requests
2784 were, in fact, successful. However, if one or more errors occur, the
2785 IoStatus will be modified to reflect the error status and byte count
2786 from the first run (by Vbo) which encountered an error. I/O status
2787 from all subsequent runs will not be indicated.
2791 RunCount - Supplies the number of multiple async requests
2792 that will be issued against the master irp.
2794 IoRuns - Supplies an array containing the Offset and ByteCount for the
2804 PIO_COMPLETION_ROUTINE CompletionRoutine
;
2805 PIO_STACK_LOCATION IrpSp
;
2809 ULONG UnwindRunCount
;
2810 BOOLEAN UseSectorCache
;
2815 // Set up things according to whether this is truely async.
2818 CompletionRoutine
= CdMultiSyncCompletionRoutine
;
2820 if (!FlagOn( IrpContext
->Flags
, IRP_CONTEXT_FLAG_WAIT
)) {
2822 CompletionRoutine
= CdMultiAsyncCompletionRoutine
;
2826 // For directories, use the sector cache.
2829 if ((SafeNodeType( Fcb
) == CDFS_NTC_FCB_INDEX
) &&
2830 (NULL
!= Fcb
->Vcb
->SectorCacheBuffer
) &&
2831 (VcbMounted
== IrpContext
->Vcb
->VcbCondition
)) {
2833 UseSectorCache
= TRUE
;
2837 UseSectorCache
= FALSE
;
2841 // Initialize some local variables.
2844 MasterIrp
= IrpContext
->Irp
;
2847 // Itterate through the runs, doing everything that can fail.
2848 // We let the cleanup in CdFinishBuffers clean up on error.
2851 for (UnwindRunCount
= 0;
2852 UnwindRunCount
< RunCount
;
2853 UnwindRunCount
+= 1) {
2855 if (UseSectorCache
) {
2857 if (!CdReadDirDataThroughCache( IrpContext
, &IoRuns
[ UnwindRunCount
])) {
2860 // Turn off using directory cache and restart all over again.
2863 UseSectorCache
= FALSE
;
2871 // Create an associated IRP, making sure there is one stack entry for
2875 IoRuns
[UnwindRunCount
].SavedIrp
=
2876 Irp
= IoMakeAssociatedIrp( MasterIrp
, (CCHAR
)(IrpContext
->Vcb
->TargetDeviceObject
->StackSize
+ 1) );
2880 IrpContext
->Irp
->IoStatus
.Information
= 0;
2881 CdRaiseStatus( IrpContext
, STATUS_INSUFFICIENT_RESOURCES
);
2885 // Allocate and build a partial Mdl for the request.
2888 Mdl
= IoAllocateMdl( IoRuns
[UnwindRunCount
].TransferVirtualAddress
,
2889 IoRuns
[UnwindRunCount
].DiskByteCount
,
2896 IrpContext
->Irp
->IoStatus
.Information
= 0;
2897 CdRaiseStatus( IrpContext
, STATUS_INSUFFICIENT_RESOURCES
);
2900 IoBuildPartialMdl( IoRuns
[UnwindRunCount
].TransferMdl
,
2902 IoRuns
[UnwindRunCount
].TransferVirtualAddress
,
2903 IoRuns
[UnwindRunCount
].DiskByteCount
);
2906 // Get the first IRP stack location in the associated Irp
2909 IoSetNextIrpStackLocation( Irp
);
2910 IrpSp
= IoGetCurrentIrpStackLocation( Irp
);
2913 // Setup the Stack location to describe our read.
2916 IrpSp
->MajorFunction
= IRP_MJ_READ
;
2917 IrpSp
->Parameters
.Read
.Length
= IoRuns
[UnwindRunCount
].DiskByteCount
;
2918 IrpSp
->Parameters
.Read
.ByteOffset
.QuadPart
= IoRuns
[UnwindRunCount
].DiskOffset
;
2921 // Set up the completion routine address in our stack frame.
2924 IoSetCompletionRoutine( Irp
,
2926 IrpContext
->IoContext
,
2932 // Setup the next IRP stack location in the associated Irp for the disk
2933 // driver beneath us.
2936 IrpSp
= IoGetNextIrpStackLocation( Irp
);
2939 // Setup the Stack location to do a read from the disk driver.
2942 IrpSp
->MajorFunction
= IRP_MJ_READ
;
2943 IrpSp
->Parameters
.Read
.Length
= IoRuns
[UnwindRunCount
].DiskByteCount
;
2944 IrpSp
->Parameters
.Read
.ByteOffset
.QuadPart
= IoRuns
[UnwindRunCount
].DiskOffset
;
2948 // If we used the cache, we're done.
2951 if (UseSectorCache
) {
2953 if (FlagOn( IrpContext
->Flags
, IRP_CONTEXT_FLAG_WAIT
)) {
2955 IrpContext
->Irp
->IoStatus
.Status
= STATUS_SUCCESS
;
2956 KeSetEvent( &IrpContext
->IoContext
->SyncEvent
, 0, FALSE
);
2963 // We only need to set the associated IRP count in the master irp to
2964 // make it a master IRP. But we set the count to one more than our
2965 // caller requested, because we do not want the I/O system to complete
2966 // the I/O. We also set our own count.
2969 IrpContext
->IoContext
->IrpCount
= RunCount
;
2970 IrpContext
->IoContext
->MasterIrp
= MasterIrp
;
2973 // We set the count in the master Irp to 1 since typically we
2974 // will clean up the associated irps ourselves. Setting this to one
2975 // means completing the last associated Irp with SUCCESS (in the async
2976 // case) will complete the master irp.
2979 MasterIrp
->AssociatedIrp
.IrpCount
= 1;
2982 // If we (FS) acquired locks, transition the lock owners to an object, since
2983 // when we return this thread could go away before request completion, and
2984 // the resource package may otherwise try to boost priority, etc.
2987 if (!FlagOn( IrpContext
->Flags
, IRP_CONTEXT_FLAG_WAIT
) &&
2988 FlagOn( IrpContext
->Flags
, IRP_CONTEXT_FLAG_TOP_LEVEL
)) {
2990 NT_ASSERT( IrpContext
->IoContext
->ResourceThreadId
== (ERESOURCE_THREAD
)PsGetCurrentThread() );
2992 IrpContext
->IoContext
->ResourceThreadId
= ((ULONG_PTR
)IrpContext
->IoContext
) | 3;
2994 ExSetResourceOwnerPointer( IrpContext
->IoContext
->Resource
,
2995 (PVOID
)IrpContext
->IoContext
->ResourceThreadId
);
2999 // Now that all the dangerous work is done, issue the Io requests
3002 for (UnwindRunCount
= 0;
3003 UnwindRunCount
< RunCount
;
3006 Irp
= IoRuns
[UnwindRunCount
].SavedIrp
;
3007 IoRuns
[UnwindRunCount
].SavedIrp
= NULL
;
3012 // If IoCallDriver returns an error, it has completed the Irp
3013 // and the error will be caught by our completion routines
3014 // and dealt with as a normal IO error.
3017 (VOID
) IoCallDriver( IrpContext
->Vcb
->TargetDeviceObject
, Irp
);
3024 // Local support routine
3029 _In_ PIRP_CONTEXT IrpContext
,
3030 _In_ ULONG RunCount
,
3031 _Inout_ PIO_RUN IoRuns
,
3032 _In_ PRAW_READ_INFO RawReads
,
3033 _In_ TRACK_MODE_TYPE TrackMode
3038 Routine Description:
3040 This routine first does the initial setup required of a Master IRP that is
3041 going to be completed using associated IRPs. This routine is used to generate
3042 the associated Irps used to read raw sectors from the disk.
3044 A context parameter is initialized, to serve as a communications area
3045 between here and the common completion routine.
3047 Next this routine reads or writes one or more contiguous sectors from
3048 a device asynchronously, and is used if there are multiple reads for a
3049 master IRP. A completion routine is used to synchronize with the
3050 completion of all of the I/O requests started by calls to this routine.
3052 Also, prior to calling this routine the caller must initialize the
3053 IoStatus field in the Context, with the correct success status and byte
3054 count which are expected if all of the parallel transfers complete
3055 successfully. After return this status will be unchanged if all requests
3056 were, in fact, successful. However, if one or more errors occur, the
3057 IoStatus will be modified to reflect the error status and byte count
3058 from the first run (by Vbo) which encountered an error. I/O status
3059 from all subsequent runs will not be indicated.
3063 RunCount - Supplies the number of multiple async requests
3064 that will be issued against the master irp.
3066 IoRuns - Supplies an array containing the Offset and ByteCount for the
3069 RawReads - Supplies an array of structures to store in the Irps passed to the
3070 device driver to perform the low-level Io.
3072 TrackMode - Supplies the recording mode of sectors in these IoRuns
3081 PIO_STACK_LOCATION IrpSp
;
3085 ULONG UnwindRunCount
;
3088 PIO_RUN ThisIoRun
= IoRuns
;
3089 PRAW_READ_INFO ThisRawRead
= RawReads
;
3094 // Initialize some local variables.
3097 MasterIrp
= IrpContext
->Irp
;
3100 // Itterate through the runs, doing everything that can fail.
3101 // We let the cleanup in CdFinishBuffers clean up on error.
3104 for (UnwindRunCount
= 0;
3105 UnwindRunCount
< RunCount
;
3106 UnwindRunCount
+= 1, ThisIoRun
+= 1, ThisRawRead
+= 1) {
3109 // Create an associated IRP, making sure there is one stack entry for
3113 ThisIoRun
->SavedIrp
=
3114 Irp
= IoMakeAssociatedIrp( MasterIrp
, (CCHAR
)(IrpContext
->Vcb
->TargetDeviceObject
->StackSize
+ 1) );
3118 IrpContext
->Irp
->IoStatus
.Information
= 0;
3119 CdRaiseStatus( IrpContext
, STATUS_INSUFFICIENT_RESOURCES
);
3123 // Should have been passed a byte count of at least one sector, and
3124 // must be a multiple of sector size
3127 NT_ASSERT( ThisIoRun
->DiskByteCount
&& !SectorOffset(ThisIoRun
->DiskByteCount
));
3129 RawByteCount
= SectorsFromBytes( ThisIoRun
->DiskByteCount
) * RAW_SECTOR_SIZE
;
3132 // Allocate and build a partial Mdl for the request.
3135 Mdl
= IoAllocateMdl( ThisIoRun
->TransferVirtualAddress
,
3143 IrpContext
->Irp
->IoStatus
.Information
= 0;
3144 CdRaiseStatus( IrpContext
, STATUS_INSUFFICIENT_RESOURCES
);
3147 IoBuildPartialMdl( ThisIoRun
->TransferMdl
,
3149 ThisIoRun
->TransferVirtualAddress
,
3152 // Get the first IRP stack location in the associated Irp
3155 IoSetNextIrpStackLocation( Irp
);
3156 IrpSp
= IoGetCurrentIrpStackLocation( Irp
);
3159 // Setup the Stack location to describe our read (using cooked values)
3160 // These values won't be used for the raw read in any case.
3163 IrpSp
->MajorFunction
= IRP_MJ_READ
;
3164 IrpSp
->Parameters
.Read
.Length
= ThisIoRun
->DiskByteCount
;
3165 IrpSp
->Parameters
.Read
.ByteOffset
.QuadPart
= ThisIoRun
->DiskOffset
;
3168 // Set up the completion routine address in our stack frame.
3171 IoSetCompletionRoutine( Irp
,
3172 CdMultiSyncCompletionRoutine
,
3173 IrpContext
->IoContext
,
3179 // Setup the next IRP stack location in the associated Irp for the disk
3180 // driver beneath us.
3183 IrpSp
= IoGetNextIrpStackLocation( Irp
);
3186 // Setup the stack location to do a read of raw sectors at this location.
3187 // Note that the storage stack always reads multiples of whole XA sectors.
3190 ThisRawRead
->DiskOffset
.QuadPart
= ThisIoRun
->DiskOffset
;
3191 ThisRawRead
->SectorCount
= ThisIoRun
->DiskByteCount
>> SECTOR_SHIFT
;
3192 ThisRawRead
->TrackMode
= TrackMode
;
3194 IrpSp
->MajorFunction
= IRP_MJ_DEVICE_CONTROL
;
3196 IrpSp
->Parameters
.DeviceIoControl
.OutputBufferLength
= ThisRawRead
->SectorCount
* RAW_SECTOR_SIZE
;
3197 Irp
->UserBuffer
= ThisIoRun
->TransferVirtualAddress
;
3199 IrpSp
->Parameters
.DeviceIoControl
.InputBufferLength
= sizeof( RAW_READ_INFO
);
3200 IrpSp
->Parameters
.DeviceIoControl
.Type3InputBuffer
= ThisRawRead
;
3202 IrpSp
->Parameters
.DeviceIoControl
.IoControlCode
= IOCTL_CDROM_RAW_READ
;
3206 // We only need to set the associated IRP count in the master irp to
3207 // make it a master IRP. But we set the count to one more than our
3208 // caller requested, because we do not want the I/O system to complete
3209 // the I/O. We also set our own count.
3212 IrpContext
->IoContext
->IrpCount
= RunCount
;
3213 IrpContext
->IoContext
->MasterIrp
= MasterIrp
;
3216 // We set the count in the master Irp to 1 since typically we
3217 // will clean up the associated irps ourselves. Setting this to one
3218 // means completing the last associated Irp with SUCCESS (in the async
3219 // case) will complete the master irp.
3222 MasterIrp
->AssociatedIrp
.IrpCount
= 1;
3225 // Now that all the dangerous work is done, issue the Io requests
3228 for (UnwindRunCount
= 0;
3229 UnwindRunCount
< RunCount
;
3232 Irp
= IoRuns
[UnwindRunCount
].SavedIrp
;
3233 IoRuns
[UnwindRunCount
].SavedIrp
= NULL
;
3237 // If IoCallDriver returns an error, it has completed the Irp
3238 // and the error will be caught by our completion routines
3239 // and dealt with as a normal IO error.
3242 (VOID
) IoCallDriver( IrpContext
->Vcb
->TargetDeviceObject
, Irp
);
3250 // Local support routine
3253 _Requires_lock_held_(_Global_critical_region_
)
3256 _In_ PIRP_CONTEXT IrpContext
,
3263 Routine Description:
3265 This routine reads one or more contiguous sectors from a device
3266 asynchronously, and is used if there is only one read necessary to
3267 complete the IRP. It implements the read by simply filling
3268 in the next stack frame in the Irp, and passing it on. The transfer
3269 occurs to the single buffer originally specified in the user request.
3273 ByteOffset - Supplies the starting Logical Byte Offset to begin reading from
3275 ByteCount - Supplies the number of bytes to read from the device
3284 PIO_STACK_LOCATION IrpSp
;
3285 PIO_COMPLETION_ROUTINE CompletionRoutine
;
3290 // For directories, look in the sector cache,
3293 if ((SafeNodeType( Fcb
) == CDFS_NTC_FCB_INDEX
) &&
3294 (NULL
!= Fcb
->Vcb
->SectorCacheBuffer
) &&
3295 (VcbMounted
== IrpContext
->Vcb
->VcbCondition
)) {
3297 if (CdReadDirDataThroughCache( IrpContext
, Run
)) {
3299 if (FlagOn( IrpContext
->Flags
, IRP_CONTEXT_FLAG_WAIT
)) {
3301 IrpContext
->Irp
->IoStatus
.Status
= STATUS_SUCCESS
;
3302 KeSetEvent( &IrpContext
->IoContext
->SyncEvent
, 0, FALSE
);
3310 // Set up things according to whether this is truely async.
3313 if (FlagOn( IrpContext
->Flags
, IRP_CONTEXT_FLAG_WAIT
)) {
3315 CompletionRoutine
= CdSingleSyncCompletionRoutine
;
3319 CompletionRoutine
= CdSingleAsyncCompletionRoutine
;
3322 // If we (FS) acquired locks, transition the lock owners to an object, since
3323 // when we return this thread could go away before request completion, and
3324 // the resource package may otherwise try to boost priority, etc.
3327 if (FlagOn( IrpContext
->Flags
, IRP_CONTEXT_FLAG_TOP_LEVEL
)) {
3329 NT_ASSERT( IrpContext
->IoContext
->ResourceThreadId
== (ERESOURCE_THREAD
)PsGetCurrentThread() );
3331 IrpContext
->IoContext
->ResourceThreadId
= ((ULONG_PTR
)IrpContext
->IoContext
) | 3;
3333 ExSetResourceOwnerPointer( IrpContext
->IoContext
->Resource
,
3334 (PVOID
)IrpContext
->IoContext
->ResourceThreadId
);
3339 // Set up the completion routine address in our stack frame.
3342 IoSetCompletionRoutine( IrpContext
->Irp
,
3344 IrpContext
->IoContext
,
3350 // Setup the next IRP stack location in the associated Irp for the disk
3351 // driver beneath us.
3354 IrpSp
= IoGetNextIrpStackLocation( IrpContext
->Irp
);
3357 // Setup the Stack location to do a read from the disk driver.
3360 IrpSp
->MajorFunction
= IrpContext
->MajorFunction
;
3361 IrpSp
->Parameters
.Read
.Length
= Run
->DiskByteCount
;
3362 IrpSp
->Parameters
.Read
.ByteOffset
.QuadPart
= Run
->DiskOffset
;
3365 // Issue the Io request
3369 // If IoCallDriver returns an error, it has completed the Irp
3370 // and the error will be caught by our completion routines
3371 // and dealt with as a normal IO error.
3374 (VOID
)IoCallDriver( IrpContext
->Vcb
->TargetDeviceObject
, IrpContext
->Irp
);
3379 // Local support routine
3384 _In_ PIRP_CONTEXT IrpContext
3389 Routine Description:
3391 This routine waits for one or more previously started I/O requests
3392 from the above routines, by simply waiting on the event.
3406 (VOID
)KeWaitForSingleObject( &IrpContext
->IoContext
->SyncEvent
,
3412 KeClearEvent( &IrpContext
->IoContext
->SyncEvent
);
3417 // Local support routine
3421 CdMultiSyncCompletionRoutine (
3422 PDEVICE_OBJECT DeviceObject
,
3429 Routine Description:
3431 This is the completion routine for all synchronous reads
3432 started via CdMultipleAsynch.
3434 The completion routine has has the following responsibilities:
3436 If the individual request was completed with an error, then
3437 this completion routine must see if this is the first error
3438 and remember the error status in the Context.
3440 If the IrpCount goes to 1, then it sets the event in the Context
3441 parameter to signal the caller that all of the asynch requests
3446 DeviceObject - Pointer to the file system device object.
3448 Irp - Pointer to the associated Irp which is being completed. (This
3449 Irp will no longer be accessible after this routine returns.)
3451 Context - The context parameter which was specified for all of
3452 the multiple asynch I/O requests for this MasterIrp.
3456 The routine returns STATUS_MORE_PROCESSING_REQUIRED so that we can
3457 immediately complete the Master Irp without being in a race condition
3458 with the IoCompleteRequest thread trying to decrement the IrpCount in
3464 PCD_IO_CONTEXT IoContext
= Context
;
3465 _Analysis_assume_(Context
!= NULL
);
3467 AssertVerifyDeviceIrp( Irp
);
3470 // If we got an error (or verify required), remember it in the Irp
3473 if (!NT_SUCCESS( Irp
->IoStatus
.Status
)) {
3475 InterlockedExchange( &IoContext
->Status
, Irp
->IoStatus
.Status
);
3476 IoContext
->MasterIrp
->IoStatus
.Information
= 0;
3480 // We must do this here since IoCompleteRequest won't get a chance
3481 // on this associated Irp.
3484 IoFreeMdl( Irp
->MdlAddress
);
3487 if (InterlockedDecrement( &IoContext
->IrpCount
) == 0) {
3490 // Update the Master Irp with any error status from the associated Irps.
3493 IoContext
->MasterIrp
->IoStatus
.Status
= IoContext
->Status
;
3494 KeSetEvent( &IoContext
->SyncEvent
, 0, FALSE
);
3497 UNREFERENCED_PARAMETER( DeviceObject
);
3499 return STATUS_MORE_PROCESSING_REQUIRED
;
3504 // Local support routine
3508 CdMultiAsyncCompletionRoutine (
3509 PDEVICE_OBJECT DeviceObject
,
3516 Routine Description:
3518 This is the completion routine for all asynchronous reads
3519 started via CdMultipleAsynch.
3521 The completion routine has has the following responsibilities:
3523 If the individual request was completed with an error, then
3524 this completion routine must see if this is the first error
3525 and remember the error status in the Context.
3529 DeviceObject - Pointer to the file system device object.
3531 Irp - Pointer to the associated Irp which is being completed. (This
3532 Irp will no longer be accessible after this routine returns.)
3534 Context - The context parameter which was specified for all of
3535 the multiple asynch I/O requests for this MasterIrp.
3539 Currently always returns STATUS_SUCCESS.
3544 PCD_IO_CONTEXT IoContext
= Context
;
3545 _Analysis_assume_(Context
!= NULL
);
3546 AssertVerifyDeviceIrp( Irp
);
3548 UNREFERENCED_PARAMETER( DeviceObject
);
3551 // If we got an error (or verify required), remember it in the Irp
3554 if (!NT_SUCCESS( Irp
->IoStatus
.Status
)) {
3556 InterlockedExchange( &IoContext
->Status
, Irp
->IoStatus
.Status
);
3560 // Decrement IrpCount and see if it goes to zero.
3563 if (InterlockedDecrement( &IoContext
->IrpCount
) == 0) {
3566 // Mark the master Irp pending
3569 IoMarkIrpPending( IoContext
->MasterIrp
);
3572 // Update the Master Irp with any error status from the associated Irps.
3575 IoContext
->MasterIrp
->IoStatus
.Status
= IoContext
->Status
;
3578 // Update the information field with the correct value.
3581 IoContext
->MasterIrp
->IoStatus
.Information
= 0;
3583 if (NT_SUCCESS( IoContext
->MasterIrp
->IoStatus
.Status
)) {
3585 IoContext
->MasterIrp
->IoStatus
.Information
= IoContext
->RequestedByteCount
;
3589 // Now release the resource
3592 _Analysis_assume_lock_held_(*IoContext
->Resource
);
3593 ExReleaseResourceForThreadLite( IoContext
->Resource
, IoContext
->ResourceThreadId
);
3596 // and finally, free the context record.
3599 CdFreeIoContext( IoContext
);
3602 // Return success in this case.
3605 return STATUS_SUCCESS
;
3610 // We need to cleanup the associated Irp and its Mdl.
3613 IoFreeMdl( Irp
->MdlAddress
);
3616 return STATUS_MORE_PROCESSING_REQUIRED
;
3623 // Local support routine
3627 CdSingleSyncCompletionRoutine (
3628 PDEVICE_OBJECT DeviceObject
,
3635 Routine Description:
3637 This is the completion routine for all reads started via CdSingleAsynch.
3639 The completion routine has has the following responsibilities:
3641 It sets the event in the Context parameter to signal the caller
3642 that all of the asynch requests are done.
3646 DeviceObject - Pointer to the file system device object.
3648 Irp - Pointer to the Irp for this request. (This Irp will no longer
3649 be accessible after this routine returns.)
3651 Context - The context parameter which was specified in the call to
3656 The routine returns STATUS_MORE_PROCESSING_REQUIRED so that we can
3657 immediately complete the Master Irp without being in a race condition
3658 with the IoCompleteRequest thread trying to decrement the IrpCount in
3664 _Analysis_assume_(Context
!= NULL
);
3666 UNREFERENCED_PARAMETER( DeviceObject
);
3668 AssertVerifyDeviceIrp( Irp
);
3671 // Store the correct information field into the Irp.
3674 if (!NT_SUCCESS( Irp
->IoStatus
.Status
)) {
3676 Irp
->IoStatus
.Information
= 0;
3679 KeSetEvent( &((PCD_IO_CONTEXT
)Context
)->SyncEvent
, 0, FALSE
);
3681 return STATUS_MORE_PROCESSING_REQUIRED
;
3686 // Local support routine
3690 CdSingleAsyncCompletionRoutine (
3691 PDEVICE_OBJECT DeviceObject
,
3698 Routine Description:
3700 This is the completion routine for all asynchronous reads
3701 started via CdSingleAsynch.
3705 DeviceObject - Pointer to the file system device object.
3707 Irp - Pointer to the Irp for this request. (This Irp will no longer
3708 be accessible after this routine returns.)
3710 Context - The context parameter which was specified in the call to
3715 Currently always returns STATUS_SUCCESS.
3720 PCD_IO_CONTEXT IoContext
= Context
;
3722 UNREFERENCED_PARAMETER( DeviceObject
);
3724 _Analysis_assume_(IoContext
!= NULL
);
3725 AssertVerifyDeviceIrp( Irp
);
3728 // Update the information field with the correct value for bytes read.
3731 Irp
->IoStatus
.Information
= 0;
3733 if (NT_SUCCESS( Irp
->IoStatus
.Status
)) {
3735 Irp
->IoStatus
.Information
= IoContext
->RequestedByteCount
;
3739 // Mark the Irp pending
3742 IoMarkIrpPending( Irp
);
3745 // Now release the resource
3748 _Analysis_assume_lock_held_(*IoContext
->Resource
);
3749 ExReleaseResourceForThreadLite( IoContext
->Resource
, IoContext
->ResourceThreadId
);
3752 // and finally, free the context record.
3755 CdFreeIoContext( IoContext
);
3756 return STATUS_SUCCESS
;
3762 // Local support routine
3765 _When_(SafeNodeType(Fcb
) != CDFS_NTC_FCB_PATH_TABLE
&& StartingOffset
== 0, _At_(ByteCount
, _In_range_(>=, CdAudioDirentSize
+ sizeof(RAW_DIRENT
))))
3766 _When_(SafeNodeType(Fcb
) != CDFS_NTC_FCB_PATH_TABLE
&& StartingOffset
!= 0, _At_(ByteCount
, _In_range_(>=, CdAudioDirentSize
+ SECTOR_SIZE
)))
3768 CdReadAudioSystemFile (
3769 _In_ PIRP_CONTEXT IrpContext
,
3771 _In_ LONGLONG StartingOffset
,
3772 _In_
_In_range_(>=, CdAudioDirentSize
) ULONG ByteCount
,
3773 _Out_writes_bytes_(ByteCount
) PVOID SystemBuffer
3778 Routine Description:
3780 This routine is called to read the pseudo root directory and path
3781 table for a music disk. We build the individual elements on the
3782 stack and copy into the cache buffer.
3786 Fcb - Fcb representing the file to read.
3788 StartingOffset - Logical offset in the file to read from.
3790 ByteCount - Number of bytes to read.
3792 SystemBuffer - Pointer to buffer to fill in. This will always be page
3802 PRAW_PATH_ISO RawPath
;
3803 PRAW_DIRENT RawDirent
;
3810 PTRACK_DATA ThisTrack
;
3812 LONGLONG CurrentOffset
;
3814 PVOID CurrentSector
;
3816 PSYSTEM_USE_XA SystemUse
;
3820 UCHAR LocalBuffer
[FIELD_OFFSET( RAW_DIRENT
, FileId
) + 12];
3825 // If this is the path table then we just need a single entry.
3828 if (SafeNodeType( Fcb
) == CDFS_NTC_FCB_PATH_TABLE
) {
3831 // Sanity check that the offset is zero.
3834 NT_ASSERT( StartingOffset
== 0 );
3837 // Store a pseudo path entry in our local buffer.
3840 RawPath
= (PRAW_PATH_ISO
) LocalBuffer
;
3842 RtlZeroMemory( RawPath
, sizeof( LocalBuffer
));
3844 RawPath
->DirIdLen
= 1;
3845 RawPath
->ParentNum
= 1;
3846 RawPath
->DirId
[0] = '\0';
3849 // Now copy to the user's buffer.
3852 BytesToCopy
= FIELD_OFFSET( RAW_PATH_ISO
, DirId
) + 2;
3854 if (BytesToCopy
> ByteCount
) {
3856 BytesToCopy
= ByteCount
;
3859 RtlCopyMemory( SystemBuffer
,
3864 // We need to deal with the multiple sector case for the root directory.
3870 // Initialize the first track to return to our caller.
3876 // If the offset is zero then store the entries for the self and parent
3880 if (StartingOffset
== 0) {
3882 RawDirent
= SystemBuffer
;
3885 // Clear all of the fields initially.
3888 RtlZeroMemory( RawDirent
, FIELD_OFFSET( RAW_DIRENT
, FileId
));
3891 // Now fill in the interesting fields.
3894 RawDirent
->DirLen
= FIELD_OFFSET( RAW_DIRENT
, FileId
) + 1;
3895 RawDirent
->FileIdLen
= 1;
3896 RawDirent
->FileId
[0] = '\0';
3897 SetFlag( RawDirent
->FlagsISO
, CD_ATTRIBUTE_DIRECTORY
);
3900 // Set the time stamp to be Jan 1, 1995
3903 RawDirent
->RecordTime
[0] = 95;
3904 RawDirent
->RecordTime
[1] = 1;
3905 RawDirent
->RecordTime
[2] = 1;
3907 SectorOffset
= RawDirent
->DirLen
;
3909 RawDirent
= Add2Ptr( RawDirent
, SectorOffset
, PRAW_DIRENT
);
3912 // Clear all of the fields initially.
3915 RtlZeroMemory( RawDirent
, FIELD_OFFSET( RAW_DIRENT
, FileId
));
3918 // Now fill in the interesting fields.
3921 RawDirent
->DirLen
= FIELD_OFFSET( RAW_DIRENT
, FileId
) + 1;
3922 RawDirent
->FileIdLen
= 1;
3923 RawDirent
->FileId
[0] = '\1';
3924 SetFlag( RawDirent
->FlagsISO
, CD_ATTRIBUTE_DIRECTORY
);
3927 // Set the time stamp to be Jan 1, 1995
3930 RawDirent
->RecordTime
[0] = 95;
3931 RawDirent
->RecordTime
[1] = 1;
3932 RawDirent
->RecordTime
[2] = 1;
3934 SectorOffset
+= RawDirent
->DirLen
;
3938 // Otherwise compute the starting track to write to the buffer.
3944 // Count the tracks in each preceding sector.
3951 CurrentTrack
+= CdAudioDirentsPerSector
;
3952 CurrentOffset
+= SECTOR_SIZE
;
3954 } while (CurrentOffset
< StartingOffset
);
3957 // Bias the track count to reflect the two default entries.
3967 // We now know the first track to return as well as where we are in
3968 // the current sector. We will walk through sector by sector adding
3969 // the entries for the separate tracks in the TOC. We will zero
3970 // any sectors or partial sectors without data.
3973 CurrentSector
= SystemBuffer
;
3974 BytesToCopy
= SECTOR_SIZE
;
3977 // Loop for each sector.
3983 // Add entries until we reach our threshold for each sector.
3989 // If we are beyond the entries in the TOC then exit.
3992 if (CurrentTrack
>= IrpContext
->Vcb
->TrackCount
) {
3997 ThisTrack
= &IrpContext
->Vcb
->CdromToc
->TrackData
[CurrentTrack
];
4000 // Point to the current position in the buffer.
4003 RawDirent
= Add2Ptr( CurrentSector
, SectorOffset
, PRAW_DIRENT
);
4006 // Clear all of the fields initially.
4009 RtlZeroMemory( RawDirent
, CdAudioDirentSize
);
4012 // Now fill in the interesting fields.
4015 RawDirent
->DirLen
= (UCHAR
) CdAudioDirentSize
;
4016 RawDirent
->FileIdLen
= CdAudioFileNameLength
;
4018 RtlCopyMemory( RawDirent
->FileId
,
4020 CdAudioFileNameLength
);
4023 // Set the time stamp to be Jan 1, 1995 00:00
4026 RawDirent
->RecordTime
[0] = 95;
4027 RawDirent
->RecordTime
[1] = 1;
4028 RawDirent
->RecordTime
[2] = 1;
4031 // Put the track number into the file name.
4034 TrackTens
= TrackOnes
= ThisTrack
->TrackNumber
;
4036 TrackOnes
= (TrackOnes
% 10) + '0';
4039 TrackTens
= (TrackTens
% 10) + '0';
4041 RawDirent
->FileId
[AUDIO_NAME_TENS_OFFSET
] = TrackTens
;
4042 RawDirent
->FileId
[AUDIO_NAME_ONES_OFFSET
] = TrackOnes
;
4044 SystemUse
= Add2Ptr( RawDirent
, CdAudioSystemUseOffset
, PSYSTEM_USE_XA
);
4046 SystemUse
->Attributes
= SYSTEM_USE_XA_DA
;
4047 SystemUse
->Signature
= SYSTEM_XA_SIGNATURE
;
4050 // Store the track number as the file number.
4053 SystemUse
->FileNumber
= (UCHAR
) CurrentTrack
;
4056 SectorOffset
+= CdAudioDirentSize
;
4059 } while (EntryCount
< CdAudioDirentsPerSector
);
4062 // Zero the remaining portion of this buffer.
4065 RtlZeroMemory( Add2Ptr( CurrentSector
, SectorOffset
, PVOID
),
4066 SECTOR_SIZE
- SectorOffset
);
4069 // Prepare for the next sector.
4073 BytesToCopy
+= SECTOR_SIZE
;
4075 CurrentSector
= Add2Ptr( CurrentSector
, SECTOR_SIZE
, PVOID
);
4077 } while (BytesToCopy
<= ByteCount
);
4085 CdHijackIrpAndFlushDevice (
4086 _In_ PIRP_CONTEXT IrpContext
,
4088 _In_ PDEVICE_OBJECT TargetDeviceObject
4093 Routine Description:
4095 This routine is called when we need to send a flush to a device but
4096 we don't have a flush Irp. What this routine does is make a copy
4097 of its current Irp stack location, but changes the Irp Major code
4098 to a IRP_MJ_FLUSH_BUFFERS amd then send it down, but cut it off at
4099 the knees in the completion routine, fix it up and return to the
4100 user as if nothing had happened.
4104 Irp - The Irp to hijack
4106 TargetDeviceObject - The device to send the request to.
4110 NTSTATUS - The Status from the flush in case anybody cares.
4117 PIO_STACK_LOCATION NextIrpSp
;
4121 UNREFERENCED_PARAMETER( IrpContext
);
4124 // Get the next stack location, and copy over the stack location
4127 NextIrpSp
= IoGetNextIrpStackLocation( Irp
);
4129 *NextIrpSp
= *IoGetCurrentIrpStackLocation( Irp
);
4131 NextIrpSp
->MajorFunction
= IRP_MJ_FLUSH_BUFFERS
;
4132 NextIrpSp
->MinorFunction
= 0;
4135 // Set up the completion routine
4138 KeInitializeEvent( &Event
, NotificationEvent
, FALSE
);
4140 IoSetCompletionRoutine( Irp
,
4141 CdSyncCompletionRoutine
,
4148 // Send the request.
4151 Status
= IoCallDriver( TargetDeviceObject
, Irp
);
4153 if (Status
== STATUS_PENDING
) {
4155 (VOID
)KeWaitForSingleObject( &Event
, Executive
, KernelMode
, FALSE
, NULL
);
4157 Status
= Irp
->IoStatus
.Status
;
4161 // If the driver doesn't support flushes, return SUCCESS.
4164 if (Status
== STATUS_INVALID_DEVICE_REQUEST
) {
4166 Status
= STATUS_SUCCESS
;
4169 Irp
->IoStatus
.Status
= 0;
4170 Irp
->IoStatus
.Information
= 0;