summaryrefslogtreecommitdiffstats
path: root/private/ntos/cache/vacbsup.c
blob: d1e0e09f951764a0f965baeddbcc717ac5a70a74 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
/*++

Copyright (c) 1990  Microsoft Corporation

Module Name:

    vacbsup.c

Abstract:

    This module implements the support routines for the Virtual Address
    Control Block support for the Cache Manager.  These routines are used
    to manage a large number of relatively small address windows to map
    file data for all forms of cache access.

Author:

    Tom Miller      [TomM]      8-Feb-1992

Revision History:

--*/

#include "cc.h"

//
//  Define our debug constant
//

#define me 0x000000040

//
//  Define a few macros for manipulating the Vacb array.
//

#define GetVacb(SCM,OFF) (                                 \
    ((OFF).HighPart != 0) ?                                \
    (SCM)->Vacbs[(ULONG)((ULONGLONG)((OFF).QuadPart) >> VACB_OFFSET_SHIFT)] : \
    (SCM)->Vacbs[(OFF).LowPart >> VACB_OFFSET_SHIFT]       \
)

#define SetVacb(SCM,OFF,VACB) {                                         \
    ASSERT((OFF).HighPart < VACB_MAPPING_GRANULARITY);                  \
    if ((OFF).HighPart != 0) {                                          \
    (SCM)->Vacbs[(ULONG)((ULONGLONG)((OFF).QuadPart) >> VACB_OFFSET_SHIFT)] = (VACB);      \
    } else {(SCM)->Vacbs[(OFF).LowPart >> VACB_OFFSET_SHIFT] = (VACB);} \
}

#define SizeOfVacbArray(LSZ) (                                        \
    ((LSZ).HighPart != 0) ?                                           \
    ((ULONG)((ULONGLONG)((LSZ).QuadPart) >> VACB_OFFSET_SHIFT) * sizeof(PVACB)) :    \
    (LSZ).LowPart > (PREALLOCATED_VACBS * VACB_MAPPING_GRANULARITY) ? \
    (((LSZ).LowPart >> VACB_OFFSET_SHIFT) * sizeof(PVACB)) :      \
    (PREALLOCATED_VACBS * sizeof(PVACB))                              \
)

#define CheckedDec(N) {  \
    ASSERT((N) != 0);    \
    (N) -= 1;            \
}

//
//  Internal Support Routines.
//

VOID
CcUnmapVacb (
    IN PVACB Vacb,
    IN PSHARED_CACHE_MAP SharedCacheMap
    );

PVACB
CcGetVacbMiss (
    IN PSHARED_CACHE_MAP SharedCacheMap,
    IN LARGE_INTEGER FileOffset,
    IN OUT PKIRQL OldIrql
    );

#ifdef ALLOC_PRAGMA
#pragma alloc_text(INIT, CcInitializeVacbs)
#endif


VOID
CcInitializeVacbs(
)

/*++

Routine Description:

    This routine must be called during Cache Manager initialization to
    initialize the Virtual Address Control Block structures.

Arguments:

    None.

Return Value:

    None.

--*/

{
    ULONG VacbBytes;

    CcNumberVacbs = (MmSizeOfSystemCacheInPages >> (VACB_OFFSET_SHIFT - PAGE_SHIFT)) - 2;
    VacbBytes = CcNumberVacbs * sizeof(VACB);

    KeInitializeSpinLock( &CcVacbSpinLock );
    CcNextVictimVacb =
    CcVacbs = (PVACB)FsRtlAllocatePool( NonPagedPool, VacbBytes );
    CcBeyondVacbs = (PVACB)((PCHAR)CcVacbs + VacbBytes);
    RtlZeroMemory( CcVacbs, VacbBytes );
}


PVOID
CcGetVirtualAddressIfMapped (
    IN PSHARED_CACHE_MAP SharedCacheMap,
    IN LONGLONG FileOffset,
    OUT PVACB *Vacb,
    OUT PULONG ReceivedLength
    )

/*++

Routine Description:

    This routine returns a virtual address for the specified FileOffset,
    iff it is mapped.  Otherwise, it informs the caller that the specified
    virtual address was not mapped.  In the latter case, it still returns
    a ReceivedLength, which may be used to advance to the next view boundary.

Arguments:

    SharedCacheMap - Supplies a pointer to the Shared Cache Map for the file.

    FileOffset - Supplies the desired FileOffset within the file.

    Vach - Returns a Vacb pointer which must be supplied later to free
           this virtual address, or NULL if not mapped.

    ReceivedLength - Returns the number of bytes to the next view boundary,
                     whether the desired file offset is mapped or not.

Return Value:

    The virtual address at which the desired data is mapped, or NULL if it
    is not mapped.

--*/

{
    KIRQL OldIrql;
    ULONG VacbOffset = (ULONG)FileOffset & (VACB_MAPPING_GRANULARITY - 1);
    PVOID Value = NULL;

    ASSERT(KeGetCurrentIrql() < DISPATCH_LEVEL);

    //
    //  Generate ReceivedLength return right away.
    //

    *ReceivedLength = VACB_MAPPING_GRANULARITY - VacbOffset;

    //
    //  Acquire the Vacb lock to see if the desired offset is already mapped.
    //

    ExAcquireFastLock( &CcVacbSpinLock, &OldIrql );

    ASSERT( FileOffset <= SharedCacheMap->SectionSize.QuadPart );

    if ((*Vacb = GetVacb( SharedCacheMap, *(PLARGE_INTEGER)&FileOffset )) != NULL) {

        if ((*Vacb)->Overlay.ActiveCount == 0) {
            SharedCacheMap->VacbActiveCount += 1;
        }

        (*Vacb)->Overlay.ActiveCount += 1;


        Value = (PVOID)((PCHAR)(*Vacb)->BaseAddress + VacbOffset);
    }

    ExReleaseFastLock( &CcVacbSpinLock, OldIrql );
    return Value;
}


PVOID
CcGetVirtualAddress (
    IN PSHARED_CACHE_MAP SharedCacheMap,
    IN LARGE_INTEGER FileOffset,
    OUT PVACB *Vacb,
    OUT PULONG ReceivedLength
    )

/*++

Routine Description:

    This is the main routine for Vacb management.  It may be called to acquire
    a virtual address for a given file offset.  If the desired file offset is
    already mapped, this routine does very little work before returning with
    the desired virtual address and Vacb pointer (which must be supplied to
    free the mapping).

    If the desired virtual address is not currently mapped, then this routine
    claims a Vacb from the tail of the Vacb LRU to reuse its mapping.  This Vacb
    is then unmapped if necessary (normally not required), and mapped to the
    desired address.

Arguments:

    SharedCacheMap - Supplies a pointer to the Shared Cache Map for the file.

    FileOffset - Supplies the desired FileOffset within the file.

    Vacb - Returns a Vacb pointer which must be supplied later to free
           this virtual address.

    ReceivedLength - Returns the number of bytes which are contiguously
                     mapped starting at the virtual address returned.

Return Value:

    The virtual address at which the desired data is mapped.

--*/

{
    KIRQL OldIrql;
    PVACB TempVacb;
    ULONG VacbOffset = FileOffset.LowPart & (VACB_MAPPING_GRANULARITY - 1);

    ASSERT(KeGetCurrentIrql() < DISPATCH_LEVEL);

    //
    //  Acquire the Vacb lock to see if the desired offset is already mapped.
    //

    ExAcquireSpinLock( &CcVacbSpinLock, &OldIrql );

    ASSERT( FileOffset.QuadPart <= SharedCacheMap->SectionSize.QuadPart );

    if ((TempVacb = GetVacb( SharedCacheMap, FileOffset )) == NULL) {

        TempVacb = CcGetVacbMiss( SharedCacheMap, FileOffset, &OldIrql );

    } else {

        if (TempVacb->Overlay.ActiveCount == 0) {
            SharedCacheMap->VacbActiveCount += 1;
        }

        TempVacb->Overlay.ActiveCount += 1;
    }

    ExReleaseSpinLock( &CcVacbSpinLock, OldIrql );

    //
    //  Now form all outputs.
    //

    *Vacb = TempVacb;
    *ReceivedLength = VACB_MAPPING_GRANULARITY - VacbOffset;

    ASSERT(KeGetCurrentIrql() < DISPATCH_LEVEL);

    return (PVOID)((PCHAR)TempVacb->BaseAddress + VacbOffset);
}


PVACB
CcGetVacbMiss (
    IN PSHARED_CACHE_MAP SharedCacheMap,
    IN LARGE_INTEGER FileOffset,
    IN OUT PKIRQL OldIrql
    )

/*++

Routine Description:

    This is the main routine for Vacb management.  It may be called to acquire
    a virtual address for a given file offset.  If the desired file offset is
    already mapped, this routine does very little work before returning with
    the desired virtual address and Vacb pointer (which must be supplied to
    free the mapping).

    If the desired virtual address is not currently mapped, then this routine
    claims a Vacb from the tail of the Vacb LRU to reuse its mapping.  This Vacb
    is then unmapped if necessary (normally not required), and mapped to the
    desired address.

Arguments:

    SharedCacheMap - Supplies a pointer to the Shared Cache Map for the file.

    FileOffset - Supplies the desired FileOffset within the file.

    OldIrql - Pointer to the OldIrql variable in the caller

Return Value:

    The Vacb.

--*/

{
    PSHARED_CACHE_MAP OldSharedCacheMap;
    PVACB Vacb, TempVacb;
    LARGE_INTEGER MappedLength;
    LARGE_INTEGER NormalOffset;
    NTSTATUS Status;
    ULONG ActivePage;
    ULONG PageIsDirty;
    PVACB ActiveVacb = NULL;
    BOOLEAN MasterAcquired = FALSE;
    ULONG VacbOffset = FileOffset.LowPart & (VACB_MAPPING_GRANULARITY - 1);

    NormalOffset = FileOffset;
    NormalOffset.LowPart -= VacbOffset;

    //
    //  For Sequential only files, we periodically unmap unused views
    //  behind us as we go, to keep from hogging memory.
    //

    if (FlagOn(SharedCacheMap->Flags, ONLY_SEQUENTIAL_ONLY_SEEN) &&
        ((NormalOffset.LowPart & (SEQUENTIAL_ONLY_MAP_LIMIT - 1)) == 0) &&
        (NormalOffset.QuadPart >= (SEQUENTIAL_ONLY_MAP_LIMIT * 2))) {

        //
        //  Use MappedLength as a scratch variable to form the offset
        //  to start unmapping.  We are not synchronized with these past
        //  views, so it is possible that CcUnmapVacbArray will kick out
        //  early when it sees an active view.  That is why we go back
        //  twice the distance, and effectively try to unmap everything
        //  twice.  The second time should normally do it.  If the file
        //  is truly sequential only, then the only collision expected
        //  might be the previous view if we are being called from readahead,
        //  or there is a small chance that we can collide with the
        //  Lazy Writer during the small window where he briefly maps
        //  the file to push out the dirty bits.
        //

        ExReleaseSpinLock( &CcVacbSpinLock, *OldIrql );
        MappedLength.QuadPart = NormalOffset.QuadPart - (SEQUENTIAL_ONLY_MAP_LIMIT * 2);
        CcUnmapVacbArray( SharedCacheMap, &MappedLength, (SEQUENTIAL_ONLY_MAP_LIMIT * 2) );
        ExAcquireSpinLock( &CcVacbSpinLock, OldIrql );
    }

    //
    //  Scan from the next victim for a free Vacb
    //

    Vacb = CcNextVictimVacb;

    while (TRUE) {

        //
        //  Handle the wrap case
        //

        if (Vacb == CcBeyondVacbs) {
            Vacb = CcVacbs;
        }

        //
        //  If this guy is not active, break out and use him.  Also, if
        //  it is an Active Vacb, nuke it now, because the reader may be idle and we
        //  want to clean up.
        //

        OldSharedCacheMap = Vacb->SharedCacheMap;
        if ((Vacb->Overlay.ActiveCount == 0) ||
            ((ActiveVacb == NULL) &&
             (OldSharedCacheMap != NULL) &&
             (OldSharedCacheMap->ActiveVacb == Vacb))) {

            //
            //  The normal case is that the Vacb is no longer mapped
            //  and we can just get out and use it.
            //

            if (Vacb->BaseAddress == NULL) {
                break;
            }

            //
            //  Else the Vacb is mapped.  If we haven't done so
            //  already, we have to bias the open count so the
            //  SharedCacheMap (and its section reference) do not
            //  get away before we complete the unmap.  Unfortunately
            //  we have to free the Vacb lock first to obey our locking
            //  order.
            //

            if (!MasterAcquired) {

                ExReleaseSpinLock( &CcVacbSpinLock, *OldIrql );
                ExAcquireSpinLock( &CcMasterSpinLock, OldIrql );
                ExAcquireSpinLockAtDpcLevel( &CcVacbSpinLock );
                MasterAcquired = TRUE;

                //
                //  Reset the next victim on this rare path to allow our guy
                //  to scan the entire list again.  Since we terminate the scan
                //  when we see we have incremented into this guy, we have cannot
                //  leave it on the first Vacb!  In this case we will terminate
                //  at CcBeyondVacbs.  Third time should be the charm on this fix!
                //

                CcNextVictimVacb = Vacb;
                if (CcNextVictimVacb == CcVacbs) {
                    CcNextVictimVacb = CcBeyondVacbs;
                }
            }

            //
            //  If this Vacb went active while we had the spin lock
            //  dropped, then we have to start a new scan!  At least
            //  now we have both locks so that this cannot happen again.
            //

            if (Vacb->Overlay.ActiveCount != 0) {

                //
                //  Most likely we are here to free an Active Vacb from copy
                //  read.  Rather than repeat all the tests from above, we will
                //  just try to get the active Vacb if we haven't already got
                //  one.
                //

                if ((ActiveVacb == NULL) && (Vacb->SharedCacheMap != NULL)) {

                    //
                    //  Get the active Vacb.
                    //

                    GetActiveVacbAtDpcLevel( Vacb->SharedCacheMap, ActiveVacb, ActivePage, PageIsDirty );
                }

            //
            //  Otherwise we will break out and use this Vacb.  If it
            //  is still mapped we can now safely increment the open
            //  count.
            //

            } else {

                if (Vacb->BaseAddress != NULL) {

                    //
                    //  Note that if the SharedCacheMap is currently
                    //  being deleted, we need to skip over
                    //  it, otherwise we will become the second
                    //  deleter.  CcDeleteSharedCacheMap clears the
                    //  pointer in the SectionObjectPointer.
                    //

                    if (Vacb->SharedCacheMap->FileObject->SectionObjectPointer->SharedCacheMap ==
                        Vacb->SharedCacheMap) {

                        Vacb->SharedCacheMap->OpenCount += 1;
                        break;
                    }

                } else {

                    break;
                }
            }
        }

        //
        //  Advance to the next guy and see if we have scanned
        //  the entire list.
        //

        Vacb += 1;

        if (Vacb == CcNextVictimVacb) {

            //
            //  Release the spinlock(s) acquired above.
            //

            if (MasterAcquired) {

                ExReleaseSpinLockFromDpcLevel( &CcVacbSpinLock );
                ExReleaseSpinLock( &CcMasterSpinLock, *OldIrql );

            } else {

                ExReleaseSpinLock( &CcVacbSpinLock, *OldIrql );
            }

            //
            //  If we found an active vacb, then free it and go back and
            //  try again.  Else it's time to bail.
            //

            if (ActiveVacb != NULL) {
                CcFreeActiveVacb( ActiveVacb->SharedCacheMap, ActiveVacb, ActivePage, PageIsDirty );
                ActiveVacb = NULL;

                //
                //  Reacquire spinlocks to loop back
                //

                ExAcquireSpinLock( &CcMasterSpinLock, OldIrql );
                ExAcquireSpinLockAtDpcLevel( &CcVacbSpinLock );
                MasterAcquired = TRUE;

            } else {
                ExRaiseStatus( STATUS_INSUFFICIENT_RESOURCES );
            }
        }
    }

    CcNextVictimVacb = Vacb + 1;

    //
    //  Unlink it from the other SharedCacheMap, so the other
    //  guy will not try to use it when we free the spin lock.
    //

    if (Vacb->SharedCacheMap != NULL) {

        OldSharedCacheMap = Vacb->SharedCacheMap;
        SetVacb( OldSharedCacheMap, Vacb->Overlay.FileOffset, NULL );
        Vacb->SharedCacheMap = NULL;
    }

    //
    //  Mark it in use so no one else will muck with it after
    //  we release the spin lock.
    //

    Vacb->Overlay.ActiveCount = 1;
    SharedCacheMap->VacbActiveCount += 1;

    //
    //  Release the spinlock(s) acquired above.
    //

    if (MasterAcquired) {

        ExReleaseSpinLockFromDpcLevel( &CcVacbSpinLock );
        ExReleaseSpinLock( &CcMasterSpinLock, *OldIrql );

    } else {

        ExReleaseSpinLock( &CcVacbSpinLock, *OldIrql );
    }

    //
    //  If the Vacb is already mapped, then unmap it.
    //

    if (Vacb->BaseAddress != NULL) {

        CcUnmapVacb( Vacb, OldSharedCacheMap );

        //
        //  Now we can decrement the open count as we normally
        //  do, possibly deleting the guy.
        //

        ExAcquireSpinLock( &CcMasterSpinLock, OldIrql );

        //
        //  Now release our open count.
        //

        OldSharedCacheMap->OpenCount -= 1;

        if ((OldSharedCacheMap->OpenCount == 0) &&
            !FlagOn(OldSharedCacheMap->Flags, WRITE_QUEUED) &&
            (OldSharedCacheMap->DirtyPages == 0)) {

            //
            //  Move to the dirty list.
            //

            RemoveEntryList( &OldSharedCacheMap->SharedCacheMapLinks );
            InsertTailList( &CcDirtySharedCacheMapList.SharedCacheMapLinks,
                            &OldSharedCacheMap->SharedCacheMapLinks );

            //
            //  Make sure the Lazy Writer will wake up, because we
            //  want him to delete this SharedCacheMap.
            //

            LazyWriter.OtherWork = TRUE;
            if (!LazyWriter.ScanActive) {
                CcScheduleLazyWriteScan();
            }
        }

        ExReleaseSpinLock( &CcMasterSpinLock, *OldIrql );
    }

    //
    //  Use try-finally to return this guy to the list if we get an
    //  exception.
    //

    try {

        //
        //  Assume we are mapping to the end of the section, but
        //  reduce to our normal mapping granularity if the section
        //  is too large.
        //

        MappedLength.QuadPart = SharedCacheMap->SectionSize.QuadPart - NormalOffset.QuadPart;

        if ((MappedLength.HighPart != 0) ||
            (MappedLength.LowPart > VACB_MAPPING_GRANULARITY)) {

            MappedLength.LowPart = VACB_MAPPING_GRANULARITY;
        }

        //
        //  Now map this one in the system cache.
        //

        DebugTrace( 0, mm, "MmMapViewInSystemCache:\n", 0 );
        DebugTrace( 0, mm, "    Section = %08lx\n", SharedCacheMap->Section );
        DebugTrace2(0, mm, "    Offset = %08lx, %08lx\n",
                                NormalOffset.LowPart,
                                NormalOffset.HighPart );
        DebugTrace( 0, mm, "    ViewSize = %08lx\n", MappedLength.LowPart );

        Status =
          MmMapViewInSystemCache( SharedCacheMap->Section,
                                  &Vacb->BaseAddress,
                                  &NormalOffset,
                                  &MappedLength.LowPart );

        DebugTrace( 0, mm, "    <BaseAddress = %08lx\n", Vacb->BaseAddress );
        DebugTrace( 0, mm, "    <ViewSize = %08lx\n", MappedLength.LowPart );

        if (!NT_SUCCESS( Status )) {

            DebugTrace( 0, 0, "Error from Map, Status = %08lx\n", Status );

            ExRaiseStatus( FsRtlNormalizeNtstatus( Status,
                                                   STATUS_UNEXPECTED_MM_MAP_ERROR ));
        }

    } finally {

        //
        //  Take this opportunity to free the active vacb.
        //

        if (ActiveVacb != NULL) {

            CcFreeActiveVacb( ActiveVacb->SharedCacheMap, ActiveVacb, ActivePage, PageIsDirty );
        }

        //
        //  On abnormal termination, get this guy back in the list.
        //

        if (AbnormalTermination()) {

            ExAcquireSpinLock( &CcVacbSpinLock, OldIrql );

            //
            //  This is like the unlucky case below.  Just back out the stuff
            //  we did and put the guy at the tail of the list.  Basically
            //  only the Map should fail, and we clear BaseAddress accordingly.
            //

            Vacb->BaseAddress = NULL;

            CheckedDec(Vacb->Overlay.ActiveCount);
            CheckedDec(SharedCacheMap->VacbActiveCount);

            //
            //  If there is someone waiting for this count to go to zero,
            //  wake them here.
            //

            if (SharedCacheMap->WaitOnActiveCount != NULL) {
                KeSetEvent( SharedCacheMap->WaitOnActiveCount, 0, FALSE );
            }

            ExReleaseSpinLock( &CcVacbSpinLock, *OldIrql );
        }
    }

    //
    //  Finish filling in the Vacb, and store its address in the array in
    //  the Shared Cache Map.  (We have to rewrite the ActiveCount
    //  since it is overlaid.)  To do this we must racquire the
    //  spin lock one more time.  Note we have to check for the unusual
    //  case that someone beat us to mapping this view, since we had to
    //  drop the spin lock.
    //

    ExAcquireSpinLock( &CcVacbSpinLock, OldIrql );

    if ((TempVacb = GetVacb( SharedCacheMap, NormalOffset )) == NULL) {

        Vacb->SharedCacheMap = SharedCacheMap;
        Vacb->Overlay.FileOffset = NormalOffset;
        Vacb->Overlay.ActiveCount = 1;

        SetVacb( SharedCacheMap, NormalOffset, Vacb );

    //
    //  This is the unlucky case where we collided with someone else
    //  trying to map the same view.  He can get in because we dropped
    //  the spin lock above.  Rather than allocating events and making
    //  someone wait, considering this case is fairly unlikely, we just
    //  dump this one at the tail of the list and use the one from the
    //  guy who beat us.
    //

    } else {

        //
        //  Now we have to increment all of the counts for the one that
        //  was already there, then ditch the one we had.
        //

        if (TempVacb->Overlay.ActiveCount == 0) {
            SharedCacheMap->VacbActiveCount += 1;
        }

        TempVacb->Overlay.ActiveCount += 1;

        //
        //  Now unmap the one we mapped and proceed with the other Vacb.
        //  On this path we have to release the spinlock to do the unmap,
        //  and then reacquire the spinlock before cleaning up.
        //

        ExReleaseSpinLock( &CcVacbSpinLock, *OldIrql );

        CcUnmapVacb( Vacb, SharedCacheMap );

        ExAcquireSpinLock( &CcVacbSpinLock, OldIrql );
        CheckedDec(Vacb->Overlay.ActiveCount);
        CheckedDec(SharedCacheMap->VacbActiveCount);
        Vacb->SharedCacheMap = NULL;

        Vacb = TempVacb;
    }

    return Vacb;
}


VOID
FASTCALL
CcFreeVirtualAddress (
    IN PVACB Vacb
    )

/*++

Routine Description:

    This routine must be called once for each call to CcGetVirtualAddress,
    to free that virtual address.

Arguments:

    Vacb - Supplies the Vacb which was returned from CcGetVirtualAddress.

Return Value:

    None.

--*/

{
    KIRQL OldIrql;
    PSHARED_CACHE_MAP SharedCacheMap = Vacb->SharedCacheMap;

    ExAcquireSpinLock( &CcVacbSpinLock, &OldIrql );

    CheckedDec(Vacb->Overlay.ActiveCount);

    //
    //  If the count goes to zero, then we want to decrement the global
    //  Active count, and the count in the Scb.
    //

    if (Vacb->Overlay.ActiveCount == 0) {

        //
        //  If the SharedCacheMap address is not NULL, then this one is
        //  in use by a shared cache map, and we have to decrement his
        //  count and see if anyone is waiting.
        //

        if (SharedCacheMap != NULL) {

            CheckedDec(SharedCacheMap->VacbActiveCount);

            //
            //  If there is someone waiting for this count to go to zero,
            //  wake them here.
            //

            if (SharedCacheMap->WaitOnActiveCount != NULL) {
                KeSetEvent( SharedCacheMap->WaitOnActiveCount, 0, FALSE );
            }
        }
    }

    ExReleaseSpinLock( &CcVacbSpinLock, OldIrql );
}


VOID
CcWaitOnActiveCount (
    IN PSHARED_CACHE_MAP SharedCacheMap
    )

/*++

Routine Description:

    This routine may be called to wait for outstanding mappings for
    a given SharedCacheMap to go inactive.  It is intended to be called
    from CcUninitializeCacheMap, which is called by the file systems
    during cleanup processing.  In that case this routine only has to
    wait if the user closed a handle without waiting for all I/Os on the
    handle to complete.

    This routine returns each time the active count is decremented.  The
    caller must recheck his wait conditions on return, either waiting for
    the ActiveCount to go to 0, or for specific views to go inactive
    (CcPurgeCacheSection case).

Arguments:

    SharedCacheMap - Supplies the Shared Cache Map on whose VacbActiveCount
                     we wish to wait.

Return Value:

    None.

--*/

{
    KIRQL OldIrql;
    PKEVENT Event;

    //
    //  In the unusual case that we get a cleanup while I/O is still going
    //  on, we can wait here.  The caller must test the count for nonzero
    //  before calling this routine.
    //
    //  Since we are being called from cleanup, we cannot afford to
    //  fail here.
    //

    ExAcquireSpinLock( &CcVacbSpinLock, &OldIrql );

    //
    //  It is possible that the count went to zero before we acquired the
    //  spinlock, so we must handle two cases here.
    //

    if (SharedCacheMap->VacbActiveCount != 0) {

        if ((Event = SharedCacheMap->WaitOnActiveCount) == NULL) {

            //
            //  If the local even is not being used as a create event,
            //  then we can use it.
            //

            if (SharedCacheMap->CreateEvent == NULL) {

                Event = &SharedCacheMap->Event;

            } else {

                Event = (PKEVENT)ExAllocatePool( NonPagedPoolMustSucceed,
                                                 sizeof(KEVENT) );
            }
        }

        KeInitializeEvent( Event,
                           NotificationEvent,
                           FALSE );

        SharedCacheMap->WaitOnActiveCount = Event;

        ExReleaseSpinLock( &CcVacbSpinLock, OldIrql );

        KeWaitForSingleObject( Event,
                               Executive,
                               KernelMode,
                               FALSE,
                               (PLARGE_INTEGER)NULL);
    } else {

        ExReleaseSpinLock( &CcVacbSpinLock, OldIrql );
    }
}


//
//  Internal Support Routine.
//

VOID
CcUnmapVacb (
    IN PVACB Vacb,
    IN PSHARED_CACHE_MAP SharedCacheMap
    )

/*++

Routine Description:

    This routine may be called to unmap a previously mapped Vacb, and
    clear its BaseAddress field.

Arguments:

    Vacb - Supplies the Vacb which was returned from CcGetVirtualAddress.

Return Value:

    None.

--*/

{
    //
    //  Make sure it is mapped.
    //

    ASSERT(SharedCacheMap != NULL);
    ASSERT(Vacb->BaseAddress != NULL);

    //
    //  Call MM to unmap it.
    //

    DebugTrace( 0, mm, "MmUnmapViewInSystemCache:\n", 0 );
    DebugTrace( 0, mm, "    BaseAddress = %08lx\n", Vacb->BaseAddress );

    MmUnmapViewInSystemCache( Vacb->BaseAddress,
                              SharedCacheMap->Section,
                              FlagOn(SharedCacheMap->Flags, ONLY_SEQUENTIAL_ONLY_SEEN) );

    Vacb->BaseAddress = NULL;
}


VOID
FASTCALL
CcCreateVacbArray (
    IN PSHARED_CACHE_MAP SharedCacheMap,
    IN LARGE_INTEGER NewSectionSize
    )

/*++

Routine Description:

    This routine must be called when a SharedCacheMap is created to create
    and initialize the initial Vacb array.

Arguments:

    SharedCacheMap - Supplies the shared cache map for which the array is
                     to be created.

    NewSectionSize - Supplies the current size of the section which must be
                     covered by the Vacb array.

Return Value:

    None.

--*/

{
    PVACB *NewAddresses;
    ULONG NewSize, SizeToAllocate;
    PLIST_ENTRY BcbListHead;

    NewSize = SizeToAllocate = SizeOfVacbArray(NewSectionSize);

    //
    //  The following limit is greater than the MM limit
    //  (i.e., MM actually only supports even smaller sections).
    //  This limit is required here in order to get the correct
    //  answer from SizeOfVacbArray.
    //

    if (NewSectionSize.HighPart & 0xFFFFC000) {
        ExRaiseStatus(STATUS_SECTION_TOO_BIG);
    }

    //
    //  See if we can use the array inside the shared cache map.
    //

    if (NewSize == (PREALLOCATED_VACBS * sizeof(PVACB))) {

        NewAddresses = &SharedCacheMap->InitialVacbs[0];

    //
    //  Else allocate the array.
    //

    } else {

        //
        //  For large metadata streams, double the size to allocate
        //  an array of Bcb listheads.  Each two Vacb pointers also
        //  gets its own Bcb listhead, thus requiring double the size.
        //

        ASSERT(SIZE_PER_BCB_LIST == (VACB_MAPPING_GRANULARITY * 2));

        //
        //  Does this stream get a Bcb Listhead array?
        //

        if (FlagOn(SharedCacheMap->Flags, MODIFIED_WRITE_DISABLED) &&
            (NewSectionSize.QuadPart > BEGIN_BCB_LIST_ARRAY)) {

            SizeToAllocate *= 2;
        }

        NewAddresses = ExAllocatePool( NonPagedPool, SizeToAllocate );
        if (NewAddresses == NULL) {
            SharedCacheMap->Status = STATUS_INSUFFICIENT_RESOURCES;
            ExRaiseStatus( STATUS_INSUFFICIENT_RESOURCES );
        }
    }

    RtlZeroMemory( NewAddresses, NewSize );

    //
    //  Loop to insert the Bcb listheads (if any) in the *descending* order
    //  Bcb list.
    //

    if (SizeToAllocate != NewSize) {

        for (BcbListHead = (PLIST_ENTRY)((PCHAR)NewAddresses + NewSize);
             BcbListHead < (PLIST_ENTRY)((PCHAR)NewAddresses + SizeToAllocate);
             BcbListHead++) {

            InsertHeadList( &SharedCacheMap->BcbList, BcbListHead );
        }
    }

    SharedCacheMap->Vacbs = NewAddresses;
    SharedCacheMap->SectionSize = NewSectionSize;
}


VOID
CcExtendVacbArray (
    IN PSHARED_CACHE_MAP SharedCacheMap,
    IN LARGE_INTEGER NewSectionSize
    )

/*++

Routine Description:

    This routine must be called any time the section for a shared cache
    map is extended, in order to extend the Vacb array (if necessary).

Arguments:

    SharedCacheMap - Supplies the shared cache map for which the array is
                     to be created.

    NewSectionSize - Supplies the new size of the section which must be
                     covered by the Vacb array.

Return Value:

    None.

--*/

{
    KIRQL OldIrql;
    PVACB *OldAddresses;
    PVACB *NewAddresses;
    ULONG OldSize;
    ULONG NewSize, SizeToAllocate;
    ULONG GrowingBcbListHeads = FALSE;

    //
    //  The following limit is greater than the MM limit
    //  (i.e., MM actually only supports even smaller sections).
    //  This limit is required here in order to get the correct
    //  answer from SizeOfVacbArray.
    //

    if (NewSectionSize.HighPart & 0xFFFFC000) {
        ExRaiseStatus(STATUS_SECTION_TOO_BIG);
    }

    //
    //  See if we will be growing the Bcb ListHeads, and take out the
    //  master lock if so.
    //

    if (FlagOn(SharedCacheMap->Flags, MODIFIED_WRITE_DISABLED) &&
        (NewSectionSize.QuadPart > BEGIN_BCB_LIST_ARRAY)) {

        GrowingBcbListHeads = TRUE;
        ExAcquireSpinLock( &CcMasterSpinLock, &OldIrql );
        ExAcquireSpinLockAtDpcLevel( &CcVacbSpinLock );

    } else {

        //
        //  Acquire the spin lock to serialize with anyone who might like
        //  to "steal" one of the mappings we are going to move.
        //

        ExAcquireSpinLock( &CcVacbSpinLock, &OldIrql );
    }

    //
    //  It's all a noop if the new size is not larger...
    //

    if (NewSectionSize.QuadPart > SharedCacheMap->SectionSize.QuadPart) {

        NewSize = SizeToAllocate = SizeOfVacbArray(NewSectionSize);
        OldSize = SizeOfVacbArray(SharedCacheMap->SectionSize);

        //
        //  Only do something if the size is growing.
        //

        if (NewSize > OldSize) {

            //
            //  Does this stream get a Bcb Listhead array?
            //

            if (GrowingBcbListHeads) {
                SizeToAllocate *= 2;
            }

            NewAddresses = ExAllocatePool( NonPagedPool, SizeToAllocate );

            if (NewAddresses == NULL) {
                if (GrowingBcbListHeads) {
                    ExReleaseSpinLockFromDpcLevel( &CcVacbSpinLock );
                    ExReleaseSpinLock( &CcMasterSpinLock, OldIrql );
                } else {
                    ExReleaseSpinLock( &CcVacbSpinLock, OldIrql );
                }
                ExRaiseStatus(STATUS_INSUFFICIENT_RESOURCES);
            }

            OldAddresses = SharedCacheMap->Vacbs;
            if (OldAddresses != NULL) {
                RtlCopyMemory( NewAddresses, OldAddresses, OldSize );
            } else {
                OldSize = 0;
            }

            RtlZeroMemory( (PCHAR)NewAddresses + OldSize, NewSize - OldSize );

            //
            //  See if we have to initialize Bcb Listheads.
            //

            if (SizeToAllocate != NewSize) {

                LARGE_INTEGER Offset;
                PLIST_ENTRY BcbListHeadNew, TempEntry;

                Offset.QuadPart = 0;
                BcbListHeadNew = (PLIST_ENTRY)((PCHAR)NewAddresses + NewSize);

                //
                //  Handle case where the old array had Bcb Listheads.
                //

                if ((SharedCacheMap->SectionSize.QuadPart > BEGIN_BCB_LIST_ARRAY) &&
                    (OldAddresses != NULL)) {

                    PLIST_ENTRY BcbListHeadOld;

                    BcbListHeadOld = (PLIST_ENTRY)((PCHAR)OldAddresses + OldSize);

                    //
                    //  Loop to remove each old listhead and insert the new one
                    //  in its place.
                    //

                    do {
                        TempEntry = BcbListHeadOld->Flink;
                        RemoveEntryList( BcbListHeadOld );
                        InsertTailList( TempEntry, BcbListHeadNew );
                        Offset.QuadPart += SIZE_PER_BCB_LIST;
                        BcbListHeadOld += 1;
                        BcbListHeadNew += 1;
                    } while (Offset.QuadPart < SharedCacheMap->SectionSize.QuadPart);

                //
                //  Otherwise, handle the case where we are adding Bcb
                //  Listheads.
                //

                } else {

                    TempEntry = SharedCacheMap->BcbList.Blink;

                    //
                    //  Loop through any/all Bcbs to insert the new listheads.
                    //

                    while (TempEntry != &SharedCacheMap->BcbList) {

                        //
                        //  Sit on this Bcb until we have inserted all listheads
                        //  that go before it.
                        //

                        while (Offset.QuadPart <= ((PBCB)CONTAINING_RECORD(TempEntry, BCB, BcbLinks))->FileOffset.QuadPart) {

                            InsertHeadList(TempEntry, BcbListHeadNew);
                            Offset.QuadPart += SIZE_PER_BCB_LIST;
                            BcbListHeadNew += 1;
                        }
                        TempEntry = TempEntry->Blink;
                    }
                }

                //
                //  Now insert the rest of the new listhead entries that were
                //  not finished in either loop above.
                //

                while (Offset.QuadPart < NewSectionSize.QuadPart) {

                    InsertHeadList(&SharedCacheMap->BcbList, BcbListHeadNew);
                    Offset.QuadPart += SIZE_PER_BCB_LIST;
                    BcbListHeadNew += 1;
                }
            }

            SharedCacheMap->Vacbs = NewAddresses;

            if ((OldAddresses != &SharedCacheMap->InitialVacbs[0]) &&
                (OldAddresses != NULL)) {
                ExFreePool( OldAddresses );
            }
        }

        SharedCacheMap->SectionSize = NewSectionSize;
    }

    if (GrowingBcbListHeads) {
        ExReleaseSpinLockFromDpcLevel( &CcVacbSpinLock );
        ExReleaseSpinLock( &CcMasterSpinLock, OldIrql );
    } else {
        ExReleaseSpinLock( &CcVacbSpinLock, OldIrql );
    }
}


BOOLEAN
FASTCALL
CcUnmapVacbArray (
    IN PSHARED_CACHE_MAP SharedCacheMap,
    IN PLARGE_INTEGER FileOffset OPTIONAL,
    IN ULONG Length
    )

/*++

Routine Description:

    This routine must be called to do any unmapping and associated
    cleanup for a shared cache map, just before it is deleted.

Arguments:

    SharedCacheMap - Supplies a pointer to the shared cache map
                     which is about to be deleted.

    FileOffset - If supplied, only unmap the specified offset and length

    Length - Completes range to unmap if FileOffset specified.  If FileOffset
             is specified, Length of 0 means unmap to the end of the section.

Return Value:

    FALSE -- if an the unmap was not done due to an active vacb
    TRUE -- if the unmap was done

--*/

{
    PVACB Vacb;
    KIRQL OldIrql;
    LARGE_INTEGER StartingFileOffset = {0,0};
    LARGE_INTEGER EndingFileOffset = SharedCacheMap->SectionSize;

    //
    //  We could be just cleaning up for error recovery.
    //

    if (SharedCacheMap->Vacbs == NULL) {
        return TRUE;
    }

    //
    //  See if a range was specified.
    //

    if (ARGUMENT_PRESENT(FileOffset)) {
        StartingFileOffset = *FileOffset;
        if (Length != 0) {
            EndingFileOffset.QuadPart = FileOffset->QuadPart + Length;
        }
    }

    //
    //  Acquire the spin lock to
    //

    ExAcquireSpinLock( &CcVacbSpinLock, &OldIrql );

    while (StartingFileOffset.QuadPart < EndingFileOffset.QuadPart) {

        //
        //  Note that the caller with an explicit range may be off the
        //  end of the section (example CcPurgeCacheSection for cache
        //  coherency).  That is the reason for the first part of the
        //  test below.
        //
        //  Check the next cell once without the spin lock, it probably will
        //  not change, but we will handle it if it does not.
        //

        if ((StartingFileOffset.QuadPart < SharedCacheMap->SectionSize.QuadPart) &&
            ((Vacb = GetVacb( SharedCacheMap, StartingFileOffset )) != NULL)) {

            //
            //  Return here if we are unlucky and see an active
            //  Vacb.  It could be Purge calling, and the Lazy Writer
            //  may have done a CcGetVirtualAddressIfMapped!
            //

            if (Vacb->Overlay.ActiveCount != 0) {

                ExReleaseSpinLock( &CcVacbSpinLock, OldIrql );
                return FALSE;
            }

            //
            //  Unlink it from the other SharedCacheMap, so the other
            //  guy will not try to use it when we free the spin lock.
            //

            SetVacb( SharedCacheMap, StartingFileOffset, NULL );
            Vacb->SharedCacheMap = NULL;

            //
            //  Increment the open count so that no one else will
            //  try to unmap or reuse until we are done.
            //

            Vacb->Overlay.ActiveCount += 1;

            //
            //  Release the spin lock.
            //

            ExReleaseSpinLock( &CcVacbSpinLock, OldIrql );

            //
            //  Unmap and free it if we really got it above.
            //

            CcUnmapVacb( Vacb, SharedCacheMap );

            //
            //  Reacquire the spin lock so that we can decrment the count.
            //

            ExAcquireSpinLock( &CcVacbSpinLock, &OldIrql );
            Vacb->Overlay.ActiveCount -= 1;
        }

        StartingFileOffset.QuadPart = StartingFileOffset.QuadPart + VACB_MAPPING_GRANULARITY;
    }

    ExReleaseSpinLock( &CcVacbSpinLock, OldIrql );

    return TRUE;
}