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
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
|
/*++
Copyright (c) 1990 Microsoft Corporation
Module Name:
copysup.c
Abstract:
This module implements the copy support routines for the Cache subsystem.
Author:
Tom Miller [TomM] 4-May-1990
Revision History:
--*/
#include "cc.h"
//
// Define our debug constant
//
#define me 0x00000004
BOOLEAN
CcCopyRead (
IN PFILE_OBJECT FileObject,
IN PLARGE_INTEGER FileOffset,
IN ULONG Length,
IN BOOLEAN Wait,
OUT PVOID Buffer,
OUT PIO_STATUS_BLOCK IoStatus
)
/*++
Routine Description:
This routine attempts to copy the specified file data from the cache
into the output buffer, and deliver the correct I/O status. It is *not*
safe to call this routine from Dpc level.
If the caller does not want to block (such as for disk I/O), then
Wait should be supplied as FALSE. If Wait was supplied as FALSE and
it is currently impossible to supply all of the requested data without
blocking, then this routine will return FALSE. However, if the
data is immediately accessible in the cache and no blocking is
required, this routine copies the data and returns TRUE.
If the caller supplies Wait as TRUE, then this routine is guaranteed
to copy the data and return TRUE. If the data is immediately
accessible in the cache, then no blocking will occur. Otherwise,
the the data transfer from the file into the cache will be initiated,
and the caller will be blocked until the data can be returned.
File system Fsd's should typically supply Wait = TRUE if they are
processing a synchronous I/O requests, or Wait = FALSE if they are
processing an asynchronous request.
File system or Server Fsp threads should supply Wait = TRUE.
Arguments:
FileObject - Pointer to the file object for a file which was
opened with NO_INTERMEDIATE_BUFFERING clear, i.e., for
which CcInitializeCacheMap was called by the file system.
FileOffset - Byte offset in file for desired data.
Length - Length of desired data in bytes.
Wait - FALSE if caller may not block, TRUE otherwise (see description
above)
Buffer - Pointer to output buffer to which data should be copied.
IoStatus - Pointer to standard I/O status block to receive the status
for the transfer. (STATUS_SUCCESS guaranteed for cache
hits, otherwise the actual I/O status is returned.)
Note that even if FALSE is returned, the IoStatus.Information
field will return the count of any bytes successfully
transferred before a blocking condition occured. The caller
may either choose to ignore this information, or resume
the copy later accounting for bytes transferred.
Return Value:
FALSE - if Wait was supplied as FALSE and the data was not delivered
TRUE - if the data is being delivered
--*/
{
PSHARED_CACHE_MAP SharedCacheMap;
PPRIVATE_CACHE_MAP PrivateCacheMap;
PVOID CacheBuffer;
LARGE_INTEGER FOffset;
PVACB Vacb;
PBCB Bcb;
PVACB ActiveVacb;
ULONG ActivePage;
ULONG PageIsDirty;
ULONG SavedState;
KIRQL OldIrql;
NTSTATUS Status;
ULONG OriginalLength = Length;
ULONG PageCount = COMPUTE_PAGES_SPANNED(((PVOID)FileOffset->LowPart), Length);
PETHREAD Thread = PsGetCurrentThread();
BOOLEAN GotAMiss = FALSE;
DebugTrace(+1, me, "CcCopyRead\n", 0 );
MmSavePageFaultReadAhead( Thread, &SavedState );
//
// Get pointer to shared and private cache maps
//
SharedCacheMap = FileObject->SectionObjectPointer->SharedCacheMap;
PrivateCacheMap = FileObject->PrivateCacheMap;
//
// Check for read past file size, the caller must filter this case out.
//
ASSERT( ( FileOffset->QuadPart + (LONGLONG)Length) <= SharedCacheMap->FileSize.QuadPart );
//
// If read ahead is enabled, then do the read ahead here so it
// overlaps with the copy (otherwise we will do it below).
// Note that we are assuming that we will not get ahead of our
// current transfer - if read ahead is working it should either
// already be in memory or else underway.
//
if (PrivateCacheMap->ReadAheadEnabled && (PrivateCacheMap->ReadAheadLength[1] == 0)) {
CcScheduleReadAhead( FileObject, FileOffset, Length );
}
FOffset = *FileOffset;
//
// Increment performance counters
//
if (Wait) {
HOT_STATISTIC(CcCopyReadWait) += 1;
//
// This is not an exact solution, but when IoPageRead gets a miss,
// it cannot tell whether it was CcCopyRead or CcMdlRead, but since
// the miss should occur very soon, by loading the pointer here
// probably the right counter will get incremented, and in any case,
// we hope the errrors average out!
//
CcMissCounter = &CcCopyReadWaitMiss;
} else {
HOT_STATISTIC(CcCopyReadNoWait) += 1;
}
//
// See if we have an active Vacb, that we can just copy to.
//
GetActiveVacb( SharedCacheMap, OldIrql, ActiveVacb, ActivePage, PageIsDirty );
if (ActiveVacb != NULL) {
if ((ULONG)(FOffset.QuadPart >> VACB_OFFSET_SHIFT) == (ActivePage >> (VACB_OFFSET_SHIFT - PAGE_SHIFT))) {
ULONG LengthToCopy = VACB_MAPPING_GRANULARITY - (FOffset.LowPart & (VACB_MAPPING_GRANULARITY - 1));
if (SharedCacheMap->NeedToZero != NULL) {
PVOID NeedToZero;
ExAcquireFastLock( &SharedCacheMap->ActiveVacbSpinLock, &OldIrql );
//
// Note that the NeedToZero could be cleared, since we
// tested it without the spinlock.
//
NeedToZero = SharedCacheMap->NeedToZero;
if (NeedToZero != NULL) {
RtlZeroMemory( NeedToZero, PAGE_SIZE - ((((ULONG)NeedToZero - 1) & (PAGE_SIZE - 1)) + 1) );
SharedCacheMap->NeedToZero = NULL;
}
ExReleaseFastLock( &SharedCacheMap->ActiveVacbSpinLock, OldIrql );
if (NeedToZero != NULL) {
MmUnlockCachedPage( (PVOID)((PCHAR)NeedToZero - 1) );
}
}
//
// Reduce LengthToCopy if it is greater than our caller's length.
//
if (LengthToCopy > Length) {
LengthToCopy = Length;
}
//
// Copy the data to the user buffer.
//
try {
MmSetPageFaultReadAhead( Thread, PageCount - 1 );
RtlCopyBytes( Buffer,
(PVOID)((PCHAR)ActiveVacb->BaseAddress +
(FOffset.LowPart & (VACB_MAPPING_GRANULARITY - 1))),
LengthToCopy );
} except( CcCopyReadExceptionFilter( GetExceptionInformation(),
&Status ) ) {
MmResetPageFaultReadAhead( Thread, SavedState );
SetActiveVacb( SharedCacheMap, OldIrql, ActiveVacb, ActivePage, PageIsDirty );
//
// If we got an access violation, then the user buffer went
// away. Otherwise we must have gotten an I/O error trying
// to bring the data in.
//
if (Status == STATUS_ACCESS_VIOLATION) {
ExRaiseStatus( STATUS_INVALID_USER_BUFFER );
}
else {
ExRaiseStatus( FsRtlNormalizeNtstatus( Status,
STATUS_UNEXPECTED_IO_ERROR ));
}
}
//
// Now adjust FOffset and Length by what we copied.
//
Buffer = (PVOID)((PCHAR)Buffer + LengthToCopy);
FOffset.QuadPart = FOffset.QuadPart + (LONGLONG)LengthToCopy;
Length -= LengthToCopy;
}
//
// If that was all the data, then remember the Vacb
//
if (Length == 0) {
SetActiveVacb( SharedCacheMap, OldIrql, ActiveVacb, ActivePage, PageIsDirty );
//
// Otherwise we must free it because we will map other vacbs below.
//
} else {
CcFreeActiveVacb( SharedCacheMap, ActiveVacb, ActivePage, PageIsDirty );
}
}
//
// Not all of the transfer will come back at once, so we have to loop
// until the entire transfer is complete.
//
while (Length != 0) {
ULONG ReceivedLength;
LARGE_INTEGER BeyondLastByte;
//
// Call local routine to Map or Access the file data, then move the data,
// then call another local routine to free the data. If we cannot map
// the data because of a Wait condition, return FALSE.
//
// Note that this call may result in an exception, however, if it
// does no Bcb is returned and this routine has absolutely no
// cleanup to perform. Therefore, we do not have a try-finally
// and we allow the possibility that we will simply be unwound
// without notice.
//
if (Wait) {
CacheBuffer = CcGetVirtualAddress( SharedCacheMap,
FOffset,
&Vacb,
&ReceivedLength );
BeyondLastByte.QuadPart = FOffset.QuadPart + (LONGLONG)ReceivedLength;
} else if (!CcPinFileData( FileObject,
&FOffset,
Length,
TRUE,
FALSE,
FALSE,
&Bcb,
&CacheBuffer,
&BeyondLastByte )) {
DebugTrace(-1, me, "CcCopyRead -> FALSE\n", 0 );
HOT_STATISTIC(CcCopyReadNoWaitMiss) += 1;
//
// Enable ReadAhead if we missed.
//
PrivateCacheMap->ReadAheadEnabled = TRUE;
return FALSE;
} else {
//
// Calculate how much data is described by Bcb starting at our desired
// file offset.
//
ReceivedLength = (ULONG)(BeyondLastByte.QuadPart - FOffset.QuadPart);
}
//
// If we got more than we need, make sure to only transfer
// the right amount.
//
if (ReceivedLength > Length) {
ReceivedLength = Length;
}
//
// It is possible for the user buffer to become no longer accessible
// since it was last checked by the I/O system. If we fail to access
// the buffer we must raise a status that the caller's exception
// filter considers as "expected". Also we unmap the Bcb here, since
// we otherwise would have no other reason to put a try-finally around
// this loop.
//
try {
ULONG PagesToGo = COMPUTE_PAGES_SPANNED( CacheBuffer,
ReceivedLength ) - 1;
//
// We know exactly how much we want to read here, and we do not
// want to read any more in case the caller is doing random access.
// Our read ahead logic takes care of detecting sequential reads,
// and tends to do large asynchronous read aheads. So far we have
// only mapped the data and we have not forced any in. What we
// do now is get into a loop where we copy a page at a time and
// just prior to each move, we tell MM how many additional pages
// we would like to have read in, in the event that we take a
// fault. With this strategy, for cache hits we never make a single
// expensive call to MM to guarantee that the data is in, yet if we
// do take a fault, we are guaranteed to only take one fault because
// we will read all of the data in for the rest of the transfer.
//
// We test first for the multiple page case, to keep the small
// reads faster.
//
if (PagesToGo != 0) {
ULONG MoveLength;
ULONG LengthToGo = ReceivedLength;
while (LengthToGo != 0) {
MoveLength = (PCHAR)(ROUND_TO_PAGES(((PCHAR)CacheBuffer + 1))) -
(PCHAR)CacheBuffer;
if (MoveLength > LengthToGo) {
MoveLength = LengthToGo;
}
//
// Here's hoping that it is cheaper to call Mm to see if
// the page is valid. If not let Mm know how many pages
// we are after before doing the move.
//
MmSetPageFaultReadAhead( Thread, PagesToGo );
GotAMiss = (BOOLEAN)!MmCheckCachedPageState( CacheBuffer, FALSE );
RtlCopyBytes( Buffer, CacheBuffer, MoveLength );
PagesToGo -= 1;
LengthToGo -= MoveLength;
Buffer = (PCHAR)Buffer + MoveLength;
CacheBuffer = (PCHAR)CacheBuffer + MoveLength;
}
//
// Handle the read here that stays on a single page.
//
} else {
//
// Here's hoping that it is cheaper to call Mm to see if
// the page is valid. If not let Mm know how many pages
// we are after before doing the move.
//
MmSetPageFaultReadAhead( Thread, 0 );
GotAMiss = (BOOLEAN)!MmCheckCachedPageState( CacheBuffer, FALSE );
RtlCopyBytes( Buffer, CacheBuffer, ReceivedLength );
Buffer = (PCHAR)Buffer + ReceivedLength;
}
}
except( CcCopyReadExceptionFilter( GetExceptionInformation(),
&Status ) ) {
CcMissCounter = &CcThrowAway;
//
// If we get an exception, then we have to renable page fault
// clustering and unmap on the way out.
//
MmResetPageFaultReadAhead( Thread, SavedState );
if (Wait) {
CcFreeVirtualAddress( Vacb );
} else {
CcUnpinFileData( Bcb, TRUE, UNPIN );
}
//
// If we got an access violation, then the user buffer went
// away. Otherwise we must have gotten an I/O error trying
// to bring the data in.
//
if (Status == STATUS_ACCESS_VIOLATION) {
ExRaiseStatus( STATUS_INVALID_USER_BUFFER );
}
else {
ExRaiseStatus( FsRtlNormalizeNtstatus( Status,
STATUS_UNEXPECTED_IO_ERROR ));
}
}
//
// Update number of bytes transferred.
//
Length -= ReceivedLength;
//
// Unmap the data now, and calculate length left to transfer.
//
if (Wait) {
//
// If there is more to go, just free this vacb.
//
if (Length != 0) {
CcFreeVirtualAddress( Vacb );
//
// Otherwise save it for the next time through.
//
} else {
SetActiveVacb( SharedCacheMap, OldIrql, Vacb, (ULONG)(FOffset.QuadPart >> PAGE_SHIFT), 0 );
break;
}
} else {
CcUnpinFileData( Bcb, TRUE, UNPIN );
}
//
// Assume we did not get all the data we wanted, and set FOffset
// to the end of the returned data.
//
FOffset = BeyondLastByte;
}
MmResetPageFaultReadAhead( Thread, SavedState );
CcMissCounter = &CcThrowAway;
//
// Now enable read ahead if it looks like we got any misses, and do
// the first one.
//
if (GotAMiss && !PrivateCacheMap->ReadAheadEnabled) {
PrivateCacheMap->ReadAheadEnabled = TRUE;
CcScheduleReadAhead( FileObject, FileOffset, OriginalLength );
}
//
// Now that we have described our desired read ahead, let's
// shift the read history down.
//
PrivateCacheMap->FileOffset1 = PrivateCacheMap->FileOffset2;
PrivateCacheMap->BeyondLastByte1 = PrivateCacheMap->BeyondLastByte2;
PrivateCacheMap->FileOffset2 = *FileOffset;
PrivateCacheMap->BeyondLastByte2.QuadPart =
FileOffset->QuadPart + (LONGLONG)OriginalLength;
IoStatus->Status = STATUS_SUCCESS;
IoStatus->Information = OriginalLength;
DebugTrace(-1, me, "CcCopyRead -> TRUE\n", 0 );
return TRUE;
}
VOID
CcFastCopyRead (
IN PFILE_OBJECT FileObject,
IN ULONG FileOffset,
IN ULONG Length,
IN ULONG PageCount,
OUT PVOID Buffer,
OUT PIO_STATUS_BLOCK IoStatus
)
/*++
Routine Description:
This routine attempts to copy the specified file data from the cache
into the output buffer, and deliver the correct I/O status.
This is a faster version of CcCopyRead which only supports 32-bit file
offsets and synchronicity (Wait = TRUE).
Arguments:
FileObject - Pointer to the file object for a file which was
opened with NO_INTERMEDIATE_BUFFERING clear, i.e., for
which CcInitializeCacheMap was called by the file system.
FileOffset - Byte offset in file for desired data.
Length - Length of desired data in bytes.
PageCount - Number of pages spanned by the read.
Buffer - Pointer to output buffer to which data should be copied.
IoStatus - Pointer to standard I/O status block to receive the status
for the transfer. (STATUS_SUCCESS guaranteed for cache
hits, otherwise the actual I/O status is returned.)
Note that even if FALSE is returned, the IoStatus.Information
field will return the count of any bytes successfully
transferred before a blocking condition occured. The caller
may either choose to ignore this information, or resume
the copy later accounting for bytes transferred.
Return Value:
None
--*/
{
PSHARED_CACHE_MAP SharedCacheMap;
PPRIVATE_CACHE_MAP PrivateCacheMap;
PVOID CacheBuffer;
LARGE_INTEGER FOffset;
PVACB Vacb;
PVACB ActiveVacb;
ULONG ActivePage;
ULONG PageIsDirty;
ULONG SavedState;
KIRQL OldIrql;
NTSTATUS Status;
LARGE_INTEGER OriginalOffset;
ULONG OriginalLength = Length;
PETHREAD Thread = PsGetCurrentThread();
BOOLEAN GotAMiss = FALSE;
DebugTrace(+1, me, "CcFastCopyRead\n", 0 );
MmSavePageFaultReadAhead( Thread, &SavedState );
//
// Get pointer to shared and private cache maps
//
SharedCacheMap = FileObject->SectionObjectPointer->SharedCacheMap;
PrivateCacheMap = FileObject->PrivateCacheMap;
//
// Check for read past file size, the caller must filter this case out.
//
ASSERT( (FileOffset + Length) <= SharedCacheMap->FileSize.LowPart );
//
// If read ahead is enabled, then do the read ahead here so it
// overlaps with the copy (otherwise we will do it below).
// Note that we are assuming that we will not get ahead of our
// current transfer - if read ahead is working it should either
// already be in memory or else underway.
//
OriginalOffset.LowPart = FileOffset;
OriginalOffset.HighPart = 0;
if (PrivateCacheMap->ReadAheadEnabled && (PrivateCacheMap->ReadAheadLength[1] == 0)) {
CcScheduleReadAhead( FileObject, &OriginalOffset, Length );
}
//
// This is not an exact solution, but when IoPageRead gets a miss,
// it cannot tell whether it was CcCopyRead or CcMdlRead, but since
// the miss should occur very soon, by loading the pointer here
// probably the right counter will get incremented, and in any case,
// we hope the errrors average out!
//
CcMissCounter = &CcCopyReadWaitMiss;
//
// Increment performance counters
//
HOT_STATISTIC(CcCopyReadWait) += 1;
//
// See if we have an active Vacb, that we can just copy to.
//
GetActiveVacb( SharedCacheMap, OldIrql, ActiveVacb, ActivePage, PageIsDirty );
if (ActiveVacb != NULL) {
if ((FileOffset >> VACB_OFFSET_SHIFT) == (ActivePage >> (VACB_OFFSET_SHIFT - PAGE_SHIFT))) {
ULONG LengthToCopy = VACB_MAPPING_GRANULARITY - (FileOffset & (VACB_MAPPING_GRANULARITY - 1));
if (SharedCacheMap->NeedToZero != NULL) {
PVOID NeedToZero;
ExAcquireFastLock( &SharedCacheMap->ActiveVacbSpinLock, &OldIrql );
//
// Note that the NeedToZero could be cleared, since we
// tested it without the spinlock.
//
NeedToZero = SharedCacheMap->NeedToZero;
if (NeedToZero != NULL) {
RtlZeroMemory( NeedToZero, PAGE_SIZE - ((((ULONG)NeedToZero - 1) & (PAGE_SIZE - 1)) + 1) );
SharedCacheMap->NeedToZero = NULL;
}
ExReleaseFastLock( &SharedCacheMap->ActiveVacbSpinLock, OldIrql );
if (NeedToZero != NULL) {
MmUnlockCachedPage( (PVOID)((PCHAR)NeedToZero - 1) );
}
}
//
// Reduce LengthToCopy if it is greater than our caller's length.
//
if (LengthToCopy > Length) {
LengthToCopy = Length;
}
//
// Copy the data to the user buffer.
//
try {
MmSetPageFaultReadAhead( Thread, PageCount - 1 );
RtlCopyBytes( Buffer,
(PVOID)((PCHAR)ActiveVacb->BaseAddress +
(FileOffset & (VACB_MAPPING_GRANULARITY - 1))),
LengthToCopy );
} except( CcCopyReadExceptionFilter( GetExceptionInformation(),
&Status ) ) {
MmResetPageFaultReadAhead( Thread, SavedState );
SetActiveVacb( SharedCacheMap, OldIrql, ActiveVacb, ActivePage, PageIsDirty );
//
// If we got an access violation, then the user buffer went
// away. Otherwise we must have gotten an I/O error trying
// to bring the data in.
//
if (Status == STATUS_ACCESS_VIOLATION) {
ExRaiseStatus( STATUS_INVALID_USER_BUFFER );
}
else {
ExRaiseStatus( FsRtlNormalizeNtstatus( Status,
STATUS_UNEXPECTED_IO_ERROR ));
}
}
//
// Now adjust FileOffset and Length by what we copied.
//
Buffer = (PVOID)((PCHAR)Buffer + LengthToCopy);
FileOffset += LengthToCopy;
Length -= LengthToCopy;
}
//
// If that was all the data, then remember the Vacb
//
if (Length == 0) {
SetActiveVacb( SharedCacheMap, OldIrql, ActiveVacb, ActivePage, PageIsDirty );
//
// Otherwise we must free it because we will map other vacbs below.
//
} else {
CcFreeActiveVacb( SharedCacheMap, ActiveVacb, ActivePage, PageIsDirty );
}
}
//
// Not all of the transfer will come back at once, so we have to loop
// until the entire transfer is complete.
//
FOffset.HighPart = 0;
FOffset.LowPart = FileOffset;
while (Length != 0) {
ULONG ReceivedLength;
ULONG BeyondLastByte;
//
// Call local routine to Map or Access the file data, then move the data,
// then call another local routine to free the data. If we cannot map
// the data because of a Wait condition, return FALSE.
//
// Note that this call may result in an exception, however, if it
// does no Bcb is returned and this routine has absolutely no
// cleanup to perform. Therefore, we do not have a try-finally
// and we allow the possibility that we will simply be unwound
// without notice.
//
CacheBuffer = CcGetVirtualAddress( SharedCacheMap,
FOffset,
&Vacb,
&ReceivedLength );
BeyondLastByte = FOffset.LowPart + ReceivedLength;
//
// If we got more than we need, make sure to only transfer
// the right amount.
//
if (ReceivedLength > Length) {
ReceivedLength = Length;
}
//
// It is possible for the user buffer to become no longer accessible
// since it was last checked by the I/O system. If we fail to access
// the buffer we must raise a status that the caller's exception
// filter considers as "expected". Also we unmap the Bcb here, since
// we otherwise would have no other reason to put a try-finally around
// this loop.
//
try {
ULONG PagesToGo = COMPUTE_PAGES_SPANNED( CacheBuffer,
ReceivedLength ) - 1;
//
// We know exactly how much we want to read here, and we do not
// want to read any more in case the caller is doing random access.
// Our read ahead logic takes care of detecting sequential reads,
// and tends to do large asynchronous read aheads. So far we have
// only mapped the data and we have not forced any in. What we
// do now is get into a loop where we copy a page at a time and
// just prior to each move, we tell MM how many additional pages
// we would like to have read in, in the event that we take a
// fault. With this strategy, for cache hits we never make a single
// expensive call to MM to guarantee that the data is in, yet if we
// do take a fault, we are guaranteed to only take one fault because
// we will read all of the data in for the rest of the transfer.
//
// We test first for the multiple page case, to keep the small
// reads faster.
//
if (PagesToGo != 0) {
ULONG MoveLength;
ULONG LengthToGo = ReceivedLength;
while (LengthToGo != 0) {
MoveLength = (PCHAR)(ROUND_TO_PAGES(((PCHAR)CacheBuffer + 1))) -
(PCHAR)CacheBuffer;
if (MoveLength > LengthToGo) {
MoveLength = LengthToGo;
}
//
// Here's hoping that it is cheaper to call Mm to see if
// the page is valid. If not let Mm know how many pages
// we are after before doing the move.
//
MmSetPageFaultReadAhead( Thread, PagesToGo );
GotAMiss = (BOOLEAN)!MmCheckCachedPageState( CacheBuffer, FALSE );
RtlCopyBytes( Buffer, CacheBuffer, MoveLength );
PagesToGo -= 1;
LengthToGo -= MoveLength;
Buffer = (PCHAR)Buffer + MoveLength;
CacheBuffer = (PCHAR)CacheBuffer + MoveLength;
}
//
// Handle the read here that stays on a single page.
//
} else {
//
// Here's hoping that it is cheaper to call Mm to see if
// the page is valid. If not let Mm know how many pages
// we are after before doing the move.
//
MmSetPageFaultReadAhead( Thread, 0 );
GotAMiss = (BOOLEAN)!MmCheckCachedPageState( CacheBuffer, FALSE );
RtlCopyBytes( Buffer, CacheBuffer, ReceivedLength );
Buffer = (PCHAR)Buffer + ReceivedLength;
}
}
except( CcCopyReadExceptionFilter( GetExceptionInformation(),
&Status ) ) {
CcMissCounter = &CcThrowAway;
//
// If we get an exception, then we have to renable page fault
// clustering and unmap on the way out.
//
MmResetPageFaultReadAhead( Thread, SavedState );
CcFreeVirtualAddress( Vacb );
//
// If we got an access violation, then the user buffer went
// away. Otherwise we must have gotten an I/O error trying
// to bring the data in.
//
if (Status == STATUS_ACCESS_VIOLATION) {
ExRaiseStatus( STATUS_INVALID_USER_BUFFER );
}
else {
ExRaiseStatus( FsRtlNormalizeNtstatus( Status,
STATUS_UNEXPECTED_IO_ERROR ));
}
}
//
// Update number of bytes transferred.
//
Length -= ReceivedLength;
//
// Unmap the data now, and calculate length left to transfer.
//
if (Length != 0) {
//
// If there is more to go, just free this vacb.
//
CcFreeVirtualAddress( Vacb );
} else {
//
// Otherwise save it for the next time through.
//
SetActiveVacb( SharedCacheMap, OldIrql, Vacb, (FOffset.LowPart >> PAGE_SHIFT), 0 );
break;
}
//
// Assume we did not get all the data we wanted, and set FOffset
// to the end of the returned data.
//
FOffset.LowPart = BeyondLastByte;
}
MmResetPageFaultReadAhead( Thread, SavedState );
CcMissCounter = &CcThrowAway;
//
// Now enable read ahead if it looks like we got any misses, and do
// the first one.
//
if (GotAMiss && !PrivateCacheMap->ReadAheadEnabled) {
PrivateCacheMap->ReadAheadEnabled = TRUE;
CcScheduleReadAhead( FileObject, &OriginalOffset, OriginalLength );
}
//
// Now that we have described our desired read ahead, let's
// shift the read history down.
//
PrivateCacheMap->FileOffset1.LowPart = PrivateCacheMap->FileOffset2.LowPart;
PrivateCacheMap->BeyondLastByte1.LowPart = PrivateCacheMap->BeyondLastByte2.LowPart;
PrivateCacheMap->FileOffset2.LowPart = OriginalOffset.LowPart;
PrivateCacheMap->BeyondLastByte2.LowPart = OriginalOffset.LowPart + OriginalLength;
IoStatus->Status = STATUS_SUCCESS;
IoStatus->Information = OriginalLength;
DebugTrace(-1, me, "CcFastCopyRead -> VOID\n", 0 );
}
BOOLEAN
CcCopyWrite (
IN PFILE_OBJECT FileObject,
IN PLARGE_INTEGER FileOffset,
IN ULONG Length,
IN BOOLEAN Wait,
IN PVOID Buffer
)
/*++
Routine Description:
This routine attempts to copy the specified file data from the specified
buffer into the Cache, and deliver the correct I/O status. It is *not*
safe to call this routine from Dpc level.
If the caller does not want to block (such as for disk I/O), then
Wait should be supplied as FALSE. If Wait was supplied as FALSE and
it is currently impossible to receive all of the requested data without
blocking, then this routine will return FALSE. However, if the
correct space is immediately accessible in the cache and no blocking is
required, this routine copies the data and returns TRUE.
If the caller supplies Wait as TRUE, then this routine is guaranteed
to copy the data and return TRUE. If the correct space is immediately
accessible in the cache, then no blocking will occur. Otherwise,
the necessary work will be initiated to read and/or free cache data,
and the caller will be blocked until the data can be received.
File system Fsd's should typically supply Wait = TRUE if they are
processing a synchronous I/O requests, or Wait = FALSE if they are
processing an asynchronous request.
File system or Server Fsp threads should supply Wait = TRUE.
Arguments:
FileObject - Pointer to the file object for a file which was
opened with NO_INTERMEDIATE_BUFFERING clear, i.e., for
which CcInitializeCacheMap was called by the file system.
FileOffset - Byte offset in file to receive the data.
Length - Length of data in bytes.
Wait - FALSE if caller may not block, TRUE otherwise (see description
above)
Buffer - Pointer to input buffer from which data should be copied.
Return Value:
FALSE - if Wait was supplied as FALSE and the data was not copied.
TRUE - if the data has been copied.
Raises:
STATUS_INSUFFICIENT_RESOURCES - If a pool allocation failure occurs.
This can only occur if Wait was specified as TRUE. (If Wait is
specified as FALSE, and an allocation failure occurs, this
routine simply returns FALSE.)
--*/
{
PSHARED_CACHE_MAP SharedCacheMap;
PVACB ActiveVacb;
ULONG ActivePage;
PVOID ActiveAddress;
ULONG PageIsDirty;
KIRQL OldIrql;
NTSTATUS Status;
PVOID CacheBuffer;
LARGE_INTEGER FOffset;
PBCB Bcb;
ULONG ZeroFlags;
LARGE_INTEGER Temp;
DebugTrace(+1, me, "CcCopyWrite\n", 0 );
//
// If the caller specified Wait == FALSE, but the FileObject is WriteThrough,
// then we need to just get out.
//
if ((FileObject->Flags & FO_WRITE_THROUGH) && !Wait) {
DebugTrace(-1, me, "CcCopyWrite->FALSE (WriteThrough && !Wait)\n", 0 );
return FALSE;
}
//
// Get pointer to shared cache map
//
SharedCacheMap = FileObject->SectionObjectPointer->SharedCacheMap;
FOffset = *FileOffset;
//
// See if we have an active Vacb, that we can just copy to.
//
GetActiveVacb( SharedCacheMap, OldIrql, ActiveVacb, ActivePage, PageIsDirty );
if (ActiveVacb != NULL) {
//
// See if the request starts in the ActivePage. WriteThrough requests must
// go the longer route through CcMapAndCopy, where WriteThrough flushes are
// implemented.
//
if (((ULONG)(FOffset.QuadPart >> PAGE_SHIFT) == ActivePage) && (Length != 0) &&
!FlagOn( FileObject->Flags, FO_WRITE_THROUGH )) {
ULONG LengthToCopy = PAGE_SIZE - (FOffset.LowPart & (PAGE_SIZE - 1));
//
// Reduce LengthToCopy if it is greater than our caller's length.
//
if (LengthToCopy > Length) {
LengthToCopy = Length;
}
//
// Copy the data to the user buffer.
//
try {
//
// If we are copying to a page that is locked down, then
// we have to do it under our spinlock, and update the
// NeedToZero field.
//
OldIrql = 0xFF;
CacheBuffer = (PVOID)((PCHAR)ActiveVacb->BaseAddress +
(FOffset.LowPart & (VACB_MAPPING_GRANULARITY - 1)));
if (SharedCacheMap->NeedToZero != NULL) {
//
// The FastLock may not write our "flag".
//
OldIrql = 0;
ExAcquireFastLock( &SharedCacheMap->ActiveVacbSpinLock, &OldIrql );
//
// Note that the NeedToZero could be cleared, since we
// tested it without the spinlock.
//
ActiveAddress = SharedCacheMap->NeedToZero;
if ((ActiveAddress != NULL) &&
(((PCHAR)CacheBuffer + LengthToCopy) > (PCHAR)ActiveAddress)) {
//
// If we are skipping some bytes in the page, then we need
// to zero them.
//
if ((PCHAR)CacheBuffer > (PCHAR)ActiveAddress) {
RtlZeroMemory( ActiveAddress, (PCHAR)CacheBuffer - (PCHAR)ActiveAddress );
}
SharedCacheMap->NeedToZero = (PVOID)((PCHAR)CacheBuffer + LengthToCopy);
}
ExReleaseFastLock( &SharedCacheMap->ActiveVacbSpinLock, OldIrql );
}
RtlCopyBytes( CacheBuffer, Buffer, LengthToCopy );
} except( CcCopyReadExceptionFilter( GetExceptionInformation(),
&Status ) ) {
//
// If we failed to overwrite the uninitialized data,
// zero it now (we cannot safely restore NeedToZero).
//
if (OldIrql != 0xFF) {
RtlZeroBytes( CacheBuffer, LengthToCopy );
}
SetActiveVacb( SharedCacheMap, OldIrql, ActiveVacb, ActivePage, ACTIVE_PAGE_IS_DIRTY );
//
// If we got an access violation, then the user buffer went
// away. Otherwise we must have gotten an I/O error trying
// to bring the data in.
//
if (Status == STATUS_ACCESS_VIOLATION) {
ExRaiseStatus( STATUS_INVALID_USER_BUFFER );
}
else {
ExRaiseStatus( FsRtlNormalizeNtstatus( Status,
STATUS_UNEXPECTED_IO_ERROR ));
}
}
//
// Now adjust FOffset and Length by what we copied.
//
Buffer = (PVOID)((PCHAR)Buffer + LengthToCopy);
FOffset.QuadPart = FOffset.QuadPart + (LONGLONG)LengthToCopy;
Length -= LengthToCopy;
//
// If that was all the data, then get outski...
//
if (Length == 0) {
SetActiveVacb( SharedCacheMap, OldIrql, ActiveVacb, ActivePage, ACTIVE_PAGE_IS_DIRTY );
return TRUE;
}
//
// Remember that the page is dirty now.
//
PageIsDirty |= ACTIVE_PAGE_IS_DIRTY;
}
CcFreeActiveVacb( SharedCacheMap, ActiveVacb, ActivePage, PageIsDirty );
//
// Else someone else could have the active page, and may want to zero
// the range we plan to write!
//
} else if (SharedCacheMap->NeedToZero != NULL) {
CcFreeActiveVacb( SharedCacheMap, NULL, 0, FALSE );
}
//
// At this point we can calculate the ZeroFlags.
//
//
// We can always zero middle pages, if any.
//
ZeroFlags = ZERO_MIDDLE_PAGES;
if (((FOffset.LowPart & (PAGE_SIZE - 1)) == 0) &&
(Length >= PAGE_SIZE)) {
ZeroFlags |= ZERO_FIRST_PAGE;
}
if (((FOffset.LowPart + Length) & (PAGE_SIZE - 1)) == 0) {
ZeroFlags |= ZERO_LAST_PAGE;
}
Temp = FOffset;
Temp.LowPart &= ~(PAGE_SIZE -1);
Temp.QuadPart = ((PFSRTL_COMMON_FCB_HEADER)FileObject->FsContext)->ValidDataLength.QuadPart -
Temp.QuadPart;
if (Temp.QuadPart <= 0) {
ZeroFlags |= ZERO_FIRST_PAGE | ZERO_MIDDLE_PAGES | ZERO_LAST_PAGE;
} else if ((Temp.HighPart == 0) && (Temp.LowPart <= PAGE_SIZE)) {
ZeroFlags |= ZERO_MIDDLE_PAGES | ZERO_LAST_PAGE;
}
//
// Call a routine to map and copy the data in Mm and get out.
//
if (Wait) {
CcMapAndCopy( SharedCacheMap,
Buffer,
&FOffset,
Length,
ZeroFlags,
BooleanFlagOn( FileObject->Flags, FO_WRITE_THROUGH ));
return TRUE;
}
//
// The rest of this routine is the Wait == FALSE case.
//
// Not all of the transfer will come back at once, so we have to loop
// until the entire transfer is complete.
//
while (Length != 0) {
ULONG ReceivedLength;
LARGE_INTEGER BeyondLastByte;
if (!CcPinFileData( FileObject,
&FOffset,
Length,
FALSE,
TRUE,
FALSE,
&Bcb,
&CacheBuffer,
&BeyondLastByte )) {
DebugTrace(-1, me, "CcCopyWrite -> FALSE\n", 0 );
return FALSE;
} else {
//
// Calculate how much data is described by Bcb starting at our desired
// file offset.
//
ReceivedLength = (ULONG)(BeyondLastByte.QuadPart - FOffset.QuadPart);
//
// If we got more than we need, make sure to only transfer
// the right amount.
//
if (ReceivedLength > Length) {
ReceivedLength = Length;
}
}
//
// It is possible for the user buffer to become no longer accessible
// since it was last checked by the I/O system. If we fail to access
// the buffer we must raise a status that the caller's exception
// filter considers as "expected". Also we unmap the Bcb here, since
// we otherwise would have no other reason to put a try-finally around
// this loop.
//
try {
RtlCopyBytes( CacheBuffer, Buffer, ReceivedLength );
CcSetDirtyPinnedData( Bcb, NULL );
CcUnpinFileData( Bcb, FALSE, UNPIN );
}
except( CcCopyReadExceptionFilter( GetExceptionInformation(),
&Status ) ) {
CcUnpinFileData( Bcb, TRUE, UNPIN );
//
// If we got an access violation, then the user buffer went
// away. Otherwise we must have gotten an I/O error trying
// to bring the data in.
//
if (Status == STATUS_ACCESS_VIOLATION) {
ExRaiseStatus( STATUS_INVALID_USER_BUFFER );
}
else {
ExRaiseStatus(FsRtlNormalizeNtstatus( Status, STATUS_UNEXPECTED_IO_ERROR ));
}
}
//
// Assume we did not get all the data we wanted, and set FOffset
// to the end of the returned data and adjust the Buffer and Length.
//
FOffset = BeyondLastByte;
Buffer = (PCHAR)Buffer + ReceivedLength;
Length -= ReceivedLength;
}
DebugTrace(-1, me, "CcCopyWrite -> TRUE\n", 0 );
return TRUE;
}
VOID
CcFastCopyWrite (
IN PFILE_OBJECT FileObject,
IN ULONG FileOffset,
IN ULONG Length,
IN PVOID Buffer
)
/*++
Routine Description:
This routine attempts to copy the specified file data from the specified
buffer into the Cache, and deliver the correct I/O status.
This is a faster version of CcCopyWrite which only supports 32-bit file
offsets and synchronicity (Wait = TRUE) and no Write Through.
Arguments:
FileObject - Pointer to the file object for a file which was
opened with NO_INTERMEDIATE_BUFFERING clear, i.e., for
which CcInitializeCacheMap was called by the file system.
FileOffset - Byte offset in file to receive the data.
Length - Length of data in bytes.
Buffer - Pointer to input buffer from which data should be copied.
Return Value:
None
Raises:
STATUS_INSUFFICIENT_RESOURCES - If a pool allocation failure occurs.
This can only occur if Wait was specified as TRUE. (If Wait is
specified as FALSE, and an allocation failure occurs, this
routine simply returns FALSE.)
--*/
{
PSHARED_CACHE_MAP SharedCacheMap;
PVOID CacheBuffer;
PVACB ActiveVacb;
ULONG ActivePage;
PVOID ActiveAddress;
ULONG PageIsDirty;
KIRQL OldIrql;
NTSTATUS Status;
ULONG ZeroFlags;
ULONG ValidDataLength;
LARGE_INTEGER FOffset;
DebugTrace(+1, me, "CcFastCopyWrite\n", 0 );
//
// Get pointer to shared cache map and a copy of valid data length
//
SharedCacheMap = FileObject->SectionObjectPointer->SharedCacheMap;
//
// See if we have an active Vacb, that we can just copy to.
//
GetActiveVacb( SharedCacheMap, OldIrql, ActiveVacb, ActivePage, PageIsDirty );
if (ActiveVacb != NULL) {
//
// See if the request starts in the ActivePage. WriteThrough requests must
// go the longer route through CcMapAndCopy, where WriteThrough flushes are
// implemented.
//
if (((FileOffset >> PAGE_SHIFT) == ActivePage) && (Length != 0) &&
!FlagOn( FileObject->Flags, FO_WRITE_THROUGH )) {
ULONG LengthToCopy = PAGE_SIZE - (FileOffset & (PAGE_SIZE - 1));
//
// Reduce LengthToCopy if it is greater than our caller's length.
//
if (LengthToCopy > Length) {
LengthToCopy = Length;
}
//
// Copy the data to the user buffer.
//
try {
//
// If we are copying to a page that is locked down, then
// we have to do it under our spinlock, and update the
// NeedToZero field.
//
OldIrql = 0xFF;
CacheBuffer = (PVOID)((PCHAR)ActiveVacb->BaseAddress +
(FileOffset & (VACB_MAPPING_GRANULARITY - 1)));
if (SharedCacheMap->NeedToZero != NULL) {
//
// The FastLock may not write our "flag".
//
OldIrql = 0;
ExAcquireFastLock( &SharedCacheMap->ActiveVacbSpinLock, &OldIrql );
//
// Note that the NeedToZero could be cleared, since we
// tested it without the spinlock.
//
ActiveAddress = SharedCacheMap->NeedToZero;
if ((ActiveAddress != NULL) &&
(((PCHAR)CacheBuffer + LengthToCopy) > (PCHAR)ActiveAddress)) {
//
// If we are skipping some bytes in the page, then we need
// to zero them.
//
if ((PCHAR)CacheBuffer > (PCHAR)ActiveAddress) {
RtlZeroMemory( ActiveAddress, (PCHAR)CacheBuffer - (PCHAR)ActiveAddress );
}
SharedCacheMap->NeedToZero = (PVOID)((PCHAR)CacheBuffer + LengthToCopy);
}
ExReleaseFastLock( &SharedCacheMap->ActiveVacbSpinLock, OldIrql );
}
RtlCopyBytes( CacheBuffer, Buffer, LengthToCopy );
} except( CcCopyReadExceptionFilter( GetExceptionInformation(),
&Status ) ) {
//
// If we failed to overwrite the uninitialized data,
// zero it now (we cannot safely restore NeedToZero).
//
if (OldIrql != 0xFF) {
RtlZeroBytes( CacheBuffer, LengthToCopy );
}
SetActiveVacb( SharedCacheMap, OldIrql, ActiveVacb, ActivePage, ACTIVE_PAGE_IS_DIRTY );
//
// If we got an access violation, then the user buffer went
// away. Otherwise we must have gotten an I/O error trying
// to bring the data in.
//
if (Status == STATUS_ACCESS_VIOLATION) {
ExRaiseStatus( STATUS_INVALID_USER_BUFFER );
}
else {
ExRaiseStatus( FsRtlNormalizeNtstatus( Status,
STATUS_UNEXPECTED_IO_ERROR ));
}
}
//
// Now adjust FileOffset and Length by what we copied.
//
Buffer = (PVOID)((PCHAR)Buffer + LengthToCopy);
FileOffset += LengthToCopy;
Length -= LengthToCopy;
//
// If that was all the data, then get outski...
//
if (Length == 0) {
SetActiveVacb( SharedCacheMap, OldIrql, ActiveVacb, ActivePage, ACTIVE_PAGE_IS_DIRTY );
return;
}
//
// Remember that the page is dirty now.
//
PageIsDirty |= ACTIVE_PAGE_IS_DIRTY;
}
CcFreeActiveVacb( SharedCacheMap, ActiveVacb, ActivePage, PageIsDirty );
//
// Else someone else could have the active page, and may want to zero
// the range we plan to write!
//
} else if (SharedCacheMap->NeedToZero != NULL) {
CcFreeActiveVacb( SharedCacheMap, NULL, 0, FALSE );
}
//
// Set up for call to CcMapAndCopy
//
FOffset.LowPart = FileOffset;
FOffset.HighPart = 0;
ValidDataLength = ((PFSRTL_COMMON_FCB_HEADER)FileObject->FsContext)->ValidDataLength.LowPart;
ASSERT((ValidDataLength == MAXULONG) ||
(((PFSRTL_COMMON_FCB_HEADER)FileObject->FsContext)->ValidDataLength.HighPart == 0));
//
// At this point we can calculate the ReadOnly flag for
// the purposes of whether to use the Bcb resource, and
// we can calculate the ZeroFlags.
//
//
// We can always zero middle pages, if any.
//
ZeroFlags = ZERO_MIDDLE_PAGES;
if (((FileOffset & (PAGE_SIZE - 1)) == 0) &&
(Length >= PAGE_SIZE)) {
ZeroFlags |= ZERO_FIRST_PAGE;
}
if (((FileOffset + Length) & (PAGE_SIZE - 1)) == 0) {
ZeroFlags |= ZERO_LAST_PAGE;
}
if ((FileOffset & ~(PAGE_SIZE - 1)) >= ValidDataLength) {
ZeroFlags |= ZERO_FIRST_PAGE | ZERO_MIDDLE_PAGES | ZERO_LAST_PAGE;
} else if (((FileOffset & ~(PAGE_SIZE - 1)) + PAGE_SIZE) >= ValidDataLength) {
ZeroFlags |= ZERO_MIDDLE_PAGES | ZERO_LAST_PAGE;
}
//
// Call a routine to map and copy the data in Mm and get out.
//
CcMapAndCopy( SharedCacheMap,
Buffer,
&FOffset,
Length,
ZeroFlags,
BooleanFlagOn( FileObject->Flags, FO_WRITE_THROUGH ));
DebugTrace(-1, me, "CcFastCopyWrite -> VOID\n", 0 );
}
LONG
CcCopyReadExceptionFilter(
IN PEXCEPTION_POINTERS ExceptionPointer,
IN PNTSTATUS ExceptionCode
)
/*++
Routine Description:
This routine serves as a exception filter and has the special job of
extracting the "real" I/O error when Mm raises STATUS_IN_PAGE_ERROR
beneath us.
Arguments:
ExceptionPointer - A pointer to the exception record that contains
the real Io Status.
ExceptionCode - A pointer to an NTSTATUS that is to receive the real
status.
Return Value:
EXCEPTION_EXECUTE_HANDLER
--*/
{
*ExceptionCode = ExceptionPointer->ExceptionRecord->ExceptionCode;
if ( (*ExceptionCode == STATUS_IN_PAGE_ERROR) &&
(ExceptionPointer->ExceptionRecord->NumberParameters >= 3) ) {
*ExceptionCode = ExceptionPointer->ExceptionRecord->ExceptionInformation[2];
}
ASSERT( !NT_SUCCESS(*ExceptionCode) );
return EXCEPTION_EXECUTE_HANDLER;
}
BOOLEAN
CcCanIWrite (
IN PFILE_OBJECT FileObject,
IN ULONG BytesToWrite,
IN BOOLEAN Wait,
IN UCHAR Retrying
)
/*++
Routine Description:
This routine tests whether it is ok to do a write to the cache
or not, according to the Thresholds of dirty bytes and available
pages. The first time this routine is called for a request (Retrying
FALSE), we automatically make the new request queue if there are other
requests in the queue.
Note that the ListEmpty test is important to prevent small requests from sneaking
in and starving large requests.
Arguments:
FileObject - for the file to be written
BytesToWrite - Number of bytes caller wishes to write to the Cache.
Wait - TRUE if the caller owns no resources, and can block inside this routine
until it is ok to write.
Retrying - Specified as FALSE when the request is first received, and
otherwise specified as TRUE if this write has already entered
the queue. Special non-zero value of MAXUCHAR indicates that
we were called within the cache manager with a MasterSpinLock held,
so do not attempt to acquire it here. MAXUCHAR - 1 means we
were called within the Cache Manager with some other spinlock
held. For either of these two special values, we do not touch
the FsRtl header.
Return Value:
TRUE if it is ok to write.
FALSE if the caller should defer the write via a call to CcDeferWrite.
--*/
{
PSHARED_CACHE_MAP SharedCacheMap;
KEVENT Event;
KIRQL OldIrql;
ULONG PagesToWrite;
BOOLEAN ExceededPerFileThreshold;
DEFERRED_WRITE DeferredWrite;
PSECTION_OBJECT_POINTERS SectionObjectPointers;
//
// Do a special test here for file objects that keep track of dirty
// pages on a per-file basis. This is used mainly for slow links.
//
ExceededPerFileThreshold = FALSE;
PagesToWrite = ((BytesToWrite < 0x40000 ?
BytesToWrite : 0x40000) + (PAGE_SIZE - 1)) / PAGE_SIZE;
//
// Don't dereference the FsContext field if we were called while holding
// a spinlock.
//
if ((Retrying >= MAXUCHAR - 1) ||
FlagOn(((PFSRTL_COMMON_FCB_HEADER)(FileObject->FsContext))->Flags,
FSRTL_FLAG_LIMIT_MODIFIED_PAGES)) {
if (Retrying != MAXUCHAR) {
ExAcquireFastLock( &CcMasterSpinLock, &OldIrql );
}
if (((SectionObjectPointers = FileObject->SectionObjectPointer) != NULL) &&
((SharedCacheMap = SectionObjectPointers->SharedCacheMap) != NULL) &&
(SharedCacheMap->DirtyPageThreshold != 0) &&
(SharedCacheMap->DirtyPages != 0) &&
((PagesToWrite + SharedCacheMap->DirtyPages) >
SharedCacheMap->DirtyPageThreshold)) {
ExceededPerFileThreshold = TRUE;
}
if (Retrying != MAXUCHAR) {
ExReleaseFastLock( &CcMasterSpinLock, OldIrql );
}
}
//
// See if it is ok to do the write right now
//
if ((Retrying || IsListEmpty(&CcDeferredWrites))
&&
(CcTotalDirtyPages + PagesToWrite < CcDirtyPageThreshold)
&&
MmEnoughMemoryForWrite()
&&
!ExceededPerFileThreshold) {
return TRUE;
//
// Otherwise, if our caller is synchronous, we will just wait here.
//
}
if (IsListEmpty(&CcDeferredWrites) ) {
//
// Get a write scan to occur NOW
//
KeSetTimer( &LazyWriter.ScanTimer, CcNoDelay, &LazyWriter.ScanDpc );
}
if (Wait) {
KeInitializeEvent( &Event, NotificationEvent, FALSE );
//
// Fill in the block. Note that we can access the Fsrtl Common Header
// even if it's paged because Wait will be FALSE if called from
// within the cache.
//
DeferredWrite.NodeTypeCode = CACHE_NTC_DEFERRED_WRITE;
DeferredWrite.NodeByteSize = sizeof(DEFERRED_WRITE);
DeferredWrite.FileObject = FileObject;
DeferredWrite.BytesToWrite = BytesToWrite;
DeferredWrite.Event = &Event;
DeferredWrite.LimitModifiedPages = BooleanFlagOn(((PFSRTL_COMMON_FCB_HEADER)(FileObject->FsContext))->Flags,
FSRTL_FLAG_LIMIT_MODIFIED_PAGES);
//
// Now insert at the appropriate end of the list
//
if (Retrying) {
(VOID)ExInterlockedInsertHeadList( &CcDeferredWrites,
&DeferredWrite.DeferredWriteLinks,
&CcDeferredWriteSpinLock );
} else {
(VOID)ExInterlockedInsertTailList( &CcDeferredWrites,
&DeferredWrite.DeferredWriteLinks,
&CcDeferredWriteSpinLock );
}
while (TRUE) {
//
// Now since we really didn't synchronize anything but the insertion,
// we call the post routine to make sure that in some wierd case we
// do not leave anyone hanging with no dirty bytes for the Lazy Writer.
//
CcPostDeferredWrites();
//
// Finally wait until the event is signalled and we can write
// and return to tell the guy he can write.
//
if (KeWaitForSingleObject( &Event,
Executive,
KernelMode,
FALSE,
&CcIdleDelay ) == STATUS_SUCCESS) {
return TRUE;
}
}
} else {
return FALSE;
}
}
VOID
CcDeferWrite (
IN PFILE_OBJECT FileObject,
IN PCC_POST_DEFERRED_WRITE PostRoutine,
IN PVOID Context1,
IN PVOID Context2,
IN ULONG BytesToWrite,
IN BOOLEAN Retrying
)
/*++
Routine Description:
This routine may be called to have the Cache Manager defer posting
of a write until the Lazy Writer makes some progress writing, or
there are more available pages. A file system would normally call
this routine after receiving FALSE from CcCanIWrite, and preparing
the request to be posted.
Arguments:
FileObject - for the file to be written
PostRoutine - Address of the PostRoutine that the Cache Manager can
call to post the request when conditions are right. Note
that it is possible that this routine will be called
immediately from this routine.
Context1 - First context parameter for the post routine.
Context2 - Secont parameter for the post routine.
BytesToWrite - Number of bytes that the request is trying to write
to the cache.
Retrying - Supplied as FALSE if the request is being posted for the
first time, TRUE otherwise.
Return Value:
None
--*/
{
PDEFERRED_WRITE DeferredWrite;
//
// Attempt to allocate a deferred write block, and if we do not get
// one, just post it immediately rather than gobbling up must succeed
// pool.
//
DeferredWrite = ExAllocatePool( NonPagedPool, sizeof(DEFERRED_WRITE) );
if (DeferredWrite == NULL) {
(*PostRoutine)( Context1, Context2 );
return;
}
//
// Fill in the block.
//
DeferredWrite->NodeTypeCode = CACHE_NTC_DEFERRED_WRITE;
DeferredWrite->NodeByteSize = sizeof(DEFERRED_WRITE);
DeferredWrite->FileObject = FileObject;
DeferredWrite->BytesToWrite = BytesToWrite;
DeferredWrite->Event = NULL;
DeferredWrite->PostRoutine = PostRoutine;
DeferredWrite->Context1 = Context1;
DeferredWrite->Context2 = Context2;
DeferredWrite->LimitModifiedPages = BooleanFlagOn(((PFSRTL_COMMON_FCB_HEADER)(FileObject->FsContext))->Flags,
FSRTL_FLAG_LIMIT_MODIFIED_PAGES);
//
// Now insert at the appropriate end of the list
//
if (Retrying) {
(VOID)ExInterlockedInsertHeadList( &CcDeferredWrites,
&DeferredWrite->DeferredWriteLinks,
&CcDeferredWriteSpinLock );
} else {
(VOID)ExInterlockedInsertTailList( &CcDeferredWrites,
&DeferredWrite->DeferredWriteLinks,
&CcDeferredWriteSpinLock );
}
//
// Now since we really didn't synchronize anything but the insertion,
// we call the post routine to make sure that in some wierd case we
// do not leave anyone hanging with no dirty bytes for the Lazy Writer.
//
CcPostDeferredWrites();
}
VOID
CcPostDeferredWrites (
)
/*++
Routine Description:
This routine may be called to see if any deferred writes should be posted
now, and to post them. It should be called any time the status of the
queue may have changed, such as when a new entry has been added, or the
Lazy Writer has finished writing out buffers and set them clean.
Arguments:
None
Return Value:
None
--*/
{
PDEFERRED_WRITE DeferredWrite;
ULONG TotalBytesLetLoose = 0;
KIRQL OldIrql;
do {
//
// Initially clear the deferred write structure pointer
// and syncrhronize.
//
DeferredWrite = NULL;
ExAcquireSpinLock( &CcDeferredWriteSpinLock, &OldIrql );
//
// If the list is empty we are done.
//
if (!IsListEmpty(&CcDeferredWrites)) {
PLIST_ENTRY Entry;
Entry = CcDeferredWrites.Flink;
while (Entry != &CcDeferredWrites) {
DeferredWrite = CONTAINING_RECORD( Entry,
DEFERRED_WRITE,
DeferredWriteLinks );
//
// Check for a paranoid case here that TotalBytesLetLoose
// wraps. We stop processing the list at this time.
//
TotalBytesLetLoose += DeferredWrite->BytesToWrite;
if (TotalBytesLetLoose < DeferredWrite->BytesToWrite) {
DeferredWrite = NULL;
break;
}
//
// If it is now ok to post this write, remove him from
// the list.
//
if (CcCanIWrite( DeferredWrite->FileObject,
TotalBytesLetLoose,
FALSE,
MAXUCHAR - 1 )) {
RemoveEntryList( &DeferredWrite->DeferredWriteLinks );
break;
//
// Otherwise, it is time to stop processing the list, so
// we clear the pointer again unless we throttled this item
// because of a private dirty page limit.
//
} else {
//
// If this was a private throttle, skip over it and
// remove its byte count from the running total.
//
if (DeferredWrite->LimitModifiedPages) {
Entry = Entry->Flink;
TotalBytesLetLoose -= DeferredWrite->BytesToWrite;
DeferredWrite = NULL;
continue;
} else {
DeferredWrite = NULL;
break;
}
}
}
}
ExReleaseSpinLock( &CcDeferredWriteSpinLock, OldIrql );
//
// If we got something, set the event or call the post routine
// and deallocate the structure.
//
if (DeferredWrite != NULL) {
if (DeferredWrite->Event != NULL) {
KeSetEvent( DeferredWrite->Event, 0, FALSE );
} else {
(*DeferredWrite->PostRoutine)( DeferredWrite->Context1,
DeferredWrite->Context2 );
ExFreePool( DeferredWrite );
}
}
//
// Loop until we find no more work to do.
//
} while (DeferredWrite != NULL);
}
|