summaryrefslogblamecommitdiffstats
path: root/private/nw/rdr/cache.c
blob: 0729b93214fcf86f906e47120a5edb0f1b009152 (plain) (tree)
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

























































































































































































































































































































































































































































































































































































































































































































                                                                                                
/*++

Copyright (c) 1994  Microsoft Corporation

Module Name:

    Cache.c

Abstract:

    This module implements internal caching support routines.  It does
    not interact with the cache manager.

Author:

    Manny Weiser     [MannyW]    05-Jan-1994

Revision History:

--*/

#include "Procs.h"

//
//  The local debug trace level
//

BOOLEAN
SpaceForWriteBehind(
    PNONPAGED_FCB NpFcb,
    ULONG FileOffset,
    ULONG BytesToWrite
    );

BOOLEAN
OkToReadAhead(
    PFCB Fcb,
    IN ULONG FileOffset,
    IN UCHAR IoType
    );

#define Dbg                              (DEBUG_TRACE_CACHE)

//
//  Local procedure prototypes
//

#ifdef ALLOC_PRAGMA
#pragma alloc_text( PAGE, CacheRead )
#pragma alloc_text( PAGE, SpaceForWriteBehind )
#pragma alloc_text( PAGE, CacheWrite )
#pragma alloc_text( PAGE, OkToReadAhead )
#pragma alloc_text( PAGE, CalculateReadAheadSize )
#pragma alloc_text( PAGE, FlushCache )
#pragma alloc_text( PAGE, AcquireFcbAndFlushCache )
#endif


ULONG
CacheRead(
    IN PNONPAGED_FCB NpFcb,
    IN ULONG FileOffset,
    IN ULONG BytesToRead,
    IN PVOID UserBuffer
    , IN BOOLEAN WholeBufferOnly
    )
/*++

Routine Description:

    This routine attempts to satisfy a user read from cache.  It returns
    the number of bytes actually copied from cache.

Arguments:

    NpFcb - A pointer the the nonpaged FCB of the file being read.

    FileOffset - The file offset to read.

    BytesToRead - The number of bytes to read.

    UserBuffer - A pointer to the users target buffer.

    WholeBufferOnly - Do a cache read only if we can satisfy the entire
        read request.

Return Value:

    The number of bytes copied to the user buffer.

--*/
{
    ULONG BytesToCopy;

    PAGED_CODE();

    if (DisableReadCache) return 0 ;

    DebugTrace(0, Dbg, "CacheRead...\n", 0 );
    DebugTrace( 0, Dbg, "FileOffset = %d\n", FileOffset );
    DebugTrace( 0, Dbg, "ByteCount  = %d\n", BytesToRead );

    NwAcquireSharedFcb( NpFcb, TRUE );

    //
    //  If this is a read ahead and it contains some data that the user
    //  could be interested in, copy the interesting data.
    //

    if ( NpFcb->CacheType == ReadAhead &&
         NpFcb->CacheDataSize != 0 &&
         FileOffset >= NpFcb->CacheFileOffset &&
         FileOffset <= NpFcb->CacheFileOffset + NpFcb->CacheDataSize ) {

        if ( NpFcb->CacheBuffer ) {

            //
            // Make sure we have a CacheBuffer.
            //

            BytesToCopy =
                MIN ( BytesToRead,
                      NpFcb->CacheFileOffset +
                          NpFcb->CacheDataSize - FileOffset );

            if ( WholeBufferOnly && BytesToCopy != BytesToRead ) {
                NwReleaseFcb( NpFcb );
                return( 0 );
            }

            RtlCopyMemory(
                UserBuffer,
                NpFcb->CacheBuffer + ( FileOffset - NpFcb->CacheFileOffset ),
                BytesToCopy );

            DebugTrace(0, Dbg, "CacheRead -> %d\n", BytesToCopy );

        } else {

            ASSERT(FALSE);      // we should never get here
            DebugTrace(0, Dbg, "CacheRead -> %08lx\n", 0 );
            BytesToCopy = 0;
        }


    } else {

        DebugTrace(0, Dbg, "CacheRead -> %08lx\n", 0 );
        BytesToCopy = 0;
    }

    NwReleaseFcb( NpFcb );
    return( BytesToCopy );
}


BOOLEAN
SpaceForWriteBehind(
    PNONPAGED_FCB NpFcb,
    ULONG FileOffset,
    ULONG BytesToWrite
    )
/*++

Routine Description:

    This routine determines if it is ok to write behind this data to
    this FCB.

Arguments:

    NpFcb - A pointer the the NONPAGED_FCB of the file being written.

    FileOffset - The file offset to write.

    BytesToWrite - The number of bytes to write.

Return Value:

    The number of bytes copied to the user buffer.

--*/
{
    PAGED_CODE();


    if ( NpFcb->CacheDataSize == 0 ) {
        NpFcb->CacheFileOffset = FileOffset;
    }

    if ( NpFcb->CacheDataSize == 0 && BytesToWrite >= NpFcb->CacheSize ) {
        return( FALSE );
    }

    if ( FileOffset - NpFcb->CacheFileOffset + BytesToWrite >
         NpFcb->CacheSize )  {

        return( FALSE );

    }

    return( TRUE );
}


BOOLEAN
CacheWrite(
    IN PIRP_CONTEXT IrpContext OPTIONAL,
    IN PNONPAGED_FCB NpFcb,
    IN ULONG FileOffset,
    IN ULONG BytesToWrite,
    IN PVOID UserBuffer
    )
/*++

Routine Description:

    This routine attempts to satisfy a user write to cache.  The write
    succeeds if it is sequential and fits in the cache buffer.

Arguments:

    IrpContext - A pointer to request parameters.

    NpFcb - A pointer the the NONPAGED_FCB of the file being read.

    FileOffset - The file offset to write.

    BytesToWrite - The number of bytes to write.

    UserBuffer - A pointer to the users source buffer.

Return Value:

    The number of bytes copied to the user buffer.

--*/
{
    ULONG CacheSize;
    NTSTATUS status;

    PAGED_CODE();

    if (DisableWriteCache) return FALSE ;

    DebugTrace( +1, Dbg, "CacheWrite...\n", 0 );
    DebugTrace(  0, Dbg, "FileOffset = %d\n", FileOffset );
    DebugTrace(  0, Dbg, "ByteCount  = %d\n", BytesToWrite );

    if ( NpFcb->Fcb->ShareAccess.SharedWrite ||
         NpFcb->Fcb->ShareAccess.SharedRead ) {

        DebugTrace(  0, Dbg, "File is not open in exclusive mode\n", 0 );
        DebugTrace( -1, Dbg, "CacheWrite -> FALSE\n", 0 );
        return( FALSE );
    }

    //
    //  Note, If we decide to send data to the server we must be at the front
    //  of the queue before we grab the Fcb exclusive.
    //

TryAgain:

    NwAcquireExclusiveFcb( NpFcb, TRUE );

    //
    //  Allocate a cache buffer if we don't already have one.
    //

    if ( NpFcb->CacheBuffer == NULL ) {

        if ( IrpContext == NULL ) {
            DebugTrace(  0, Dbg, "No cache buffer\n", 0 );
            DebugTrace( -1, Dbg, "CacheWrite -> FALSE\n", 0 );
            NwReleaseFcb( NpFcb );
            return( FALSE );
        }

        NpFcb->CacheType = WriteBehind;

        if (( IrpContext->pNpScb->SendBurstModeEnabled ) ||
            ( IrpContext->pNpScb->ReceiveBurstModeEnabled )) {

           CacheSize = IrpContext->pNpScb->MaxReceiveSize;

        } else {

           CacheSize = IrpContext->pNpScb->BufferSize;

        }

        try {

            NpFcb->CacheBuffer = ALLOCATE_POOL_EX( NonPagedPool, CacheSize );
            NpFcb->CacheSize = CacheSize;

            NpFcb->CacheMdl = ALLOCATE_MDL( NpFcb->CacheBuffer, CacheSize, FALSE, FALSE, NULL );

            if ( NpFcb->CacheMdl == NULL ) {
                ExRaiseStatus( STATUS_INSUFFICIENT_RESOURCES );
            }

            MmBuildMdlForNonPagedPool( NpFcb->CacheMdl );

        } except ( EXCEPTION_EXECUTE_HANDLER ) {

            if ( NpFcb->CacheBuffer != NULL) {
                FREE_POOL( NpFcb->CacheBuffer );

                NpFcb->CacheBuffer = NULL;
                NpFcb->CacheSize = 0;

            }

            DebugTrace(  0, Dbg, "Allocate failed\n", 0 );
            DebugTrace( -1, Dbg, "CacheWrite -> FALSE\n", 0 );

            NpFcb->CacheDataSize = 0;
            NwReleaseFcb( NpFcb );
            return( FALSE );
        }

        NpFcb->CacheFileOffset = 0;
        NpFcb->CacheDataSize = 0;

    } else if ( NpFcb->CacheType != WriteBehind ) {

        DebugTrace( -1, Dbg, "CacheWrite not writebehind -> FALSE\n", 0 );
        NwReleaseFcb( NpFcb );
        return( FALSE );

    }

    //
    //  If the data is non sequential and non overlapping, flush the
    //  existing cache.
    //

    if ( NpFcb->CacheDataSize != 0 &&
         ( FileOffset < NpFcb->CacheFileOffset ||
           FileOffset > NpFcb->CacheFileOffset + NpFcb->CacheDataSize ) ) {

        //
        // Release and then AcquireFcbAndFlush() will get us to the front
        // of the queue before re-acquiring. This avoids potential deadlocks.
        //

        NwReleaseFcb( NpFcb );

        if ( IrpContext != NULL ) {
            DebugTrace(  0, Dbg, "Data is not sequential, flushing data\n", 0 );

            status = AcquireFcbAndFlushCache( IrpContext, NpFcb );

            if ( !NT_SUCCESS( status ) ) {
                ExRaiseStatus( status );
            }

        }

    DebugTrace( -1, Dbg, "CacheWrite -> FALSE\n", 0 );
    return( FALSE );

    }

    //
    //  The data is sequential, see if it fits.
    //

    if ( SpaceForWriteBehind( NpFcb, FileOffset, BytesToWrite ) ) {

        try {

            RtlCopyMemory(
                NpFcb->CacheBuffer + ( FileOffset - NpFcb->CacheFileOffset ),
                UserBuffer,
                BytesToWrite );

        } except ( EXCEPTION_EXECUTE_HANDLER ) {

            DebugTrace( 0, Dbg, "Bad user mode buffer in CacheWrite.\n", 0 );
            DebugTrace(-1, Dbg, "CacheWrite -> FALSE\n", 0 );
            NwReleaseFcb( NpFcb );
            return ( FALSE );
        }

        if ( NpFcb->CacheDataSize <
             (FileOffset - NpFcb->CacheFileOffset + BytesToWrite) ) {

            NpFcb->CacheDataSize =
                FileOffset - NpFcb->CacheFileOffset + BytesToWrite;

        }

        DebugTrace(-1, Dbg, "CacheWrite -> TRUE\n", 0 );
        NwReleaseFcb( NpFcb );
        return( TRUE );

    } else if ( IrpContext != NULL ) {

        //
        //  The data didn't fit in the cache. If the cache is empty
        //  then its time to return because it never will fit and we
        //  have no stale data. This can happen if this request or
        //  another being processed in parallel flush the cache and
        //  TryAgain.
        //

        if ( NpFcb->CacheDataSize == 0 ) {
            DebugTrace(-1, Dbg, "CacheWrite -> FALSE\n", 0 );
            NwReleaseFcb( NpFcb );
            return( FALSE );
        }

        //
        //  The data didn't fit in the cache, flush the cache
        //

        DebugTrace(  0, Dbg, "Cache is full, flushing data\n", 0 );

        //
        //  We must be at the front of the Queue before writing.
        //

        NwReleaseFcb( NpFcb );

        status = AcquireFcbAndFlushCache( IrpContext, NpFcb );

        if ( !NT_SUCCESS( status ) ) {
            ExRaiseStatus( status );
        }

        //
        //  Now see if it fits in the cache. We need to repeat all
        //  the tests again because two requests can flush the cache at the
        //  same time and the other one of them could have nearly filled it again.
        //

        goto TryAgain;

    } else {
        DebugTrace(-1, Dbg, "CacheWrite full -> FALSE\n", 0 );
        NwReleaseFcb( NpFcb );
        return( FALSE );
    }
}


BOOLEAN
OkToReadAhead(
    PFCB Fcb,
    IN ULONG FileOffset,
    IN UCHAR IoType
    )
/*++

Routine Description:

    This routine determines whether the attempted i/o is sequential (so that
    we can use the cache).

Arguments:

    Fcb - A pointer the the Fcb of the file being read.

    FileOffset - The file offset to read.

Return Value:

    TRUE - The operation is sequential.
    FALSE - The operation is not sequential.

--*/
{
    PAGED_CODE();

    if ( Fcb->NonPagedFcb->CacheType == IoType &&
         !Fcb->ShareAccess.SharedWrite &&
         FileOffset == Fcb->LastReadOffset + Fcb->LastReadSize ) {

        DebugTrace(0, Dbg, "Io is sequential\n", 0 );
        return( TRUE );

    } else {

        DebugTrace(0, Dbg, "Io is not sequential\n", 0 );
        return( FALSE );

    }
}


ULONG
CalculateReadAheadSize(
    IN PIRP_CONTEXT IrpContext,
    IN PNONPAGED_FCB NpFcb,
    IN ULONG CacheReadSize,
    IN ULONG FileOffset,
    IN ULONG ByteCount
    )
/*++

Routine Description:

    This routine determines the amount of data that can be read ahead,
    and sets up for the read.

    Note: Fcb must be acquired exclusive before calling.

Arguments:

    NpFcb - A pointer the the nonpaged FCB of the file being read.

    FileOffset - The file offset to read.

Return Value:

    The amount of data to read.

--*/
{
    ULONG ReadSize;
    ULONG CacheSize;

    PAGED_CODE();

    DebugTrace(+1, Dbg, "CalculateReadAheadSize\n", 0 );

    if (( IrpContext->pNpScb->SendBurstModeEnabled ) ||
        ( IrpContext->pNpScb->ReceiveBurstModeEnabled )) {

        CacheSize = IrpContext->pNpScb->MaxReceiveSize;

    } else {

        CacheSize = IrpContext->pNpScb->BufferSize;

    }

    if ( OkToReadAhead( NpFcb->Fcb, FileOffset - CacheReadSize, ReadAhead ) &&
         ByteCount < CacheSize ) {

        ReadSize = CacheSize;

    } else {

        //
        //  Do not read ahead.
        //

        DebugTrace( 0, Dbg, "No read ahead\n", 0 );
        DebugTrace(-1, Dbg, "CalculateReadAheadSize -> %d\n", ByteCount );
        return ( ByteCount );

    }

    //
    //  Allocate pool for the segment of the read
    //

    if ( NpFcb->CacheBuffer == NULL ) {

        try {

            NpFcb->CacheBuffer = ALLOCATE_POOL_EX( NonPagedPool, ReadSize );
            NpFcb->CacheSize = ReadSize;

            NpFcb->CacheMdl = ALLOCATE_MDL( NpFcb->CacheBuffer, ReadSize, FALSE, FALSE, NULL );
            if ( NpFcb->CacheMdl == NULL ) {
                ExRaiseStatus( STATUS_INSUFFICIENT_RESOURCES );
            }

            MmBuildMdlForNonPagedPool( NpFcb->CacheMdl );

        } except ( EXCEPTION_EXECUTE_HANDLER ) {

            if ( NpFcb->CacheBuffer != NULL) {
                FREE_POOL( NpFcb->CacheBuffer );

                NpFcb->CacheBuffer = NULL;
            }

            NpFcb->CacheSize = 0;
            NpFcb->CacheDataSize = 0;

            DebugTrace( 0, Dbg, "Failed to allocated buffer\n", 0 );
            DebugTrace(-1, Dbg, "CalculateReadAheadSize -> %d\n", ByteCount );
            return( ByteCount );
        }

    } else {
        ReadSize = MIN ( NpFcb->CacheSize, ReadSize );
    }

    DebugTrace(-1, Dbg, "CalculateReadAheadSize -> %d\n", ReadSize );
    return( ReadSize );
}

NTSTATUS
FlushCache(
    PIRP_CONTEXT IrpContext,
    PNONPAGED_FCB NpFcb
    )
/*++

Routine Description:

    This routine flushes the cache buffer for the NpFcb.  The caller must
    have acquired the FCB exclusive prior to making this call!

Arguments:

    IrpContext - A pointer to request parameters.

    NpFcb - A pointer the the nonpaged FCB of the file to flush.

Return Value:

    The amount of data to read.

--*/
{
    NTSTATUS status = STATUS_SUCCESS;

    PAGED_CODE();

    if ( NpFcb->CacheDataSize != 0 && NpFcb->CacheType == WriteBehind ) {

        LARGE_INTEGER ByteOffset;

        ByteOffset.QuadPart = NpFcb->CacheFileOffset;

        status = DoWrite(
                    IrpContext,
                    ByteOffset,
                    NpFcb->CacheDataSize,
                    NpFcb->CacheBuffer,
                    NpFcb->CacheMdl );

        //
        // DoWrite leaves us at the head of the queue.  The caller
        // is responsible for dequeueing the irp context appropriately.
        //

        if ( NT_SUCCESS( status ) ) {
            NpFcb->CacheDataSize = 0;
        }
    }

    return( status );
}

NTSTATUS
AcquireFcbAndFlushCache(
    PIRP_CONTEXT IrpContext,
    PNONPAGED_FCB NpFcb
    )
/*++

Routine Description:

    This routine acquires the FCB exclusive and flushes the cache
    buffer for the acquired NpFcb.

Arguments:

    IrpContext - A pointer to request parameters.

    NpFcb - A pointer the the nonpaged FCB of the file to flush.

Return Value:

    The amount of data to read.

--*/
{
    NTSTATUS status = STATUS_SUCCESS;

    PAGED_CODE();

    NwAppendToQueueAndWait( IrpContext );

    NwAcquireExclusiveFcb( NpFcb, TRUE );

    status = FlushCache( IrpContext, NpFcb );

    //
    //  Release the FCB and remove ourselves from the queue.
    //  Frequently the caller will want to grab a resource so
    //  we need to be off the queue then.
    //

    NwReleaseFcb( NpFcb );
    NwDequeueIrpContext( IrpContext, FALSE );

    return( status );
}