summaryrefslogtreecommitdiffstats
path: root/private/ntos/fsrtl/filelock.c
blob: 9fc7dc9966073468c7e0360179b7848cc175d8d6 (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
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
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
/*++

Copyright (c) 1989  Microsoft Corporation

Module Name:

    FileLock.c

Abstract:

    The file lock package provides a set of routines that allow the
    caller to handle byte range file lock requests.  A variable of
    type FILE_LOCK is needed for every file with byte range locking.
    The package provides routines to set and clear locks, and to
    test for read or write access to a file with byte range locks.

    The main idea of the package is to have the file system initialize
    a FILE_LOCK variable for every data file as its opened, and then
    to simply call a file lock processing routine to handle all IRP's
    with a major function code of LOCK_CONTROL.  The package is responsible
    for keeping track of locks and for completing the LOCK_CONTROL IRPS.
    When processing a read or write request the file system can then call
    two query routines to check for access.

    Most of the code for processing IRPS and checking for access use
    paged pool and can encounter a page fault, therefore the check routines
    cannot be called at DPC level.  To help servers that do call the file
    system to do read/write operations at DPC level there is a additional
    routine that simply checks for the existence of a lock on a file and
    can be run at DPC level.

    Concurrent access to the FILE_LOCK variable must be controlled by the
    caller.

    The functions provided in this package are as follows:

      o  FsRtlInitializeFileLock - Initialize a new FILE_LOCK structure.

      o  FsRtlUninitializeFileLock - Uninitialize an existing FILE_LOCK
         structure.

      o  FsRtlProcessFileLock - Process an IRP whose major function code
         is LOCK_CONTROL.

      o  FsRtlCheckLockForReadAccess - Check for read access to a range
         of bytes in a file given an IRP.

      o  FsRtlCheckLockForWriteAccess - Check for write access to a range
         of bytes in a file given an IRP.

      o  FsRtlAreThereCurrentFileLocks - Check if there are any locks
         currently assigned to a file.

      o  FsRtlGetNextFileLock - This procedure enumerates the current locks
         of a file lock variable.

      o  FsRtlFastCheckLockForRead - Check for read access to a range of
         bytes in a file given separate parameters.

      o  FsRtlFastCheckLockForWrite - Check for write access to a range of
         bytes in a file given separate parameters.

      o  FsRtlFastLock - A fast non-Irp based way to get a lock

      o  FsRtlFastUnlockSingle - A fast non-Irp based way to release a single
         lock

      o  FsRtlFastUnlockAll - A fast non-Irp based way to release all locks
         held by a file object.

      o  FsRtlFastUnlockAllByKey - A fast non-Irp based way to release all
         locks held by a file object that match a key.


Authors:

    Gary Kimura     [GaryKi]    24-Apr-1990
    Dan Lovinger    [DanLo]     22-Sep-1995

Revision History:

--*/

#include "FsRtlP.h"

#define FsRtlAllocateSharedLock( C )   {                            \
    PKPRCB  Prcb = KeGetCurrentPrcb();                              \
    *(C) = (PSH_LOCK) PopEntryList(&Prcb->FsRtlFreeSharedLockList); \
    if (*(C) == NULL) {                                             \
        *(C) = FsRtlAllocatePool( NonPagedPool, sizeof(SH_LOCK) );  \
    }                                                               \
}

#define FsRtlAllocateExclusiveLock( C )   {                            \
    PKPRCB  Prcb = KeGetCurrentPrcb();                                 \
    *(C) = (PEX_LOCK) PopEntryList(&Prcb->FsRtlFreeExclusiveLockList); \
    if (*(C) == NULL) {                                                \
        *(C) = FsRtlAllocatePool( NonPagedPool, sizeof(EX_LOCK) );     \
    }                                                                  \
}

#define FsRtlAllocateLockTreeNode( C )   {                                  \
    PKPRCB  Prcb = KeGetCurrentPrcb();                                      \
    *(C) = (PLOCKTREE_NODE) PopEntryList(&Prcb->FsRtlFreeLockTreeNodeList); \
    if (*(C) == NULL) {                                                     \
        *(C) = FsRtlAllocatePool( NonPagedPool, sizeof(LOCKTREE_NODE) );    \
    }                                                                       \
}

#define FsRtlAllocateWaitingLock( C )  {                                    \
    PKPRCB  Prcb = KeGetCurrentPrcb();                                      \
    *(C) = (PWAITING_LOCK) PopEntryList(&Prcb->FsRtlFreeWaitingLockList);   \
    if (*(C) == NULL) {                                                     \
        *(C) = FsRtlAllocatePool( NonPagedPool, sizeof(WAITING_LOCK) );     \
    }                                                                       \
}

#define FsRtlFreeSharedLock( C ) {                                  \
    PKPRCB  Prcb = KeGetCurrentPrcb();                              \
    PushEntryList(&Prcb->FsRtlFreeSharedLockList, &(C)->Link);      \
}

#define FsRtlFreeExclusiveLock( C ) {                               \
    PKPRCB  Prcb = KeGetCurrentPrcb();                              \
    PushEntryList(&Prcb->FsRtlFreeExclusiveLockList, &(C)->Link);   \
}

#define FsRtlFreeLockTreeNode( C ) {                                \
    PKPRCB  Prcb = KeGetCurrentPrcb();                              \
    PushEntryList(&Prcb->FsRtlFreeLockTreeNodeList, &(C)->Locks);   \
}

#define FsRtlFreeWaitingLock( C ) {                             \
    PKPRCB  Prcb = KeGetCurrentPrcb();                          \
    PushEntryList(&Prcb->FsRtlFreeWaitingLockList, &(C)->Link); \
}

#define FsRtlAcquireLockQueue(a,b)                  \
        ExAcquireSpinLock(&(a)->QueueSpinLock, b);

#define FsRtlReacquireLockQueue(a,b,c)              \
        ExAcquireSpinLock(&(b)->QueueSpinLock, c);

#define FsRtlReleaseLockQueue(a,b)                  \
        ExReleaseSpinLock(&(a)->QueueSpinLock, b);

#define FsRtlCompleteLockIrp(_FileLock, _Context, _Irp, _Status, _NewStatus, _FileObject) \
    if (_FileLock->CompleteLockIrpRoutine != NULL) {                     \
        if ((_FileObject) != NULL) {                                     \
            ((PFILE_OBJECT)(_FileObject))->LastLock = NULL;              \
        }                                                                \
        _Irp->IoStatus.Status = _Status;                                 \
        *_NewStatus = _FileLock->CompleteLockIrpRoutine(_Context, _Irp); \
    } else {                                                             \
        FsRtlCompleteRequest( _Irp, _Status );                           \
        *_NewStatus = _Status;                                           \
    }

//
//  Define USERTEST to get a version which compiles into a usermode test rig
//

#ifdef USERTEST
#include <stdio.h>
#include <stdlib.h>
#undef FsRtlAllocateSharedLock
#undef FsRtlAllocateExclusiveLock
#undef FsRtlAllocateLockTreeNode
#undef FsRtlAllocateWaitingLock
#undef FsRtlFreeSharedLock
#undef FsRtlFreeExclusiveLock
#undef FsRtlFreeLockTreeNode
#undef FsRtlFreeWaitingLock
#undef FsRtlAcquireLockQueue
#undef FsRtlReacquireLockQueue
#undef FsRtlReleaseLockQueue
#undef FsRtlCompleteLockIrp
#undef IoCompleteRequest

#define FsRtlAllocateSharedLock( C )        *(C) = (PSH_LOCK)malloc(sizeof(SH_LOCK))
#define FsRtlAllocateExclusiveLock( C )     *(C) = (PEX_LOCK)malloc(sizeof(EX_LOCK))
#define FsRtlAllocateLockTreeNode( C )      *(C) = (PLOCKTREE_NODE)malloc(sizeof(LOCKTREE_NODE))
#define FsRtlAllocateWaitingLock( C )       *(C) = (PWAITING_LOCK)malloc(sizeof(WAITING_LOCK))
#define FsRtlFreeSharedLock( C )            free(C)
#define FsRtlFreeExclusiveLock( C )         free(C)
#define FsRtlFreeLockTreeNode( C )          free(C)
#define FsRtlFreeWaitingLock( C )           free(C)
#define FsRtlAcquireLockQueue(a,b)          (*(b) = '\0')
#define FsRtlReacquireLockQueue(a,b,c)      (*(c) = '\0')
#define FsRtlReleaseLockQueue(a,b)
#define FsRtlCompleteLockIrp(_FileLock, _Context, _Irp, _Status, _NewStatus, _FileObject)   \
    {                                                                                       \
        DbgBreakPoint();                                                                    \
        *_NewStatus = STATUS_SUCCESS;                                                       \
    }

#define ExReleaseFastMutex(M)
#define ExAcquireFastMutex(M)
#define KeInitializeSpinLock(L)
#define KfRaiseIrql(L)                      ('\0')
#define KfLowerIrql(I)
#define IoAcquireCancelSpinLock(I)
#define IoReleaseCancelSpinLock(I)
#define IoCompleteRequest(I, S)
#endif

FAST_MUTEX FsRtlCreateLockInfo;

//
//  Local debug trace level
//

#define Dbg                 (0x20000000)

#define FREE_LOCK_SIZE      16


/*++

    Some of the decisions made regarding the internal datastructres may not be clear,
    so I should discuss the evolution of this design.

    The original file lock implementation was a single linked list, extended in the MP
    case to a set of linked lists which each held locks in page-aligned segments of the
    file. If locks spilled over these page-aligned segments the code fell back to the
    UP single linked list. There are clearly peformance implications with substantial
    usage of file locks, since these are mandatory locks.

    This implementation goes for O(lgn) search performance by using splay trees. In order to
    apply simple trees to this problem no node of the tree can overlap, so since shared
    locks can in fact overlap something must be done. The solution used here is to have
    a meta-structure contain all locks which do overlap and have the tree operations
    split and merge these nodes of (potentially) multiple locks. This is the LOCKTREE_NODE.
    It should be noted that the worst case add/delete lock times are still linear.

    Exclusive locks pose a problem because of an asymmetry in the semantics of applying
    locks to a file. If a process applies a shared lock to a section of a file, no application
    of an exclusive lock to bytes in that section can succeed. However, if a process
    applies an exclusive lock, that same process can get a shared lock as well. This
    behavior conflicts with the mergeable node since by applying locks in a given order
    we can get a node to have many shared locks and "rogue" exclusive locks which are
    hidden except to a linear search, which is what we're designing out. So exclusive locks
    must be seperated from the shared locks. This is the reason we have two lock trees.

    Since we have two lock trees, the worst case search is now O(lgm + lgn) for m exlcusive
    and n shared. Also, since no exclusive locks can ever overlap each other it is now
    unreasonable to have them use LOCKTREE_NODES - this would impose a memory penalty on code
    which was weighted toward exclusive locks. This means that the exclusive locks should
    be wired into the splay tree directly. So we need an RTL_SPLAY_LINKS, but this is 64 bits
    bigger than the SINGLE_LIST_ENTRY which shared locks need (to be threaded off of a
    LOCKTREE_NODE), which dictates seperate shared and exclusive lock structures to avoid
    penalizing code which was weighted toward shared locks by having that wasted 64 bits per
    lock. Hence EX_LOCK and SH_LOCK.

    Zero length locks are a bizzare creation, and there is some errata relating to them. It
    used to be the case that zero length locks would be granted without exception. This is
    flat out against the spec, and has been dropped. They are now subject to failure if they
    occupy a point interior to a lock of a type that can cause an access failure. A particular
    case that was previously allowed was a zero length exclusive lock interior to another
    exclusive lock.

    Zero length locks cannot conflict with zero length locks. This is the subject of some
    special code throughout the module. Note especially that zero length exclusive locks can
    overlap. Zero length locks also cannot conflict at the starting byte and ending byte of a
    range - they are points on the line.

--*/

typedef struct {
    //
    // List of locks under this node
    //

    SINGLE_LIST_ENTRY Locks;

    //
    // Maximum byte offset affected by locks under Locks
    // Note: minimum offset is the starting offset of the
    // first lock at this node.
    //

    ULONGLONG Extent;

    //
    // Splay tree links to parent, lock groups strictly less than
    // and lock groups strictly greater than locks under Locks
    //

    RTL_SPLAY_LINKS Links;

    //
    // Last lock in the list (useful for node collapse under insert)
    //

    SINGLE_LIST_ENTRY Tail;

} LOCKTREE_NODE, *PLOCKTREE_NODE;

//
//  Define the threading wrappers for lock information
//

//
//  Each shared lock record corresponds to a current granted lock and is
//  maintained in a queue off of a LOCKTREE_NODE's Locks list.  The list
//  of current locks is ordered according to the starting byte of the lock.
//

typedef struct _SH_LOCK {

    //
    //  The link structures for the list of shared locks.
    //  (must be first element - see FsRtlPrivateLimitFreeLockList)
    //

    SINGLE_LIST_ENTRY   Link;

    //
    //  The actual locked range
    //

    FILE_LOCK_INFO LockInfo;

} SH_LOCK;
typedef SH_LOCK *PSH_LOCK;

//
//  Each exclusive lock record corresponds to a current granted lock and is
//  threaded into the exclusive lock tree.
//

typedef struct _EX_LOCK {

    //
    //  The link structures for the list of current locks.
    //  (must be first element - see FsRtlPrivateLimitFreeLockList)
    //

    union {

        //
        //  Simple list reference for the freelist
        //

        SINGLE_LIST_ENTRY   Link;

        //
        //  The actual splay links when inserted
        //

        RTL_SPLAY_LINKS     Links;
    };

    //
    //  The actual locked range
    //

    FILE_LOCK_INFO LockInfo;

} EX_LOCK;
typedef EX_LOCK *PEX_LOCK;

//
//  Each Waiting lock record corresponds to a IRP that is waiting for a
//  lock to be granted and is maintained in a queue off of the FILE_LOCK's
//  WaitingLockQueue list.
//

typedef struct _WAITING_LOCK {

    //
    //  The link structures for the list of waiting locks
    //  (must be first element - see FsRtlPrivateLimitFreeLockList)
    //

    SINGLE_LIST_ENTRY   Link;

    //
    //  The context field to use when completing the irp via the alternate
    //  routine
    //

    PVOID Context;

    //
    //  A pointer to the IRP that is waiting for a lock
    //

    PIRP Irp;

} WAITING_LOCK;
typedef WAITING_LOCK *PWAITING_LOCK;


//
//  Each lock or waiting onto some lock queue.
//

typedef struct _LOCK_QUEUE {

    //
    // SpinLock to guard queue access
    //

    KSPIN_LOCK  QueueSpinLock;

    //
    //  The items contain locktrees of the current granted
    //  locks and a list of the waiting locks
    //

    PRTL_SPLAY_LINKS SharedLockTree;
    PRTL_SPLAY_LINKS ExclusiveLockTree;
    SINGLE_LIST_ENTRY WaitingLocks;
    SINGLE_LIST_ENTRY WaitingLocksTail;

} LOCK_QUEUE, *PLOCK_QUEUE;


//
//  Any file_lock which has had a lock applied gets non-paged pool
//  lock_info structure which tracks the current locks applied to
//  the file
//
typedef struct _LOCK_INFO {

    //
    //  LowestLockOffset retains the offset of the lowest existing
    //  lock.  This facilitates a quick check to see if a read or
    //  write can proceed without locking the lock database.  This is
    //  helpful for applications that use mirrored locks -- all locks
    //  are higher than file data.
    //
    //  If the lowest lock has an offset > 0xffffffff, LowestLockOffset
    //  is set to 0xffffffff.
    //

    ULONG LowestLockOffset;

    //
    //  The optional procedure to call to complete a request
    //

    PCOMPLETE_LOCK_IRP_ROUTINE CompleteLockIrpRoutine;

    //
    //  The optional procedure to call when unlocking a byte range
    //

    PUNLOCK_ROUTINE UnlockRoutine;

    //
    // The locked ranges
    //

    LOCK_QUEUE  LockQueue;

} LOCK_INFO, *PLOCK_INFO;

//
//  The following routines are private to this module
//

VOID
FsRtlSplitLocks (
    IN PLOCKTREE_NODE ParentNode,
    IN PSINGLE_LIST_ENTRY *pStartLink,
    IN PLARGE_INTEGER LastShadowedByte,
    IN PLARGE_INTEGER GlueOffset
    );

PRTL_SPLAY_LINKS
FsRtlFindFirstOverlappingSharedNode (
    IN PRTL_SPLAY_LINKS        Tree,
    IN PLARGE_INTEGER          StartingByte,
    IN PLARGE_INTEGER          EndingByte,
    IN OUT PRTL_SPLAY_LINKS    *LastEdgeNode,
    IN OUT PBOOLEAN            GreaterThan
    );

PRTL_SPLAY_LINKS
FsRtlFindFirstOverlappingExclusiveNode (
    IN PRTL_SPLAY_LINKS        Tree,
    IN PLARGE_INTEGER          StartingByte,
    IN PLARGE_INTEGER          EndingByte,
    IN OUT PRTL_SPLAY_LINKS    *LastEdgeNode,
    IN OUT PBOOLEAN            GreaterThan
    );

VOID
FsRtlPrivateInsertLock (
    IN PLOCK_INFO LockInfo,
    IN PFILE_OBJECT FileObject,
    IN PFILE_LOCK_INFO FileLockInfo
    );

VOID
FsRtlPrivateInsertSharedLock (
    IN PLOCK_QUEUE LockQueue,
    IN PSH_LOCK NewLock
    );

VOID
FsRtlPrivateInsertExclusiveLock (
    IN PLOCK_QUEUE LockQueue,
    IN PEX_LOCK NewLock
    );

VOID
FsRtlPrivateCheckWaitingLocks (
    IN PLOCK_INFO   LockInfo,
    IN PLOCK_QUEUE  LockQueue,
    IN KIRQL        OldIrql
    );

VOID
FsRtlPrivateCancelFileLockIrp (
    IN PDEVICE_OBJECT DeviceObject,
    IN PIRP Irp
    );

BOOLEAN
FsRtlPrivateCheckForExclusiveLockAccess (
    IN PLOCK_QUEUE LockInfo,
    IN PFILE_LOCK_INFO FileLockInfo
    );

BOOLEAN
FsRtlPrivateCheckForSharedLockAccess (
    IN PLOCK_QUEUE LockInfo,
    IN PFILE_LOCK_INFO FileLockInfo
    );

NTSTATUS
FsRtlPrivateFastUnlockAll (
    IN PFILE_LOCK FileLock,
    IN PFILE_OBJECT FileObject,
    IN PEPROCESS ProcessId,
    IN ULONG Key,
    IN BOOLEAN MatchKey,
    IN PVOID Context OPTIONAL
    );

BOOLEAN
FsRtlPrivateInitializeFileLock (
    IN PFILE_LOCK   FileLock,
    IN BOOLEAN ViaFastCall
    );

VOID
FsRtlPrivateRemoveLock (
    IN PLOCK_INFO LockInfo,
    IN PFILE_LOCK_INFO,
    IN BOOLEAN CheckForWaiters
    );

VOID
FsRtlPrivateLimitFreeLockList (
    IN PSINGLE_LIST_ENTRY   Link
    );

BOOLEAN
FsRtlCheckNoSharedConflict (
   IN PLOCK_QUEUE LockQueue,
   IN PLARGE_INTEGER Starting,
   IN PLARGE_INTEGER Ending
   );

BOOLEAN
FsRtlCheckNoExclusiveConflict (
    IN PLOCK_QUEUE LockQueue,
    IN PLARGE_INTEGER Starting,
    IN PLARGE_INTEGER Ending,
    IN ULONG Key,
    IN PFILE_OBJECT FileObject,
    IN PVOID ProcessId
    );

VOID
FsRtlPrivateResetLowestLockOffset (
    PLOCK_INFO LockInfo
    );

NTSTATUS
FsRtlFastUnlockSingleShared (
    IN PLOCK_INFO LockInfo,
    IN PFILE_OBJECT FileObject,
    IN LARGE_INTEGER UNALIGNED *FileOffset,
    IN PLARGE_INTEGER Length,
    IN PEPROCESS ProcessId,
    IN ULONG Key,
    IN PVOID Context OPTIONAL,
    IN BOOLEAN IgnoreUnlockRoutine,
    IN BOOLEAN CheckForWaiters
    );

NTSTATUS
FsRtlFastUnlockSingleExclusive (
    IN PLOCK_INFO LockInfo,
    IN PFILE_OBJECT FileObject,
    IN LARGE_INTEGER UNALIGNED *FileOffset,
    IN PLARGE_INTEGER Length,
    IN PEPROCESS ProcessId,
    IN ULONG Key,
    IN PVOID Context OPTIONAL,
    IN BOOLEAN IgnoreUnlockRoutine,
    IN BOOLEAN CheckForWaiters
    );


VOID
FsRtlInitProcessorLockQueue (
    VOID
    )
/*++

Routine Description:

    Initializes and pre-allocates some lock structures for this
    processor.

Arguments:

    None

Return Value:

    None.

--*/
{
#ifndef USERTEST
    PKPRCB          Prcb;
#if !defined(NT_UP)
    ULONG           Count;
    PSH_LOCK        ShLock;
    PEX_LOCK        ExLock;
    PLOCKTREE_NODE  Node;
    PWAITING_LOCK   WaitingLock;
#endif

    Prcb = KeGetCurrentPrcb();

    Prcb->FsRtlFreeSharedLockList.Next = NULL;
    Prcb->FsRtlFreeExclusiveLockList.Next = NULL;
    Prcb->FsRtlFreeLockTreeNodeList.Next = NULL;
    Prcb->FsRtlFreeWaitingLockList.Next = NULL;

#if !defined(NT_UP)
    for (Count = FREE_LOCK_SIZE/2; Count; Count--) {
        ShLock = FsRtlAllocatePool( NonPagedPool, sizeof(SH_LOCK) );
        PushEntryList( &Prcb->FsRtlFreeSharedLockList, &ShLock->Link );

        ExLock = FsRtlAllocatePool( NonPagedPool, sizeof(EX_LOCK) );
        PushEntryList( &Prcb->FsRtlFreeExclusiveLockList, &ExLock->Link );

        WaitingLock = FsRtlAllocatePool( NonPagedPool, sizeof(WAITING_LOCK) );
        PushEntryList( &Prcb->FsRtlFreeWaitingLockList, &WaitingLock->Link );

        //
        // The Locks field is overloaded for the freelist (still first in the
        // structure as per other requirements)
        //

        Node = FsRtlAllocatePool( NonPagedPool, sizeof(LOCKTREE_NODE) );
        PushEntryList( &Prcb->FsRtlFreeLockTreeNodeList, &Node->Locks );
    }
#endif
#endif
}


VOID
FsRtlInitializeFileLock (
    IN PFILE_LOCK FileLock,
    IN PCOMPLETE_LOCK_IRP_ROUTINE CompleteLockIrpRoutine OPTIONAL,
    IN PUNLOCK_ROUTINE UnlockRoutine OPTIONAL
    )

/*++

Routine Description:

    This routine initializes a new FILE_LOCK structure.  The caller must
    supply the memory for the structure.  This call must precede all other
    calls that utilize the FILE_LOCK variable.

Arguments:

    FileLock - Supplies a pointer to the FILE_LOCK structure to
        initialize.

    CompleteLockIrpRoutine - Optionally supplies an alternate routine to
        call for completing IRPs.  FsRtlProcessFileLock by default will
        call IoCompleteRequest to finish up an IRP; however if the caller
        want to process the completion itself then it needs to specify
        a completion routine here.  This routine will then be called in
        place of IoCompleteRequest.

    UnlockRoutine - Optionally supplies a routine to call when removing
        a lock.

Return Value:

    None.

--*/

{
    DebugTrace(+1, Dbg, "FsRtlInitializeFileLock, FileLock = %08lx\n", FileLock);

    //
    // Clear non-paged pool pointer
    //

    FileLock->LockInformation = NULL;
    FileLock->CompleteLockIrpRoutine = CompleteLockIrpRoutine;
    FileLock->UnlockRoutine = UnlockRoutine;

    FileLock->FastIoIsQuestionable = FALSE;

    //
    //  and return to our caller
    //

    DebugTrace(-1, Dbg, "FsRtlInitializeFileLock -> VOID\n", 0 );

    return;
}


BOOLEAN
FsRtlPrivateInitializeFileLock (
    IN PFILE_LOCK   FileLock,
    IN BOOLEAN ViaFastCall
    )
/*++

Routine Description:

    This routine initializes a new LOCK_INFO structure in non-paged
    pool for the FILE_LOCK.  This routines only occurs once for a given
    FILE_LOCK and it only occurs if any locks are applied to that file.

Arguments:

    FileLock - Supplies a pointer to the FILE_LOCK structure to
        initialize.

    ViaFastCall - Indicates if we are being invoked via a fast call or
        via the slow irp based method.

Return Value:

    TRUE - If LockInfo structure was allocated and initialized

--*/
{
    PLOCK_INFO  LockInfo;
    BOOLEAN     Results = FALSE;

    ExAcquireFastMutex(&FsRtlCreateLockInfo);

    try {
        if (FileLock->LockInformation != NULL) {

            //
            // Structure is already allocated, just return
            //

            try_return( Results = TRUE );
        }

        //
        //  Allocate pool for lock structures.  If we fail then we will either return false or
        //  raise based on if we know the caller has an try-except to handle a raise.
        //

        if ((LockInfo = ExAllocatePoolWithTag( NonPagedPool, sizeof(LOCK_INFO), 'trSF')) == NULL) {

            if (ViaFastCall) {

                try_return( Results = FALSE );

            } else {

                ExRaiseStatus( STATUS_INSUFFICIENT_RESOURCES );
            }
        }

        //
        //  Allocate and initialize the waiting lock queue
        //  spinlock, and initialize the queues
        //

        LockInfo->LowestLockOffset = 0xffffffff;

        KeInitializeSpinLock (&LockInfo->LockQueue.QueueSpinLock);
        LockInfo->LockQueue.SharedLockTree = NULL;
        LockInfo->LockQueue.ExclusiveLockTree = NULL;
        LockInfo->LockQueue.WaitingLocks.Next = NULL;
        LockInfo->LockQueue.WaitingLocksTail.Next = NULL;

        //
        // Copy Irp & Unlock routines from pagable FileLock structure
        // to non-pagable LockInfo structure
        //

        LockInfo->CompleteLockIrpRoutine = FileLock->CompleteLockIrpRoutine;
        LockInfo->UnlockRoutine = FileLock->UnlockRoutine;

        //
        // Clear continuation info for enum routine
        //

        FileLock->LastReturnedLockInfo.FileObject = NULL;
        FileLock->LastReturnedLock = NULL;

        //
        // Link LockInfo into FileLock
        //

        FileLock->LockInformation = (PVOID) LockInfo;
        Results = TRUE;

    try_exit: NOTHING;
    } finally {

        ExReleaseFastMutex(&FsRtlCreateLockInfo);
    }

    return Results;
}


VOID
FsRtlUninitializeFileLock (
    IN PFILE_LOCK FileLock
    )

/*++

Routine Description:

    This routine uninitializes a FILE_LOCK structure.  After calling this
    routine the File lock must be reinitialized before being used again.

    This routine will free all files locks and completes any outstanding
    lock requests as a result of cleaning itself up.

Arguments:

    FileLock - Supplies a pointer to the FILE_LOCK struture being
        decommissioned.

Return Value:

    None.

--*/

{
    PLOCK_INFO          LockInfo;
    PSH_LOCK            ShLock;
    PEX_LOCK            ExLock;
    PSINGLE_LIST_ENTRY  Link;
    PWAITING_LOCK       WaitingLock;
    PLOCKTREE_NODE      LockTreeNode;
    PIRP                Irp;
    NTSTATUS            NewStatus;
    KIRQL               OldIrql;
    PKPRCB              Prcb;

    DebugTrace(+1, Dbg, "FsRtlUninitializeFileLock, FileLock = %08lx\n", FileLock);


    if ((LockInfo = (PLOCK_INFO) FileLock->LockInformation) == NULL) {
        return ;
    }

    //
    //  Lock the queue
    //

    FsRtlAcquireLockQueue(&LockInfo->LockQueue, &OldIrql);

    //
    //  Free lock trees
    //

    while (LockInfo->LockQueue.SharedLockTree != NULL) {

        LockTreeNode = CONTAINING_RECORD(LockInfo->LockQueue.SharedLockTree, LOCKTREE_NODE, Links);

        //
        //  Remove all locks associated with the root node
        //

        while (LockTreeNode->Locks.Next != NULL) {
            Link = PopEntryList (&LockTreeNode->Locks);
            ShLock = CONTAINING_RECORD( Link, SH_LOCK, Link );
    
            FsRtlFreeSharedLock(ShLock);
        }

        //
        //  Slice off the root node of the tree
        //

        RtlDeleteNoSplay(&LockTreeNode->Links, &LockInfo->LockQueue.SharedLockTree);

        FsRtlFreeLockTreeNode(LockTreeNode);
    }

    while (LockInfo->LockQueue.ExclusiveLockTree != NULL) {

        ExLock = CONTAINING_RECORD(LockInfo->LockQueue.ExclusiveLockTree, EX_LOCK, Links);

        RtlDeleteNoSplay(&ExLock->Links, &LockInfo->LockQueue.ExclusiveLockTree);

        FsRtlFreeExclusiveLock(ExLock);
    }

    //
    //  Free WaitingLockQueue
    //

    while (LockInfo->LockQueue.WaitingLocks.Next != NULL) {

        Link = PopEntryList( &LockInfo->LockQueue.WaitingLocks );
        WaitingLock = CONTAINING_RECORD( Link, WAITING_LOCK, Link );

        Irp = WaitingLock->Irp;

        //
        //  To complete an irp in the waiting queue we need to
        //  void the cancel routine (protected by a spinlock) before
        //  we can complete the irp
        //

        FsRtlReleaseLockQueue (&LockInfo->LockQueue, OldIrql);

        IoAcquireCancelSpinLock( &Irp->CancelIrql );
        IoSetCancelRoutine( Irp, NULL );
        IoReleaseCancelSpinLock( Irp->CancelIrql );

        Irp->IoStatus.Information = 0;

        FsRtlCompleteLockIrp(
             LockInfo,
             WaitingLock->Context,
             Irp,
             STATUS_RANGE_NOT_LOCKED,
             &NewStatus,
             NULL );

        FsRtlAcquireLockQueue(&LockInfo->LockQueue, &OldIrql);
        FsRtlFreeWaitingLock( WaitingLock );
    }

#ifndef USERTEST
    //
    // If lots of locks were freed verify, go check non-paged pool
    // usage on this processor
    //

    Prcb = KeGetCurrentPrcb();
    FsRtlPrivateLimitFreeLockList (&Prcb->FsRtlFreeSharedLockList);
    FsRtlPrivateLimitFreeLockList (&Prcb->FsRtlFreeExclusiveLockList);
    FsRtlPrivateLimitFreeLockList (&Prcb->FsRtlFreeWaitingLockList);
    FsRtlPrivateLimitFreeLockList (&Prcb->FsRtlFreeLockTreeNodeList);
#endif

    //
    // Free pool used to track the lock info on this file
    //

    FsRtlReleaseLockQueue (&LockInfo->LockQueue, OldIrql);
    ExFreePool (LockInfo);

    //
    // Unlink LockInfo from FileLock
    //

    FileLock->LockInformation = NULL;

    //
    //  And return to our caller
    //

    DebugTrace(-1, Dbg, "FsRtlUninitializeFileLock -> VOID\n", 0 );
    return;
}


NTSTATUS
FsRtlProcessFileLock (
    IN PFILE_LOCK FileLock,
    IN PIRP Irp,
    IN PVOID Context OPTIONAL
    )

/*++

Routine Description:

    This routine processes a file lock IRP it does either a lock request,
    or an unlock request.  It also completes the IRP.  Once called the user
    (i.e., File System) has relinquished control of the input IRP.

    If pool is not available to store the information this routine will raise a
    status value indicating insufficient resources.

Arguments:

    FileLock - Supplies the File lock being modified/queried.

    Irp - Supplies the Irp being processed.

    Context - Optionally supplies a context to use when calling the user
        alternate IRP completion routine.

Return Value:

    NTSTATUS - The return status for the operation.

--*/

{
    PIO_STACK_LOCATION IrpSp;

    IO_STATUS_BLOCK Iosb;
    NTSTATUS        Status;
    LARGE_INTEGER   ByteOffset;

    DebugTrace(+1, Dbg, "FsRtlProcessFileLock, FileLock = %08lx\n", FileLock);

    Iosb.Information = 0;

    //
    //  Get a pointer to the current Irp stack location and assert that
    //  the major function code is for a lock operation
    //

    IrpSp = IoGetCurrentIrpStackLocation( Irp );

    ASSERT( IrpSp->MajorFunction == IRP_MJ_LOCK_CONTROL );

    //
    //  Now process the different minor lock operations
    //

    switch (IrpSp->MinorFunction) {

    case IRP_MN_LOCK:

        ByteOffset = IrpSp->Parameters.LockControl.ByteOffset;

        (VOID) FsRtlPrivateLock( FileLock,
                                 IrpSp->FileObject,
                                 &ByteOffset,
                                 IrpSp->Parameters.LockControl.Length,
                                 IoGetRequestorProcess(Irp),
                                 IrpSp->Parameters.LockControl.Key,
                                 BooleanFlagOn(IrpSp->Flags, SL_FAIL_IMMEDIATELY),
                                 BooleanFlagOn(IrpSp->Flags, SL_EXCLUSIVE_LOCK),
                                 &Iosb,
                                 Irp,
                                 Context,
                                 FALSE );

        break;

    case IRP_MN_UNLOCK_SINGLE:

        ByteOffset = IrpSp->Parameters.LockControl.ByteOffset;

        Iosb.Status = FsRtlFastUnlockSingle( FileLock,
                                             IrpSp->FileObject,
                                             &ByteOffset,
                                             IrpSp->Parameters.LockControl.Length,
                                             IoGetRequestorProcess(Irp),
                                             IrpSp->Parameters.LockControl.Key,
                                             Context,
                                             FALSE );

        FsRtlCompleteLockIrp( FileLock, Context, Irp, Iosb.Status, &Status, NULL );
        break;

    case IRP_MN_UNLOCK_ALL:

        Iosb.Status = FsRtlFastUnlockAll( FileLock,
                                          IrpSp->FileObject,
                                          IoGetRequestorProcess(Irp),
                                          Context );

        FsRtlCompleteLockIrp( FileLock, Context, Irp, Iosb.Status, &Status, NULL );
        break;

    case IRP_MN_UNLOCK_ALL_BY_KEY:

        Iosb.Status = FsRtlFastUnlockAllByKey( FileLock,
                                               IrpSp->FileObject,
                                               IoGetRequestorProcess(Irp),
                                               IrpSp->Parameters.LockControl.Key,
                                               Context );

        FsRtlCompleteLockIrp( FileLock, Context, Irp, Iosb.Status, &Status, NULL );
        break;

    default:

        //
        //  For all other minor function codes we say they're invalid and
        //  complete the request.  Note that the IRP has not been marked
        //  pending so this error will be returned directly to the caller.
        //

        DebugTrace(0, 1, "Invalid LockFile Minor Function Code %08lx\n", IrpSp->MinorFunction);


        FsRtlCompleteRequest( Irp, STATUS_INVALID_DEVICE_REQUEST );

        Iosb.Status = STATUS_INVALID_DEVICE_REQUEST;
        break;
    }

    //
    //  And return to our caller
    //

    DebugTrace(-1, Dbg, "FsRtlProcessFileLock -> %08lx\n", Iosb.Status);

    return Iosb.Status;
}


BOOLEAN
FsRtlCheckLockForReadAccess (
    IN PFILE_LOCK FileLock,
    IN PIRP Irp
    )

/*++

Routine Description:

    This routine checks to see if the caller has read access to the
    range indicated in the IRP due to file locks.  This call does not
    complete the Irp it only uses it to get the lock information and read
    information.  The IRP must be for a read operation.

Arguments:

    FileLock - Supplies the File Lock to check.

    Irp - Supplies the Irp being processed.

Return Value:

    BOOLEAN - TRUE if the indicated user/request has read access to the
        entire specified byte range, and FALSE otherwise

--*/

{
    BOOLEAN Result;

    PIO_STACK_LOCATION IrpSp;

    PLOCK_INFO     LockInfo;
    LARGE_INTEGER  StartingByte;
    LARGE_INTEGER  Length;
    ULONG          Key;
    PFILE_OBJECT   FileObject;
    PVOID          ProcessId;
    LARGE_INTEGER  BeyondLastByte;

    DebugTrace(+1, Dbg, "FsRtlCheckLockForReadAccess, FileLock = %08lx\n", FileLock);

    if ((LockInfo = (PLOCK_INFO) FileLock->LockInformation) == NULL) {
        DebugTrace(-1, Dbg, "FsRtlCheckLockForReadAccess (No current lock info) -> TRUE\n", 0);
        return TRUE;
    }

    //
    //  Do a really fast test to see if there are any exclusive locks to start with
    //

    if (LockInfo->LockQueue.ExclusiveLockTree == NULL) {
        DebugTrace(-1, Dbg, "FsRtlCheckLockForReadAccess (No current locks) -> TRUE\n", 0);
        return TRUE;
    }

    //
    //  Get the read offset and compare it to the lowest existing lock.
    //

    IrpSp = IoGetCurrentIrpStackLocation( Irp );

    StartingByte  = IrpSp->Parameters.Read.ByteOffset;
    (ULONGLONG)Length.QuadPart = (ULONGLONG)IrpSp->Parameters.Read.Length;

    (ULONGLONG)BeyondLastByte.QuadPart = (ULONGLONG)StartingByte.QuadPart + Length.LowPart;
    if ( (ULONGLONG)BeyondLastByte.QuadPart <= (ULONGLONG)LockInfo->LowestLockOffset ) {
        DebugTrace(-1, Dbg, "FsRtlCheckLockForReadAccess (Below lowest lock) -> TRUE\n", 0);
        return TRUE;
    }

    //
    //  Get remaining parameters.
    //

    Key           = IrpSp->Parameters.Read.Key;
    FileObject    = IrpSp->FileObject;
    ProcessId     = IoGetRequestorProcess( Irp );

    //
    //  Call our private work routine to do the real check
    //

    Result = FsRtlFastCheckLockForRead( FileLock,
                                        &StartingByte,
                                        &Length,
                                        Key,
                                        FileObject,
                                        ProcessId );

    //
    //  And return to our caller
    //

    DebugTrace(-1, Dbg, "FsRtlCheckLockForReadAccess -> %08lx\n", Result);

    return Result;
}


BOOLEAN
FsRtlCheckLockForWriteAccess (
    IN PFILE_LOCK FileLock,
    IN PIRP Irp
    )

/*++

Routine Description:

    This routine checks to see if the caller has write access to the
    indicated range due to file locks.  This call does not complete the
    Irp it only uses it to get the lock information and write information.
    The IRP must be for a write operation.

Arguments:

    FileLock - Supplies the File Lock to check.

    Irp - Supplies the Irp being processed.

Return Value:

    BOOLEAN - TRUE if the indicated user/request has write access to the
        entire specified byte range, and FALSE otherwise

--*/

{
    BOOLEAN Result;

    PIO_STACK_LOCATION IrpSp;

    PLOCK_INFO      LockInfo;
    LARGE_INTEGER   StartingByte;
    LARGE_INTEGER   Length;
    ULONG           Key;
    PFILE_OBJECT    FileObject;
    PVOID           ProcessId;
    LARGE_INTEGER   BeyondLastByte;

    DebugTrace(+1, Dbg, "FsRtlCheckLockForWriteAccess, FileLock = %08lx\n", FileLock);

    if ((LockInfo = (PLOCK_INFO) FileLock->LockInformation) == NULL) {
        DebugTrace(-1, Dbg, "FsRtlCheckLockForWriteAccess (No current lock info) -> TRUE\n", 0);
        return TRUE;
    }

    //
    //  Do a really fast test to see if there are any locks to start with
    //

    if (LockInfo->LockQueue.ExclusiveLockTree == NULL && LockInfo->LockQueue.SharedLockTree == NULL) {
        DebugTrace(-1, Dbg, "FsRtlCheckLockForWriteAccess (No current locks) -> TRUE\n", 0);
        return TRUE;
    }

    //
    //  Get the write offset and compare it to the lowest existing lock.
    //

    IrpSp = IoGetCurrentIrpStackLocation( Irp );

    StartingByte  = IrpSp->Parameters.Write.ByteOffset;
    (ULONGLONG)Length.QuadPart = (ULONGLONG)IrpSp->Parameters.Write.Length;

    (ULONGLONG)BeyondLastByte.QuadPart = (ULONGLONG)StartingByte.QuadPart + Length.LowPart;
    if ( (ULONGLONG)BeyondLastByte.QuadPart <= (ULONGLONG)LockInfo->LowestLockOffset ) {
        DebugTrace(-1, Dbg, "FsRtlCheckLockForWriteAccess (Below lowest lock) -> TRUE\n", 0);
        return TRUE;
    }

    //
    //  Get remaining parameters.
    //

    Key           = IrpSp->Parameters.Write.Key;
    FileObject    = IrpSp->FileObject;
    ProcessId     = IoGetRequestorProcess( Irp );

    //
    //  Call our private work routine to do the real work
    //

    Result = FsRtlFastCheckLockForWrite( FileLock,
                                         &StartingByte,
                                         &Length,
                                         Key,
                                         FileObject,
                                         ProcessId );

    //
    //  And return to our caller
    //

    DebugTrace(-1, Dbg, "FsRtlCheckLockForWriteAccess -> %08lx\n", Result);

    return Result;
}


PRTL_SPLAY_LINKS
FsRtlFindFirstOverlappingSharedNode (
    IN PRTL_SPLAY_LINKS         Tree,
    IN PLARGE_INTEGER           StartingByte,
    IN PLARGE_INTEGER           EndingByte,
    IN OUT PRTL_SPLAY_LINKS     *LastEdgeNode,
    IN OUT PBOOLEAN             GreaterThan
    )
/*++

Routine Description:

    This routine returns the first node in the shared lock tree which
    overlaps with the range given. No nodes given by RtlRealPredecessor()
    on the result overlap the range.

Arguments:

    Tree - supplies the splay links of the root node of the shared tree
        to search

    Starting - supplies the first byte offset of the range to check

    Ending - supplies the last byte offset of the range to check

    LastEdgeNode - optional, will be set to the last node searched in the
        not including returned node (presumeably where a new node will
        be inserted if return is NULL).

    GreaterThan - optional, set according to whether LastEdgeNode is covering
        a range greater than the queried range. !GreaterThan == LessThan, since
        we would have returned this node in the "Equals" (overlap) case.

Return Value:

    The splay links of the node, if such a node exists, NULL otherwise

--*/
{
    PLOCKTREE_NODE        Node, LastOverlapNode;
    PRTL_SPLAY_LINKS      SplayLinks;
    PSH_LOCK              Lock;
    LARGE_INTEGER         Starting;
    LARGE_INTEGER         Ending;

    if (LastEdgeNode) *LastEdgeNode = NULL;
    if (GreaterThan) *GreaterThan = FALSE;

    Starting = *StartingByte;
    Ending = *EndingByte;

    LastOverlapNode = NULL;
    SplayLinks = Tree;

    while (SplayLinks) {

        Node = CONTAINING_RECORD( SplayLinks, LOCKTREE_NODE, Links );

        //
        //  Pull up the first lock on the chain at this node to check
        //  the starting byte offset of locks at this node
        //

        Lock = CONTAINING_RECORD( Node->Locks.Next, SH_LOCK, Link );

        if (Node->Extent < (ULONGLONG)Starting.QuadPart) {

            if ((ULONGLONG)Lock->LockInfo.EndingByte.QuadPart == (ULONGLONG)Ending.QuadPart &&
                (ULONGLONG)Lock->LockInfo.StartingByte.QuadPart == (ULONGLONG)Starting.QuadPart) {

                //
                //  The extent of the node is less than the starting position of the
                //  range we are checking and the first lock on this node is equal to
                //  the range, which implies that the range and the lock are zero
                //  length.
                //
                //  This is a zero length lock node and we are searching for zero
                //  length overlap. This makes multiple zero length shared locks
                //  occupy the same node, which is a win, but makes application of
                //  zero length exclusive locks check the length of the overlapping
                //  lock to see if they really conflict.
                //

                break;
            }

            //
            //  All locks at this node are strictly less than this
            //  byterange, so go right in the tree.
            //

            if (LastEdgeNode) *LastEdgeNode = SplayLinks;
            if (GreaterThan) *GreaterThan = FALSE;

            SplayLinks = RtlRightChild(SplayLinks);
            continue;
        }

        if ((ULONGLONG)Lock->LockInfo.StartingByte.QuadPart <= (ULONGLONG)Ending.QuadPart) {

            //
            //  We have an overlap, but we need to see if the byterange starts
            //  before this node so that there is the guarantee that we start
            //  the search at the correct point. There may be still be predecessor
            //  nodes covering the byterange.
            //

            if ((ULONGLONG)Lock->LockInfo.StartingByte.QuadPart <= (ULONGLONG)Starting.QuadPart) {

                //
                //  This node begins at a byte offset prior to the byterange we
                //  are checking, so it must be the correct starting position.
                //

                break;
            }

            //
            //  Drop a marker at this node so that we can come back if it turns out
            //  that the left subtree does not cover the range of bytes before this
            //  node in the byterange.
            //

            LastOverlapNode = Node;
        }

        //
        //  It must now be the case that all locks at this node are strictly greater
        //  than the byterange, or we have the candidate overlap case above,
        //  so go left in the tree.
        //

        if (LastEdgeNode) *LastEdgeNode = SplayLinks;
        if (GreaterThan) *GreaterThan = TRUE;

        SplayLinks = RtlLeftChild(SplayLinks);
    }

    if (SplayLinks == NULL) {

        //
        //  We hit the edge of the tree. If the LastOverlapNode is set, it means that
        //  we had kept searching left in the tree for a node that covered the starting
        //  byte of the byterange, but didn't find it. If it isn't set, we'll do the
        //  right thing anyway since Node <- NULL.
        //

        Node = LastOverlapNode;
    }

    if (Node == NULL) {

        //
        // No overlapping node existed
        //

        return NULL;
    }

    //
    // Return the splay links of the first overlapping node
    //

    return &Node->Links;
}


PRTL_SPLAY_LINKS
FsRtlFindFirstOverlappingExclusiveNode (
    IN PRTL_SPLAY_LINKS        Tree,
    IN PLARGE_INTEGER          StartingByte,
    IN PLARGE_INTEGER          EndingByte,
    IN OUT PRTL_SPLAY_LINKS    *LastEdgeNode,
    IN OUT PBOOLEAN            GreaterThan
    )
/*++

Routine Description:

    This routine returns the first node in the exclusive lock tree which
    overlaps with the range given. No nodes given by RtlRealPredecessor()
    on the result overlap the range.

Arguments:

    Tree - supplies the splay links of the root node of the exclusive tree
        to search

    Starting - supplies the first byte offset of the range to check

    Ending - supplies the last byte offset of the range to check

    LastEdgeNode - optional, will be set to the last node searched
        not including returned node (presumeably where a new node will
        be inserted if return is NULL).

    GreaterThan - optional, set according to whether LastEdgeNode is covering
        a range greater than the queried range. !GreaterThan == LessThan, since
        we would have returned this node in the "Equals" (overlap) case.

Return Value:

    The splay links of the node, if such a node exists, NULL otherwise

--*/
{
    PRTL_SPLAY_LINKS    SplayLinks;
    PEX_LOCK            Lock, LastOverlapNode;
    LARGE_INTEGER       Starting;
    LARGE_INTEGER       Ending;

    if (LastEdgeNode) *LastEdgeNode = NULL;
    if (GreaterThan) *GreaterThan = FALSE;

    Starting = *StartingByte;
    Ending = *EndingByte;

    LastOverlapNode = NULL;
    SplayLinks = Tree;

    while (SplayLinks) {

        Lock = CONTAINING_RECORD( SplayLinks, EX_LOCK, Link );

        if ((ULONGLONG)Lock->LockInfo.EndingByte.QuadPart < (ULONGLONG)Starting.QuadPart) {

            if ((ULONGLONG)Lock->LockInfo.EndingByte.QuadPart == (ULONGLONG)Ending.QuadPart &&
                (ULONGLONG)Lock->LockInfo.StartingByte.QuadPart == (ULONGLONG)Starting.QuadPart) {

                //
                //  The extent of the lock is less than the starting position of the
                //  range we are checking and the lock is equal to the range, which
                //  implies that the range and the lock are zero length.
                //
                //  This is a zero length lock node and we are searching for zero
                //  length overlap. Since the exclusive tree is one lock per node,
                //  we are in the potential middle of a run of zero length locks in
                //  the tree. Go left to find the first zero length lock.
                //
                //  This is actually the same logic we'd use for equivalent locks,
                //  but the only time that can happen in this tree is for zero length
                //  locks.
                //

                LastOverlapNode = Lock;

                if (LastEdgeNode) *LastEdgeNode = SplayLinks;
                if (GreaterThan) *GreaterThan = FALSE;

                SplayLinks = RtlLeftChild(SplayLinks);
                continue;
            }

            //
            //  This lock is strictly less than this byterange, so go
            //  right in the tree.
            //

            if (LastEdgeNode) *LastEdgeNode = SplayLinks;
            if (GreaterThan) *GreaterThan = FALSE;

            SplayLinks = RtlRightChild(SplayLinks);
            continue;
        }

        if ((ULONGLONG)Lock->LockInfo.StartingByte.QuadPart <= (ULONGLONG)Ending.QuadPart) {

            //
            //  We have an overlap, but we need to see if the byterange starts
            //  before this node so that there is the guarantee that we start
            //  the search at the correct point. There may be still be predecessor
            //  nodes covering the byterange.
            //

            if ((ULONGLONG)Lock->LockInfo.StartingByte.QuadPart <= (ULONGLONG)Starting.QuadPart) {

                //
                //  This node begins at a byte offset prior to the byterange we
                //  are checking, so it must be the correct starting position.
                //

                break;
            }

            //
            //  Drop a marker at this node so that we can come back if it turns out
            //  that the left subtree does not cover the range of bytes before this
            //  node in the byterange.
            //

            LastOverlapNode = Lock;
        }

        //
        //  It must now be the case this lock is strictly greater than the byterange,
        //  or we have the candidate overlap case above, so go left in the tree.
        //

        if (LastEdgeNode) *LastEdgeNode = SplayLinks;
        if (GreaterThan) *GreaterThan = TRUE;

        SplayLinks = RtlLeftChild(SplayLinks);
    }

    if (SplayLinks == NULL) {

        //
        //  We hit the edge of the tree. If the LastOverlapNode is set, it means that
        //  we had kept searching left in the tree for a node that covered the starting
        //  byte of the byterange, but didn't find it. If it isn't set, we'll do the
        //  right thing anyway since Node <- NULL.
        //

        Lock = LastOverlapNode;
    }

    if (Lock == NULL) {

        //
        // No overlapping lock existed
        //

        return NULL;
    }

    //
    // Return the splay links of the first overlapping lock
    //

    return &Lock->Links;
}


PFILE_LOCK_INFO
FsRtlGetNextFileLock (
    IN PFILE_LOCK FileLock,
    IN BOOLEAN Restart
    )

/*++

Routine Description:

    This routine enumerates the individual file locks denoted by the input file lock
    variable. It returns a pointer to the file lock information stored for each lock.
    The caller is responsible for synchronizing call to this procedure and for not
    altering any of the data returned by this procedure. If the caller does not
    synchronize the enumeration will not be reliably complete.

    The way a programmer will use this procedure to enumerate all of the locks
    is as follows:

    for (p = FsRtlGetNextFileLock( FileLock, TRUE );
         p != NULL;
         p = FsRtlGetNextFileLock( FileLock, FALSE )) {

            // Process the lock information referenced by p
    }

    Order is *not* guaranteed.

Arguments:

    FileLock - Supplies the File Lock to enumerate.  The current
        enumeration state is stored in the file lock variable so if multiple
        threads are enumerating the lock at the same time the results will
        be unpredictable.

    Restart - Indicates if the enumeration is to start at the beginning of the
        file lock tree or if we are continuing from a previous call.

Return Value:

    PFILE_LOCK_INFO - Either it returns a pointer to the next file lock
        record for the input file lock or it returns NULL if there
        are not more locks.

--*/

{
    FILE_LOCK_INFO      FileLockInfo;
    PVOID               ContinuationPointer;
    PLOCK_INFO          LockInfo;
    PLOCKTREE_NODE      Node;
    PSINGLE_LIST_ENTRY  Link;
    PRTL_SPLAY_LINKS    SplayLinks, LastSplayLinks;
    PSH_LOCK            ShLock;
    PEX_LOCK            ExLock;
    BOOLEAN             FoundReturnable, GreaterThan;
    KIRQL               OldIrql;

    DebugTrace(+1, Dbg, "FsRtlGetNextFileLock, FileLock = %08lx\n", FileLock);

    if ((LockInfo = (PLOCK_INFO) FileLock->LockInformation) == NULL) {
        //
        //  No lock information on this FileLock
        //

        return NULL;
    }

    FoundReturnable = FALSE;

    //
    //  Before getting the spinlock, copy pagable info onto stack
    //

    FileLockInfo = FileLock->LastReturnedLockInfo;
    ContinuationPointer = FileLock->LastReturnedLock;

    FsRtlAcquireLockQueue (&LockInfo->LockQueue, &OldIrql);

    if (!Restart) {
        //
        //  Given the last returned lock, find its current successor in the tree.
        //  Previous implementations would reset the enumeration if the last returned
        //  lock had been removed from the tree but I think we can be better in that
        //  case since every other structure modifying event (add new locks, delete
        //  other locks) would *not* have caused the reset. Possible minor performance
        //  enhancement.
        //

        //
        //  Find the node which could contain the last returned lock. We enumerate the
        //  exclusive lock tree, then the shared lock tree. Find the one we're enumerating.
        //

        if (FileLockInfo.ExclusiveLock) {

            //
            //  Continue enumeration in the exclusive lock tree
            //

            ExLock = NULL;

            SplayLinks = FsRtlFindFirstOverlappingExclusiveNode( LockInfo->LockQueue.ExclusiveLockTree,
                                                                 &FileLockInfo.StartingByte,
                                                                 &FileLockInfo.EndingByte,
                                                                 &LastSplayLinks,
                                                                 &GreaterThan );

            if (SplayLinks == NULL) {
    
                //
                //  No overlapping nodes were found, try to find successor
                //
    
                if (GreaterThan) {
    
                    //
                    //  Last node looked at was greater than the lock so it is
                    //  the place to pick up the enumeration
                    //

                    SplayLinks = LastSplayLinks;
    
                } else {
    
                    //
                    // Last node looked at was less than the lock so grab its successor
                    //
    
                    if (LastSplayLinks) {
    
                        SplayLinks = RtlRealSuccessor(LastSplayLinks);
                    }
                }

            } else {

                //
                //  Found an overlapping lock, see if it is the last returned
                //

                for (;
                    SplayLinks;
                    SplayLinks = RtlRealSuccessor(SplayLinks)) {

                    ExLock = CONTAINING_RECORD( SplayLinks, EX_LOCK, Links );
    
                    if (ContinuationPointer == ExLock &&
                        (ULONGLONG)FileLockInfo.StartingByte.QuadPart == (ULONGLONG)ExLock->LockInfo.StartingByte.QuadPart &&
                        (ULONGLONG)FileLockInfo.Length.QuadPart == (ULONGLONG)ExLock->LockInfo.Length.QuadPart &&
                        FileLockInfo.Key == ExLock->LockInfo.Key &&
                        FileLockInfo.FileObject == ExLock->LockInfo.FileObject &&
                        FileLockInfo.ProcessId == ExLock->LockInfo.ProcessId) {
    
                        //
                        //  Found last returned, dig up its successor
                        //
    
                        SplayLinks = RtlRealSuccessor(SplayLinks);
    
                        //
                        //  Got the node cold, so we're done
                        //

                        break;
                    }

                    //
                    //  This lock overlapped and was not the last returned. In fact, since this lock would
                    //  have conflicted with the last returned we know it could not have been returned
                    //  before, so this should be returned to the caller.
                    //
                    //  However, if it is a zero length lock we are looking for and a zero length lock we hit,
                    //  we are at the beginning of a run we need to inspect. If we cannot find the last lock
                    //  we returned, resume the enumeration at the beginning of the run.
                    //
    
                    if (ExLock->LockInfo.Length.QuadPart != 0 || FileLockInfo.Length.QuadPart != 0) {

                        break;
                    }

                    //
                    //  Keep wandering down the run
                    //
                }
            }

            //
            //  Were we able to find a lock to return?
            //

            if (SplayLinks == NULL) {

                //
                //  There aren't any more exclusive locks, fall over to the shared tree
                //

                SplayLinks = LockInfo->LockQueue.SharedLockTree;

                if (SplayLinks) {

                    while (RtlLeftChild(SplayLinks)) {
    
                        SplayLinks = RtlLeftChild(SplayLinks);
                    }
    
                    Node = CONTAINING_RECORD(SplayLinks, LOCKTREE_NODE, Links);
                    ShLock = CONTAINING_RECORD(Node->Locks.Next, SH_LOCK, Link);
    
                    FileLockInfo = ShLock->LockInfo;
                    ContinuationPointer = ShLock;
                    FoundReturnable = TRUE;
                }

            } else {

                //
                //  This is the lock to return
                //
              
                ExLock = CONTAINING_RECORD( SplayLinks, EX_LOCK, Links );

                FileLockInfo = ExLock->LockInfo;
                ContinuationPointer = ExLock;
                FoundReturnable = TRUE;
            }

        } else {

            //
            //  Continue enumeration in the shared lock tree
            //

            Node = NULL;
    
            SplayLinks = FsRtlFindFirstOverlappingSharedNode( LockInfo->LockQueue.SharedLockTree,
                                                              &FileLockInfo.StartingByte,
                                                              &FileLockInfo.EndingByte,
                                                              &LastSplayLinks,
                                                              &GreaterThan );
    
            if (SplayLinks == NULL) {
    
                //
                //  No overlapping nodes were found
                //
    
                if (GreaterThan) {
    
                    //
                    //  Last node looked at was greater than the lock so it is
                    //  the place to pick up the enumeration
                    //
    
                    if (LastSplayLinks) {
    
                        SplayLinks = LastSplayLinks;
                        Node = CONTAINING_RECORD( LastSplayLinks, LOCKTREE_NODE, Links );
                    }
    
                } else {
    
                    //
                    // Last node looked at was less than the lock so grab its successor
                    //
    
                    if (LastSplayLinks) {
    
                        SplayLinks = RtlRealSuccessor(LastSplayLinks);
    
                        if (SplayLinks) {
    
                            Node = CONTAINING_RECORD( SplayLinks, LOCKTREE_NODE, Links );
                        }
                    }
                }

            } else {

                //
                //  Grab the node we found
                //

                Node = CONTAINING_RECORD( SplayLinks, LOCKTREE_NODE, Links );
            }

            //
            //  If we have a node to look at, it may still not contain the the last returned lock
            //  if this isn't synchronized.
            //

            if (Node != NULL) {
    
                //
                //    Walk down the locks at this node looking for the last returned lock
                //
    
                for (Link = Node->Locks.Next;
                     Link;
                     Link = Link->Next) {
    
                    //
                    //  Get a pointer to the current lock record
                    //
    
                    ShLock = CONTAINING_RECORD( Link, SH_LOCK, Link );
    
                    //
                    // See if it's a match
                    //
    
                    if (ContinuationPointer == ShLock &&
                        (ULONGLONG)FileLockInfo.StartingByte.QuadPart == (ULONGLONG)ShLock->LockInfo.StartingByte.QuadPart &&
                        (ULONGLONG)FileLockInfo.Length.QuadPart == (ULONGLONG)ShLock->LockInfo.Length.QuadPart &&
                        FileLockInfo.Key == ShLock->LockInfo.Key &&
                        FileLockInfo.FileObject == ShLock->LockInfo.FileObject &&
                        FileLockInfo.ProcessId == ShLock->LockInfo.ProcessId) {
    
                        Link = Link->Next;
                        break;
                    }
    
                    //
                    // See if we passed by its slot
                    //
    
                    if ((ULONGLONG)FileLockInfo.StartingByte.QuadPart < (ULONGLONG)ShLock->LockInfo.StartingByte.QuadPart) {

                        break;
                    }
                }
    
                if (Link == NULL) {
            
                    //
                    //  This node doesn't contain the successor, so move
                    //  up to the successor node in the tree and return the
                    //  first lock. If we're actually at the end of the tree
                    //  we just fall off the end correctly.
                    //
            
                    SplayLinks = RtlRealSuccessor(SplayLinks);

                    if (SplayLinks) {

                        Node = CONTAINING_RECORD( SplayLinks, LOCKTREE_NODE, Links );
        
                        Link = Node->Locks.Next;
                    }
                }

                if (Link) {
            
                    //
                    //  Found a Lock to return, copy it to the stack
                    //
            
                    ShLock = CONTAINING_RECORD( Link, SH_LOCK, Link );

                    FileLockInfo = ShLock->LockInfo;
                    ContinuationPointer = ShLock;
                    FoundReturnable = TRUE;
                }

            }
        }

    } else {

        //
        //  Restarting the enumeration. Find leftmost node in the exclusive tree and hand back
        //  the first lock, falling over to the shared if no exlcusive locks are applied
        //

        if (LockInfo->LockQueue.ExclusiveLockTree) {

            SplayLinks = LockInfo->LockQueue.ExclusiveLockTree;

            while (RtlLeftChild(SplayLinks) != NULL) {
    
                SplayLinks = RtlLeftChild(SplayLinks);
            }
    
            ExLock = CONTAINING_RECORD( SplayLinks, EX_LOCK, Links );

            FileLockInfo = ExLock->LockInfo;
            ContinuationPointer = ExLock;
            FoundReturnable = TRUE;

        } else {

            if (LockInfo->LockQueue.SharedLockTree) {

                SplayLinks = LockInfo->LockQueue.SharedLockTree;
    
                while (RtlLeftChild(SplayLinks) != NULL) {
    
                    SplayLinks = RtlLeftChild(SplayLinks);
                }
    
                Node = CONTAINING_RECORD( SplayLinks, LOCKTREE_NODE, Links );
                ShLock = CONTAINING_RECORD( Node->Locks.Next, SH_LOCK, Link );

                FileLockInfo = ShLock->LockInfo;
                ContinuationPointer = ShLock;
                FoundReturnable = TRUE;
            }
        }
    }

    //
    //  Release all the lock queues
    //

    FsRtlReleaseLockQueue (&LockInfo->LockQueue, OldIrql);

    if (!FoundReturnable) {

        //
        //  No returnable lock was found, end of list
        //

        return NULL;
    }

    //
    // Update current enum location information
    //

    FileLock->LastReturnedLockInfo = FileLockInfo;
    FileLock->LastReturnedLock = ContinuationPointer;

    //
    // Return lock record to caller
    //

    return &FileLock->LastReturnedLockInfo;
}


BOOLEAN
FsRtlCheckNoSharedConflict (
   IN PLOCK_QUEUE LockQueue,
   IN PLARGE_INTEGER Starting,
   IN PLARGE_INTEGER Ending
   )
/*++

Routine Description:

    This routine checks to see if there is overlap in the shared locks with
    the given range. It is intended for use in the write access check path
    so that a rebalance will occur.

Arguments:

    FileLock - Supplies the File Lock to check

    StartingByte - Supplies the first byte (zero based) to check

    Length - Supplies the length, in bytes, to check

    Key - Supplies the key to use in the check

    FileObject - Supplies the file object to use in the check

    ProcessId - Supplies the Process Id to use in the check

Return Value:

    BOOLEAN - TRUE if the indicated user/request doesn't conflict in
        entire specified byte range, and FALSE otherwise

--*/
{
    PRTL_SPLAY_LINKS SplayLinks, BeginLinks;

    SplayLinks = FsRtlFindFirstOverlappingSharedNode( LockQueue->SharedLockTree,
                                                      Starting,
                                                      Ending,
                                                      &BeginLinks,
                                                      NULL);

    if (BeginLinks) {

        LockQueue->SharedLockTree = RtlSplay(BeginLinks);
    }

    return (SplayLinks == NULL);
}


BOOLEAN
FsRtlCheckNoExclusiveConflict (
    IN PLOCK_QUEUE LockQueue,
    IN PLARGE_INTEGER Starting,
    IN PLARGE_INTEGER Ending,
    IN ULONG Key,
    IN PFILE_OBJECT FileObject,
    IN PVOID ProcessId
    )
/*++

Routine Description:

    This routine checks to see if there is conflict in the exclusive locks with
    a given range and identifying tuple of key, fileobject and process. This is
    for part of the read access path.

Arguments:

    FileLock - Supplies the File Lock to check

    StartingByte - Supplies the first byte (zero based) to check

    Length - Supplies the length, in bytes, to check

    Key - Supplies the key to use in the check

    FileObject - Supplies the file object to use in the check

    ProcessId - Supplies the Process Id to use in the check

Return Value:

    BOOLEAN - TRUE if the indicated user/request doesn't conflict in
        entire specified byte range, and FALSE otherwise

--*/
{
    PRTL_SPLAY_LINKS SplayLinks, BeginLinks;
    PEX_LOCK Lock;
    BOOLEAN Status = TRUE;

    //
    //  Find the node to begin the search at and go
    //

    for (SplayLinks = FsRtlFindFirstOverlappingExclusiveNode( LockQueue->ExclusiveLockTree,
                                                              Starting,
                                                              Ending,
                                                              &BeginLinks,
                                                              NULL);
         SplayLinks;
         SplayLinks = RtlRealSuccessor(SplayLinks)) {

        Lock = CONTAINING_RECORD( SplayLinks, EX_LOCK, Links );

        //
        //  If the current lock is greater than the end of the range we're
        //  looking for then the the user doesn't conflict
        //
        //  if (Ending < Lock->StartingByte) ...
        //

        if ((ULONGLONG)Ending->QuadPart < (ULONGLONG)Lock->LockInfo.StartingByte.QuadPart) {

            DebugTrace(0, Dbg, "FsRtlCheckForExclusiveConflict, Ending < Lock->StartingByte\n", 0);

            break;
        }

        //
        //  Check for any overlap with the request. The test for
        //  overlap is that starting byte is less than or equal to the locks
        //  ending byte, and the ending byte is greater than or equal to the
        //  locks starting byte.  We already tested for this latter case in
        //  the preceding statement.
        //
        //  if (Starting <= Lock->StartingByte + Lock->Length - 1) ...
        //

        if ((ULONGLONG)Starting->QuadPart <= (ULONGLONG)Lock->LockInfo.EndingByte.QuadPart) {

            //
            //  This request overlaps the lock. We cannot grant the request
            //  if the file object, process id, and key do not match. Otherwise
            //  we'll continue looping looking at locks
            //

            if ((Lock->LockInfo.FileObject != FileObject) ||
                (Lock->LockInfo.ProcessId != ProcessId) ||
                (Lock->LockInfo.Key != Key)) {
                
                DebugTrace(0, Dbg, "FsRtlCheckForExclusiveConflict, Range locked already\n", 0);

                Status = FALSE;
                break;
            }
        }
    }

    if (BeginLinks) {

        LockQueue->ExclusiveLockTree = RtlSplay(BeginLinks);
    }

    //
    //  We searched the entire range without a conflict so we'll note no conflict
    //

    return Status;
}


BOOLEAN
FsRtlFastCheckLockForRead (
    IN PFILE_LOCK FileLock,
    IN PLARGE_INTEGER StartingByte,
    IN PLARGE_INTEGER Length,
    IN ULONG Key,
    IN PFILE_OBJECT FileObject,
    IN PVOID ProcessId
    )

/*++

Routine Description:

    This routine checks to see if the caller has read access to the
    indicated range due to file locks.

Arguments:

    FileLock - Supplies the File Lock to check

    StartingByte - Supplies the first byte (zero based) to check

    Length - Supplies the length, in bytes, to check

    Key - Supplies the to use in the check

    FileObject - Supplies the file object to use in the check

    ProcessId - Supplies the Process Id to use in the check

Return Value:

    BOOLEAN - TRUE if the indicated user/request has read access to the
        entire specified byte range, and FALSE otherwise

--*/

{
    LARGE_INTEGER Starting;
    LARGE_INTEGER Ending;

    PLOCK_INFO            LockInfo;
    PLOCK_QUEUE           LockQueue;
    KIRQL                 OldIrql;
    PFILE_LOCK_INFO       LastLock;
    BOOLEAN               Status;

    if ((LockInfo = (PLOCK_INFO) FileLock->LockInformation) == NULL) {

        //
        // No lock information on this FileLock
        //

        DebugTrace(0, Dbg, "FsRtlFastCheckLockForRead, No lock info\n", 0);
        return TRUE;
    }

    //
    // If there isn't an exclusive lock then we can immediately grant access
    //

    if (LockInfo->LockQueue.ExclusiveLockTree == NULL) {
        DebugTrace(0, Dbg, "FsRtlFastCheckLockForRead, No exlocks present\n", 0);
        return TRUE;
    }

    //
    // If length is zero then automatically give grant access
    //

    if ((ULONGLONG)Length->QuadPart == 0) {

        DebugTrace(0, Dbg, "FsRtlFastCheckLockForRead, Length == 0\n", 0);
        return TRUE;
    }

    //
    //  Get our starting and ending byte position
    //

    Starting = *StartingByte;
    (ULONGLONG)Ending.QuadPart = (ULONGLONG)Starting.QuadPart + (ULONGLONG)Length->QuadPart - 1;

    //
    // Now check lock queue
    //

    LockQueue = &LockInfo->LockQueue;

    //
    //  Grab the waiting lock queue spinlock to exclude anyone from messing
    //  with the queue while we're using it
    //

    FsRtlReacquireLockQueue(LockInfo, LockQueue, &OldIrql);

    //
    //  If the range ends below the lowest existing lock, this read is OK.
    //

    if ( ((ULONGLONG)Ending.QuadPart < (ULONGLONG)LockInfo->LowestLockOffset) ) {
        DebugTrace(0, Dbg, "FsRtlFastCheckLockForRead (below lowest lock)\n", 0);

        FsRtlReleaseLockQueue(LockQueue, OldIrql);
        return TRUE;
    }

    //
    //  If the caller just locked this range, he can read it.
    //

    LastLock = (PFILE_LOCK_INFO)FileObject->LastLock;
    if ((LastLock != NULL) &&
        ((ULONGLONG)Starting.QuadPart >= (ULONGLONG)LastLock->StartingByte.QuadPart) &&
        ((ULONGLONG)Ending.QuadPart <= (ULONGLONG)LastLock->EndingByte.QuadPart) &&
        (LastLock->Key == Key) &&
        (LastLock->ProcessId == ProcessId)) {

        FsRtlReleaseLockQueue(LockQueue, OldIrql);
        return TRUE;
    }

    //
    //  Check the exclusive locks for a conflict. It is impossible to have
    //  a read conflict with any shared lock.
    //

    Status = FsRtlCheckNoExclusiveConflict(LockQueue, &Starting, &Ending, Key, FileObject, ProcessId);

    FsRtlReleaseLockQueue(LockQueue, OldIrql);

    return Status;
}


BOOLEAN
FsRtlFastCheckLockForWrite (
    IN PFILE_LOCK FileLock,
    IN PLARGE_INTEGER StartingByte,
    IN PLARGE_INTEGER Length,
    IN ULONG Key,
    IN PVOID FileObject,
    IN PVOID ProcessId
    )

/*++

Routine Description:

    This routine checks to see if the caller has write access to the
    indicated range due to file locks

Arguments:

    FileLock - Supplies the File Lock to check

    StartingByte - Supplies the first byte (zero based) to check

    Length - Supplies the length, in bytes, to check

    Key - Supplies the to use in the check

    FileObject - Supplies the file object to use in the check

    ProcessId - Supplies the Process Id to use in the check

Return Value:

    BOOLEAN - TRUE if the indicated user/request has write access to the
        entire specified byte range, and FALSE otherwise

--*/

{
    LARGE_INTEGER Starting;
    LARGE_INTEGER Ending;

    PLOCK_INFO              LockInfo;
    PLOCK_QUEUE             LockQueue;
    KIRQL                   OldIrql;
    PFILE_LOCK_INFO         LastLock;
    BOOLEAN                 Status;

    if ((LockInfo = (PLOCK_INFO) FileLock->LockInformation) == NULL) {

        //
        // No lock information on this FileLock
        //

        DebugTrace(0, Dbg, "FsRtlFastCheckLockForRead, No lock info\n", 0);
        return TRUE;
    }

    //
    //  If there isn't a lock then we can immediately grant access
    //

    if (LockInfo->LockQueue.SharedLockTree == NULL && LockInfo->LockQueue.ExclusiveLockTree == NULL) {

        DebugTrace(0, Dbg, "FsRtlFastCheckLockForWrite, No locks present\n", 0);
        return TRUE;
    }

    //
    //  If length is zero then automatically grant access
    //

    if ((ULONGLONG)Length->QuadPart == 0) {

        DebugTrace(0, Dbg, "FsRtlFastCheckLockForWrite, Length == 0\n", 0);
        return TRUE;
    }

    //
    //  Get our starting and ending byte position
    //

    Starting = *StartingByte;
    (ULONGLONG)Ending.QuadPart = (ULONGLONG)Starting.QuadPart + (ULONGLONG)Length->QuadPart - 1;

    //
    //  Now check lock queue
    //

    LockQueue = &LockInfo->LockQueue;

    //
    //  Grab the waiting lock queue spinlock to exclude anyone from messing
    //  with the queue while we're using it
    //

    FsRtlReacquireLockQueue(LockInfo, LockQueue, &OldIrql);

    //
    //  If the range ends below the lowest existing lock, this write is OK.
    //

    if ( ((ULONGLONG)Ending.QuadPart < (ULONGLONG)LockInfo->LowestLockOffset) ) {

        DebugTrace(0, Dbg, "FsRtlFastCheckLockForWrite (below lowest lock)\n", 0);

        FsRtlReleaseLockQueue(LockQueue, OldIrql);
        return TRUE;
    }

    //
    //  If the caller just locked this range exclusively, he can write it.
    //

    LastLock = (PFILE_LOCK_INFO)((PFILE_OBJECT)FileObject)->LastLock;
    if ((LastLock != NULL) &&
        ((ULONGLONG)Starting.QuadPart >= (ULONGLONG)LastLock->StartingByte.QuadPart) &&
        ((ULONGLONG)Ending.QuadPart <= (ULONGLONG)LastLock->EndingByte.QuadPart) &&
        (LastLock->Key == Key) &&
        (LastLock->ProcessId == ProcessId) &&
        LastLock->ExclusiveLock) {

        FsRtlReleaseLockQueue(LockQueue, OldIrql);
        return TRUE;
    }

    //
    //  Check the shared locks for overlap. Any overlap in the shared locks is fatal.
    //

    Status = FsRtlCheckNoSharedConflict(LockQueue, &Starting, &Ending);

    if (Status == TRUE) {

        //
        //  No overlap in the shared locks, so check the exclusive locks for overlap.
        //

        Status = FsRtlCheckNoExclusiveConflict(LockQueue, &Starting, &Ending, Key, FileObject, ProcessId);
    }

    FsRtlReleaseLockQueue(LockQueue, OldIrql);

    return Status;
}


VOID
FsRtlSplitLocks (
    IN PLOCKTREE_NODE ParentNode,
    IN PSINGLE_LIST_ENTRY *pStartLink,
    IN PLARGE_INTEGER LastShadowedByte,
    IN PLARGE_INTEGER GlueOffset
    )
/*++

Routine Description:

    This routine examines and possibly splits off shared locks associated
    with a node into new nodes of the lock tree. Called from routines that
    have just deleted locks.

Arguments:

    ParentNode- Supplies the node the locks are coming from

    pStartLink - Supplies the pointer to the link address of the start of the
        range of locks in the ParentNode's locklist that need to be checked

    LastShadowedByte - Supplies the last byte offset that needs to be checked

    GlueOffset - Supplies the maximum offset affected by locks prior to this
        point in the list

Return Value:

    None

--*/
{
    PSH_LOCK                Lock;
    PLOCKTREE_NODE          NewNode;
    PSINGLE_LIST_ENTRY      Link, *pLink, *NextpLink;
    BOOLEAN                 ExtentValid;
    LARGE_INTEGER           MaxOffset, StartOffset;

    MaxOffset = *GlueOffset;
    StartOffset.QuadPart = 0;

    if (!ParentNode->Locks.Next ||
        (ULONGLONG)LastShadowedByte->QuadPart <= (ULONGLONG)MaxOffset.QuadPart) {

        //
        //  The parent node is not there, doesn't have links associated, or the
        //  last possible byte that is affected by the operation our caller made
        //  is interior to the max extent of all locks still in this node - in
        //  which case there is nothing that needs to be done.
        //

        return;
    }

    //
    //  If the extent of the node is past the last byte affected by whatever
    //  operations were done to this node, we can avoid the linear scan of
    //  the list past that last affected byte since we already know the
    //  extent of the entire list! If it is not (note that it would have to
    //  be equal - by defintion) then we need to recalculate the extents of
    //  all nodes we touch in this operation.
    //

    ExtentValid = (ParentNode->Extent > (ULONGLONG)LastShadowedByte->QuadPart);

    for (pLink = pStartLink;
         (Link = *pLink) != NULL;
         pLink = NextpLink) {

        NextpLink = &Link->Next;

        Lock = CONTAINING_RECORD( Link, SH_LOCK, Link );

        if (ParentNode->Locks.Next == *pLink) {
    
            //
            //  We're at the first lock in the node, and we know that we're going to leave
            //  at least one lock here. Skip over that lock. We also know that the max
            //  offset must be that locks's ending byte - make sure it is. Note that this
            //  code is *exactly* the same as the update MaxOffset code at the bottom of
            //  the loop.
            //
    
            MaxOffset.QuadPart = Lock->LockInfo.EndingByte.QuadPart;

            //
            //  Set the starting offset of the node to assist in getting zero length locks right
            //

            StartOffset.QuadPart = Lock->LockInfo.StartingByte.QuadPart;

            //
            //  If extents are invalid we also need to set it in case this turns out to
            //  be the only lock at this node.
            //

            if (!ExtentValid) {

                ParentNode->Extent = (ULONGLONG)MaxOffset.QuadPart;
            }

            continue;
        }
    
        //
        //  If the lock begins at a byte offset greater than the maximum offset seen to this
        //  point, AND the starting offset of this node is not the same as this lock, break
        //  the node. The second half of the test keeps overlapping zero length locks in the
        //  same node. (zero length lock ---> starting = ending + 1)
        //

        if ((ULONGLONG)Lock->LockInfo.StartingByte.QuadPart > (ULONGLONG)MaxOffset.QuadPart &&
            StartOffset.QuadPart != Lock->LockInfo.StartingByte.QuadPart) {

            //
            //  Break the node up here
            //

            FsRtlAllocateLockTreeNode(&NewNode);
            RtlInitializeSplayLinks(&NewNode->Links);
        
            //
            //  Find the spot in the tree to take the new node(s). If the current node has
            //  a free right child, we use it, else find the successor node and use its
            //  left child. One of these cases must be avaliable since we know there are
            //  no nodes between this node and its successor.
            //
        
            if (RtlRightChild(&ParentNode->Links) == NULL) {
        
                RtlInsertAsRightChild(&ParentNode->Links, &NewNode->Links);
        
            } else {
        
                ASSERT(RtlLeftChild(RtlRealSuccessor(&ParentNode->Links)) == NULL);
                RtlInsertAsLeftChild(RtlRealSuccessor(&ParentNode->Links), &NewNode->Links);
            }
        
            //
            //  Move the remaining locks over to the new node and fix up extents
            //

            NewNode->Locks.Next = *pLink;
            *pLink = NULL;

            NewNode->Tail.Next = ParentNode->Tail.Next;
            ParentNode->Tail.Next = CONTAINING_RECORD( pLink, SINGLE_LIST_ENTRY, Next );

            //
            //  This will cause us to fall into the first-lock clause above on the next pass
            //

            NextpLink = &NewNode->Locks.Next;

            //
            // The new node's extent is now copied from the parent. The old node's extent must be
            // the maximum offset we have seen to this point.
            //
            // Note that if ExtentValid is true, that must mean that the lock ending at that extent
            // is in the new node since if it was in the old node we wouldn't have been able to split.
            //

            NewNode->Extent = ParentNode->Extent;
            ParentNode->Extent = (ULONGLONG)MaxOffset.QuadPart;

            ParentNode = NewNode;
        
            continue;
        }

        if (ExtentValid && (ULONGLONG)Lock->LockInfo.StartingByte.QuadPart > (ULONGLONG)LastShadowedByte->QuadPart) {

            //
            //  Our extents are good and this lock is past the shadow, so we can stop
            //

            return;
        }

        if ((ULONGLONG)MaxOffset.QuadPart < (ULONGLONG)Lock->LockInfo.EndingByte.QuadPart) {

            //
            //  Update maximum offset
            //

            MaxOffset.QuadPart = Lock->LockInfo.EndingByte.QuadPart;

            if (!ExtentValid) {
    
                //
                //  Extents are not good so we must update the extent
                //
    
                ParentNode->Extent = (ULONGLONG)MaxOffset.QuadPart;
            }
        }
    }

    //
    //  Reached the end of the list, so update the extent (case of all subsequent locks
    //  having been interior to GlueOffset)
    //

    ParentNode->Extent = (ULONGLONG)MaxOffset.QuadPart;

    return;
}


VOID
FsRtlPrivateRemoveLock (
    IN PLOCK_INFO LockInfo,
    IN PFILE_LOCK_INFO FileLockInfo,
    IN BOOLEAN CheckForWaiters
    )

/*++

Routine Description:

    General purpose cleanup routine.  Finds the given lock structure
    and removes it from the file lock list. Differs from UnlockSingle
    only in that it disables the UnlockRoutine of the FileLock and
    optionalizes walking the waiting locks list.

Arguments:

    FileLock - Supplies the file's lock structure supposedly containing a stale lock

    FileLockInfo - Supplies file lock data being freed

    CheckForWaiters - If true check for possible waiting locks, caused
        by freeing the locked range

Return Value:

    None.

--*/

{
    NTSTATUS Status;

    if (FileLockInfo->ExclusiveLock) {

        //
        //  We must find it in the exclusive lock tree
        //

        Status = FsRtlFastUnlockSingleExclusive( LockInfo,
    
                                                 FileLockInfo->FileObject,
                                                 &FileLockInfo->StartingByte,
                                                 &FileLockInfo->Length,
                                                 FileLockInfo->ProcessId,
                                                 FileLockInfo->Key,
    
                                                 NULL,
                                                 TRUE,
                                                 CheckForWaiters );

        ASSERT( Status == STATUS_SUCCESS);

    } else {

        //
        //  We must find it in the shared lock tree
        //

        Status = FsRtlFastUnlockSingleShared( LockInfo,
    
                                              FileLockInfo->FileObject,
                                              &FileLockInfo->StartingByte,
                                              &FileLockInfo->Length,
                                              FileLockInfo->ProcessId,
                                              FileLockInfo->Key,
    
                                              NULL,
                                              TRUE,
                                              CheckForWaiters );

        ASSERT( Status == STATUS_SUCCESS);
    }

    return;
}


NTSTATUS
FsRtlFastUnlockSingle (
    IN PFILE_LOCK FileLock,
    IN PFILE_OBJECT FileObject,
    IN LARGE_INTEGER UNALIGNED *FileOffset,
    IN PLARGE_INTEGER Length,
    IN PEPROCESS ProcessId,
    IN ULONG Key,
    IN PVOID Context OPTIONAL,
    IN BOOLEAN AlreadySynchronized
    )

/*++

Routine Description:

    This routine performs an Unlock Single operation on the current locks
    associated with the specified file lock.  Only the lock with a matching
    file object, process id, key, and range is freed.

Arguments:

    FileLock - Supplies the file lock being freed.

    FileObject - Supplies the file object holding the locks

    FileOffset - Supplies the offset to be unlocked

    Length - Supplies the length in bytes to be unlocked

    ProcessId - Supplies the process Id to use in this operation

    Key - Supplies the key to use in this operation

    Context - Optionally supplies context to use when completing Irps

    AlreadySynchronized - Indicates that the caller has already synchronized
        access to the file lock so the fields in the file lock and
        be updated without further locking, but not the queues.

Return Value:

    NTSTATUS - The completion status for this operation

--*/

{
    NTSTATUS Status;

    //
    //  XXX AlreadySynchronized is obsolete. It was apparently added for the dead
    //  XXX SoloLock code.
    //

    if (FileLock->LockInformation == NULL) {

        //
        //  Fast exit - no locks are applied
        //

        return STATUS_RANGE_NOT_LOCKED;
    }

    Status = FsRtlFastUnlockSingleExclusive( FileLock->LockInformation,
                                             FileObject,
                                             FileOffset,
                                             Length,
                                             ProcessId,
                                             Key,
                                             Context,
                                             FALSE,
                                             TRUE );

    if (Status == STATUS_SUCCESS) {

        //
        //  Found and unlocked in the exclusive tree, so we're done
        //

        return Status;
    }

    Status = FsRtlFastUnlockSingleShared( FileLock->LockInformation,
                                          FileObject,
                                          FileOffset,
                                          Length,
                                          ProcessId,
                                          Key,
                                          Context,
                                          FALSE,
                                          TRUE );

    return Status;
}


NTSTATUS
FsRtlFastUnlockSingleShared (
    IN PLOCK_INFO LockInfo,
    IN PFILE_OBJECT FileObject,
    IN LARGE_INTEGER UNALIGNED *FileOffset,
    IN PLARGE_INTEGER Length,
    IN PEPROCESS ProcessId,
    IN ULONG Key,
    IN PVOID Context OPTIONAL,
    IN BOOLEAN IgnoreUnlockRoutine,
    IN BOOLEAN CheckForWaiters
    )

/*++

Routine Description:

    This routine performs an Unlock Single operation on the current locks
    associated with the specified file lock.  Only the lock with a matching
    file object, process id, key, and range is freed.

Arguments:

    LockInfo - Supplies the lock data being operated on

    FileObject - Supplies the file object holding the locks

    FileOffset - Supplies the offset to be unlocked

    Length - Supplies the length in bytes to be unlocked

    ProcessId - Supplies the process Id to use in this operation

    Key - Supplies the key to use in this operation

    Context - Optionally supplies context to use when completing Irps

    IgnoreUnlockRoutine - inidicates that the filelock's unlock routine
        should not be called on lock removal (for removal of aborted
        locks)

    CheckForWaiters - If true check for possible waiting locks, caused
        by freeing the locked range

Return Value:

    NTSTATUS - The completion status for this operation

--*/

{
    PSINGLE_LIST_ENTRY      *pLink, Link;
    KIRQL                   OldIrql;

    PLOCK_QUEUE             LockQueue;
    PRTL_SPLAY_LINKS        SplayLinks;
    LARGE_INTEGER           EndingOffset, MaxOffset;
    PLOCKTREE_NODE          Node;
    LARGE_INTEGER           AlignedFileOffset;

    //
    //  General case - search the outstanding lock queue for this lock
    //

    AlignedFileOffset = *FileOffset;

    LockQueue = &LockInfo->LockQueue;

    FsRtlAcquireLockQueue(LockQueue, &OldIrql);

    //
    //  Check for the no locks currently held
    //

    if (LockQueue->SharedLockTree == NULL) {

        FsRtlReleaseLockQueue( LockQueue, OldIrql );

        return STATUS_RANGE_NOT_LOCKED;
    }

    //
    //  Find the overlapping node, if it exists, to search. Note that
    //  we don't have to go through more than one node in the tree
    //  since we are assuming this is an existing lock.
    //

    EndingOffset.QuadPart = (ULONGLONG)AlignedFileOffset.QuadPart + (ULONGLONG)Length->QuadPart - 1;

    SplayLinks = FsRtlFindFirstOverlappingSharedNode( LockQueue->SharedLockTree,
                                                      &AlignedFileOffset,
                                                      &EndingOffset,
                                                      NULL,
                                                      NULL );

    if (SplayLinks == NULL) {

        //
        //  No node in the tree overlaps this range, so we're done
        //

        FsRtlReleaseLockQueue(LockQueue, OldIrql);

        return STATUS_RANGE_NOT_LOCKED;
    }

    Node = CONTAINING_RECORD( SplayLinks, LOCKTREE_NODE, Links );
    MaxOffset.QuadPart = 0;

    for (pLink = &Node->Locks.Next;
         (Link = *pLink) != NULL;
         pLink = &Link->Next) {

        PSH_LOCK Lock;

        Lock = CONTAINING_RECORD( Link, SH_LOCK, Link );

        DebugTrace(0, Dbg, "Sh Top of Loop, Lock = %08lx\n", Lock );

        if ((Lock->LockInfo.FileObject == FileObject) &&
            (Lock->LockInfo.ProcessId == ProcessId) &&
            (Lock->LockInfo.Key == Key) &&
            ((ULONGLONG)Lock->LockInfo.StartingByte.QuadPart == (ULONGLONG)AlignedFileOffset.QuadPart) &&
            ((ULONGLONG)Lock->LockInfo.Length.QuadPart == (ULONGLONG)Length->QuadPart)) {

            DebugTrace(0, Dbg, "Sh Found one to unlock\n", 0);

            //
            //  We have an exact match so now is the time to delete this
            //  lock.  Remove the lock from the list, then call the
            //  optional unlock routine, then delete the lock.
            //

            if (FileObject->LastLock == &Lock->LockInfo) {

                FileObject->LastLock = NULL;
            }

            if (*pLink == Node->Tail.Next) {

                //
                //  Deleting the tail node of the list. Safe even if deleting the
                //  first node since this implies we're also deleting the last node
                //  in the node which means we'll delete the node ...
                //

                Node->Tail.Next = CONTAINING_RECORD( pLink, SINGLE_LIST_ENTRY, Next );
            }

            //
            //  Snip the deleted lock
            //

            *pLink = Link->Next;

            if (pLink == &Node->Locks.Next) {

                //
                //  Deleted first lock in node
                //

                if (Node->Locks.Next == NULL) {

                    //
                    // Just deleted last lock on this node, so free it
                    //

                    LockQueue->SharedLockTree = RtlDelete(SplayLinks);

                    FsRtlFreeLockTreeNode(Node);

                    Node = NULL;
                }

                if (LockInfo->LowestLockOffset != 0xffffffff &&
                    LockInfo->LowestLockOffset == Lock->LockInfo.StartingByte.LowPart) {

                    //
                    //  This was the lowest lock in the trees, reset the lowest lock offset
                    //

                    FsRtlPrivateResetLowestLockOffset(LockInfo);
                }
            }

            //
            //  Now the fun begins. It may be the case that the lock just snipped from
            //  the chain was gluing locks at this node together, so we need to
            //  inspect the chain.
            //

            if (Node) {

                FsRtlSplitLocks(Node, pLink, &Lock->LockInfo.EndingByte, &MaxOffset);
            }
            
            if (!IgnoreUnlockRoutine && LockInfo->UnlockRoutine != NULL) {

                FsRtlReleaseLockQueue( LockQueue, OldIrql );

                LockInfo->UnlockRoutine( Context, &Lock->LockInfo );

                FsRtlReacquireLockQueue( LockInfo, LockQueue, &OldIrql );

            }

            FsRtlFreeSharedLock( Lock );

            //
            //  See if there are additional waiting locks that we can
            //  now release.
            //

            if (CheckForWaiters && LockQueue->WaitingLocks.Next) {

                FsRtlPrivateCheckWaitingLocks( LockInfo, LockQueue, OldIrql );
            }

            FsRtlReleaseLockQueue( LockQueue, OldIrql );

            return STATUS_SUCCESS;
        }

        if ((ULONGLONG)Lock->LockInfo.StartingByte.QuadPart > (ULONGLONG)AlignedFileOffset.QuadPart) {

            //
            //  The current lock begins at a byte offset greater than the range we are seeking
            //  to unlock. This range must therefore not be locked.
            //

            break;
        }

        if ((ULONGLONG)MaxOffset.QuadPart < (ULONGLONG)Lock->LockInfo.EndingByte.QuadPart) {

            //
            // Maintain the maximum offset affected by locks up to this point.
            //

            MaxOffset.QuadPart = Lock->LockInfo.EndingByte.QuadPart;
        }
    }

    //
    //  Lock was not found, return to our caller
    //

    FsRtlReleaseLockQueue(LockQueue, OldIrql);
    return STATUS_RANGE_NOT_LOCKED;
}


NTSTATUS
FsRtlFastUnlockSingleExclusive (
    IN PLOCK_INFO LockInfo,
    IN PFILE_OBJECT FileObject,
    IN LARGE_INTEGER UNALIGNED *FileOffset,
    IN PLARGE_INTEGER Length,
    IN PEPROCESS ProcessId,
    IN ULONG Key,
    IN PVOID Context OPTIONAL,
    IN BOOLEAN IgnoreUnlockRoutine,
    IN BOOLEAN CheckForWaiters
    )

/*++

Routine Description:

    This routine performs an Unlock Single operation on the exclusive locks
    associated with the specified lock data.  Only the lock with a matching
    file object, process id, key, and range is freed.

Arguments:

    LockInfo - Supplies the lock data being operated on

    FileObject - Supplies the file object holding the locks

    FileOffset - Supplies the offset to be unlocked

    Length - Supplies the length in bytes to be unlocked

    ProcessId - Supplies the process Id to use in this operation

    Key - Supplies the key to use in this operation

    Context - Optionally supplies context to use when completing Irps

    IgnoreUnlockRoutine - inidicates that the filelock's unlock routine
        should not be called on lock removal (for removal of aborted
        locks)

    CheckForWaiters - If true check for possible waiting locks, caused
        by freeing the locked range

Return Value:

    NTSTATUS - The completion status for this operation

--*/

{
    KIRQL                   OldIrql;
    PLOCK_QUEUE             LockQueue;
    PRTL_SPLAY_LINKS        SplayLinks;
    LARGE_INTEGER           EndingOffset;
    PEX_LOCK                Lock;
    LARGE_INTEGER           AlignedFileOffset;

    //
    //  General case - search the outstanding lock queue for this lock
    //

    AlignedFileOffset = *FileOffset;

    LockQueue = &LockInfo->LockQueue;

    FsRtlAcquireLockQueue(LockQueue, &OldIrql);

    //
    //  Check for the no locks currently held
    //

    if (LockQueue->ExclusiveLockTree == NULL) {

        FsRtlReleaseLockQueue( LockQueue, OldIrql );

        return STATUS_RANGE_NOT_LOCKED;
    }

    //
    //  Find the overlapping lock, if it exists. Note that this is usually
    //  the only lock we need to check since we are assuming this is an
    //  existing lock. However, if the lock is a zero length lock we will
    //  have a run of locks to check.
    //

    EndingOffset.QuadPart = (ULONGLONG)AlignedFileOffset.QuadPart + (ULONGLONG)Length->QuadPart - 1;

    for (SplayLinks = FsRtlFindFirstOverlappingExclusiveNode( LockQueue->ExclusiveLockTree,
                                                              &AlignedFileOffset,
                                                              &EndingOffset,
                                                              NULL,
                                                              NULL );
         SplayLinks;
         SplayLinks = RtlRealSuccessor(SplayLinks)) {

        Lock = CONTAINING_RECORD( SplayLinks, EX_LOCK, Links );
    
        if ((Lock->LockInfo.FileObject == FileObject) &&
            (Lock->LockInfo.ProcessId == ProcessId) &&
            (Lock->LockInfo.Key == Key) &&
            ((ULONGLONG)Lock->LockInfo.StartingByte.QuadPart == (ULONGLONG)AlignedFileOffset.QuadPart) &&
            ((ULONGLONG)Lock->LockInfo.Length.QuadPart == (ULONGLONG)Length->QuadPart)) {
    
            DebugTrace(0, Dbg, "Ex Found one to unlock\n", 0);
    
            //
            //  We have an exact match so now is the time to delete this
            //  lock.  Remove the lock from the list, then call the
            //  optional unlock routine, then delete the lock.
            //
    
            if (FileObject->LastLock == &Lock->LockInfo) {
    
                FileObject->LastLock = NULL;
            }
    
            //
            //  Snip the deleted lock
            //
    
            LockQueue->ExclusiveLockTree = RtlDelete(&Lock->Links);
    
            if (LockInfo->LowestLockOffset != 0xffffffff &&
                LockInfo->LowestLockOffset == Lock->LockInfo.StartingByte.LowPart) {
    
                //
                //  This was the lowest lock in the tree, so reset the lowest lock
                //  offset
                //
    
                FsRtlPrivateResetLowestLockOffset(LockInfo);
            }
            
            if (!IgnoreUnlockRoutine && LockInfo->UnlockRoutine != NULL) {
    
                FsRtlReleaseLockQueue( LockQueue, OldIrql );
    
                LockInfo->UnlockRoutine( Context, &Lock->LockInfo );
    
                FsRtlReacquireLockQueue( LockInfo, LockQueue, &OldIrql );
    
            }
    
            FsRtlFreeExclusiveLock( Lock );

            //
            //  See if there are additional waiting locks that we can
            //  now release.
            //
    
            if (CheckForWaiters && LockQueue->WaitingLocks.Next) {
    
                FsRtlPrivateCheckWaitingLocks( LockInfo, LockQueue, OldIrql );
            }
    
            FsRtlReleaseLockQueue( LockQueue, OldIrql );
    
            return STATUS_SUCCESS;
        }

        if ((ULONGLONG)Lock->LockInfo.StartingByte.QuadPart > (ULONGLONG)AlignedFileOffset.QuadPart) {

            //
            //  The current lock begins at a byte offset greater than the range we are seeking
            //  to unlock. This range must therefore not be locked.
            //
            
            break;
        }
    }

    //
    //  Lock was not found, return to our caller
    //

    FsRtlReleaseLockQueue(LockQueue, OldIrql);
    return STATUS_RANGE_NOT_LOCKED;
}


NTSTATUS
FsRtlFastUnlockAll (
    IN PFILE_LOCK FileLock,
    IN PFILE_OBJECT FileObject,
    IN PEPROCESS ProcessId,
    IN PVOID Context OPTIONAL
    )

/*++

Routine Description:

    This routine performs an Unlock all operation on the current locks
    associated with the specified file lock.  Only those locks with
    a matching file object and process id are freed.

Arguments:

    FileLock - Supplies the file lock being freed.

    FileObject - Supplies the file object associated with the file lock

    ProcessId - Supplies the Process Id assoicated with the locks to be
        freed

    Context - Supplies an optional context to use when completing waiting
        lock irps.

Return Value:

    None

--*/

{
    return FsRtlPrivateFastUnlockAll(
                FileLock,
                FileObject,
                ProcessId,
                0, FALSE,           // No Key
                Context );
}


NTSTATUS
FsRtlFastUnlockAllByKey (
    IN PFILE_LOCK FileLock,
    IN PFILE_OBJECT FileObject,
    IN PEPROCESS ProcessId,
    IN ULONG Key,
    IN PVOID Context OPTIONAL
    )

/*++

Routine Description:

    This routine performs an Unlock All by Key operation on the current locks
    associated with the specified file lock.  Only those locks with
    a matching file object, process id, and key are freed.  The input Irp
    is completed by this procedure

Arguments:

    FileLock - Supplies the file lock being freed.

    FileObject - Supplies the file object associated with the file lock

    ProcessId - Supplies the Process Id assoicated with the locks to be
        freed

    Key - Supplies the Key to use in this operation

    Context - Supplies an optional context to use when completing waiting
        lock irps.

Return Value:

    NTSTATUS - The return status for the operation.

--*/

{
    return FsRtlPrivateFastUnlockAll(
                FileLock,
                FileObject,
                ProcessId,
                Key, TRUE,
                Context );

}


//
//  Local Support Routine
//

BOOLEAN
FsRtlPrivateLock (
    IN PFILE_LOCK FileLock,
    IN PFILE_OBJECT FileObject,
    IN PLARGE_INTEGER FileOffset,
    IN PLARGE_INTEGER Length,
    IN PEPROCESS ProcessId,
    IN ULONG Key,
    IN BOOLEAN FailImmediately,
    IN BOOLEAN ExclusiveLock,
    OUT PIO_STATUS_BLOCK Iosb,
    IN PIRP Irp OPTIONAL,
    IN PVOID Context,
    IN BOOLEAN AlreadySynchronized
    )

/*++

Routine Description:

    This routine preforms a lock operation request.  This handles both the fast
    get lock and the Irp based get lock.  If the Irp is supplied then
    this routine will either complete the Irp or enqueue it as a waiting
    lock request.

Arguments:

    FileLock - Supplies the File Lock to work against

    FileObject - Supplies the file object used in this operation

    FileOffset - Supplies the file offset used in this operation

    Length - Supplies the length used in this operation

    ProcessId - Supplies the process ID used in this operation

    Key - Supplies the key used in this operation

    FailImmediately - Indicates if the request should fail immediately
        if the lock cannot be granted.

    ExclusiveLock - Indicates if this is a request for an exclusive or
        shared lock

    Iosb - Receives the Status if this operation is successful

    Context - Supplies the context with which to complete Irp with

    AlreadySynchronized - Indicates that the caller has already synchronized
        access to the file lock so the fields in the file lock and
        be updated without further locking, but not the queues.

Return Value:

    BOOLEAN - TRUE if this operation completed and FALSE otherwise.

--*/

{
    BOOLEAN Results;
    BOOLEAN AccessGranted;

    PLOCK_INFO  LockInfo;
    PLOCK_QUEUE LockQueue;
    KIRQL       OldIrql;
    FILE_LOCK_INFO FileLockInfo;

    DebugTrace(+1, Dbg, "FsRtlPrivateLock, FileLock = %08lx\n", FileLock);

    if ((LockInfo = (PLOCK_INFO) FileLock->LockInformation) == NULL) {
        DebugTrace(+2, Dbg, "FsRtlPrivateLock, New LockInfo required\n", 0);

        //
        // No lock information on this FileLock, create the structure.  If the irp
        // is null then this is being called via the fast call method.
        //
        //

        if (!FsRtlPrivateInitializeFileLock (FileLock, (BOOLEAN)(Irp == NULL))) {

            return FALSE;
        }

        //
        // Set flag so file locks will be checked on the fast io
        // code paths
        //

        FileLock->FastIoIsQuestionable = TRUE;

        //
        // Pickup allocated lockinfo structure
        //

        LockInfo = (PLOCK_INFO) FileLock->LockInformation;
    }

    //
    // Assume success and build LockData structure prior to acquiring
    // the lock queue spinlock.  (mp perf enhancement)
    //

    FileLockInfo.StartingByte = *FileOffset;
    FileLockInfo.Length = *Length;
    (ULONGLONG)FileLockInfo.EndingByte.QuadPart =
            (ULONGLONG)FileLockInfo.StartingByte.QuadPart + (ULONGLONG)FileLockInfo.Length.QuadPart - 1;

    FileLockInfo.Key = Key;
    FileLockInfo.FileObject = FileObject;
    FileLockInfo.ProcessId = ProcessId;
    FileLockInfo.ExclusiveLock = ExclusiveLock;

    LockQueue = &LockInfo->LockQueue;

    //
    //  Now we need to actually run through our current lock queue so if
    //  we didn't already grab the spinlock then grab it now
    //

    FsRtlAcquireLockQueue(LockQueue, &OldIrql);

    try {
        //ASSERTMSG("LockCount/CurrentLockQueue disagree ", LockInfo->CurrentLockQueue.Next != NULL));

        //
        //  Case on whether we're trying to take out an exclusive lock or
        //  a shared lock.  And in both cases try to get appropriate access.
        //

        if (ExclusiveLock) {

            DebugTrace(0, Dbg, "Check for write access\n", 0);

            AccessGranted = FsRtlPrivateCheckForExclusiveLockAccess(
                                LockQueue,
                                &FileLockInfo );

        } else {

            DebugTrace(0, Dbg, "Check for read access\n", 0);

            AccessGranted = FsRtlPrivateCheckForSharedLockAccess(
                                LockQueue,
                                &FileLockInfo );
        }

        //
        //  Now AccessGranted tells us whether we can really get the access
        //  for the range we want
        //

        if (!AccessGranted) {

            DebugTrace(0, Dbg, "We do not have access\n", 0);

            //
            //  We cannot read/write to the range, so we cannot take out
            //  the lock.  Now if the user wanted to fail immediately then
            //  we'll complete the Irp, otherwise we'll enqueue this Irp
            //  to the waiting lock queue
            //

            if (FailImmediately) {

                //
                //  Set our status and return, the finally clause will
                //  complete the request
                //

                DebugTrace(0, Dbg, "And we fail immediately\n", 0);

                Iosb->Status = STATUS_LOCK_NOT_GRANTED;
                try_return( Results = TRUE );

            } else if (ARGUMENT_PRESENT(Irp)) {

                PWAITING_LOCK WaitingLock;

                DebugTrace(0, Dbg, "And we enqueue the Irp for later\n", 0);

                //
                //  Allocate a new waiting record, set it to point to the
                //  waiting Irp, and insert it in the tail of the waiting
                //  locks queue
                //

                FsRtlAllocateWaitingLock( &WaitingLock );

                WaitingLock->Irp = Irp;
                WaitingLock->Context = Context;
                IoMarkIrpPending( Irp );

                //
                // Add WaitingLock WaitingLockQueue
                //

                WaitingLock->Link.Next = NULL;
                if (LockQueue->WaitingLocks.Next == NULL) {

                    //
                    // Create new list
                    //

                    LockQueue->WaitingLocks.Next = &WaitingLock->Link;
                    LockQueue->WaitingLocksTail.Next = &WaitingLock->Link;

                } else {

                    //
                    // Add waiter to tail of list
                    //

                    LockQueue->WaitingLocksTail.Next->Next = &WaitingLock->Link;
                    LockQueue->WaitingLocksTail.Next = &WaitingLock->Link;
                }


                //
                //  Setup IRP in case it's canceled - then set the
                //  IRP's cancel routine
                //

                Irp->IoStatus.Information = (ULONG)LockInfo;
                IoSetCancelRoutine( Irp, FsRtlPrivateCancelFileLockIrp );

                if (Irp->Cancel) {

                    //
                    // Irp is in the canceled state; however we set the
                    // cancel routine without using IoAcquireCancleSpinLock.
                    // We need to synchronize with the Io system and recheck
                    // the irp to see if the cancel routine needs invoked
                    //

                    FsRtlReleaseLockQueue(LockQueue, OldIrql);
                    IoAcquireCancelSpinLock( &Irp->CancelIrql );

                    if (Irp->CancelRoutine == FsRtlPrivateCancelFileLockIrp) {

                        //
                        // Irp's cancel routine was not called, clear
                        // it in the irp and do it now
                        //
                        // IoCancelSpinLock is freed in the cancel routine
                        //

                        IoSetCancelRoutine( Irp, NULL );
                        FsRtlPrivateCancelFileLockIrp( NULL, Irp );

                    } else {

                        //
                        // The irp's cancel routine has/is being invoked
                        // by the Io subsystem.
                        //

                        IoReleaseCancelSpinLock( Irp->CancelIrql );
                    }

                    FsRtlReacquireLockQueue(LockInfo, LockQueue, &OldIrql);
                }

                Iosb->Status = STATUS_PENDING;
                try_return( Results = TRUE );

            } else {

                try_return( Results = FALSE );
            }
        }

        DebugTrace(0, Dbg, "We have access\n", 0);

        FsRtlPrivateInsertLock( LockInfo, FileObject, &FileLockInfo );

        //
        //  Get ready to ready to our caller
        //

        Iosb->Status = STATUS_SUCCESS;
        Results = TRUE;

    try_exit: NOTHING;
    } finally {

        FsRtlReleaseLockQueue(LockQueue, OldIrql);

        //
        //  Complete the request provided we were given one and it is not a pending status
        //

        if (ARGUMENT_PRESENT(Irp) && (Iosb->Status != STATUS_PENDING)) {

            NTSTATUS NewStatus;

            //
            //  We must reference the fileobject for the case that the IRP completion
            //  fails and we need to lift the lock.  Although the only reason we have
            //  to touch the fileobject in the remove case is to unset the LastLock field,
            //  we have no way of knowing if we will race with a reference count drop
            //  and lose.
            //

            ObReferenceObject( FileObject );

            //
            //  Complete the request, if the don't get back success then
            //  we need to possibly remove the lock that we just
            //  inserted.
            //

            FsRtlCompleteLockIrp(
                LockInfo,
                Context,
                Irp,
                Iosb->Status,
                &NewStatus,
                FileObject );

            if (!NT_SUCCESS(NewStatus)  &&  NT_SUCCESS(Iosb->Status) ) {

                //
                // Irp failed, remove the lock which was added
                //

                FsRtlPrivateRemoveLock (
                    LockInfo,
                    &FileLockInfo,
                    TRUE );
            }

            //
            //  Lift our private reference to the fileobject. This may induce deletion.
            //

            ObDereferenceObject( FileObject );

            Iosb->Status = NewStatus;
        }

        DebugTrace(-1, Dbg, "FsRtlPrivateLock -> %08lx\n", Results);
    }

    //
    //  and return to our caller
    //

    return Results;
}


//
//  Internal Support Routine
//

VOID
FsRtlPrivateInsertLock (
    IN PLOCK_INFO LockInfo,
    IN PFILE_OBJECT FileObject,
    IN PFILE_LOCK_INFO FileLockInfo
    )

/*++

Routine Description:

    This routine fills in a new lock record of the appropriate type and inserts
    it into the lock information.

Arguments:

    LockInfo - Supplies the lock being modified

    FileObject - The associated file object to update hints in

    FileLockInfo - Supplies the new lock data to add to the lock queue

Return Value:

    None.

--*/

{
    //
    //  Fix up the lowest lock offset if need be
    //

    if ((ULONGLONG)FileLockInfo->StartingByte.QuadPart < (ULONGLONG)LockInfo->LowestLockOffset) {

        ASSERT( FileLockInfo->StartingByte.HighPart == 0 );
        LockInfo->LowestLockOffset = FileLockInfo->StartingByte.LowPart;
    }

    if (FileLockInfo->ExclusiveLock) {

        PEX_LOCK ExLock;

        FsRtlAllocateExclusiveLock( &ExLock );
        ExLock->LockInfo = *FileLockInfo;

        FsRtlPrivateInsertExclusiveLock( &LockInfo->LockQueue, ExLock );

        FileObject->LastLock = &ExLock->LockInfo;

    } else {

        PSH_LOCK ShLock;

        FsRtlAllocateSharedLock( &ShLock );
        ShLock->LockInfo = *FileLockInfo;

        FsRtlPrivateInsertSharedLock( &LockInfo->LockQueue, ShLock );

        FileObject->LastLock = &ShLock->LockInfo;
    }

    return;
}


//
//  Internal Support Routine
//

VOID
FsRtlPrivateInsertSharedLock (
    IN PLOCK_QUEUE LockQueue,
    IN PSH_LOCK NewLock
    )

/*++

Routine Description:

    This routine adds a new shared lock record to the File lock's current
    lock queue. Locks are inserted into nodes ordered by their starting byte.

Arguments:

    LockQueue - Supplies the lock queue being modified

    NewLock - Supplies the new shared lock to add to the lock queue

Return Value:

    None.

--*/
{
    PSINGLE_LIST_ENTRY pLink, Link;
    PRTL_SPLAY_LINKS OverlappedSplayLinks, ParentSplayLinks;
    PLOCKTREE_NODE Node, NextNode;
    PSH_LOCK NextLock;
    BOOLEAN GreaterThan;

    OverlappedSplayLinks = FsRtlFindFirstOverlappingSharedNode( LockQueue->SharedLockTree,
                                                                &NewLock->LockInfo.StartingByte,
                                                                &NewLock->LockInfo.EndingByte,
                                                                &ParentSplayLinks,
                                                                &GreaterThan );

    if (OverlappedSplayLinks == NULL) {

        //
        //  Simple insert case, build a new node
        //

        FsRtlAllocateLockTreeNode(&NextNode);
        RtlInitializeSplayLinks(&NextNode->Links);

        NextNode->Locks.Next = NextNode->Tail.Next = &NewLock->Link;
        NextNode->Extent = (ULONGLONG)NewLock->LockInfo.EndingByte.QuadPart;
        NewLock->Link.Next = NULL;

        if (ParentSplayLinks) {

            //
            //  We have a real parent node in the tree
            //

            if (GreaterThan) {
    
                ASSERT(RtlLeftChild(ParentSplayLinks) == NULL);
                RtlInsertAsLeftChild(ParentSplayLinks, &NextNode->Links);

            } else {

                ASSERT(RtlRightChild(ParentSplayLinks) == NULL);
                RtlInsertAsRightChild(ParentSplayLinks, &NextNode->Links);
            }

            //
            //  Splay all new nodes in the tree
            //

            LockQueue->SharedLockTree = RtlSplay(&NextNode->Links);

        } else {

            //
            //  First node in the tree
            //

            LockQueue->SharedLockTree = &NextNode->Links;
        }

        return;
    }

    //
    //  Search down the overlapped node finding the position for the new lock
    //

    Node = CONTAINING_RECORD( OverlappedSplayLinks, LOCKTREE_NODE, Links );

    for (pLink = &Node->Locks;
         (Link = pLink->Next) != NULL;
         pLink = Link) {

        PSH_LOCK Lock;

        Lock = CONTAINING_RECORD( Link, SH_LOCK, Link );

        //
        //  If the new lock can go right before the lock already in the
        //  list then we break out of the loop
        //
        //  if (NewLock->StartingByte <= Lock->StartingByte) ...
        //

        if ((ULONGLONG)NewLock->LockInfo.StartingByte.QuadPart <= (ULONGLONG)Lock->LockInfo.StartingByte.QuadPart) {

            break;
        }
    }

    //
    //  At this point pLink points to the record that comes right after
    //  the new lock that we're inserting so we can simply push the
    //  newlock into the entrylist
    //

    DebugTrace(0, Dbg, "InsertSharedLock, Insert Before = %08lx\n", Link);

    if (pLink->Next == NULL) {

        //
        //    Adding onto the tail of the list
        //

        Node->Tail.Next = &NewLock->Link;
    }

    NewLock->Link.Next = pLink->Next;
    pLink->Next = &NewLock->Link;

    //
    //  And splay the node we inserted into
    //

    LockQueue->SharedLockTree = RtlSplay(OverlappedSplayLinks);

    if ((ULONGLONG)NewLock->LockInfo.EndingByte.QuadPart > Node->Extent) {

        //
        //  The new lock extends the range of this node, so fix up the extent
        //

        Node->Extent = NewLock->LockInfo.EndingByte.QuadPart;

        //
        //  Walk across the remainder of the tree integrating newly overlapping
        //  nodes into the node we just inserted the new lock into
        //
    
        ParentSplayLinks = OverlappedSplayLinks;
    
        for (OverlappedSplayLinks = RtlRealSuccessor(ParentSplayLinks);
             OverlappedSplayLinks;
             OverlappedSplayLinks = RtlRealSuccessor(ParentSplayLinks)) {

            NextNode = CONTAINING_RECORD( OverlappedSplayLinks, LOCKTREE_NODE, Links );
            NextLock = CONTAINING_RECORD( NextNode->Locks.Next, SH_LOCK, Link );

            if ((ULONGLONG)NextLock->LockInfo.StartingByte.QuadPart > Node->Extent) {

                //
                //  This node is not overlapped, so stop
                //
    
                break;
            }

            //
            //  Integrate the locks in this node into our list
            //

            Node->Tail.Next->Next = NextNode->Locks.Next;
            Node->Tail.Next = NextNode->Tail.Next;

            if (NextNode->Extent > Node->Extent) {

                Node->Extent = NextNode->Extent;
            }

            //
            //  Free the now empty node.
            //

            RtlDeleteNoSplay(OverlappedSplayLinks, &LockQueue->SharedLockTree);

            FsRtlFreeLockTreeNode(NextNode);
        }
    }

    //
    //  And return to our caller
    //

    return;
}


//
//  Internal Support Routine
//

VOID
FsRtlPrivateInsertExclusiveLock (
    IN PLOCK_QUEUE LockQueue,
    IN PEX_LOCK NewLock
    )

/*++

Routine Description:

    This routine adds a new exclusive lock record to the File lock's current
    lock queue.

Arguments:

    LockQueue - Supplies the lock queue being modified

    NewLock - Supplies the new exclusive lock to add to the lock queue

Return Value:

    None.

--*/

{
    PRTL_SPLAY_LINKS OverlappedSplayLinks, ParentSplayLinks;
    BOOLEAN GreaterThan;

    OverlappedSplayLinks = FsRtlFindFirstOverlappingExclusiveNode( LockQueue->ExclusiveLockTree,
                                                                   &NewLock->LockInfo.StartingByte,
                                                                   &NewLock->LockInfo.EndingByte,
                                                                   &ParentSplayLinks,
                                                                   &GreaterThan );

    //
    //  This is the exclusive tree. Nothing can overlap (caller is supposed to insure this) unless
    //  the lock is a zero length lock, in which case we just insert it - still.
    //

    ASSERT(!OverlappedSplayLinks || NewLock->LockInfo.Length.QuadPart == 0);

    //
    //  Simple insert ...
    //

    RtlInitializeSplayLinks(&NewLock->Links);

    if (OverlappedSplayLinks) {

        //
        //  With zero length locks we have OverlappedSplayLinks at the starting point
        //  of a run of zero length locks, so we have to e flexible about where the new
        //  node is inserted.
        //

        if (RtlRightChild(OverlappedSplayLinks)) {

            //
            //  Right slot taken. We can use the left slot or go to the sucessor's left slot
            //

            if (RtlLeftChild(OverlappedSplayLinks)) {

                ASSERT(RtlLeftChild(RtlRealSuccessor(OverlappedSplayLinks)) == NULL);
                RtlInsertAsLeftChild(RtlRealSuccessor(OverlappedSplayLinks), &NewLock->Links);

            } else {

                RtlInsertAsLeftChild(OverlappedSplayLinks, &NewLock->Links);
            }


        } else {

            RtlInsertAsRightChild(OverlappedSplayLinks, &NewLock->Links);
        }

    } else if (ParentSplayLinks) {

        //
        //  We have a real parent node in the tree, and must be at a leaf since
        //  there was no overlap
        //

        if (GreaterThan) {

            ASSERT(RtlLeftChild(ParentSplayLinks) == NULL);
            RtlInsertAsLeftChild(ParentSplayLinks, &NewLock->Links);

        } else {

            ASSERT(RtlRightChild(ParentSplayLinks) == NULL);
            RtlInsertAsRightChild(ParentSplayLinks, &NewLock->Links);
        }

    } else {

        //
        //  First node in the tree
        //

        LockQueue->ExclusiveLockTree = &NewLock->Links;
    }

    //
    //  And return to our caller
    //

    return;
}


//
//  Internal Support Routine
//

VOID
FsRtlPrivateCheckWaitingLocks (
    IN PLOCK_INFO   LockInfo,
    IN PLOCK_QUEUE  LockQueue,
    IN KIRQL        OldIrql
    )

/*++

Routine Description:

    This routine checks to see if any of the current waiting locks are now
    be satisfied, and if so it completes their IRPs.

Arguments:

    LockInfo - LockInfo which LockQueue is member of

    LockQueue - Supplies queue which needs to be checked

    OldIrql - Irql to restore when LockQueue is released

Return Value:

    PLOCK_QUEUE - Normally returns the input LockQueue, but if we switch
        from multiple queues to a single queue while this routine is
        running, may return a different queue.

--*/

{
    PSINGLE_LIST_ENTRY *pLink, Link;
    NTSTATUS    NewStatus;

    pLink = &LockQueue->WaitingLocks.Next;
    while ((Link = *pLink) != NULL) {

        PWAITING_LOCK WaitingLock;

        PIRP Irp;
        PIO_STACK_LOCATION IrpSp;

        BOOLEAN AccessGranted;

        FILE_LOCK_INFO FileLockInfo;

        //
        //  Get a pointer to the waiting lock record
        //

        WaitingLock = CONTAINING_RECORD( Link, WAITING_LOCK, Link );

        DebugTrace(0, Dbg, "FsRtlCheckWaitingLocks, Loop top, WaitingLock = %08lx\n", WaitingLock);

        //
        //  Get a local copy of the necessary fields we'll need to use
        //

        Irp = WaitingLock->Irp;
        IrpSp = IoGetCurrentIrpStackLocation( Irp );

        FileLockInfo.StartingByte  = IrpSp->Parameters.LockControl.ByteOffset;
        FileLockInfo.Length        = *IrpSp->Parameters.LockControl.Length;
        (ULONGLONG)FileLockInfo.EndingByte.QuadPart =
            (ULONGLONG)FileLockInfo.StartingByte.QuadPart + (ULONGLONG)FileLockInfo.Length.QuadPart - 1;

        FileLockInfo.FileObject    = IrpSp->FileObject;
        FileLockInfo.ProcessId     = IoGetRequestorProcess( Irp );
        FileLockInfo.Key           = IrpSp->Parameters.LockControl.Key;
        FileLockInfo.ExclusiveLock = BooleanFlagOn(IrpSp->Flags, SL_EXCLUSIVE_LOCK);

        //
        //  Now case on whether we're trying to take out an exclusive lock or
        //  a shared lock.  And in both cases try to get the appropriate access
        //  For the exclusive case we send in a NULL file object and process
        //  id, this will ensure that the lookup does not give us write
        //  access through an exclusive lock.
        //

        if (FileLockInfo.ExclusiveLock) {

            DebugTrace(0, Dbg, "FsRtlCheckWaitingLocks do we have write access?\n", 0);

            AccessGranted = FsRtlPrivateCheckForExclusiveLockAccess(
                                LockQueue,
                                &FileLockInfo );
        } else {

            DebugTrace(0, Dbg, "FsRtlCheckWaitingLocks do we have read access?\n", 0);

            AccessGranted = FsRtlPrivateCheckForSharedLockAccess(
                                LockQueue,
                                &FileLockInfo );

        }

        //
        //  Now AccessGranted tells us whether we can really get the
        //  access for the range we want
        //

        if (AccessGranted) {

            DebugTrace(0, Dbg, "FsRtlCheckWaitingLocks now has access\n", 0);

            //
            //  Clear the cancel routine
            //

            IoSetCancelRoutine( Irp, NULL );

            FsRtlPrivateInsertLock( LockInfo, IrpSp->FileObject, &FileLockInfo );

            //
            //  Now we need to remove this granted waiter and complete
            //  it's irp.
            //

            *pLink = Link->Next;
            if (Link == LockQueue->WaitingLocksTail.Next) {
                LockQueue->WaitingLocksTail.Next = (PSINGLE_LIST_ENTRY) pLink;
            }

            //
            // Release LockQueue and complete this waiter
            //

            FsRtlReleaseLockQueue(LockQueue, OldIrql);

            //
            //  Reference the fileobject over the completion attempt so we can have a
            //  chance to cleanup safely if we fail
            //

            ObReferenceObject( FileLockInfo.FileObject );

            //
            //  Now we can complete the IRP, if we don't get back success
            //  from the completion routine then we remove the lock we just
            //  inserted.
            //

            FsRtlCompleteLockIrp(
                LockInfo,
                WaitingLock->Context,
                Irp,
                STATUS_SUCCESS,
                &NewStatus,
                FileLockInfo.FileObject );

            if (!NT_SUCCESS(NewStatus)) {

                //
                // Irp was not sucessfull, remove lock
                //

                FsRtlPrivateRemoveLock (
                    LockInfo,
                    &FileLockInfo,
                    FALSE );
            }

            //
            //  Drop our private reference to the fileobject
            //

            ObDereferenceObject( FileLockInfo.FileObject );

            //
            // Re-acquire queue lock
            //

            FsRtlReacquireLockQueue(LockInfo, LockQueue, &OldIrql);

            //
            // Start scan over from begining
            //

            pLink = &LockQueue->WaitingLocks.Next;


            //
            //  Free up pool
            //

            FsRtlFreeWaitingLock( WaitingLock );


        } else {

            DebugTrace( 0, Dbg, "FsRtlCheckWaitingLocks still no access\n", 0);

            //
            // Move to next lock
            //

            pLink = &Link->Next;
        }

    }

    //
    //  And return to our caller
    //

    return;
}


BOOLEAN
FsRtlPrivateCheckForExclusiveLockAccess (
    IN PLOCK_QUEUE LockQueue,
    IN PFILE_LOCK_INFO FileLockInfo
    )
/*++

Routine Description:

    This routine checks to see if the caller can get an exclusive lock on
    the indicated range due to file locks in the passed in lock queue.

    Assumes Lock queue SpinLock is held by caller

Arguments:

    LockQueue - Queue which needs to be checked for collision

    FileLockInfo - Lock which is being checked


Return Value:

    BOOLEAN - TRUE if the indicated user can place the exclusive lock over the
        entire specified byte range, and FALSE otherwise

--*/

{
    PRTL_SPLAY_LINKS SplayLinks, LastSplayLinks = NULL;
    PLOCKTREE_NODE Node;
    PSH_LOCK ShLock;
    PEX_LOCK ExLock;

    if (LockQueue->SharedLockTree &&
        (SplayLinks = FsRtlFindFirstOverlappingSharedNode( LockQueue->SharedLockTree,
                                                           &FileLockInfo->StartingByte,
                                                           &FileLockInfo->EndingByte,
                                                           &LastSplayLinks, NULL))) {

        Node = CONTAINING_RECORD(SplayLinks, LOCKTREE_NODE, Links);
        ShLock = CONTAINING_RECORD(Node->Locks.Next, SH_LOCK, Link);

        if (FileLockInfo->Length.QuadPart || ShLock->LockInfo.Length.QuadPart) {

            //
            //  If we are checking a nonzero extent and overlapped, it is fatal. If we
            //  are checking a zero extent and overlapped a nonzero extent, it is fatal.
            //
    
            return FALSE;
        }
    }

    if (LastSplayLinks) {

        LockQueue->SharedLockTree = RtlSplay(LastSplayLinks);
        LastSplayLinks = NULL;
    }

    if (LockQueue->ExclusiveLockTree &&
        (SplayLinks = FsRtlFindFirstOverlappingExclusiveNode( LockQueue->ExclusiveLockTree,
                                                              &FileLockInfo->StartingByte,
                                                              &FileLockInfo->EndingByte,
                                                              &LastSplayLinks, NULL))) {

        ExLock = CONTAINING_RECORD(SplayLinks, EX_LOCK, Links);

        if (FileLockInfo->Length.QuadPart || ExLock->LockInfo.Length.QuadPart) {

            //
            //  If we are checking a nonzero extent and overlapped, it is fatal. If we
            //  are checking a zero extent and overlapped a nonzero extent, it is fatal.
            //
    
            return FALSE;
        }
    }

    if (LastSplayLinks) {

        LockQueue->ExclusiveLockTree = RtlSplay(LastSplayLinks);
    }

    //
    //  We searched the entire range without a conflict so we can grant
    //  the exclusive lock
    //

    return TRUE;
}


BOOLEAN
FsRtlPrivateCheckForSharedLockAccess (
    IN PLOCK_QUEUE LockQueue,
    IN PFILE_LOCK_INFO FileLockInfo
    )
/*++

Routine Description:

    This routine checks to see if the caller can get a shared lock on
    the indicated range due to file locks in the passed in lock queue.

    Assumes Lock queue SpinLock is held by caller

Arguments:

    LockQueue - Queue which needs to be checked for collision

    FileLockInfo - Lock which is being checked

Arguments:

Return Value:

    BOOLEAN - TRUE if the indicated user can place the shared lock over
        entire specified byte range, and FALSE otherwise

--*/

{
    PEX_LOCK Lock;
    PRTL_SPLAY_LINKS SplayLinks, LastSplayLinks;
    BOOLEAN Status = TRUE;

    //
    // If there are no exclusive locks, this is quick ...
    //

    if (LockQueue->ExclusiveLockTree == NULL) {

        return TRUE;
    }

    //
    //  No lock in the shared lock tree can prevent access, so just search the exclusive
    //  tree for conflict.
    //

    for (SplayLinks = FsRtlFindFirstOverlappingExclusiveNode( LockQueue->ExclusiveLockTree,
                                                              &FileLockInfo->StartingByte,
                                                              &FileLockInfo->EndingByte,
                                                              &LastSplayLinks, NULL);
         SplayLinks;
         SplayLinks = RtlRealSuccessor(SplayLinks)) {

        Lock = CONTAINING_RECORD( SplayLinks, EX_LOCK, Links );

        if ((ULONGLONG)Lock->LockInfo.StartingByte.QuadPart > (ULONGLONG)FileLockInfo->EndingByte.QuadPart) {

            //
            //  This node is covering a range greater than the range we care about,
            //  so we're done
            //

            break;
        }

        //
        //  We may not be able to grant the request if the fileobject, processid,
        //  and key do not match.
        //
        
        if ((Lock->LockInfo.FileObject != FileLockInfo->FileObject) ||
             (Lock->LockInfo.ProcessId != FileLockInfo->ProcessId) ||
             (Lock->LockInfo.Key != FileLockInfo->Key)) {

            //
            //  We have a mismatch between caller and owner. It is ok not to conflict
            //  if the caller and owner will have/have zero length locks (zero length
            //  locks cannot conflict).
            //

            if (FileLockInfo->Length.QuadPart || Lock->LockInfo.Length.QuadPart) {

                Status = FALSE;
                break;
            }
        }
    }

    if (LastSplayLinks) {

        LockQueue->ExclusiveLockTree = RtlSplay(LastSplayLinks);
    }

    //
    //  We searched the entire range without a conflict so we can grant
    //  the shared lock
    //

    return Status;
}


VOID
FsRtlPrivateResetLowestLockOffset (
    PLOCK_INFO LockInfo
    )

/*++

Routine Description:

    This routine resets the lowest lock offset hint in a LOCK_INFO to
    the lowest lock offset currently held by a lock inside of the LOCK_INFO.

Arguments:

    LockInfo - the lock data to operate on

Return Value:

    None

--*/

{
    PEX_LOCK ExLock = NULL;
    PSH_LOCK ShLock = NULL;
    PFILE_LOCK_INFO LowestLockInfo = NULL;
    PRTL_SPLAY_LINKS SplayLinks;
    PLOCKTREE_NODE Node;

    //
    //  Fix up the lowest lock offset if we have non-empty trees and there was
    //  a lock in the low 32 bit region
    //

    if (LockInfo->LowestLockOffset != 0xffffffff &&
        (LockInfo->LockQueue.SharedLockTree != NULL ||
         LockInfo->LockQueue.ExclusiveLockTree != NULL)) {

        //
        //  Grab the lowest nodes in the trees
        //

        if (LockInfo->LockQueue.SharedLockTree) {
    
            SplayLinks = LockInfo->LockQueue.SharedLockTree;
        
            while (RtlLeftChild(SplayLinks) != NULL) {
        
                SplayLinks = RtlLeftChild(SplayLinks);
            }
    
            Node = CONTAINING_RECORD( SplayLinks, LOCKTREE_NODE, Links );
            ShLock = CONTAINING_RECORD( Node->Locks.Next, SH_LOCK, Link );
        }

        if (LockInfo->LockQueue.ExclusiveLockTree) {
    
            SplayLinks = LockInfo->LockQueue.ExclusiveLockTree;
        
            while (RtlLeftChild(SplayLinks) != NULL) {
        
                SplayLinks = RtlLeftChild(SplayLinks);
            }
    
            ExLock = CONTAINING_RECORD( SplayLinks, EX_LOCK, Links );
        }

        //
        //  Figure out which of the lowest locks is actually lowest. We know that one of the lock
        //  trees at least has a lock, so if we have don't have exclusive locks then we do know
        //  we have shared locks ...
        //

        if (ExLock &&
            (!ShLock ||
             (ULONGLONG)ExLock->LockInfo.StartingByte.QuadPart < (ULONGLONG)ShLock->LockInfo.StartingByte.QuadPart)) {

            LowestLockInfo = &ExLock->LockInfo;

        } else {

            LowestLockInfo = &ShLock->LockInfo;
        }

        if (LowestLockInfo->StartingByte.HighPart == 0) {

            LockInfo->LowestLockOffset = LowestLockInfo->StartingByte.LowPart;

        } else {

            LockInfo->LowestLockOffset = 0xffffffff;
        }

    } else {

        //
        //  If there are no locks, set the lock offset high
        //

        LockInfo->LowestLockOffset = 0xffffffff;
    }
}


NTSTATUS
FsRtlPrivateFastUnlockAll (
    IN PFILE_LOCK FileLock,
    IN PFILE_OBJECT FileObject,
    IN PEPROCESS ProcessId,
    IN ULONG Key,
    IN BOOLEAN MatchKey,
    IN PVOID Context OPTIONAL
    )

/*++

Routine Description:

    This routine performs an Unlock all operation on the current locks
    associated with the specified file lock.  Only those locks with
    a matching file object and process id are freed.  Additionally,
    it is possible to free only those locks which also match a given
    key.

Arguments:

    FileLock - Supplies the file lock being freed.

    FileObject - Supplies the file object associated with the file lock

    ProcessId - Supplies the Process Id assoicated with the locks to be
        freed

    Key - Supplies the Key to use in this operation

    MatchKey - Whether or not the Key must also match for lock to be freed.

    Context - Supplies an optional context to use when completing waiting
        lock irps.

Return Value:

    None

--*/

{
    PLOCK_INFO              LockInfo;
    PLOCK_QUEUE             LockQueue;
    PSINGLE_LIST_ENTRY      *pLink, *SavepLink, Link;
    NTSTATUS                NewStatus;
    KIRQL                   OldIrql;
    LARGE_INTEGER           MaxOffset, SaveEndingByte;
    BOOLEAN                 UnlockRoutine;
    PSH_LOCK                ShLock;
    PEX_LOCK                ExLock;
    PRTL_SPLAY_LINKS        SplayLinks, SuccessorLinks;
    PLOCKTREE_NODE          Node;


    DebugTrace(+1, Dbg, "FsRtlPrivateFastUnlockAll, FileLock = %08lx\n", FileLock);

    if ((LockInfo = FileLock->LockInformation) == NULL) {

        //
        // No lock information on this FileLock
        //

        DebugTrace(+1, Dbg, "FsRtlPrivateFastUnlockAll, No LockInfo\n", FileLock);
        return STATUS_RANGE_NOT_LOCKED;
    }

    FileObject->LastLock = NULL;

    LockQueue = &LockInfo->LockQueue;

    //
    //  Grab the waiting lock queue spinlock to exclude anyone from messing
    //  with the queue while we're using it
    //

    FsRtlReacquireLockQueue(LockInfo, LockQueue, &OldIrql);

    if (LockQueue->SharedLockTree == NULL && LockQueue->ExclusiveLockTree == NULL) {

        //
        // No locks on this FileLock
        //

        DebugTrace(+1, Dbg, "FsRtlPrivateFastUnlockAll, No LockTrees\n", FileLock);
        FsRtlReleaseLockQueue(LockQueue, OldIrql);
        
        return STATUS_RANGE_NOT_LOCKED;
    }

    //
    //  Remove all matching locks in the shared lock tree
    //

    if (LockQueue->SharedLockTree != NULL) {

        //
        //  Grab the lowest node in the tree
        //
    
        SplayLinks = LockQueue->SharedLockTree;
    
        while (RtlLeftChild(SplayLinks) != NULL) {
    
            SplayLinks = RtlLeftChild(SplayLinks);
        }
    
        //
        //  Walk all nodes in the tree
        //
    
        UnlockRoutine = FALSE;
    
        for (;
             SplayLinks;
             SplayLinks = SuccessorLinks) {
    
            Node = CONTAINING_RECORD(SplayLinks, LOCKTREE_NODE, Links );
    
            //
            //  Save the next node because we may split this node apart in the process
            //  of deleting locks. It would be a waste of time to traverse those split
            //  nodes. The only case in which we will not have traversed the entire list
            //  before doing the split will be if there is an unlock routine attached
            //  to this FileLock in which case we will be restarting the entire scan
            //  anyway.
            //
    
            SuccessorLinks = RtlRealSuccessor(SplayLinks);
    
            //
            //  Search down the current lock queue looking for a match on
            //  the file object and process id
            //
    
            SavepLink = NULL;
            SaveEndingByte.QuadPart = 0;
    
            pLink = &Node->Locks.Next;
            while ((Link = *pLink) != NULL) {
        
                ShLock = CONTAINING_RECORD( Link, SH_LOCK, Link );
        
                DebugTrace(0, Dbg, "Top of ShLock Loop, Lock = %08lx\n", ShLock );
        
                if ((ShLock->LockInfo.FileObject == FileObject) &&
                    (ShLock->LockInfo.ProcessId == ProcessId) &&
                    (!MatchKey || ShLock->LockInfo.Key == Key)) {
        
                    DebugTrace(0, Dbg, "Found one to unlock\n", 0);
        
                    //
                    //  We have a match so now is the time to delete this lock.
                    //  Save the neccesary information to do the split node check.
                    //  Remove the lock from the list, then call the
                    //  optional unlock routine, then delete the lock.
                    //
    
                    if (SavepLink == NULL) {
                        
                        //
                        //  Need to remember where the first lock was deleted
                        //
    
                        SavepLink = pLink;
                    }
    
                    if ((ULONGLONG)ShLock->LockInfo.EndingByte.QuadPart > (ULONGLONG)SaveEndingByte.QuadPart) {
    
                        //
                        //  Need to remember where the last offset affected by deleted locks is
                        //
    
                        SaveEndingByte.QuadPart = ShLock->LockInfo.EndingByte.QuadPart;
                    }
    
                    if (*pLink == Node->Tail.Next) {
        
                        //
                        //  Deleting the tail node of the list. Safe even if deleting the
                        //  first node since this implies we're also deleting the last node
                        //  in the node which means we'll delete the node ...
                        //
        
                        Node->Tail.Next = CONTAINING_RECORD( pLink, SINGLE_LIST_ENTRY, Next );
                    }
    
                    *pLink = Link->Next;
        
                    if (LockInfo->UnlockRoutine != NULL) {
    
                        //
                        //  Signal a lock that needs to have a special unlock routine
                        //  called on it. This is complex to deal with since we'll have
                        //  to release the queue, call it, and reacquire - meaning we
                        //  also have to restart. But we still need to reorder the node
                        //  first ...
                        //
    
                        UnlockRoutine = TRUE;
        
                        break;
                    }
    
                    FsRtlFreeSharedLock( ShLock );
        
                } else {
        
                    //
                    // Move to next lock
                    //
        
                    pLink = &Link->Next;
                }
    
                if (SavepLink == NULL && (ULONGLONG)ShLock->LockInfo.EndingByte.QuadPart > (ULONGLONG)MaxOffset.QuadPart) {
    
                    //
                    //  Save the max offset until we have deleted our first node
                    //
    
                    MaxOffset.QuadPart = ShLock->LockInfo.EndingByte.QuadPart;
                }
            }
    
            if (SavepLink) {
    
                //
                //  Locks were actually deleted here, so we have to check the state of the node
                //
    
                if (Node->Locks.Next == NULL) {
    
                    //
                    //  We have just deleted everything at this node
                    //
    
                    LockQueue->SharedLockTree = RtlDelete(SplayLinks);
    
                    FsRtlFreeLockTreeNode(Node);
    
                } else {
    
                    //
                    //  Now that we have deleted all matching locks in this node, we do the
                    //  check on the node to split out any now non-overlapping locks. Conceptually,
                    //  we have deleted just one big lock that starts at the starting byte of the
                    //  first deleted lock and extends to the last byte of the last deleted lock.
                    //
        
                    FsRtlSplitLocks(Node, SavepLink, &SaveEndingByte, &MaxOffset);
                }
            }
    
            if (UnlockRoutine) {
    
                //
                //  We dropped out of the node scan because we had a lock that needs extra
                //  processing during unlock. Do it.
                //
    
                FsRtlReleaseLockQueue(LockQueue, OldIrql);
                
                LockInfo->UnlockRoutine(Context, &ShLock->LockInfo);
        
                FsRtlReacquireLockQueue(LockInfo, LockQueue, &OldIrql);
    
                FsRtlFreeSharedLock(ShLock);
    
                UnlockRoutine = FALSE;
        
                //
                //  We have to restart the scan, because the list may have changed while
                //  we were in the unlock routine. Careful, because the tree may be empty.
                //
        
                if (SuccessorLinks = LockQueue->SharedLockTree) {

                    while (RtlLeftChild(SuccessorLinks) != NULL) {
                
                        SuccessorLinks = RtlLeftChild(SuccessorLinks);
                    }
                }
            }
        }
    }

    //
    //  Remove all matching locks in the exclusive lock tree
    //

    if (LockQueue->ExclusiveLockTree != NULL) {

        SplayLinks = LockQueue->ExclusiveLockTree;
    
        while (RtlLeftChild(SplayLinks) != NULL) {
    
            SplayLinks = RtlLeftChild(SplayLinks);
        }
    
        //
        //  Walk all nodes in the tree
        //
    
        UnlockRoutine = FALSE;

        for (; SplayLinks;
               SplayLinks = SuccessorLinks ) {

            SuccessorLinks = RtlRealSuccessor(SplayLinks);

            ExLock = CONTAINING_RECORD( SplayLinks, EX_LOCK, Link );
    
            DebugTrace(0, Dbg, "Top of ExLock Loop, Lock = %08lx\n", ExLock );
    
            if ((ExLock->LockInfo.FileObject == FileObject) &&
                (ExLock->LockInfo.ProcessId == ProcessId) &&
                (!MatchKey || ExLock->LockInfo.Key == Key)) {

                LockQueue->ExclusiveLockTree = RtlDelete(&ExLock->Links);

                if (LockInfo->UnlockRoutine != NULL) {

                    //
                    //  We're dropping out of the node scan because we have a lock
                    //  that needs extra processing during unlock. Do it.
                    //
        
                    FsRtlReleaseLockQueue(LockQueue, OldIrql);
                    
                    LockInfo->UnlockRoutine(Context, &ExLock->LockInfo);
            
                    FsRtlReacquireLockQueue(LockInfo, LockQueue, &OldIrql);
        
                    //
                    //  We have to restart the scan, because the list may have changed while
                    //  we were in the unlock routine. Careful, because the tree may be empty.
                    //
            
                    if (SuccessorLinks = LockQueue->ExclusiveLockTree) {

                        while (RtlLeftChild(SuccessorLinks) != NULL) {
                    
                            SuccessorLinks = RtlLeftChild(SuccessorLinks);
                        }
                    }
                }

                FsRtlFreeExclusiveLock(ExLock);
            }
        }
    }

    //
    //  Search down the waiting lock queue looking for a match on the
    //  file object and process id.
    //

    pLink = &LockQueue->WaitingLocks.Next;
    while ((Link = *pLink) != NULL) {

        PWAITING_LOCK WaitingLock;
        PIRP WaitingIrp;
        PIO_STACK_LOCATION WaitingIrpSp;

        WaitingLock = CONTAINING_RECORD( Link, WAITING_LOCK, Link );

        DebugTrace(0, Dbg, "Top of Waiting Loop, WaitingLock = %08lx\n", WaitingLock);

        //
        //  Get a copy of the necessary fields we'll need to use
        //

        WaitingIrp = WaitingLock->Irp;
        WaitingIrpSp = IoGetCurrentIrpStackLocation( WaitingIrp );

        if ((FileObject == WaitingIrpSp->FileObject) &&
            (ProcessId == IoGetRequestorProcess( WaitingIrp )) &&
            (!MatchKey || Key == WaitingIrpSp->Parameters.LockControl.Key)) {
            
            DebugTrace(0, Dbg, "Found a waiting lock to abort\n", 0);

            //
            //  We now void the cancel routine in the irp
            //

            IoSetCancelRoutine( WaitingIrp, NULL );
            WaitingIrp->IoStatus.Information = 0;

            //
            //  We have a match so now is the time to delete this waiter
            //  But we must not mess up our link iteration variable.  We
            //  do this by simply starting the iteration over again,
            //  after we delete ourselves.  We also will deallocate the
            //  lock after we delete it.
            //

            *pLink = Link->Next;
            if (Link == LockQueue->WaitingLocksTail.Next) {
                LockQueue->WaitingLocksTail.Next = (PSINGLE_LIST_ENTRY) pLink;
            }

            FsRtlReleaseLockQueue(LockQueue, OldIrql);

            //
            //  And complete this lock request Irp
            //

            FsRtlCompleteLockIrp( LockInfo,
                                    WaitingLock->Context,
                                    WaitingIrp,
                                    STATUS_SUCCESS,
                                    &NewStatus,
                                    NULL );

            //
            // Reaqcuire lock queue spinlock and start over
            //

            FsRtlReacquireLockQueue(LockInfo, LockQueue, &OldIrql);

            //
            // Start over
            //

            pLink = &LockQueue->WaitingLocks.Next;
            
            //
            // Put memory onto free list
            //

            FsRtlFreeWaitingLock( WaitingLock );
            continue;
        }

        //
        // Move to next lock
        //

        pLink = &Link->Next;
    }

    //
    //  At this point we've gone through unlocking everything. So
    //  now try and release any waiting locks.
    //

    FsRtlPrivateCheckWaitingLocks( LockInfo, LockQueue, OldIrql );

    //
    //  We deleted a (possible) bunch of locks, go repair the lowest lock offset
    //

    FsRtlPrivateResetLowestLockOffset( LockInfo );

    FsRtlReleaseLockQueue( LockQueue, OldIrql );

    //
    // Check free lock/node lists to be within reason
    //
#ifndef USERTEST
    KeRaiseIrql (DISPATCH_LEVEL, &OldIrql);
    FsRtlPrivateLimitFreeLockList (&KeGetCurrentPrcb()->FsRtlFreeSharedLockList);
    FsRtlPrivateLimitFreeLockList (&KeGetCurrentPrcb()->FsRtlFreeExclusiveLockList);
    FsRtlPrivateLimitFreeLockList (&KeGetCurrentPrcb()->FsRtlFreeWaitingLockList);
    FsRtlPrivateLimitFreeLockList (&KeGetCurrentPrcb()->FsRtlFreeLockTreeNodeList);
    KeLowerIrql (OldIrql);
#endif

    //
    //  and return to our caller
    //

    DebugTrace(-1, Dbg, "FsRtlFastUnlockAll -> VOID\n", 0);
    return STATUS_SUCCESS;
}


VOID
FsRtlPrivateLimitFreeLockList (
    IN PSINGLE_LIST_ENTRY   Link
    )
/*++

Routine Description:

    Scans list and free exceesive elments back to pool.

    Note: this function assumes that the Link field is the first
    element in the allocated structures.

Arguments:

    Link    - List to check length on

Return Value:

    None

--*/
{
    PSINGLE_LIST_ENTRY   FreeLink;
    ULONG   Count;

    //
    // Leave some entries on the free list
    //

    for (Count=FREE_LOCK_SIZE; Count && Link; Count--, Link = Link->Next) ;

    //
    // If not end of list, then free the remaining entires
    //

    if (Link) {

        //
        // Chop free list, and get list of Links to free
        //

        FreeLink = Link->Next;
        Link->Next = NULL;

        //
        // Free all remaining links
        //

        while (FreeLink) {
            Link = FreeLink->Next;
            ExFreePool (FreeLink);
            FreeLink = Link;
        }
    }
}


VOID
FsRtlPrivateCancelFileLockIrp (
    IN PDEVICE_OBJECT DeviceObject,
    IN PIRP Irp
    )

/*++

Routine Description:

    This routine implements the cancel function for an irp saved in a
    waiting lock queue

Arguments:

    DeviceObject - Ignored

    Irp - Supplies the Irp being cancelled.  A pointer to the FileLock
        structure for the lock is stored in the information field of the
        irp's iosb.

Return Value:

    none.

--*/

{
    PSINGLE_LIST_ENTRY *pLink, Link;
    PLOCK_INFO  LockInfo;
    PLOCK_QUEUE LockQueue;
    KIRQL       OldIrql;
    NTSTATUS    NewStatus;


    UNREFERENCED_PARAMETER( DeviceObject );

    //
    //  The information field is used to store a pointer to the file lock
    //  containing the irp
    //

    LockInfo = (PLOCK_INFO) (Irp->IoStatus.Information);

    //
    //  Release the cancel spinlock
    //

    IoReleaseCancelSpinLock( Irp->CancelIrql );

    //
    // Iterate through all lock queues.  Note on a UP build there is
    // only one lock queue.
    //

    LockQueue = &LockInfo->LockQueue;

    //
    // Iterate through all of the waiting locks looking for a canceled one
    // Lock the waiting queue
    //

    FsRtlReacquireLockQueue(LockInfo, LockQueue, &OldIrql);

    pLink = &LockQueue->WaitingLocks.Next;
    while ((Link = *pLink) != NULL) {

        PWAITING_LOCK WaitingLock;

        //
        //  Get a pointer to the waiting lock record
        //

        WaitingLock = CONTAINING_RECORD( Link, WAITING_LOCK, Link );

        DebugTrace(0, Dbg, "FsRtlPrivateCancelFileLockIrp, Loop top, WaitingLock = %08lx\n", WaitingLock);
        if( WaitingLock->Irp != Irp ) {
            pLink = &Link->Next;
            continue;
        }

        //
        //  We've found it -- remove it from the list
        //

        *pLink = Link->Next;
        if (Link == LockQueue->WaitingLocksTail.Next) {
            LockQueue->WaitingLocksTail.Next = (PSINGLE_LIST_ENTRY) pLink;
        }

        Irp->IoStatus.Information = 0;

        //
        // Release LockQueue and complete this waiter
        //

        FsRtlReleaseLockQueue(LockQueue, OldIrql);

        //
        // Complete this waiter
        //

        FsRtlCompleteLockIrp(
            LockInfo,
            WaitingLock->Context,
            Irp,
            STATUS_CANCELLED,
            &NewStatus,
            NULL );

        //
        //  Free up pool
        //

        FsRtlFreeWaitingLock( WaitingLock );

        //
        // Our job is done!
        //

        return;
    }

    //
    // Release lock queue
    //

    FsRtlReleaseLockQueue(LockQueue, OldIrql);

    return;
}

#ifdef USERTEST
void DumpTree( FILE_LOCK *FileLock, ULONG DumpType)
{
    PLOCK_INFO LockInfo;
    PRTL_SPLAY_LINKS SplayLinks, Ptr;
    PLOCKTREE_NODE Node;
    PSINGLE_LIST_ENTRY Link;
    ULONG Indent = 1, i;

    printf("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n");

    LockInfo = FileLock->LockInformation;

    if (LockInfo == NULL) {

        printf("No LockInfo\n");
        goto end;
    }

    printf("LowestLockOffset = %08x\n", LockInfo->LowestLockOffset);

    SplayLinks = LockInfo->LockQueue.SharedLockTree;

    if (SplayLinks == NULL) {

        printf("Shared LockTree is empty\n");
        goto excl;
    }

    while (RtlLeftChild(SplayLinks) != NULL) {

        SplayLinks = RtlLeftChild(SplayLinks);
        Indent++;
    }

    while (SplayLinks) {

        PSH_LOCK Lock;

        Node = CONTAINING_RECORD( SplayLinks, LOCKTREE_NODE, Links );

        for (i = 1; i < Indent; i++) {
            printf("   ");
        }

        printf("Node 0x%08x  Extent = %08x%08x\n", Node, (ULONG)((Node->Extent >> 32) & 0xffffffff),
                                                    (ULONG)(Node->Extent & 0xffffffff));

        for (Link = Node->Locks.Next;
             Link;
             Link = Link->Next) {

            Lock = CONTAINING_RECORD( Link, SH_LOCK, Link );

            for (i = 1; i < Indent; i++) {
                printf("   ");
            }
    
            printf("Start = %08x%08x  Len = %08x%08x  End = %08x%08x\n",
                Lock->LockInfo.StartingByte.HighPart, Lock->LockInfo.StartingByte.LowPart,
                Lock->LockInfo.Length.HighPart, Lock->LockInfo.Length.LowPart,
                Lock->LockInfo.EndingByte.HighPart, Lock->LockInfo.EndingByte.LowPart);
        }

        printf("\n");

        Ptr = SplayLinks;

        /*
          first check to see if there is a right subtree to the input link
          if there is then the real successor is the left most node in
          the right subtree.  That is find and return P in the following diagram
    
                      Links
                         \
                          .
                         .
                        .
                       /
                      P
                       \
        */
    
        if ((Ptr = RtlRightChild(SplayLinks)) != NULL) {
    
            Indent++;
            while (RtlLeftChild(Ptr) != NULL) {

                Indent++;
                Ptr = RtlLeftChild(Ptr);
            }

            SplayLinks = Ptr;

        } else {
            /*
              we do not have a right child so check to see if have a parent and if
              so find the first ancestor that we are a left decendent of. That
              is find and return P in the following diagram
        
                               P
                              /
                             .
                              .
                               .
                              Links
            */
        
            Ptr = SplayLinks;
            while (RtlIsRightChild(Ptr)) {

                Indent--;
                Ptr = RtlParent(Ptr);
            }
        
            if (!RtlIsLeftChild(Ptr)) {

                //
                //  we do not have a real successor so we simply return
                //  NULL
                //
                SplayLinks = NULL;

            } else {

                Indent--;
                SplayLinks = RtlParent(Ptr);
            }
        }
    }

    //
    //  .. and the exclusive side
    //
  excl:

    SplayLinks = LockInfo->LockQueue.ExclusiveLockTree;
    Indent = 1;

    if (SplayLinks == NULL) {

        printf("Exclusive LockTree is empty\n");
        goto end;
    }
    
    while (RtlLeftChild(SplayLinks) != NULL) {
    
        SplayLinks = RtlLeftChild(SplayLinks);
        Indent++;
    }

    while (SplayLinks) {

        PEX_LOCK Lock;

        Lock = CONTAINING_RECORD( SplayLinks, EX_LOCK, Links );
    
        for (i = 1; i < Indent; i++) {
            printf("   ");
        }

        printf("Start = %08x%08x  Len = %08x%08x  End = %08x%08x\n",
            Lock->LockInfo.StartingByte.HighPart, Lock->LockInfo.StartingByte.LowPart,
            Lock->LockInfo.Length.HighPart, Lock->LockInfo.Length.LowPart,
            Lock->LockInfo.EndingByte.HighPart, Lock->LockInfo.EndingByte.LowPart);
    
        Ptr = SplayLinks;
    
        /*
          first check to see if there is a right subtree to the input link
          if there is then the real successor is the left most node in
          the right subtree.  That is find and return P in the following diagram
    
                      Links
                         \
                          .
                         .
                        .
                       /
                      P
                       \
        */
    
        if ((Ptr = RtlRightChild(SplayLinks)) != NULL) {
    
            Indent++;
            while (RtlLeftChild(Ptr) != NULL) {
    
                Indent++;
                Ptr = RtlLeftChild(Ptr);
            }
    
            SplayLinks = Ptr;
    
        } else {
            /*
              we do not have a right child so check to see if have a parent and if
              so find the first ancestor that we are a left decendent of. That
              is find and return P in the following diagram
        
                               P
                              /
                             .
                              .
                               .
                              Links
            */
        
            Ptr = SplayLinks;
            while (RtlIsRightChild(Ptr)) {
    
                Indent--;
                Ptr = RtlParent(Ptr);
            }
        
            if (!RtlIsLeftChild(Ptr)) {
    
                //
                //  we do not have a real successor so we simply return
                //  NULL
                //
                SplayLinks = NULL;
    
            } else {
    
                Indent--;
                SplayLinks = RtlParent(Ptr);
            }
        }
    }

  end:
    printf("------------------------------------------------------------------\n");
}
#endif