summaryrefslogtreecommitdiffstats
path: root/src/lib/nt/kFsCache.c
blob: 77c9655fd789cd4ff510765cddfc0333a0c9a496 (plain)
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
/* $Id: kFsCache.c 3381 2020-06-12 11:36:10Z bird $ */
/** @file
 * ntdircache.c - NT directory content cache.
 */

/*
 * Copyright (c) 2016 knut st. osmundsen <bird-kBuild-spamx@anduin.net>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 *
 * Alternatively, the content of this file may be used under the terms of the
 * GPL version 2 or later, or LGPL version 2.1 or later.
 */


/*********************************************************************************************************************************
*   Header Files                                                                                                                 *
*********************************************************************************************************************************/
#include <k/kHlp.h>

#include "nthlp.h"
#include "ntstat.h"

#include <stdio.h>
#include <mbstring.h>
#include <wchar.h>
#ifdef _MSC_VER
# include <intrin.h>
#endif
//#include <setjmp.h>
//#include <ctype.h>


//#include <Windows.h>
//#include <winternl.h>

#include "kFsCache.h"


/*********************************************************************************************************************************
*   Defined Constants And Macros                                                                                                 *
*********************************************************************************************************************************/
/** @def KFSCACHE_LOG2
 * More logging. */
#if 0
# define KFSCACHE_LOG2(a) KFSCACHE_LOG(a)
#else
# define KFSCACHE_LOG2(a) do { } while (0)
#endif

/** The minimum time between a directory last populated time and its
 * modification time for the cache to consider it up-to-date.
 *
 * This helps work around races between us reading a directory and someone else
 * adding / removing files and directories to /from it.  Given that the
 * effective time resolution typically is around 2000Hz these days, unless you
 * use the new *TimePrecise API variants, there is plenty of room for a race
 * here.
 *
 * The current value is 20ms in NT time units (100ns each), which translates
 * to a 50Hz time update frequency. */
#define KFSCACHE_MIN_LAST_POPULATED_VS_WRITE (20*1000*10)


/*********************************************************************************************************************************
*   Structures and Typedefs                                                                                                      *
*********************************************************************************************************************************/
/**
 * Used by the code re-populating a directory.
 */
typedef struct KFSDIRREPOP
{
    /** The old papChildren array. */
    PKFSOBJ    *papOldChildren;
    /** Number of children in the array. */
    KU32        cOldChildren;
    /** The index into papOldChildren we expect to find the next entry.  */
    KU32        iNextOldChild;
    /** Add this to iNextOldChild . */
    KI32        cNextOldChildInc;
    /** Pointer to the cache (name changes). */
    PKFSCACHE   pCache;
} KFSDIRREPOP;
/** Pointer to directory re-population data. */
typedef KFSDIRREPOP *PKFSDIRREPOP;



/*********************************************************************************************************************************
*   Internal Functions                                                                                                           *
*********************************************************************************************************************************/
static KBOOL kFsCacheRefreshObj(PKFSCACHE pCache, PKFSOBJ pObj, KFSLOOKUPERROR *penmError);


/**
 * Retains a reference to a cache object, internal version.
 *
 * @returns pObj
 * @param   pObj                The object.
 */
K_INLINE PKFSOBJ kFsCacheObjRetainInternal(PKFSOBJ pObj)
{
    KU32 cRefs = ++pObj->cRefs;
    kHlpAssert(cRefs < 16384);
    K_NOREF(cRefs);
    return pObj;
}


#ifndef NDEBUG

/**
 * Debug printing.
 * @param   pszFormat           Debug format string.
 * @param   ...                 Format argument.
 */
void kFsCacheDbgPrintfV(const char *pszFormat, va_list va)
{
    if (1)
    {
        DWORD const dwSavedErr = GetLastError();

        fprintf(stderr, "debug: ");
        vfprintf(stderr, pszFormat, va);

        SetLastError(dwSavedErr);
    }
}


/**
 * Debug printing.
 * @param   pszFormat           Debug format string.
 * @param   ...                 Format argument.
 */
void kFsCacheDbgPrintf(const char *pszFormat, ...)
{
    if (1)
    {
        va_list va;
        va_start(va, pszFormat);
        kFsCacheDbgPrintfV(pszFormat, va);
        va_end(va);
    }
}

#endif /* !NDEBUG */



/**
 * Hashes a string.
 *
 * @returns 32-bit string hash.
 * @param   pszString           String to hash.
 */
static KU32 kFsCacheStrHash(const char *pszString)
{
    /* This algorithm was created for sdbm (a public-domain reimplementation of
       ndbm) database library. it was found to do well in scrambling bits,
       causing better distribution of the keys and fewer splits. it also happens
       to be a good general hashing function with good distribution. the actual
       function is hash(i) = hash(i - 1) * 65599 + str[i]; what is included below
       is the faster version used in gawk. [there is even a faster, duff-device
       version] the magic constant 65599 was picked out of thin air while
       experimenting with different constants, and turns out to be a prime.
       this is one of the algorithms used in berkeley db (see sleepycat) and
       elsewhere. */
    KU32 uHash = 0;
    KU32 uChar;
    while ((uChar = (unsigned char)*pszString++) != 0)
        uHash = uChar + (uHash << 6) + (uHash << 16) - uHash;
    return uHash;
}


/**
 * Hashes a string.
 *
 * @returns The string length.
 * @param   pszString           String to hash.
 * @param   puHash              Where to return the 32-bit string hash.
 */
static KSIZE kFsCacheStrHashEx(const char *pszString, KU32 *puHash)
{
    const char * const pszStart = pszString;
    KU32 uHash = 0;
    KU32 uChar;
    while ((uChar = (unsigned char)*pszString) != 0)
    {
        uHash = uChar + (uHash << 6) + (uHash << 16) - uHash;
        pszString++;
    }
    *puHash = uHash;
    return pszString - pszStart;
}


/**
 * Hashes a substring.
 *
 * @returns 32-bit substring hash.
 * @param   pchString           Pointer to the substring (not terminated).
 * @param   cchString           The length of the substring.
 */
static KU32 kFsCacheStrHashN(const char *pchString, KSIZE cchString)
{
    KU32 uHash = 0;
    while (cchString-- > 0)
    {
        KU32 uChar = (unsigned char)*pchString++;
        uHash = uChar + (uHash << 6) + (uHash << 16) - uHash;
    }
    return uHash;
}


/**
 * Hashes a UTF-16 string.
 *
 * @returns The string length in wchar_t units.
 * @param   pwszString          String to hash.
 * @param   puHash              Where to return the 32-bit string hash.
 */
static KSIZE kFsCacheUtf16HashEx(const wchar_t *pwszString, KU32 *puHash)
{
    const wchar_t * const pwszStart = pwszString;
    KU32 uHash = 0;
    KU32 uChar;
    while ((uChar = *pwszString) != 0)
    {
        uHash = uChar + (uHash << 6) + (uHash << 16) - uHash;
        pwszString++;
    }
    *puHash = uHash;
    return pwszString - pwszStart;
}


/**
 * Hashes a UTF-16 substring.
 *
 * @returns 32-bit substring hash.
 * @param   pwcString           Pointer to the substring (not terminated).
 * @param   cchString           The length of the substring (in wchar_t's).
 */
static KU32 kFsCacheUtf16HashN(const wchar_t *pwcString, KSIZE cwcString)
{
    KU32 uHash = 0;
    while (cwcString-- > 0)
    {
        KU32 uChar = *pwcString++;
        uHash = uChar + (uHash << 6) + (uHash << 16) - uHash;
    }
    return uHash;
}


/**
 * For use when kFsCacheIAreEqualW hit's something non-trivial.
 *
 * @returns K_TRUE if equal, K_FALSE if different.
 * @param   pwcName1            The first string.
 * @param   pwcName2            The second string.
 * @param   cwcName             The length of the two strings (in wchar_t's).
 */
KBOOL kFsCacheIAreEqualSlowW(const wchar_t *pwcName1, const wchar_t *pwcName2, KU16 cwcName)
{
    MY_UNICODE_STRING UniStr1 = { cwcName * sizeof(wchar_t), cwcName * sizeof(wchar_t), (wchar_t *)pwcName1 };
    MY_UNICODE_STRING UniStr2 = { cwcName * sizeof(wchar_t), cwcName * sizeof(wchar_t), (wchar_t *)pwcName2 };
    return g_pfnRtlEqualUnicodeString(&UniStr1, &UniStr2, TRUE /*fCaseInsensitive*/);
}


/**
 * Compares two UTF-16 strings in a case-insensitive fashion.
 *
 * You would think we should be using _wscnicmp here instead, however it is
 * locale dependent and defaults to ASCII upper/lower handling setlocale hasn't
 * been called.
 *
 * @returns K_TRUE if equal, K_FALSE if different.
 * @param   pwcName1            The first string.
 * @param   pwcName2            The second string.
 * @param   cwcName             The length of the two strings (in wchar_t's).
 */
K_INLINE KBOOL kFsCacheIAreEqualW(const wchar_t *pwcName1, const wchar_t *pwcName2, KU32 cwcName)
{
    while (cwcName > 0)
    {
        wchar_t wc1 = *pwcName1;
        wchar_t wc2 = *pwcName2;
        if (wc1 == wc2)
        { /* not unlikely */ }
        else if (  (KU16)wc1 < (KU16)0xc0 /* U+00C0 is the first upper/lower letter after 'z'. */
                && (KU16)wc2 < (KU16)0xc0)
        {
            /* ASCII upper case. */
            if ((KU16)wc1 - (KU16)0x61 < (KU16)26)
                wc1 &= ~(wchar_t)0x20;
            if ((KU16)wc2 - (KU16)0x61 < (KU16)26)
                wc2 &= ~(wchar_t)0x20;
            if (wc1 != wc2)
                return K_FALSE;
        }
        else
            return kFsCacheIAreEqualSlowW(pwcName1, pwcName2, (KU16)cwcName);

        pwcName2++;
        pwcName1++;
        cwcName--;
    }

    return K_TRUE;
}


/**
 * Looks for '..' in the path.
 *
 * @returns K_TRUE if '..' component found, K_FALSE if not.
 * @param   pszPath             The path.
 * @param   cchPath             The length of the path.
 */
static KBOOL kFsCacheHasDotDotA(const char *pszPath, KSIZE cchPath)
{
    const char *pchDot = (const char *)kHlpMemChr(pszPath, '.', cchPath);
    while (pchDot)
    {
        if (pchDot[1] != '.')
        {
            pchDot++;
            pchDot = (const char *)kHlpMemChr(pchDot, '.', &pszPath[cchPath] - pchDot);
        }
        else
        {
            char ch;
            if (   (ch = pchDot[2]) != '\0'
                && IS_SLASH(ch))
            {
                if (pchDot == pszPath)
                    return K_TRUE;
                ch = pchDot[-1];
                if (   IS_SLASH(ch)
                    || ch == ':')
                    return K_TRUE;
            }
            pchDot = (const char *)kHlpMemChr(pchDot + 2, '.', &pszPath[cchPath] - pchDot - 2);
        }
    }

    return K_FALSE;
}


/**
 * Looks for '..' in the path.
 *
 * @returns K_TRUE if '..' component found, K_FALSE if not.
 * @param   pwszPath            The path.
 * @param   cwcPath             The length of the path (in wchar_t's).
 */
static KBOOL kFsCacheHasDotDotW(const wchar_t *pwszPath, KSIZE cwcPath)
{
    const wchar_t *pwcDot = wmemchr(pwszPath, '.', cwcPath);
    while (pwcDot)
    {
        if (pwcDot[1] != '.')
        {
            pwcDot++;
            pwcDot = wmemchr(pwcDot, '.', &pwszPath[cwcPath] - pwcDot);
        }
        else
        {
            wchar_t wch;
            if (   (wch = pwcDot[2]) != '\0'
                && IS_SLASH(wch))
            {
                if (pwcDot == pwszPath)
                    return K_TRUE;
                wch = pwcDot[-1];
                if (   IS_SLASH(wch)
                    || wch == ':')
                    return K_TRUE;
            }
            pwcDot = wmemchr(pwcDot + 2, '.', &pwszPath[cwcPath] - pwcDot - 2);
        }
    }

    return K_FALSE;
}


/**
 * Creates an ANSI hash table entry for the given path.
 *
 * @returns The hash table entry or NULL if out of memory.
 * @param   pCache              The hash
 * @param   pFsObj              The resulting object.
 * @param   pszPath             The path.
 * @param   cchPath             The length of the path.
 * @param   uHashPath           The hash of the path.
 * @param   fAbsolute           Whether it can be refreshed using an absolute
 *                              lookup or requires the slow treatment.
 * @parma   idxMissingGen       The missing generation index.
 * @param   idxHashTab          The hash table index of the path.
 * @param   enmError            The lookup error.
 */
static PKFSHASHA kFsCacheCreatePathHashTabEntryA(PKFSCACHE pCache, PKFSOBJ pFsObj, const char *pszPath, KU32 cchPath,
                                                 KU32 uHashPath, KU32 idxHashTab, BOOL fAbsolute, KU32 idxMissingGen,
                                                 KFSLOOKUPERROR enmError)
{
    PKFSHASHA pHashEntry = (PKFSHASHA)kHlpAlloc(sizeof(*pHashEntry) + cchPath + 1);
    if (pHashEntry)
    {
        pHashEntry->uHashPath       = uHashPath;
        pHashEntry->cchPath         = (KU16)cchPath;
        pHashEntry->fAbsolute       = fAbsolute;
        pHashEntry->idxMissingGen   = (KU8)idxMissingGen;
        pHashEntry->enmError        = enmError;
        pHashEntry->pszPath         = (const char *)kHlpMemCopy(pHashEntry + 1, pszPath, cchPath + 1);
        if (pFsObj)
        {
            pHashEntry->pFsObj      = kFsCacheObjRetainInternal(pFsObj);
            pHashEntry->uCacheGen   = pFsObj->bObjType != KFSOBJ_TYPE_MISSING
                                    ? pCache->auGenerations[       pFsObj->fFlags & KFSOBJ_F_USE_CUSTOM_GEN]
                                    : pCache->auGenerationsMissing[pFsObj->fFlags & KFSOBJ_F_USE_CUSTOM_GEN];
            pFsObj->cPathHashRefs += 1; // for debugging
        }
        else
        {
            pHashEntry->pFsObj      = NULL;
            if (enmError != KFSLOOKUPERROR_UNSUPPORTED)
                pHashEntry->uCacheGen = pCache->auGenerationsMissing[idxMissingGen];
            else
                pHashEntry->uCacheGen = KFSOBJ_CACHE_GEN_IGNORE;
        }

        pHashEntry->pNext = pCache->apAnsiPaths[idxHashTab];
        pCache->apAnsiPaths[idxHashTab] = pHashEntry;

        pCache->cbAnsiPaths += sizeof(*pHashEntry) + cchPath + 1;
        pCache->cAnsiPaths++;
        if (pHashEntry->pNext)
            pCache->cAnsiPathCollisions++;
    }
    return pHashEntry;
}


/**
 * Creates an UTF-16 hash table entry for the given path.
 *
 * @returns The hash table entry or NULL if out of memory.
 * @param   pCache              The hash
 * @param   pFsObj              The resulting object.
 * @param   pwszPath            The path.
 * @param   cwcPath             The length of the path (in wchar_t's).
 * @param   uHashPath           The hash of the path.
 * @param   fAbsolute           Whether it can be refreshed using an absolute
 *                              lookup or requires the slow treatment.
 * @parma   idxMissingGen       The missing generation index.
 * @param   idxHashTab          The hash table index of the path.
 * @param   enmError            The lookup error.
 */
static PKFSHASHW kFsCacheCreatePathHashTabEntryW(PKFSCACHE pCache, PKFSOBJ pFsObj, const wchar_t *pwszPath, KU32 cwcPath,
                                                 KU32 uHashPath, KU32 idxHashTab, BOOL fAbsolute, KU32 idxMissingGen,
                                                 KFSLOOKUPERROR enmError)
{
    PKFSHASHW pHashEntry = (PKFSHASHW)kHlpAlloc(sizeof(*pHashEntry) + (cwcPath + 1) * sizeof(wchar_t));
    if (pHashEntry)
    {
        pHashEntry->uHashPath       = uHashPath;
        pHashEntry->cwcPath         = cwcPath;
        pHashEntry->fAbsolute       = fAbsolute;
        pHashEntry->idxMissingGen   = (KU8)idxMissingGen;
        pHashEntry->enmError        = enmError;
        pHashEntry->pwszPath        = (const wchar_t *)kHlpMemCopy(pHashEntry + 1, pwszPath, (cwcPath + 1) * sizeof(wchar_t));
        if (pFsObj)
        {
            pHashEntry->pFsObj      = kFsCacheObjRetainInternal(pFsObj);
            pHashEntry->uCacheGen   = pFsObj->bObjType != KFSOBJ_TYPE_MISSING
                                    ? pCache->auGenerations[       pFsObj->fFlags & KFSOBJ_F_USE_CUSTOM_GEN]
                                    : pCache->auGenerationsMissing[pFsObj->fFlags & KFSOBJ_F_USE_CUSTOM_GEN];
            pFsObj->cPathHashRefs += 1; // for debugging
        }
        else
        {
            pHashEntry->pFsObj      = NULL;
            if (enmError != KFSLOOKUPERROR_UNSUPPORTED)
                pHashEntry->uCacheGen = pCache->auGenerationsMissing[idxMissingGen];
            else
                pHashEntry->uCacheGen = KFSOBJ_CACHE_GEN_IGNORE;
        }

        pHashEntry->pNext = pCache->apUtf16Paths[idxHashTab];
        pCache->apUtf16Paths[idxHashTab] = pHashEntry;

        pCache->cbUtf16Paths += sizeof(*pHashEntry) + (cwcPath + 1) * sizeof(wchar_t);
        pCache->cUtf16Paths++;
        if (pHashEntry->pNext)
            pCache->cAnsiPathCollisions++;
    }
    return pHashEntry;
}


/**
 * Links the child in under the parent.
 *
 * @returns K_TRUE on success, K_FALSE if out of memory.
 * @param   pParent             The parent node.
 * @param   pChild              The child node.
 */
static KBOOL kFsCacheDirAddChild(PKFSCACHE pCache, PKFSDIR pParent, PKFSOBJ pChild, KFSLOOKUPERROR *penmError)
{
    if (pParent->cChildren >= pParent->cChildrenAllocated)
    {
        void *pvNew = kHlpRealloc(pParent->papChildren, (pParent->cChildrenAllocated + 16) * sizeof(pParent->papChildren[0]));
        if (!pvNew)
            return K_FALSE;
        pParent->papChildren = (PKFSOBJ *)pvNew;
        pParent->cChildrenAllocated += 16;
        pCache->cbObjects += 16 * sizeof(pParent->papChildren[0]);
    }
    pParent->papChildren[pParent->cChildren++] = kFsCacheObjRetainInternal(pChild);
    return K_TRUE;
}


/**
 * Creates a new cache object.
 *
 * @returns Pointer (with 1 reference) to the new object.  The object will not
 *          be linked to the parent directory yet.
 *
 *          NULL if we're out of memory.
 *
 * @param   pCache          The cache.
 * @param   pParent         The parent directory.
 * @param   pszName         The ANSI name.
 * @param   cchName         The length of the ANSI name.
 * @param   pwszName        The UTF-16 name.
 * @param   cwcName         The length of the UTF-16 name.
 * @param   pszShortName    The ANSI short name, NULL if none.
 * @param   cchShortName    The length of the ANSI short name, 0 if none.
 * @param   pwszShortName   The UTF-16 short name, NULL if none.
 * @param   cwcShortName    The length of the UTF-16 short name, 0 if none.
 * @param   bObjType        The objct type.
 * @param   penmError       Where to explain failures.
 */
PKFSOBJ kFsCacheCreateObject(PKFSCACHE pCache, PKFSDIR pParent,
                             char const *pszName, KU16 cchName, wchar_t const *pwszName, KU16 cwcName,
#ifdef KFSCACHE_CFG_SHORT_NAMES
                             char const *pszShortName, KU16 cchShortName, wchar_t const *pwszShortName, KU16 cwcShortName,
#endif
                             KU8 bObjType, KFSLOOKUPERROR *penmError)
{
    /*
     * Allocate the object.
     */
    KBOOL const fDirish = bObjType != KFSOBJ_TYPE_FILE && bObjType != KFSOBJ_TYPE_OTHER;
    KSIZE const cbObj   = fDirish ? sizeof(KFSDIR) : sizeof(KFSOBJ);
    KSIZE const cbNames = (cwcName + 1) * sizeof(wchar_t)                           + cchName + 1
#ifdef KFSCACHE_CFG_SHORT_NAMES
                        + (cwcShortName > 0 ? (cwcShortName + 1) * sizeof(wchar_t)  + cchShortName + 1 : 0)
#endif
                          ;
    PKFSOBJ pObj;
    kHlpAssert(pCache->u32Magic == KFSCACHE_MAGIC);

    pObj = (PKFSOBJ)kHlpAlloc(cbObj + cbNames);
    if (pObj)
    {
        KU8 *pbExtra = (KU8 *)pObj + cbObj;

        KFSCACHE_LOCK(pCache); /** @todo reduce the amount of work done holding the lock */

        pCache->cbObjects += cbObj + cbNames;
        pCache->cObjects++;

        /*
         * Initialize the object.
         */
        pObj->u32Magic      = KFSOBJ_MAGIC;
        pObj->cRefs         = 1;
        pObj->uCacheGen     = bObjType != KFSOBJ_TYPE_MISSING
                            ? pCache->auGenerations[pParent->Obj.fFlags & KFSOBJ_F_USE_CUSTOM_GEN]
                            : pCache->auGenerationsMissing[pParent->Obj.fFlags & KFSOBJ_F_USE_CUSTOM_GEN];
        pObj->bObjType      = bObjType;
        pObj->fHaveStats    = K_FALSE;
        pObj->cPathHashRefs = 0;
        pObj->idxUserDataLock = KU8_MAX;
        pObj->fFlags        = pParent->Obj.fFlags & KFSOBJ_F_INHERITED_MASK;
        pObj->pParent       = pParent;
        pObj->uNameHash     = 0;
        pObj->pNextNameHash = NULL;
        pObj->pNameAlloc    = NULL;
        pObj->pUserDataHead = NULL;

#ifdef KFSCACHE_CFG_UTF16
        pObj->cwcParent = pParent->Obj.cwcParent + pParent->Obj.cwcName + !!pParent->Obj.cwcName;
        pObj->pwszName  = (wchar_t *)kHlpMemCopy(pbExtra, pwszName, cwcName * sizeof(wchar_t));
        pObj->cwcName   = cwcName;
        pbExtra += cwcName * sizeof(wchar_t);
        *pbExtra++ = '\0';
        *pbExtra++ = '\0';
# ifdef KFSCACHE_CFG_SHORT_NAMES
        pObj->cwcShortParent = pParent->Obj.cwcShortParent + pParent->Obj.cwcShortName + !!pParent->Obj.cwcShortName;
        if (cwcShortName)
        {
            pObj->pwszShortName = (wchar_t *)kHlpMemCopy(pbExtra, pwszShortName, cwcShortName * sizeof(wchar_t));
            pObj->cwcShortName  = cwcShortName;
            pbExtra += cwcShortName * sizeof(wchar_t);
            *pbExtra++ = '\0';
            *pbExtra++ = '\0';
        }
        else
        {
            pObj->pwszShortName = pObj->pwszName;
            pObj->cwcShortName  = cwcName;
        }
# endif
#endif
        pObj->cchParent = pParent->Obj.cchParent + pParent->Obj.cchName + !!pParent->Obj.cchName;
        pObj->pszName   = (char *)kHlpMemCopy(pbExtra, pszName, cchName);
        pObj->cchName   = cchName;
        pbExtra += cchName;
        *pbExtra++ = '\0';
# ifdef KFSCACHE_CFG_SHORT_NAMES
        pObj->cchShortParent = pParent->Obj.cchShortParent + pParent->Obj.cchShortName + !!pParent->Obj.cchShortName;
        if (cchShortName)
        {
            pObj->pszShortName = (char *)kHlpMemCopy(pbExtra, pszShortName, cchShortName);
            pObj->cchShortName = cchShortName;
            pbExtra += cchShortName;
            *pbExtra++ = '\0';
        }
        else
        {
            pObj->pszShortName = pObj->pszName;
            pObj->cchShortName = cchName;
        }
#endif
        kHlpAssert(pbExtra - (KU8 *)pObj == cbObj);

        /*
         * Type specific initialization.
         */
        if (fDirish)
        {
            PKFSDIR pDirObj = (PKFSDIR)pObj;
            pDirObj->cChildren          = 0;
            pDirObj->cChildrenAllocated = 0;
            pDirObj->papChildren        = NULL;
            pDirObj->fHashTabMask       = 0;
            pDirObj->papHashTab         = NULL;
            pDirObj->hDir               = INVALID_HANDLE_VALUE;
            pDirObj->uDevNo             = pParent->uDevNo;
            pDirObj->iLastWrite         = 0;
            pDirObj->iLastPopulated     = 0;
            pDirObj->fPopulated         = K_FALSE;
        }

        KFSCACHE_UNLOCK(pCache);
    }
    else
        *penmError = KFSLOOKUPERROR_OUT_OF_MEMORY;
    return pObj;
}


/**
 * Creates a new object given wide char names.
 *
 * This function just converts the paths and calls kFsCacheCreateObject.
 *
 *
 * @returns Pointer (with 1 reference) to the new object.  The object will not
 *          be linked to the parent directory yet.
 *
 *          NULL if we're out of memory.
 *
 * @param   pCache          The cache.
 * @param   pParent         The parent directory.
 * @param   pszName         The ANSI name.
 * @param   cchName         The length of the ANSI name.
 * @param   pwszName        The UTF-16 name.
 * @param   cwcName         The length of the UTF-16 name.
 * @param   pwszShortName   The UTF-16 short name, NULL if none.
 * @param   cwcShortName    The length of the UTF-16 short name, 0 if none.
 * @param   bObjType        The objct type.
 * @param   penmError       Where to explain failures.
 */
PKFSOBJ kFsCacheCreateObjectW(PKFSCACHE pCache, PKFSDIR pParent, wchar_t const *pwszName, KU32 cwcName,
#ifdef KFSCACHE_CFG_SHORT_NAMES
                              wchar_t const *pwszShortName, KU32 cwcShortName,
#endif
                              KU8 bObjType, KFSLOOKUPERROR *penmError)
{
    /* Convert names to ANSI first so we know their lengths. */
    char szName[KFSCACHE_CFG_MAX_ANSI_NAME];
    int  cchName = WideCharToMultiByte(CP_ACP, 0, pwszName, cwcName, szName, sizeof(szName) - 1, NULL, NULL);
    if (cchName >= 0)
    {
#ifdef KFSCACHE_CFG_SHORT_NAMES
        char szShortName[12*3 + 1];
        int  cchShortName = 0;
        if (   cwcShortName == 0
            || (cchShortName = WideCharToMultiByte(CP_ACP, 0, pwszShortName, cwcShortName,
                                                   szShortName, sizeof(szShortName) - 1, NULL, NULL)) > 0)
#endif
        {
            /* No locking needed here, kFsCacheCreateObject takes care of that. */
            return kFsCacheCreateObject(pCache, pParent,
                                        szName, cchName, pwszName, cwcName,
#ifdef KFSCACHE_CFG_SHORT_NAMES
                                        szShortName, cchShortName, pwszShortName, cwcShortName,
#endif
                                        bObjType, penmError);
        }
    }
    *penmError = KFSLOOKUPERROR_ANSI_CONVERSION_ERROR;
    return NULL;
}


/**
 * Creates a missing object.
 *
 * This is used for caching negative results.
 *
 * @returns Pointer to the newly created object on success (already linked into
 *          pParent).  No reference.
 *
 *          NULL on failure.
 *
 * @param   pCache              The cache.
 * @param   pParent             The parent directory.
 * @param   pchName             The name.
 * @param   cchName             The length of the name.
 * @param   penmError           Where to return failure explanations.
 */
static PKFSOBJ kFsCacheCreateMissingA(PKFSCACHE pCache, PKFSDIR pParent, const char *pchName, KU32 cchName,
                                      KFSLOOKUPERROR *penmError)
{
    /*
     * Just convert the name to UTF-16 and call kFsCacheCreateObject to do the job.
     */
    wchar_t wszName[KFSCACHE_CFG_MAX_PATH];
    int cwcName = MultiByteToWideChar(CP_ACP, 0, pchName, cchName, wszName, KFSCACHE_CFG_MAX_UTF16_NAME - 1);
    if (cwcName > 0)
    {
        /** @todo check that it actually doesn't exists before we add it.  We should not
         *        trust the directory enumeration here, or maybe we should?? */

        PKFSOBJ pMissing = kFsCacheCreateObject(pCache, pParent, pchName, cchName, wszName, cwcName,
#ifdef KFSCACHE_CFG_SHORT_NAMES
                                                NULL, 0, NULL, 0,
#endif
                                                KFSOBJ_TYPE_MISSING, penmError);
        if (pMissing)
        {
            KBOOL fRc = kFsCacheDirAddChild(pCache, pParent, pMissing, penmError);
            kFsCacheObjRelease(pCache, pMissing);
            return fRc ? pMissing : NULL;
        }
        return NULL;
    }
    *penmError = KFSLOOKUPERROR_UTF16_CONVERSION_ERROR;
    return NULL;
}


/**
 * Creates a missing object, UTF-16 version.
 *
 * This is used for caching negative results.
 *
 * @returns Pointer to the newly created object on success (already linked into
 *          pParent).  No reference.
 *
 *          NULL on failure.
 *
 * @param   pCache              The cache.
 * @param   pParent             The parent directory.
 * @param   pwcName             The name.
 * @param   cwcName             The length of the name.
 * @param   penmError           Where to return failure explanations.
 */
static PKFSOBJ kFsCacheCreateMissingW(PKFSCACHE pCache, PKFSDIR pParent, const wchar_t *pwcName, KU32 cwcName,
                                      KFSLOOKUPERROR *penmError)
{
    /** @todo check that it actually doesn't exists before we add it.  We should not
     *        trust the directory enumeration here, or maybe we should?? */
    PKFSOBJ pMissing = kFsCacheCreateObjectW(pCache, pParent, pwcName, cwcName,
#ifdef KFSCACHE_CFG_SHORT_NAMES
                                             NULL, 0,
#endif
                                             KFSOBJ_TYPE_MISSING, penmError);
    if (pMissing)
    {
        KBOOL fRc = kFsCacheDirAddChild(pCache, pParent, pMissing, penmError);
        kFsCacheObjRelease(pCache, pMissing);
        return fRc ? pMissing : NULL;
    }
    return NULL;
}


/**
 * Does the growing of names.
 *
 * @returns pCur
 * @param   pCache          The cache.
 * @param   pCur            The object.
 * @param   pchName         The name (not necessarily terminated).
 * @param   cchName         Name length.
 * @param   pwcName         The UTF-16 name (not necessarily terminated).
 * @param   cwcName         The length of the UTF-16 name in wchar_t's.
 * @param   pchShortName    The short name.
 * @param   cchShortName    The length of the short name.  This is 0 if no short
 *                          name.
 * @param   pwcShortName    The short UTF-16 name.
 * @param   cwcShortName    The length of the short UTF-16 name.  This is 0 if
 *                          no short name.
 */
static PKFSOBJ kFsCacheRefreshGrowNames(PKFSCACHE pCache, PKFSOBJ pCur,
                                        const char *pchName, KU32 cchName,
                                        wchar_t const *pwcName, KU32 cwcName
#ifdef KFSCACHE_CFG_SHORT_NAMES
                                        , const char *pchShortName, KU32 cchShortName,
                                        wchar_t const *pwcShortName, KU32 cwcShortName
#endif
                                        )
{
    PKFSOBJNAMEALLOC    pNameAlloc;
    char               *pch;
    KU32                cbNeeded;

    pCache->cNameGrowths++;

    /*
     * Figure out our requirements.
     */
    cbNeeded = sizeof(KU32) + cchName + 1;
#ifdef KFSCACHE_CFG_UTF16
    cbNeeded += (cwcName + 1) * sizeof(wchar_t);
#endif
#ifdef KFSCACHE_CFG_SHORT_NAMES
    cbNeeded += cchShortName + !!cchShortName;
# ifdef KFSCACHE_CFG_UTF16
    cbNeeded += (cwcShortName + !!cwcShortName) * sizeof(wchar_t);
# endif
#endif
    cbNeeded = K_ALIGN_Z(cbNeeded, 8); /* Memory will likely be 8 or 16 byte aligned, so we might just claim it. */

    /*
     * Allocate memory.
     */
    pNameAlloc = pCur->pNameAlloc;
    if (!pNameAlloc)
    {
        pNameAlloc = (PKFSOBJNAMEALLOC)kHlpAlloc(cbNeeded);
        if (!pNameAlloc)
            return pCur;
        pCache->cbObjects += cbNeeded;
        pCur->pNameAlloc = pNameAlloc;
        pNameAlloc->cb = cbNeeded;
    }
    else if (pNameAlloc->cb < cbNeeded)
    {
        pNameAlloc = (PKFSOBJNAMEALLOC)kHlpRealloc(pNameAlloc, cbNeeded);
        if (!pNameAlloc)
            return pCur;
        pCache->cbObjects += cbNeeded - pNameAlloc->cb;
        pCur->pNameAlloc = pNameAlloc;
        pNameAlloc->cb = cbNeeded;
    }

    /*
     * Copy out the new names, starting with the wide char ones to avoid misaligning them.
     */
    pch = &pNameAlloc->abSpace[0];

#ifdef KFSCACHE_CFG_UTF16
    pCur->pwszName = (wchar_t *)pch;
    pCur->cwcName  = cwcName;
    pch = kHlpMemPCopy(pch, pwcName, cwcName * sizeof(wchar_t));
    *pch++ = '\0';
    *pch++ = '\0';

# ifdef KFSCACHE_CFG_SHORT_NAMES
    if (cwcShortName == 0)
    {
        pCur->pwszShortName = pCur->pwszName;
        pCur->cwcShortName  = pCur->cwcName;
    }
    else
    {
        pCur->pwszShortName = (wchar_t *)pch;
        pCur->cwcShortName  = cwcShortName;
        pch = kHlpMemPCopy(pch, pwcShortName, cwcShortName * sizeof(wchar_t));
        *pch++ = '\0';
        *pch++ = '\0';
    }
# endif
#endif

    pCur->pszName = pch;
    pCur->cchName = cchName;
    pch = kHlpMemPCopy(pch, pchName, cchName);
    *pch++ = '\0';

#ifdef KFSCACHE_CFG_SHORT_NAMES
    if (cchShortName == 0)
    {
        pCur->pszShortName = pCur->pszName;
        pCur->cchShortName = pCur->cchName;
    }
    else
    {
        pCur->pszShortName = pch;
        pCur->cchShortName = cchShortName;
        pch = kHlpMemPCopy(pch, pchShortName, cchShortName);
        *pch++ = '\0';
    }
#endif

    return pCur;
}


/**
 * Worker for kFsCacheDirFindOldChild that refreshes the file ID value on an
 * object found by name.
 *
 * @returns pCur.
 * @param   pDirRePop       Repopulation data.
 * @param   pCur            The object to check the names of.
 * @param   idFile          The file ID.
 */
static PKFSOBJ kFsCacheDirRefreshOldChildFileId(PKFSDIRREPOP pDirRePop, PKFSOBJ pCur, KI64 idFile)
{
    KFSCACHE_LOG(("Refreshing %s/%s/ - %s changed file ID from %#llx -> %#llx...\n",
                  pCur->pParent->Obj.pParent->Obj.pszName, pCur->pParent->Obj.pszName, pCur->pszName,
                  pCur->Stats.st_ino, idFile));
    pCur->Stats.st_ino = idFile;
    /** @todo inform user data items...  */
    return pCur;
}


/**
 * Worker for kFsCacheDirFindOldChild that checks the names after an old object
 * has been found the file ID.
 *
 * @returns pCur.
 * @param   pDirRePop       Repopulation data.
 * @param   pCur            The object to check the names of.
 * @param   pwcName         The file name.
 * @param   cwcName         The length of the filename (in wchar_t's).
 * @param   pwcShortName    The short name, if present.
 * @param   cwcShortName    The length of the short name (in wchar_t's).
 */
static PKFSOBJ kFsCacheDirRefreshOldChildName(PKFSDIRREPOP pDirRePop, PKFSOBJ pCur, wchar_t const *pwcName, KU32 cwcName
#ifdef KFSCACHE_CFG_SHORT_NAMES
                                              , wchar_t const *pwcShortName, KU32 cwcShortName
#endif
                                              )
{
    char szName[KFSCACHE_CFG_MAX_ANSI_NAME];
    int  cchName;

    pDirRePop->pCache->cNameChanges++;

    /*
     * Convert the names to ANSI first, that way we know all the lengths.
     */
    cchName = WideCharToMultiByte(CP_ACP, 0, pwcName, cwcName, szName, sizeof(szName) - 1, NULL, NULL);
    if (cchName >= 0)
    {
#ifdef KFSCACHE_CFG_SHORT_NAMES
        char szShortName[12*3 + 1];
        int  cchShortName = 0;
        if (   cwcShortName == 0
            || (cchShortName = WideCharToMultiByte(CP_ACP, 0, pwcShortName, cwcShortName,
                                                   szShortName, sizeof(szShortName) - 1, NULL, NULL)) > 0)
#endif
        {
            /*
             * Shortening is easy for non-directory objects, for
             * directory object we're only good when the length doesn't change
             * on any of the components (cchParent et al).
             *
             * This deals with your typical xxxx.ext.tmp -> xxxx.ext renames.
             */
            if (   cchName <= pCur->cchName
#ifdef KFSCACHE_CFG_UTF16
                && cwcName <= pCur->cwcName
#endif
#ifdef KFSCACHE_CFG_SHORT_NAMES
                && (   cchShortName == 0
                    || (   cchShortName <= pCur->cchShortName
                        && pCur->pszShortName != pCur->pszName
# ifdef KFSCACHE_CFG_UTF16
                        && cwcShortName <= pCur->cwcShortName
                        && pCur->pwszShortName != pCur->pwszName
# endif
                       )
                   )
#endif
               )
            {
                if (   pCur->bObjType != KFSOBJ_TYPE_DIR
                    || (   cchName == pCur->cchName
#ifdef KFSCACHE_CFG_UTF16
                        && cwcName == pCur->cwcName
#endif
#ifdef KFSCACHE_CFG_SHORT_NAMES
                        && (   cchShortName == 0
                            || (   cchShortName == pCur->cchShortName
# ifdef KFSCACHE_CFG_UTF16
                                && cwcShortName == pCur->cwcShortName
                                )
# endif
                           )
#endif
                       )
                   )
                {
                    KFSCACHE_LOG(("Refreshing %ls - name changed to '%*.*ls'\n", pCur->pwszName, cwcName, cwcName, pwcName));
                    *(char *)kHlpMemPCopy((void *)pCur->pszName, szName, cchName) = '\0';
                    pCur->cchName = cchName;
#ifdef KFSCACHE_CFG_UTF16
                    *(wchar_t *)kHlpMemPCopy((void *)pCur->pwszName, pwcName, cwcName * sizeof(wchar_t)) = '\0';
                    pCur->cwcName = cwcName;
#endif
#ifdef KFSCACHE_CFG_SHORT_NAMES
                    *(char *)kHlpMemPCopy((void *)pCur->pszShortName, szShortName, cchShortName) = '\0';
                    pCur->cchShortName = cchShortName;
# ifdef KFSCACHE_CFG_UTF16
                    *(wchar_t *)kHlpMemPCopy((void *)pCur->pwszShortName, pwcShortName, cwcShortName * sizeof(wchar_t)) = '\0';
                    pCur->cwcShortName = cwcShortName;
# endif
#endif
                    return pCur;
                }
            }

            return kFsCacheRefreshGrowNames(pDirRePop->pCache, pCur, szName, cchName, pwcName, cwcName,
#ifdef KFSCACHE_CFG_SHORT_NAMES
                                            szShortName, cchShortName, pwcShortName, cwcShortName
#endif
                                            );
        }
    }

    fprintf(stderr, "kFsCacheDirRefreshOldChildName: WideCharToMultiByte error\n");
    return pCur;
}


/**
 * Worker for kFsCacheDirFindOldChild that checks the names after an old object
 * has been found by the file ID.
 *
 * @returns pCur.
 * @param   pDirRePop       Repopulation data.
 * @param   pCur            The object to check the names of.
 * @param   pwcName         The file name.
 * @param   cwcName         The length of the filename (in wchar_t's).
 * @param   pwcShortName    The short name, if present.
 * @param   cwcShortName    The length of the short name (in wchar_t's).
 */
K_INLINE PKFSOBJ kFsCacheDirCheckOldChildName(PKFSDIRREPOP pDirRePop, PKFSOBJ pCur, wchar_t const *pwcName, KU32 cwcName
#ifdef KFSCACHE_CFG_SHORT_NAMES
                                              , wchar_t const *pwcShortName, KU32 cwcShortName
#endif
                                              )
{
    if (   pCur->cwcName == cwcName
        && kHlpMemComp(pCur->pwszName, pwcName, cwcName * sizeof(wchar_t)) == 0)
    {
#ifdef KFSCACHE_CFG_SHORT_NAMES
        if (cwcShortName == 0
            ?    pCur->pwszShortName == pCur->pwszName
              || (   pCur->cwcShortName == cwcName
                  && kHlpMemComp(pCur->pwszShortName, pCur->pwszName, cwcName * sizeof(wchar_t)) == 0)
            :    pCur->cwcShortName == cwcShortName
              && kHlpMemComp(pCur->pwszShortName, pwcShortName, cwcShortName * sizeof(wchar_t)) == 0 )
#endif
        {
            return pCur;
        }
    }
#ifdef KFSCACHE_CFG_SHORT_NAMES
    return kFsCacheDirRefreshOldChildName(pDirRePop, pCur, pwcName, cwcName, pwcShortName, cwcShortName);
#else
    return kFsCacheDirRefreshOldChildName(pDirRePop, pCur, pwcName, cwcName);
#endif
}


/**
 * Worker for kFsCachePopuplateOrRefreshDir that locates an old child object
 * while re-populating a directory.
 *
 * @returns Pointer to the existing object if found, NULL if not.
 * @param   pDirRePop       Repopulation data.
 * @param   idFile          The file ID, 0 if none.
 * @param   pwcName         The file name.
 * @param   cwcName         The length of the filename (in wchar_t's).
 * @param   pwcShortName    The short name, if present.
 * @param   cwcShortName    The length of the short name (in wchar_t's).
 */
static PKFSOBJ kFsCacheDirFindOldChildSlow(PKFSDIRREPOP pDirRePop, KI64 idFile, wchar_t const *pwcName, KU32 cwcName
#ifdef KFSCACHE_CFG_SHORT_NAMES
                                           , wchar_t const *pwcShortName, KU32 cwcShortName
#endif
                                           )
{
    KU32        cOldChildren  = pDirRePop->cOldChildren;
    KU32 const  iNextOldChild = K_MIN(pDirRePop->iNextOldChild, cOldChildren - 1);
    KU32        iCur;
    KI32        cInc;
    KI32        cDirLefts;

    kHlpAssertReturn(cOldChildren > 0, NULL);

    /*
     * Search by file ID first, if we've got one.
     * ASSUMES that KU32 wraps around when -1 is added to 0.
     */
    if (   idFile != 0
        && idFile != KI64_MAX
        && idFile != KI64_MIN)
    {
        cInc = pDirRePop->cNextOldChildInc;
        kHlpAssert(cInc == -1 || cInc == 1);
        for (cDirLefts = 2; cDirLefts > 0; cDirLefts--)
        {
            for (iCur = iNextOldChild; iCur < cOldChildren; iCur += cInc)
            {
                PKFSOBJ pCur = pDirRePop->papOldChildren[iCur];
                if (pCur->Stats.st_ino == idFile)
                {
                    /* Remove it and check the name. */
                    pDirRePop->cOldChildren = --cOldChildren;
                    if (iCur < cOldChildren)
                        pDirRePop->papOldChildren[iCur] = pDirRePop->papOldChildren[cOldChildren];
                    else
                        cInc = -1;
                    pDirRePop->cNextOldChildInc = cInc;
                    pDirRePop->iNextOldChild    = iCur + cInc;

#ifdef KFSCACHE_CFG_SHORT_NAMES
                    return kFsCacheDirCheckOldChildName(pDirRePop, pCur, pwcName, cwcName, pwcShortName, cwcShortName);
#else
                    return kFsCacheDirCheckOldChildName(pDirRePop, pCur, pwcName, cwcName, pwcShortName, cwcShortName);
#endif
                }
            }
            cInc = -cInc;
        }
    }

    /*
     * Search by name.
     * ASSUMES that KU32 wraps around when -1 is added to 0.
     */
    cInc = pDirRePop->cNextOldChildInc;
    kHlpAssert(cInc == -1 || cInc == 1);
    for (cDirLefts = 2; cDirLefts > 0; cDirLefts--)
    {
        for (iCur = iNextOldChild; iCur < cOldChildren; iCur += cInc)
        {
            PKFSOBJ pCur = pDirRePop->papOldChildren[iCur];
            if (   (   pCur->cwcName == cwcName
                    && kFsCacheIAreEqualW(pCur->pwszName, pwcName, cwcName))
#ifdef KFSCACHE_CFG_SHORT_NAMES
                || (   pCur->cwcShortName == cwcName
                    && pCur->pwszShortName != pCur->pwszName
                    && kFsCacheIAreEqualW(pCur->pwszShortName, pwcName, cwcName))
#endif
               )
            {
                /* Do this first so the compiler can share the rest with the above file ID return. */
                if (pCur->Stats.st_ino == idFile)
                { /* likely */ }
                else
                    pCur = kFsCacheDirRefreshOldChildFileId(pDirRePop, pCur, idFile);

                /* Remove it and check the name. */
                pDirRePop->cOldChildren = --cOldChildren;
                if (iCur < cOldChildren)
                    pDirRePop->papOldChildren[iCur] = pDirRePop->papOldChildren[cOldChildren];
                else
                    cInc = -1;
                pDirRePop->cNextOldChildInc = cInc;
                pDirRePop->iNextOldChild    = iCur + cInc;

#ifdef KFSCACHE_CFG_SHORT_NAMES
                return kFsCacheDirCheckOldChildName(pDirRePop, pCur, pwcName, cwcName, pwcShortName, cwcShortName);
#else
                return kFsCacheDirCheckOldChildName(pDirRePop, pCur, pwcName, cwcName, pwcShortName, cwcShortName);
#endif
            }
        }
        cInc = -cInc;
    }

    return NULL;
}



/**
 * Worker for kFsCachePopuplateOrRefreshDir that locates an old child object
 * while re-populating a directory.
 *
 * @returns Pointer to the existing object if found, NULL if not.
 * @param   pDirRePop       Repopulation data.
 * @param   idFile          The file ID, 0 if none.
 * @param   pwcName         The file name.
 * @param   cwcName         The length of the filename (in wchar_t's).
 * @param   pwcShortName    The short name, if present.
 * @param   cwcShortName    The length of the short name (in wchar_t's).
 */
K_INLINE PKFSOBJ kFsCacheDirFindOldChild(PKFSDIRREPOP pDirRePop, KI64 idFile, wchar_t const *pwcName, KU32 cwcName
#ifdef KFSCACHE_CFG_SHORT_NAMES
                                         , wchar_t const *pwcShortName, KU32 cwcShortName
#endif
                                         )
{
    /*
     * We only check the iNextOldChild element here, hoping that the compiler
     * will actually inline this code, letting the slow version of the function
     * do the rest.
     */
    KU32 cOldChildren = pDirRePop->cOldChildren;
    if (cOldChildren > 0)
    {
        KU32 const  iNextOldChild = K_MIN(pDirRePop->iNextOldChild, cOldChildren - 1);
        PKFSOBJ     pCur          = pDirRePop->papOldChildren[iNextOldChild];

        if (   pCur->Stats.st_ino == idFile
            && idFile != 0
            && idFile != KI64_MAX
            && idFile != KI64_MIN)
            pCur = kFsCacheDirCheckOldChildName(pDirRePop, pCur, pwcName, cwcName, pwcShortName, cwcShortName);
        else if (   pCur->cwcName == cwcName
                 && kHlpMemComp(pCur->pwszName,  pwcName, cwcName * sizeof(wchar_t)) == 0)
        {
            if (pCur->Stats.st_ino == idFile)
            { /* likely */ }
            else
                pCur = kFsCacheDirRefreshOldChildFileId(pDirRePop, pCur, idFile);

#ifdef KFSCACHE_CFG_SHORT_NAMES
            if (cwcShortName == 0
                ?    pCur->pwszShortName == pCur->pwszName
                  || (   pCur->cwcShortName == cwcName
                      && kHlpMemComp(pCur->pwszShortName, pCur->pwszName, cwcName * sizeof(wchar_t)) == 0)
                :    pCur->cwcShortName == cwcShortName
                  && kHlpMemComp(pCur->pwszShortName, pwcShortName, cwcShortName * sizeof(wchar_t)) == 0 )
             { /* likely */ }
             else
                 pCur = kFsCacheDirRefreshOldChildName(pDirRePop, pCur, pwcName, cwcName, pwcShortName, cwcShortName);
#endif
        }
        else
            pCur = NULL;
        if (pCur)
        {
            /*
             * Got a match.  Remove the child from the array, replacing it with
             * the last element.  (This means we're reversing the second half of
             * the elements, which is why we need cNextOldChildInc.)
             */
            pDirRePop->cOldChildren = --cOldChildren;
            if (iNextOldChild < cOldChildren)
                pDirRePop->papOldChildren[iNextOldChild] = pDirRePop->papOldChildren[cOldChildren];
            pDirRePop->iNextOldChild = iNextOldChild + pDirRePop->cNextOldChildInc;
            return pCur;
        }

#ifdef KFSCACHE_CFG_SHORT_NAMES
        return kFsCacheDirFindOldChildSlow(pDirRePop, idFile, pwcName, cwcName, pwcShortName, cwcShortName);
#else
        return kFsCacheDirFindOldChildSlow(pDirRePop, idFile, pwcName, cwcName);
#endif
    }

    return NULL;
}



/**
 * Does the initial directory populating or refreshes it if it has been
 * invalidated.
 *
 * This assumes the parent directory is opened.
 *
 * @returns K_TRUE on success, K_FALSE on error.
 * @param   pCache              The cache.
 * @param   pDir                The directory.
 * @param   penmError           Where to store K_FALSE explanation.
 */
static KBOOL kFsCachePopuplateOrRefreshDir(PKFSCACHE pCache, PKFSDIR pDir, KFSLOOKUPERROR *penmError)
{
    KBOOL                       fRefreshing = K_FALSE;
    KFSDIRREPOP                 DirRePop    = { NULL, 0, 0, 0, NULL };
    MY_UNICODE_STRING           UniStrStar  = { 1 * sizeof(wchar_t), 2 * sizeof(wchar_t), L"*" };
    FILETIME                    Now;

    /** @todo May have to make this more flexible wrt information classes since
     *        older windows versions (XP, w2K) might not correctly support the
     *        ones with file ID on all file systems. */
#ifdef KFSCACHE_CFG_SHORT_NAMES
    MY_FILE_INFORMATION_CLASS const enmInfoClassWithId = MyFileIdBothDirectoryInformation;
    MY_FILE_INFORMATION_CLASS       enmInfoClass = MyFileIdBothDirectoryInformation;
#else
    MY_FILE_INFORMATION_CLASS const enmInfoClassWithId = MyFileIdFullDirectoryInformation;
    MY_FILE_INFORMATION_CLASS       enmInfoClass = MyFileIdFullDirectoryInformation;
#endif
    MY_NTSTATUS                 rcNt;
    MY_IO_STATUS_BLOCK          Ios;
    union
    {
        /* Include the structures for better alignment. */
        MY_FILE_ID_BOTH_DIR_INFORMATION     WithId;
        MY_FILE_ID_FULL_DIR_INFORMATION     NoId;
        /** Buffer padding. We're using a 56KB buffer here to avoid size troubles
         * with CIFS and such that starts at 64KB. */
        KU8                                 abBuf[56*1024];
    } uBuf;


    /*
     * Open the directory.
     */
    if (pDir->hDir == INVALID_HANDLE_VALUE)
    {
        MY_OBJECT_ATTRIBUTES    ObjAttr;
        MY_UNICODE_STRING       UniStr;

        kHlpAssert(!pDir->fPopulated);

        Ios.Information = -1;
        Ios.u.Status    = -1;

        UniStr.Buffer        = (wchar_t *)pDir->Obj.pwszName;
        UniStr.Length        = (USHORT)(pDir->Obj.cwcName * sizeof(wchar_t));
        UniStr.MaximumLength = UniStr.Length + sizeof(wchar_t);

        kHlpAssertStmtReturn(pDir->Obj.pParent, *penmError = KFSLOOKUPERROR_INTERNAL_ERROR, K_FALSE);
        kHlpAssertStmtReturn(pDir->Obj.pParent->hDir != INVALID_HANDLE_VALUE, *penmError = KFSLOOKUPERROR_INTERNAL_ERROR, K_FALSE);
        MyInitializeObjectAttributes(&ObjAttr, &UniStr, OBJ_CASE_INSENSITIVE, pDir->Obj.pParent->hDir, NULL /*pSecAttr*/);

        /** @todo FILE_OPEN_REPARSE_POINT? */
        rcNt = g_pfnNtCreateFile(&pDir->hDir,
                                 FILE_READ_DATA | FILE_LIST_DIRECTORY | FILE_READ_ATTRIBUTES | SYNCHRONIZE,
                                 &ObjAttr,
                                 &Ios,
                                 NULL, /*cbFileInitialAlloc */
                                 FILE_ATTRIBUTE_NORMAL,
                                 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
                                 FILE_OPEN,
                                 FILE_DIRECTORY_FILE | FILE_OPEN_FOR_BACKUP_INTENT | FILE_SYNCHRONOUS_IO_NONALERT,
                                 NULL, /*pEaBuffer*/
                                 0);   /*cbEaBuffer*/
        if (MY_NT_SUCCESS(rcNt))
        {  /* likely */ }
        else
        {
            pDir->hDir = INVALID_HANDLE_VALUE;
            *penmError = KFSLOOKUPERROR_DIR_OPEN_ERROR;
            return K_FALSE;
        }
    }
    /*
     * When re-populating, we replace papChildren in the directory and pick
     * from the old one as we go along.
     */
    else if (pDir->fPopulated)
    {
        KU32  cAllocated;
        void *pvNew;

        /* Make sure we really need to do this first. */
        if (!pDir->fNeedRePopulating)
        {
            if (   pDir->Obj.uCacheGen == KFSOBJ_CACHE_GEN_IGNORE
                || pDir->Obj.uCacheGen == pCache->auGenerations[pDir->Obj.fFlags & KFSOBJ_F_USE_CUSTOM_GEN])
                return K_TRUE;
            if (   kFsCacheRefreshObj(pCache, &pDir->Obj, penmError)
                && !pDir->fNeedRePopulating)
                return K_TRUE;
        }

        /* Yes we do need to. */
        cAllocated = K_ALIGN_Z(pDir->cChildren, 16);
        pvNew      = kHlpAlloc(sizeof(pDir->papChildren[0]) * cAllocated);
        if (pvNew)
        {
            DirRePop.papOldChildren     = pDir->papChildren;
            DirRePop.cOldChildren       = pDir->cChildren;
            DirRePop.iNextOldChild      = 0;
            DirRePop.cNextOldChildInc   = 1;
            DirRePop.pCache             = pCache;

            pDir->cChildren             = 0;
            pDir->cChildrenAllocated    = cAllocated;
            pDir->papChildren           = (PKFSOBJ *)pvNew;
        }
        else
        {
            *penmError = KFSLOOKUPERROR_OUT_OF_MEMORY;
            return K_FALSE;
        }

        fRefreshing = K_TRUE;
    }
    if (!fRefreshing)
        KFSCACHE_LOG(("Populating %s...\n", pDir->Obj.pszName));
    else
        KFSCACHE_LOG(("Refreshing %s...\n", pDir->Obj.pszName));

    /*
     * Enumerate the directory content.
     *
     * Note! The "*" filter is necessary because kFsCacheRefreshObj may have
     *       previously quried a single file name and just passing NULL would
     *       restart that single file name query.
     */
    GetSystemTimeAsFileTime(&Now);
    pDir->iLastPopulated = ((KI64)Now.dwHighDateTime << 32) | Now.dwLowDateTime;
    Ios.Information = -1;
    Ios.u.Status    = -1;
    rcNt = g_pfnNtQueryDirectoryFile(pDir->hDir,
                                     NULL,      /* hEvent */
                                     NULL,      /* pfnApcComplete */
                                     NULL,      /* pvApcCompleteCtx */
                                     &Ios,
                                     &uBuf,
                                     sizeof(uBuf),
                                     enmInfoClass,
                                     FALSE,     /* fReturnSingleEntry */
                                     &UniStrStar, /* Filter / restart pos. */
                                     TRUE);     /* fRestartScan */
    while (MY_NT_SUCCESS(rcNt))
    {
        /*
         * Process the entries in the buffer.
         */
        KSIZE offBuf = 0;
        for (;;)
        {
            union
            {
                KU8                             *pb;
#ifdef KFSCACHE_CFG_SHORT_NAMES
                MY_FILE_ID_BOTH_DIR_INFORMATION *pWithId;
                MY_FILE_BOTH_DIR_INFORMATION    *pNoId;
#else
                MY_FILE_ID_FULL_DIR_INFORMATION *pWithId;
                MY_FILE_FULL_DIR_INFORMATION    *pNoId;
#endif
            }           uPtr;
            PKFSOBJ     pCur;
            KU32        offNext;
            KU32        cbMinCur;
            wchar_t    *pwchFilename;

            /* ASSUME only the FileName member differs between the two structures. */
            uPtr.pb = &uBuf.abBuf[offBuf];
            if (enmInfoClass == enmInfoClassWithId)
            {
                pwchFilename = &uPtr.pWithId->FileName[0];
                cbMinCur  = (KU32)((uintptr_t)&uPtr.pWithId->FileName[0] - (uintptr_t)uPtr.pWithId);
                cbMinCur += uPtr.pNoId->FileNameLength;
            }
            else
            {
                pwchFilename = &uPtr.pNoId->FileName[0];
                cbMinCur  = (KU32)((uintptr_t)&uPtr.pNoId->FileName[0] - (uintptr_t)uPtr.pNoId);
                cbMinCur += uPtr.pNoId->FileNameLength;
            }

            /* We need to skip the '.' and '..' entries. */
            if (   *pwchFilename != '.'
                ||  uPtr.pNoId->FileNameLength > 4
                ||  !(   uPtr.pNoId->FileNameLength == 2
                      ||  (   uPtr.pNoId->FileNameLength == 4
                           && pwchFilename[1] == '.') )
               )
            {
                KBOOL       fRc;
                KU8 const   bObjType = uPtr.pNoId->FileAttributes & FILE_ATTRIBUTE_DIRECTORY ? KFSOBJ_TYPE_DIR
                                     : uPtr.pNoId->FileAttributes & (FILE_ATTRIBUTE_DEVICE | FILE_ATTRIBUTE_REPARSE_POINT)
                                     ? KFSOBJ_TYPE_OTHER : KFSOBJ_TYPE_FILE;

                /*
                 * If refreshing, we must first see if this directory entry already
                 * exists.
                 */
                if (!fRefreshing)
                    pCur = NULL;
                else
                {
                    pCur = kFsCacheDirFindOldChild(&DirRePop,
                                                   enmInfoClass == enmInfoClassWithId ? uPtr.pWithId->FileId.QuadPart : 0,
                                                   pwchFilename, uPtr.pWithId->FileNameLength / sizeof(wchar_t)
#ifdef KFSCACHE_CFG_SHORT_NAMES
                                                   , uPtr.pWithId->ShortName, uPtr.pWithId->ShortNameLength / sizeof(wchar_t)
#endif
                                                   );
                    if (pCur)
                    {
                        if (pCur->bObjType == bObjType)
                        {
                            if (pCur->bObjType == KFSOBJ_TYPE_DIR)
                            {
                                PKFSDIR pCurDir = (PKFSDIR)pCur;
                                if (   !pCurDir->fPopulated
                                    ||  (   pCurDir->iLastWrite == uPtr.pWithId->LastWriteTime.QuadPart
                                         && (pCur->fFlags & KFSOBJ_F_WORKING_DIR_MTIME)
                                         &&    pCurDir->iLastPopulated - pCurDir->iLastWrite
                                            >= KFSCACHE_MIN_LAST_POPULATED_VS_WRITE ))
                                { /* kind of likely */ }
                                else
                                {
                                    KFSCACHE_LOG(("Refreshing %s/%s/ - %s/ needs re-populating...\n",
                                                  pDir->Obj.pParent->Obj.pszName, pDir->Obj.pszName, pCur->pszName));
                                    pCurDir->fNeedRePopulating = K_TRUE;
                                }
                            }
                            if (pCur->uCacheGen != KFSOBJ_CACHE_GEN_IGNORE)
                                pCur->uCacheGen = pCache->auGenerations[pCur->fFlags & KFSOBJ_F_USE_CUSTOM_GEN];
                        }
                        else if (pCur->bObjType == KFSOBJ_TYPE_MISSING)
                        {
                            KFSCACHE_LOG(("Refreshing %s/%s/ - %s appeared as %u, was missing.\n",
                                          pDir->Obj.pParent->Obj.pszName, pDir->Obj.pszName, pCur->pszName, bObjType));
                            pCur->bObjType = bObjType;
                            if (pCur->uCacheGen != KFSOBJ_CACHE_GEN_IGNORE)
                                pCur->uCacheGen = pCache->auGenerations[pCur->fFlags & KFSOBJ_F_USE_CUSTOM_GEN];
                        }
                        else
                        {
                            KFSCACHE_LOG(("Refreshing %s/%s/ - %s changed type from %u to %u! Dropping old object.\n",
                                          pDir->Obj.pParent->Obj.pszName, pDir->Obj.pszName, pCur->pszName,
                                          pCur->bObjType, bObjType));
                            kFsCacheObjRelease(pCache, pCur);
                            pCur = NULL;
                        }
                    }
                    else
                        KFSCACHE_LOG(("Refreshing %s/%s/ - %*.*ls added.\n", pDir->Obj.pParent->Obj.pszName, pDir->Obj.pszName,
                                      uPtr.pNoId->FileNameLength / sizeof(wchar_t), uPtr.pNoId->FileNameLength / sizeof(wchar_t),
                                      pwchFilename));
                }

                if (!pCur)
                {
                    /*
                     * Create the entry (not linked yet).
                     */
                    pCur = kFsCacheCreateObjectW(pCache, pDir, pwchFilename, uPtr.pNoId->FileNameLength / sizeof(wchar_t),
#ifdef KFSCACHE_CFG_SHORT_NAMES
                                                 uPtr.pNoId->ShortName, uPtr.pNoId->ShortNameLength / sizeof(wchar_t),
#endif
                                                 bObjType, penmError);
                    if (!pCur)
                        return K_FALSE;
                    kHlpAssert(pCur->cRefs == 1);
                }

#ifdef KFSCACHE_CFG_SHORT_NAMES
                if (enmInfoClass == enmInfoClassWithId)
                    birdStatFillFromFileIdBothDirInfo(&pCur->Stats, uPtr.pWithId);
                else
                    birdStatFillFromFileBothDirInfo(&pCur->Stats, uPtr.pNoId);
#else
                if (enmInfoClass == enmInfoClassWithId)
                    birdStatFillFromFileIdFullDirInfo(&pCur->Stats, uPtr.pWithId);
                else
                    birdStatFillFromFileFullDirInfo(&pCur->Stats, uPtr.pNoId);
#endif
                pCur->Stats.st_dev = pDir->uDevNo;
                pCur->fHaveStats   = K_TRUE;

                /*
                 * Add the entry to the directory.
                 */
                fRc = kFsCacheDirAddChild(pCache, pDir, pCur, penmError);
                kFsCacheObjRelease(pCache, pCur);
                if (fRc)
                { /* likely */ }
                else
                {
                    rcNt = STATUS_NO_MEMORY;
                    break;
                }
            }
            /*
             * When seeing '.' we update the directory info.
             */
            else if (uPtr.pNoId->FileNameLength == 2)
            {
                pDir->iLastWrite = uPtr.pNoId->LastWriteTime.QuadPart;
#ifdef KFSCACHE_CFG_SHORT_NAMES
                if (enmInfoClass == enmInfoClassWithId)
                    birdStatFillFromFileIdBothDirInfo(&pDir->Obj.Stats, uPtr.pWithId);
                else
                    birdStatFillFromFileBothDirInfo(&pDir->Obj.Stats, uPtr.pNoId);
#else
                if (enmInfoClass == enmInfoClassWithId)
                    birdStatFillFromFileIdFullDirInfo(&pDir->Obj.Stats, uPtr.pWithId);
                else
                    birdStatFillFromFileFullDirInfo(&pDir->Obj.Stats, uPtr.pNoId);
#endif
            }

            /*
             * Advance.
             */
            offNext = uPtr.pNoId->NextEntryOffset;
            if (   offNext >= cbMinCur
                && offNext < sizeof(uBuf))
                offBuf += offNext;
            else
                break;
        }

        /*
         * Read the next chunk.
         */
        rcNt = g_pfnNtQueryDirectoryFile(pDir->hDir,
                                         NULL,      /* hEvent */
                                         NULL,      /* pfnApcComplete */
                                         NULL,      /* pvApcCompleteCtx */
                                         &Ios,
                                         &uBuf,
                                         sizeof(uBuf),
                                         enmInfoClass,
                                         FALSE,     /* fReturnSingleEntry */
                                         &UniStrStar, /* Filter / restart pos. */
                                         FALSE);    /* fRestartScan */
    }

    if (rcNt == MY_STATUS_NO_MORE_FILES)
    {
        /*
         * If refreshing, add missing children objects and ditch the rest.
         * We ignore errors while adding missing children (lazy bird).
         */
        if (!fRefreshing)
        { /* more likely */ }
        else
        {
            while (DirRePop.cOldChildren > 0)
            {
                KFSLOOKUPERROR enmErrorIgn;
                PKFSOBJ pOldChild = DirRePop.papOldChildren[--DirRePop.cOldChildren];
                if (pOldChild->bObjType == KFSOBJ_TYPE_MISSING)
                    kFsCacheDirAddChild(pCache, pDir, pOldChild, &enmErrorIgn);
                else
                {
                    KFSCACHE_LOG(("Refreshing %s/%s/ - %s was removed.\n",
                                  pDir->Obj.pParent->Obj.pszName, pDir->Obj.pszName, pOldChild->pszName));
                    kHlpAssert(pOldChild->bObjType != KFSOBJ_TYPE_DIR);
                    /* Remove from hash table. */
                    if (pOldChild->uNameHash != 0)
                    {
                        KU32    idx = pOldChild->uNameHash & pDir->fHashTabMask;
                        PKFSOBJ pPrev = pDir->papHashTab[idx];
                        if (pPrev == pOldChild)
                            pDir->papHashTab[idx] = pOldChild->pNextNameHash;
                        else
                        {
                            while (pPrev && pPrev->pNextNameHash != pOldChild)
                                pPrev = pPrev->pNextNameHash;
                            kHlpAssert(pPrev);
                            if (pPrev)
                                pPrev->pNextNameHash = pOldChild->pNextNameHash;
                        }
                        pOldChild->uNameHash = 0;
                    }
                }
                kFsCacheObjRelease(pCache, pOldChild);
            }
            kHlpFree(DirRePop.papOldChildren);
        }

        /*
         * Mark the directory as fully populated and up to date.
         */
        pDir->fPopulated        = K_TRUE;
        pDir->fNeedRePopulating = K_FALSE;
        if (pDir->Obj.uCacheGen != KFSOBJ_CACHE_GEN_IGNORE)
            pDir->Obj.uCacheGen = pCache->auGenerations[pDir->Obj.fFlags & KFSOBJ_F_USE_CUSTOM_GEN];
        return K_TRUE;
    }

    /*
     * If we failed during refresh, add back remaining old children.
     */
    if (!fRefreshing)
    {
        while (DirRePop.cOldChildren > 0)
        {
            KFSLOOKUPERROR enmErrorIgn;
            PKFSOBJ pOldChild = DirRePop.papOldChildren[--DirRePop.cOldChildren];
            kFsCacheDirAddChild(pCache, pDir, pOldChild, &enmErrorIgn);
            kFsCacheObjRelease(pCache, pOldChild);
        }
        kHlpFree(DirRePop.papOldChildren);
    }

    kHlpAssertMsgFailed(("%#x\n", rcNt));
    *penmError = KFSLOOKUPERROR_DIR_READ_ERROR;
    return K_TRUE;
}


/**
 * Does the initial directory populating or refreshes it if it has been
 * invalidated.
 *
 * This assumes the parent directory is opened.
 *
 * @returns K_TRUE on success, K_FALSE on error.
 * @param   pCache              The cache.
 * @param   pDir                The directory.
 * @param   penmError           Where to store K_FALSE explanation.  Optional.
 */
KBOOL kFsCacheDirEnsurePopuplated(PKFSCACHE pCache, PKFSDIR pDir, KFSLOOKUPERROR *penmError)
{
    KFSLOOKUPERROR enmIgnored;
    KBOOL          fRet;
    KFSCACHE_LOCK(pCache);
    if (   pDir->fPopulated
        && !pDir->fNeedRePopulating
        && (   pDir->Obj.uCacheGen == KFSOBJ_CACHE_GEN_IGNORE
            || pDir->Obj.uCacheGen == pCache->auGenerations[pDir->Obj.fFlags & KFSOBJ_F_USE_CUSTOM_GEN]) )
        fRet = K_TRUE;
    else
        fRet = kFsCachePopuplateOrRefreshDir(pCache, pDir, penmError ? penmError : &enmIgnored);
    KFSCACHE_UNLOCK(pCache);
    return fRet;
}


/**
 * Checks whether the modified timestamp differs on this directory.
 *
 * @returns K_TRUE if possibly modified, K_FALSE if definitely not modified.
 * @param   pDir                The directory..
 */
static KBOOL kFsCacheDirIsModified(PKFSDIR pDir)
{
    if (   pDir->hDir != INVALID_HANDLE_VALUE
        && (pDir->Obj.fFlags & KFSOBJ_F_WORKING_DIR_MTIME) )
    {
        if (!pDir->fNeedRePopulating)
        {
            MY_IO_STATUS_BLOCK          Ios;
            MY_FILE_BASIC_INFORMATION   BasicInfo;
            MY_NTSTATUS                 rcNt;

            Ios.Information = -1;
            Ios.u.Status    = -1;

            rcNt = g_pfnNtQueryInformationFile(pDir->hDir, &Ios, &BasicInfo, sizeof(BasicInfo), MyFileBasicInformation);
            if (MY_NT_SUCCESS(rcNt))
            {
                if (   BasicInfo.LastWriteTime.QuadPart != pDir->iLastWrite
                    || pDir->iLastPopulated - pDir->iLastWrite < KFSCACHE_MIN_LAST_POPULATED_VS_WRITE)
                {
                    pDir->fNeedRePopulating = K_TRUE;
                    return K_TRUE;
                }
                return K_FALSE;
            }
        }
    }
    /* The cache root never changes. */
    else if (!pDir->Obj.pParent)
        return K_FALSE;

    return K_TRUE;
}


static KBOOL kFsCacheRefreshMissing(PKFSCACHE pCache, PKFSOBJ pMissing, KFSLOOKUPERROR *penmError)
{
    /*
     * If we can, we start by checking whether the parent directory
     * has been modified.   If it has, we need to check if this entry
     * was added or not, most likely it wasn't added.
     */
    if (!kFsCacheDirIsModified(pMissing->pParent))
    {
        KFSCACHE_LOG(("Parent of missing not written to %s/%s\n", pMissing->pParent->Obj.pszName, pMissing->pszName));
        pMissing->uCacheGen = pCache->auGenerationsMissing[pMissing->fFlags & KFSOBJ_F_USE_CUSTOM_GEN];
    }
    else
    {
        MY_UNICODE_STRING           UniStr;
        MY_OBJECT_ATTRIBUTES        ObjAttr;
        MY_FILE_BASIC_INFORMATION   BasicInfo;
        MY_NTSTATUS                 rcNt;

        UniStr.Buffer        = (wchar_t *)pMissing->pwszName;
        UniStr.Length        = (USHORT)(pMissing->cwcName * sizeof(wchar_t));
        UniStr.MaximumLength = UniStr.Length + sizeof(wchar_t);

        kHlpAssert(pMissing->pParent->hDir != INVALID_HANDLE_VALUE);
        MyInitializeObjectAttributes(&ObjAttr, &UniStr, OBJ_CASE_INSENSITIVE, pMissing->pParent->hDir, NULL /*pSecAttr*/);

        rcNt = g_pfnNtQueryAttributesFile(&ObjAttr, &BasicInfo);
        if (!MY_NT_SUCCESS(rcNt))
        {
            /*
             * Probably more likely that a missing node stays missing.
             */
            pMissing->uCacheGen = pCache->auGenerationsMissing[pMissing->fFlags & KFSOBJ_F_USE_CUSTOM_GEN];
            KFSCACHE_LOG(("Still missing %s/%s\n", pMissing->pParent->Obj.pszName, pMissing->pszName));
        }
        else
        {
            /*
             * We must metamorphose this node.  This is tedious business
             * because we need to check the file name casing.  We might
             * just as well update the parent directory...
             */
            KU8 const   bObjType = BasicInfo.FileAttributes & FILE_ATTRIBUTE_DIRECTORY ? KFSOBJ_TYPE_DIR
                                 : BasicInfo.FileAttributes & (FILE_ATTRIBUTE_DEVICE | FILE_ATTRIBUTE_REPARSE_POINT)
                                 ? KFSOBJ_TYPE_OTHER : KFSOBJ_TYPE_FILE;

            KFSCACHE_LOG(("Birth of %s/%s as %d with attribs %#x...\n",
                          pMissing->pParent->Obj.pszName, pMissing->pszName, bObjType, BasicInfo.FileAttributes));
            pMissing->bObjType  = bObjType;
            /* (auGenerations[] - 1): make sure it's not considered up to date */
            pMissing->uCacheGen = pCache->auGenerations[pMissing->fFlags & KFSOBJ_F_USE_CUSTOM_GEN] - 1;
            /* Trigger parent directory repopulation. */
            if (pMissing->pParent->fPopulated)
                pMissing->pParent->fNeedRePopulating = K_TRUE;
/**
 * @todo refresh missing object names when it appears.
 */
        }
    }

    return K_TRUE;
}


static KBOOL kFsCacheRefreshMissingIntermediateDir(PKFSCACHE pCache, PKFSOBJ pMissing, KFSLOOKUPERROR *penmError)
{
    if (kFsCacheRefreshMissing(pCache, pMissing, penmError))
    {
        if (   pMissing->bObjType == KFSOBJ_TYPE_DIR
            || pMissing->bObjType == KFSOBJ_TYPE_MISSING)
            return K_TRUE;
        *penmError = KFSLOOKUPERROR_PATH_COMP_NOT_DIR;
    }

    return K_FALSE;
}


/**
 * Generic object refresh.
 *
 * This does not refresh the content of directories.
 *
 * @returns K_TRUE on success.  K_FALSE and *penmError on failure.
 * @param   pCache              The cache.
 * @param   pObj                The object.
 * @param   penmError           Where to return error info.
 */
static KBOOL kFsCacheRefreshObj(PKFSCACHE pCache, PKFSOBJ pObj, KFSLOOKUPERROR *penmError)
{
    KBOOL fRc;

    /*
     * Since we generally assume nothing goes away in this cache, we only really
     * have a hard time with negative entries.  So, missing stuff goes to
     * complicated land.
     */
    if (pObj->bObjType == KFSOBJ_TYPE_MISSING)
        fRc = kFsCacheRefreshMissing(pCache, pObj, penmError);
    else
    {
        /*
         * This object is supposed to exist, so all we need to do is query essential
         * stats again.  Since we've already got handles on directories, there are
         * two ways to go about this.
         */
        union
        {
            MY_FILE_NETWORK_OPEN_INFORMATION    FullInfo;
            MY_FILE_STANDARD_INFORMATION        StdInfo;
#ifdef KFSCACHE_CFG_SHORT_NAMES
            MY_FILE_ID_BOTH_DIR_INFORMATION     WithId;
            //MY_FILE_BOTH_DIR_INFORMATION        NoId;
#else
            MY_FILE_ID_FULL_DIR_INFORMATION     WithId;
            //MY_FILE_FULL_DIR_INFORMATION        NoId;
#endif
            KU8                                 abPadding[  sizeof(wchar_t) * KFSCACHE_CFG_MAX_UTF16_NAME
                                                          + sizeof(MY_FILE_ID_BOTH_DIR_INFORMATION)];
        } uBuf;
        MY_IO_STATUS_BLOCK                      Ios;
        MY_NTSTATUS                             rcNt;
        if (   pObj->bObjType != KFSOBJ_TYPE_DIR
            || ((PKFSDIR)pObj)->hDir == INVALID_HANDLE_VALUE)
        {
#if 1
            /* This always works and doesn't mess up NtQueryDirectoryFile. */
            MY_UNICODE_STRING    UniStr;
            MY_OBJECT_ATTRIBUTES ObjAttr;

            UniStr.Buffer        = (wchar_t *)pObj->pwszName;
            UniStr.Length        = (USHORT)(pObj->cwcName * sizeof(wchar_t));
            UniStr.MaximumLength = UniStr.Length + sizeof(wchar_t);

            kHlpAssert(pObj->pParent->hDir != INVALID_HANDLE_VALUE);
            MyInitializeObjectAttributes(&ObjAttr, &UniStr, OBJ_CASE_INSENSITIVE, pObj->pParent->hDir, NULL /*pSecAttr*/);

            rcNt = g_pfnNtQueryFullAttributesFile(&ObjAttr, &uBuf.FullInfo);
            if (MY_NT_SUCCESS(rcNt))
            {
                pObj->Stats.st_size          = uBuf.FullInfo.EndOfFile.QuadPart;
                birdNtTimeToTimeSpec(uBuf.FullInfo.CreationTime.QuadPart,   &pObj->Stats.st_birthtim);
                birdNtTimeToTimeSpec(uBuf.FullInfo.ChangeTime.QuadPart,     &pObj->Stats.st_ctim);
                birdNtTimeToTimeSpec(uBuf.FullInfo.LastWriteTime.QuadPart,  &pObj->Stats.st_mtim);
                birdNtTimeToTimeSpec(uBuf.FullInfo.LastAccessTime.QuadPart, &pObj->Stats.st_atim);
                pObj->Stats.st_attribs       = uBuf.FullInfo.FileAttributes;
                pObj->Stats.st_blksize       = 65536;
                pObj->Stats.st_blocks        = (uBuf.FullInfo.AllocationSize.QuadPart + BIRD_STAT_BLOCK_SIZE - 1)
                                             / BIRD_STAT_BLOCK_SIZE;
            }
#else
            /* This alternative lets us keep the inode number up to date and
               detect name case changes.
               Update: This doesn't work on windows 7, it ignores the UniStr
                       and continue with the "*" search. So, we're using the
                       above query instead for the time being. */
            MY_UNICODE_STRING    UniStr;
# ifdef KFSCACHE_CFG_SHORT_NAMES
            MY_FILE_INFORMATION_CLASS enmInfoClass = MyFileIdBothDirectoryInformation;
# else
            MY_FILE_INFORMATION_CLASS enmInfoClass = MyFileIdFullDirectoryInformation;
# endif

            UniStr.Buffer        = (wchar_t *)pObj->pwszName;
            UniStr.Length        = (USHORT)(pObj->cwcName * sizeof(wchar_t));
            UniStr.MaximumLength = UniStr.Length + sizeof(wchar_t);

            kHlpAssert(pObj->pParent->hDir != INVALID_HANDLE_VALUE);

            Ios.Information = -1;
            Ios.u.Status    = -1;
            rcNt = g_pfnNtQueryDirectoryFile(pObj->pParent->hDir,
                                             NULL,      /* hEvent */
                                             NULL,      /* pfnApcComplete */
                                             NULL,      /* pvApcCompleteCtx */
                                             &Ios,
                                             &uBuf,
                                             sizeof(uBuf),
                                             enmInfoClass,
                                             TRUE,      /* fReturnSingleEntry */
                                             &UniStr,   /* Filter / restart pos. */
                                             TRUE);     /* fRestartScan */

            if (MY_NT_SUCCESS(rcNt))
            {
                if (pObj->Stats.st_ino == uBuf.WithId.FileId.QuadPart)
                    KFSCACHE_LOG(("Refreshing %s/%s, no ID change...\n", pObj->pParent->Obj.pszName, pObj->pszName));
                else if (   pObj->cwcName == uBuf.WithId.FileNameLength / sizeof(wchar_t)
# ifdef KFSCACHE_CFG_SHORT_NAMES
                         && (  uBuf.WithId.ShortNameLength == 0
                             ?    pObj->pwszName == pObj->pwszShortName
                               || (   pObj->cwcName == pObj->cwcShortName
                                   && memcmp(pObj->pwszName, pObj->pwszShortName, pObj->cwcName * sizeof(wchar_t)) == 0)
                             : pObj->cwcShortName == uBuf.WithId.ShortNameLength / sizeof(wchar_t)
                               && memcmp(pObj->pwszShortName, uBuf.WithId.ShortName, uBuf.WithId.ShortNameLength) == 0
                            )
# endif
                         && memcmp(pObj->pwszName, uBuf.WithId.FileName, uBuf.WithId.FileNameLength) == 0
                         )
                {
                    KFSCACHE_LOG(("Refreshing %s/%s, ID changed %#llx -> %#llx...\n",
                                  pObj->pParent->Obj.pszName, pObj->pszName, pObj->Stats.st_ino, uBuf.WithId.FileId.QuadPart));
                    pObj->Stats.st_ino = uBuf.WithId.FileId.QuadPart;
                }
                else
                {
                    KFSCACHE_LOG(("Refreshing %s/%s, ID changed %#llx -> %#llx and names too...\n",
                                  pObj->pParent->Obj.pszName, pObj->pszName, pObj->Stats.st_ino, uBuf.WithId.FileId.QuadPart));
                    fprintf(stderr, "kFsCacheRefreshObj - ID + name change not implemented!!\n");
                    fflush(stderr);
                    __debugbreak();
                    pObj->Stats.st_ino = uBuf.WithId.FileId.QuadPart;
                    /** @todo implement as needed.   */
                }

                pObj->Stats.st_size          = uBuf.WithId.EndOfFile.QuadPart;
                birdNtTimeToTimeSpec(uBuf.WithId.CreationTime.QuadPart,   &pObj->Stats.st_birthtim);
                birdNtTimeToTimeSpec(uBuf.WithId.ChangeTime.QuadPart,     &pObj->Stats.st_ctim);
                birdNtTimeToTimeSpec(uBuf.WithId.LastWriteTime.QuadPart,  &pObj->Stats.st_mtim);
                birdNtTimeToTimeSpec(uBuf.WithId.LastAccessTime.QuadPart, &pObj->Stats.st_atim);
                pObj->Stats.st_attribs       = uBuf.WithId.FileAttributes;
                pObj->Stats.st_blksize       = 65536;
                pObj->Stats.st_blocks        = (uBuf.WithId.AllocationSize.QuadPart + BIRD_STAT_BLOCK_SIZE - 1)
                                             / BIRD_STAT_BLOCK_SIZE;
            }
#endif
            if (MY_NT_SUCCESS(rcNt))
            {
                pObj->uCacheGen = pCache->auGenerations[pObj->fFlags & KFSOBJ_F_USE_CUSTOM_GEN];
                fRc = K_TRUE;
            }
            else
            {
                /* ouch! */
                kHlpAssertMsgFailed(("%#x\n", rcNt));
                fprintf(stderr, "kFsCacheRefreshObj - rcNt=%#x on non-dir - not implemented!\n", rcNt);
                __debugbreak();
                fRc = K_FALSE;
            }
        }
        else
        {
            /*
             * An open directory.  Query information via the handle, the
             * file ID shouldn't have been able to change, so we can use
             * NtQueryInformationFile.  Right...
             */
            PKFSDIR pDir = (PKFSDIR)pObj;
            Ios.Information = -1;
            Ios.u.Status    = -1;
            rcNt = g_pfnNtQueryInformationFile(pDir->hDir, &Ios, &uBuf.FullInfo, sizeof(uBuf.FullInfo),
                                               MyFileNetworkOpenInformation);
            if (MY_NT_SUCCESS(rcNt))
                rcNt = Ios.u.Status;
            if (MY_NT_SUCCESS(rcNt))
            {
                pObj->Stats.st_size          = uBuf.FullInfo.EndOfFile.QuadPart;
                birdNtTimeToTimeSpec(uBuf.FullInfo.CreationTime.QuadPart,   &pObj->Stats.st_birthtim);
                birdNtTimeToTimeSpec(uBuf.FullInfo.ChangeTime.QuadPart,     &pObj->Stats.st_ctim);
                birdNtTimeToTimeSpec(uBuf.FullInfo.LastWriteTime.QuadPart,  &pObj->Stats.st_mtim);
                birdNtTimeToTimeSpec(uBuf.FullInfo.LastAccessTime.QuadPart, &pObj->Stats.st_atim);
                pObj->Stats.st_attribs       = uBuf.FullInfo.FileAttributes;
                pObj->Stats.st_blksize       = 65536;
                pObj->Stats.st_blocks        = (uBuf.FullInfo.AllocationSize.QuadPart + BIRD_STAT_BLOCK_SIZE - 1)
                                             / BIRD_STAT_BLOCK_SIZE;

                if (   pDir->iLastWrite == uBuf.FullInfo.LastWriteTime.QuadPart
                    && (pObj->fFlags & KFSOBJ_F_WORKING_DIR_MTIME)
                    && pDir->iLastPopulated - pDir->iLastWrite >= KFSCACHE_MIN_LAST_POPULATED_VS_WRITE)
                    KFSCACHE_LOG(("Refreshing %s/%s/ - no re-populating necessary.\n",
                                  pObj->pParent->Obj.pszName, pObj->pszName));
                else
                {
                    KFSCACHE_LOG(("Refreshing %s/%s/ - needs re-populating...\n",
                                  pObj->pParent->Obj.pszName, pObj->pszName));
                    pDir->fNeedRePopulating = K_TRUE;
#if 0
                    /* Refresh the link count. */
                    rcNt = g_pfnNtQueryInformationFile(pDir->hDir, &Ios, &StdInfo, sizeof(StdInfo), FileStandardInformation);
                    if (MY_NT_SUCCESS(rcNt))
                        rcNt = Ios.s.Status;
                    if (MY_NT_SUCCESS(rcNt))
                        pObj->Stats.st_nlink = StdInfo.NumberOfLinks;
#endif
                }
            }
            if (MY_NT_SUCCESS(rcNt))
            {
                pObj->uCacheGen = pCache->auGenerations[pObj->fFlags & KFSOBJ_F_USE_CUSTOM_GEN];
                fRc = K_TRUE;
            }
            else
            {
                /* ouch! */
                kHlpAssertMsgFailed(("%#x\n", rcNt));
                fprintf(stderr, "kFsCacheRefreshObj - rcNt=%#x on dir - not implemented!\n", rcNt);
                fflush(stderr);
                __debugbreak();
                fRc = K_FALSE;
            }
        }
    }

    return fRc;
}



/**
 * Looks up a drive letter.
 *
 * Will enter the drive if necessary.
 *
 * @returns Pointer to the root directory of the drive or an update-to-date
 *          missing node.
 * @param   pCache              The cache.
 * @param   chLetter            The uppercased drive letter.
 * @param   fFlags              Lookup flags, KFSCACHE_LOOKUP_F_XXX.
 * @param   penmError           Where to return details as to why the lookup
 *                              failed.
 */
static PKFSOBJ kFsCacheLookupDrive(PKFSCACHE pCache, char chLetter, KU32 fFlags, KFSLOOKUPERROR *penmError)
{
    KU32 const          uNameHash = chLetter - 'A';
    PKFSOBJ             pCur      = pCache->RootDir.papHashTab[uNameHash];

    KU32                cLeft;
    PKFSOBJ            *ppCur;
    MY_UNICODE_STRING   NtPath;
    wchar_t             wszTmp[8];
    char                szTmp[4];

    /*
     * Custom drive letter hashing.
     */
    kHlpAssert((uNameHash & pCache->RootDir.fHashTabMask) == uNameHash);
    while (pCur)
    {
        if (   pCur->uNameHash == uNameHash
            && pCur->cchName == 2
            && pCur->pszName[0] == chLetter
            && pCur->pszName[1] == ':')
        {
            if (pCur->bObjType == KFSOBJ_TYPE_DIR)
                return pCur;
            if (   (fFlags & KFSCACHE_LOOKUP_F_NO_REFRESH)
                || kFsCacheRefreshMissingIntermediateDir(pCache, pCur, penmError))
                return pCur;
            return NULL;
        }
        pCur = pCur->pNextNameHash;
    }

    /*
     * Make 100% sure it's not there.
     */
    cLeft = pCache->RootDir.cChildren;
    ppCur = pCache->RootDir.papChildren;
    while (cLeft-- > 0)
    {
        pCur = *ppCur++;
        if (   pCur->cchName == 2
            && pCur->pszName[0] == chLetter
            && pCur->pszName[1] == ':')
        {
            if (pCur->bObjType == KFSOBJ_TYPE_DIR)
                return pCur;
            kHlpAssert(pCur->bObjType == KFSOBJ_TYPE_MISSING);
            if (   (fFlags & KFSCACHE_LOOKUP_F_NO_REFRESH)
                || kFsCacheRefreshMissingIntermediateDir(pCache, pCur, penmError))
                return pCur;
            return NULL;
        }
    }

    if (fFlags & KFSCACHE_LOOKUP_F_NO_INSERT)
    {
        *penmError = KFSLOOKUPERROR_PATH_COMP_NOT_FOUND; /* close enough */
        return NULL;
    }

    /*
     * Need to add it.  We always keep the drive letters open for the benefit
     * of kFsCachePopuplateOrRefreshDir and others.
     */
    wszTmp[0] = szTmp[0] = chLetter;
    wszTmp[1] = szTmp[1] = ':';
    wszTmp[2] = szTmp[2] = '\\';
    wszTmp[3] = '.';
    wszTmp[4] = '\0';
    szTmp[2] = '\0';

    NtPath.Buffer        = NULL;
    NtPath.Length        = 0;
    NtPath.MaximumLength = 0;
    if (g_pfnRtlDosPathNameToNtPathName_U(wszTmp, &NtPath, NULL, NULL))
    {
        HANDLE      hDir;
        MY_NTSTATUS rcNt;
        rcNt = birdOpenFileUniStr(NULL /*hRoot*/,
                                  &NtPath,
                                  FILE_READ_DATA  | FILE_LIST_DIRECTORY | FILE_READ_ATTRIBUTES | SYNCHRONIZE,
                                  FILE_ATTRIBUTE_NORMAL,
                                  FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
                                  FILE_OPEN,
                                  FILE_DIRECTORY_FILE | FILE_OPEN_FOR_BACKUP_INTENT | FILE_SYNCHRONOUS_IO_NONALERT,
                                  OBJ_CASE_INSENSITIVE,
                                  &hDir);
        birdFreeNtPath(&NtPath);
        if (MY_NT_SUCCESS(rcNt))
        {
            PKFSDIR pDir = (PKFSDIR)kFsCacheCreateObject(pCache, &pCache->RootDir, szTmp, 2, wszTmp, 2,
#ifdef KFSCACHE_CFG_SHORT_NAMES
                                                         NULL, 0, NULL, 0,
#endif
                                                         KFSOBJ_TYPE_DIR, penmError);
            if (pDir)
            {
                /*
                 * We need a little bit of extra info for a drive root.  These things are typically
                 * inherited by subdirectories down the tree, so, we do it all here for till that changes.
                 */
                union
                {
                    MY_FILE_FS_VOLUME_INFORMATION       VolInfo;
                    MY_FILE_FS_ATTRIBUTE_INFORMATION    FsAttrInfo;
                    char abPadding[sizeof(MY_FILE_FS_VOLUME_INFORMATION) + 512];
                } uBuf;
                MY_IO_STATUS_BLOCK Ios;
                KBOOL fRc;

                kHlpAssert(pDir->hDir == INVALID_HANDLE_VALUE);
                pDir->hDir = hDir;

                if (birdStatHandle(hDir, &pDir->Obj.Stats, pDir->Obj.pszName) == 0)
                {
                    pDir->Obj.fHaveStats = K_TRUE;
                    pDir->uDevNo = pDir->Obj.Stats.st_dev;
                }
                else
                {
                    /* Just in case. */
                    pDir->Obj.fHaveStats = K_FALSE;
                    rcNt = birdQueryVolumeDeviceNumber(hDir, &uBuf.VolInfo, sizeof(uBuf), &pDir->uDevNo);
                    kHlpAssertMsg(MY_NT_SUCCESS(rcNt), ("%#x\n", rcNt));
                }

                /* Get the file system. */
                pDir->Obj.fFlags &= ~(KFSOBJ_F_NTFS | KFSOBJ_F_WORKING_DIR_MTIME);
                Ios.Information = -1;
                Ios.u.Status    = -1;
                rcNt = g_pfnNtQueryVolumeInformationFile(hDir, &Ios, &uBuf.FsAttrInfo, sizeof(uBuf),
                                                         MyFileFsAttributeInformation);
                if (MY_NT_SUCCESS(rcNt))
                    rcNt = Ios.u.Status;
                if (MY_NT_SUCCESS(rcNt))
                {
                    if (   uBuf.FsAttrInfo.FileSystemName[0] == 'N'
                        && uBuf.FsAttrInfo.FileSystemName[1] == 'T'
                        && uBuf.FsAttrInfo.FileSystemName[2] == 'F'
                        && uBuf.FsAttrInfo.FileSystemName[3] == 'S'
                        && uBuf.FsAttrInfo.FileSystemName[4] == '\0')
                    {
                        DWORD dwDriveType = GetDriveTypeW(wszTmp);
                        if (   dwDriveType == DRIVE_FIXED
                            || dwDriveType == DRIVE_RAMDISK)
                            pDir->Obj.fFlags |= KFSOBJ_F_NTFS | KFSOBJ_F_WORKING_DIR_MTIME;
                    }
                }

                /*
                 * Link the new drive letter into the root dir.
                 */
                fRc = kFsCacheDirAddChild(pCache, &pCache->RootDir, &pDir->Obj, penmError);
                kFsCacheObjRelease(pCache, &pDir->Obj);
                if (fRc)
                {
                    pDir->Obj.pNextNameHash = pCache->RootDir.papHashTab[uNameHash];
                    pCache->RootDir.papHashTab[uNameHash] = &pDir->Obj;
                    return &pDir->Obj;
                }
                return NULL;
            }

            g_pfnNtClose(hDir);
            return NULL;
        }

        /* Assume it doesn't exist if this happens... This may be a little to
           restrictive wrt status code checks. */
        kHlpAssertMsgStmtReturn(   rcNt == MY_STATUS_OBJECT_NAME_NOT_FOUND
                                || rcNt == MY_STATUS_OBJECT_PATH_NOT_FOUND
                                || rcNt == MY_STATUS_OBJECT_PATH_INVALID
                                || rcNt == MY_STATUS_OBJECT_PATH_SYNTAX_BAD,
                                ("%#x\n", rcNt),
                                *penmError = KFSLOOKUPERROR_DIR_OPEN_ERROR,
                                NULL);
    }
    else
    {
        kHlpAssertFailed();
        *penmError = KFSLOOKUPERROR_OUT_OF_MEMORY;
        return NULL;
    }

    /*
     * Maybe create a missing entry.
     */
    if (pCache->fFlags & KFSCACHE_F_MISSING_OBJECTS)
    {
        PKFSOBJ pMissing = kFsCacheCreateObject(pCache, &pCache->RootDir, szTmp, 2, wszTmp, 2,
#ifdef KFSCACHE_CFG_SHORT_NAMES
                                        NULL, 0, NULL, 0,
#endif
                                        KFSOBJ_TYPE_MISSING, penmError);
        if (pMissing)
        {
            KBOOL fRc = kFsCacheDirAddChild(pCache, &pCache->RootDir, pMissing, penmError);
            kFsCacheObjRelease(pCache, pMissing);
            return fRc ? pMissing : NULL;
        }
    }
    else
    {
        /** @todo this isn't necessary correct for a root spec.   */
        *penmError = KFSLOOKUPERROR_PATH_COMP_NOT_FOUND;
    }
    return NULL;
}


/**
 * Slow path that allocates the child hash table and enters the given one.
 *
 * Allocation fialures are ignored.
 *
 * @param   pCache              The cache (for stats).
 * @param   pDir                The directory.
 * @param   uNameHash           The name hash  to enter @a pChild under.
 * @param   pChild              The child to enter into the hash table.
 */
static void kFsCacheDirAllocHashTabAndEnterChild(PKFSCACHE pCache, PKFSDIR pDir, KU32 uNameHash, PKFSOBJ pChild)
{
    if (uNameHash != 0) /* paranoia ^ 4! */
    {
        /*
         * Double the current number of children and round up to a multiple of
         * two so we can avoid division.
         */
        KU32 cbHashTab;
        KU32 cEntries;
        kHlpAssert(pDir->cChildren > 0);
        if (pDir->cChildren <= KU32_MAX / 4)
        {
#if defined(_MSC_VER) && 1
            KU32 cEntriesRaw = pDir->cChildren * 2;
            KU32 cEntriesShift;
            kHlpAssert(sizeof(cEntries) == (unsigned long));
            if (_BitScanReverse(&cEntriesShift, cEntriesRaw))
            {
                if (   K_BIT32(cEntriesShift) < cEntriesRaw
                    && cEntriesShift < 31U)
                    cEntriesShift++;
                cEntries = K_BIT32(cEntriesShift);
            }
            else
            {
                kHlpAssertFailed();
                cEntries = KU32_MAX / 2 + 1;
            }
#else
            cEntries = pDir->cChildren * 2 - 1;
            cEntries |= cEntries >> 1;
            cEntries |= cEntries >> 2;
            cEntries |= cEntries >> 4;
            cEntries |= cEntries >> 8;
            cEntries |= cEntries >> 16;
            cEntries++;
#endif
        }
        else
            cEntries = KU32_MAX / 2 + 1;
        kHlpAssert((cEntries & (cEntries -  1)) == 0);

        cbHashTab = cEntries * sizeof(pDir->papHashTab[0]);
        pDir->papHashTab = (PKFSOBJ *)kHlpAllocZ(cbHashTab);
        if (pDir->papHashTab)
        {
            KU32 idx;
            pDir->fHashTabMask = cEntries - 1;
            pCache->cbObjects += cbHashTab;
            pCache->cChildHashTabs++;
            pCache->cChildHashEntriesTotal += cEntries;

            /*
             * Insert it.
             */
            pChild->uNameHash     = uNameHash;
            idx = uNameHash & (pDir->fHashTabMask);
            pChild->pNextNameHash = pDir->papHashTab[idx];
            pDir->papHashTab[idx] = pChild;
            pCache->cChildHashed++;
        }
    }
}


/**
 * Look up a child node, ANSI version.
 *
 * @returns Pointer to the child if found, NULL if not.
 * @param   pCache              The cache.
 * @param   pParent             The parent directory to search.
 * @param   pchName             The child name to search for (not terminated).
 * @param   cchName             The length of the child name.
 */
static PKFSOBJ kFsCacheFindChildA(PKFSCACHE pCache, PKFSDIR pParent, const char *pchName, KU32 cchName)
{
    /*
     * Check for '.' first ('..' won't appear).
     */
    if (cchName != 1 || *pchName != '.')
    {
        PKFSOBJ    *ppCur;
        KU32        cLeft;
        KU32        uNameHash;

        /*
         * Do hash table lookup.
         *
         * This caches previous lookups, which should be useful when looking up
         * intermediate directories at least.
         */
        if (pParent->papHashTab != NULL)
        {
            PKFSOBJ pCur;
            uNameHash = kFsCacheStrHashN(pchName, cchName);
            pCur = pParent->papHashTab[uNameHash & pParent->fHashTabMask];
            while (pCur)
            {
                if (   pCur->uNameHash == uNameHash
                    && (   (   pCur->cchName == cchName
                            && _mbsnicmp(pCur->pszName, pchName, cchName) == 0)
#ifdef KFSCACHE_CFG_SHORT_NAMES
                        || (   pCur->cchShortName == cchName
                            && pCur->pszShortName != pCur->pszName
                            && _mbsnicmp(pCur->pszShortName, pchName, cchName) == 0)
#endif
                        )
                   )
                {
                    pCache->cChildHashHits++;
                    pCache->cChildSearches++;
                    return pCur;
                }
                pCur = pCur->pNextNameHash;
            }
        }
        else
            uNameHash = 0;

        /*
         * Do linear search.
         */
        cLeft = pParent->cChildren;
        ppCur = pParent->papChildren;
        while (cLeft-- > 0)
        {
            PKFSOBJ pCur = *ppCur++;
            if (   (   pCur->cchName == cchName
                    && _mbsnicmp(pCur->pszName, pchName, cchName) == 0)
#ifdef KFSCACHE_CFG_SHORT_NAMES
                || (   pCur->cchShortName == cchName
                    && pCur->pszShortName != pCur->pszName
                    && _mbsnicmp(pCur->pszShortName, pchName, cchName) == 0)
#endif
               )
            {
                /*
                 * Consider entering it into the parent hash table.
                 * Note! We hash the input, not the name we found.
                 */
                if (   pCur->uNameHash == 0
                    && pParent->cChildren >= 2)
                {
                    if (pParent->papHashTab)
                    {
                        if (uNameHash != 0)
                        {
                            KU32 idxNameHash = uNameHash & pParent->fHashTabMask;
                            pCur->uNameHash     = uNameHash;
                            pCur->pNextNameHash = pParent->papHashTab[idxNameHash];
                            pParent->papHashTab[idxNameHash] = pCur;
                            if (pCur->pNextNameHash)
                                pCache->cChildHashCollisions++;
                            pCache->cChildHashed++;
                        }
                    }
                    else
                        kFsCacheDirAllocHashTabAndEnterChild(pCache, pParent, kFsCacheStrHashN(pchName, cchName), pCur);
                }

                pCache->cChildSearches++;
                return pCur;
            }
        }

        pCache->cChildSearches++;
        return NULL;
    }
    return &pParent->Obj;
}


/**
 * Look up a child node, UTF-16 version.
 *
 * @returns Pointer to the child if found, NULL if not.
 * @param   pCache              The cache.
 * @param   pParent             The parent directory to search.
 * @param   pwcName             The child name to search for (not terminated).
 * @param   cwcName             The length of the child name (in wchar_t's).
 */
static PKFSOBJ kFsCacheFindChildW(PKFSCACHE pCache, PKFSDIR pParent, const wchar_t *pwcName, KU32 cwcName)
{
    /*
     * Check for '.' first ('..' won't appear).
     */
    if (cwcName != 1 || *pwcName != '.')
    {
        PKFSOBJ    *ppCur;
        KU32        cLeft;
        KU32        uNameHash;

        /*
         * Do hash table lookup.
         *
         * This caches previous lookups, which should be useful when looking up
         * intermediate directories at least.
         */
        if (pParent->papHashTab != NULL)
        {
            PKFSOBJ pCur;
            uNameHash = kFsCacheUtf16HashN(pwcName, cwcName);
            pCur = pParent->papHashTab[uNameHash & pParent->fHashTabMask];
            while (pCur)
            {
                if (   pCur->uNameHash == uNameHash
                    && (   (   pCur->cwcName == cwcName
                            && kFsCacheIAreEqualW(pCur->pwszName, pwcName, cwcName))
#ifdef KFSCACHE_CFG_SHORT_NAMES
                         || (   pCur->cwcShortName == cwcName
                             && pCur->pwszShortName != pCur->pwszName
                             && kFsCacheIAreEqualW(pCur->pwszShortName, pwcName, cwcName))
#endif
                       )
                   )
                {
                    pCache->cChildHashHits++;
                    pCache->cChildSearches++;
                    return pCur;
                }
                pCur = pCur->pNextNameHash;
            }
        }
        else
            uNameHash = 0;

        /*
         * Do linear search.
         */
        cLeft = pParent->cChildren;
        ppCur = pParent->papChildren;
        while (cLeft-- > 0)
        {
            PKFSOBJ pCur = *ppCur++;
            if (   (   pCur->cwcName == cwcName
                    && kFsCacheIAreEqualW(pCur->pwszName, pwcName, cwcName))
#ifdef KFSCACHE_CFG_SHORT_NAMES
                || (   pCur->cwcShortName == cwcName
                    && pCur->pwszShortName != pCur->pwszName
                    && kFsCacheIAreEqualW(pCur->pwszShortName, pwcName, cwcName))
#endif
               )
            {
                /*
                 * Consider entering it into the parent hash table.
                 * Note! We hash the input, not the name we found.
                 */
                if (   pCur->uNameHash == 0
                    && pParent->cChildren >= 4)
                {
                    if (pParent->papHashTab)
                    {
                        if (uNameHash != 0)
                        {
                            KU32 idxNameHash = uNameHash & pParent->fHashTabMask;
                            pCur->uNameHash     = uNameHash;
                            pCur->pNextNameHash = pParent->papHashTab[idxNameHash];
                            pParent->papHashTab[idxNameHash] = pCur;
                            if (pCur->pNextNameHash)
                                pCache->cChildHashCollisions++;
                            pCache->cChildHashed++;
                        }
                    }
                    else
                        kFsCacheDirAllocHashTabAndEnterChild(pCache, pParent, kFsCacheUtf16HashN(pwcName, cwcName), pCur);
                }

                pCache->cChildSearches++;
                return pCur;
            }
        }
        pCache->cChildSearches++;
        return NULL;
    }
    return &pParent->Obj;
}


/**
 * Looks up a UNC share, ANSI version.
 *
 * We keep both the server and share in the root directory entry.  This means we
 * have to clean up the entry name before we can insert it.
 *
 * @returns Pointer to the share root directory or an update-to-date missing
 *          node.
 * @param   pCache              The cache.
 * @param   pszPath             The path.
 * @param   fFlags              Lookup flags, KFSCACHE_LOOKUP_F_XXX.
 * @param   poff                Where to return the root dire.
 * @param   penmError           Where to return details as to why the lookup
 *                              failed.
 */
static PKFSOBJ kFsCacheLookupUncShareA(PKFSCACHE pCache, const char *pszPath, KU32 fFlags,
                                       KU32 *poff, KFSLOOKUPERROR *penmError)
{
    /*
     * Special case: Long path prefix w/ drive letter following it.
     * Note! Must've been converted from wide char to ANSI.
     */
    if (   IS_SLASH(pszPath[0])
        && IS_SLASH(pszPath[1])
        && pszPath[2] == '?'
        && IS_SLASH(pszPath[3])
        && IS_ALPHA(pszPath[4])
        && pszPath[5] == ':'
        && IS_SLASH(pszPath[6]) )
    {
        *poff = 4 + 2;
        return kFsCacheLookupDrive(pCache, pszPath[4], fFlags, penmError);
    }

#if 0 /* later */
    KU32 offStartServer;
    KU32 offEndServer;
    KU32 offStartShare;

    KU32 offEnd = 2;
    while (IS_SLASH(pszPath[offEnd]))
        offEnd++;

    offStartServer = offEnd;
    while (   (ch = pszPath[offEnd]) != '\0'
           && !IS_SLASH(ch))
        offEnd++;
    offEndServer = offEnd;

    if (ch != '\0')
    { /* likely */ }
    else
    {
        *penmError = KFSLOOKUPERROR_NOT_FOUND;
        return NULL;
    }

    while (IS_SLASH(pszPath[offEnd]))
        offEnd++;
    offStartServer = offEnd;
    while (   (ch = pszPath[offEnd]) != '\0'
           && !IS_SLASH(ch))
        offEnd++;
#endif
    *penmError = KFSLOOKUPERROR_UNSUPPORTED;
    return NULL;
}


/**
 * Looks up a UNC share, UTF-16 version.
 *
 * We keep both the server and share in the root directory entry.  This means we
 * have to clean up the entry name before we can insert it.
 *
 * @returns Pointer to the share root directory or an update-to-date missing
 *          node.
 * @param   pCache              The cache.
 * @param   pwszPath            The path.
 * @param   fFlags              Lookup flags, KFSCACHE_LOOKUP_F_XXX.
 * @param   poff                Where to return the root dir.
 * @param   penmError           Where to return details as to why the lookup
 *                              failed.
 */
static PKFSOBJ kFsCacheLookupUncShareW(PKFSCACHE pCache, const wchar_t *pwszPath, KU32 fFlags,
                                       KU32 *poff, KFSLOOKUPERROR *penmError)
{
    /*
     * Special case: Long path prefix w/ drive letter following it.
     */
    if (   IS_SLASH(pwszPath[0])
        && IS_SLASH(pwszPath[1])
        && pwszPath[2] == '?'
        && IS_SLASH(pwszPath[3])
        && IS_ALPHA(pwszPath[4])
        && pwszPath[5] == ':'
        && IS_SLASH(pwszPath[6]) )
    {
        *poff = 4 + 2;
        return kFsCacheLookupDrive(pCache, (char)pwszPath[4], fFlags, penmError);
    }


#if 0 /* later */
    KU32 offStartServer;
    KU32 offEndServer;
    KU32 offStartShare;

    KU32 offEnd = 2;
    while (IS_SLASH(pwszPath[offEnd]))
        offEnd++;

    offStartServer = offEnd;
    while (   (ch = pwszPath[offEnd]) != '\0'
           && !IS_SLASH(ch))
        offEnd++;
    offEndServer = offEnd;

    if (ch != '\0')
    { /* likely */ }
    else
    {
        *penmError = KFSLOOKUPERROR_NOT_FOUND;
        return NULL;
    }

    while (IS_SLASH(pwszPath[offEnd]))
        offEnd++;
    offStartServer = offEnd;
    while (   (ch = pwszPath[offEnd]) != '\0'
           && !IS_SLASH(ch))
        offEnd++;
#endif
    *penmError = KFSLOOKUPERROR_UNSUPPORTED;
    return NULL;
}


/**
 * Walks an full path relative to the given directory, ANSI version.
 *
 * This will create any missing nodes while walking.
 *
 * The caller will have to do the path hash table insertion of the result.
 *
 * @returns Pointer to the tree node corresponding to @a pszPath.
 *          NULL on lookup failure, see @a penmError for details.
 * @param   pCache              The cache.
 * @param   pParent             The directory to start the lookup in.
 * @param   pszPath             The path to walk.
 * @param   cchPath             The length of the path.
 * @param   fFlags              Lookup flags, KFSCACHE_LOOKUP_F_XXX.
 * @param   penmError           Where to return details as to why the lookup
 *                              failed.
 * @param   ppLastAncestor      Where to return the last parent element found
 *                              (referenced) in case of error like an path/file
 *                              not found problem.  Optional.
 */
PKFSOBJ kFsCacheLookupRelativeToDirA(PKFSCACHE pCache, PKFSDIR pParent, const char *pszPath, KU32 cchPath, KU32 fFlags,
                                     KFSLOOKUPERROR *penmError, PKFSOBJ *ppLastAncestor)
{
    /*
     * Walk loop.
     */
    KU32 off = 0;
    if (ppLastAncestor)
        *ppLastAncestor = NULL;
    KFSCACHE_LOCK(pCache);
    for (;;)
    {
        PKFSOBJ pChild;

        /*
         * Find the end of the component, counting trailing slashes.
         */
        char    ch;
        KU32    cchSlashes = 0;
        KU32    offEnd     = off + 1;
        while ((ch = pszPath[offEnd]) != '\0')
        {
            if (!IS_SLASH(ch))
                offEnd++;
            else
            {
                do
                    cchSlashes++;
                while (IS_SLASH(pszPath[offEnd + cchSlashes]));
                break;
            }
        }

        /*
         * Do we need to populate or refresh this directory first?
         */
        if (   !pParent->fNeedRePopulating
            && pParent->fPopulated
            && (   pParent->Obj.uCacheGen == KFSOBJ_CACHE_GEN_IGNORE
                || pParent->Obj.uCacheGen == pCache->auGenerations[pParent->Obj.fFlags & KFSOBJ_F_USE_CUSTOM_GEN]) )
        { /* likely */ }
        else if (   (fFlags & (KFSCACHE_LOOKUP_F_NO_INSERT | KFSCACHE_LOOKUP_F_NO_REFRESH))
                 || kFsCachePopuplateOrRefreshDir(pCache, pParent, penmError))
        { /* likely */ }
        else
        {
            if (ppLastAncestor)
                *ppLastAncestor = kFsCacheObjRetainInternal(&pParent->Obj);
            KFSCACHE_UNLOCK(pCache);
            return NULL;
        }

        /*
         * Search the current node for the name.
         *
         * If we don't find it, we may insert a missing node depending on
         * the cache configuration.
         */
        pChild = kFsCacheFindChildA(pCache, pParent, &pszPath[off], offEnd - off);
        if (pChild != NULL)
        { /* probably likely */ }
        else
        {
            if (    (pCache->fFlags & KFSCACHE_F_MISSING_OBJECTS)
                && !(fFlags & KFSCACHE_LOOKUP_F_NO_INSERT))
                pChild = kFsCacheCreateMissingA(pCache, pParent, &pszPath[off], offEnd - off, penmError);
            if (cchSlashes == 0 || offEnd + cchSlashes >= cchPath)
            {
                if (pChild)
                {
                    kFsCacheObjRetainInternal(pChild);
                    KFSCACHE_UNLOCK(pCache);
                    return pChild;
                }
                *penmError = KFSLOOKUPERROR_NOT_FOUND;
            }
            else
                *penmError = KFSLOOKUPERROR_PATH_COMP_NOT_FOUND;
            if (ppLastAncestor)
                *ppLastAncestor = kFsCacheObjRetainInternal(&pParent->Obj);
            KFSCACHE_UNLOCK(pCache);
            return NULL;
        }

        /* Advance off and check if we're done already. */
        off = offEnd + cchSlashes;
        if (   cchSlashes == 0
            || off >= cchPath)
        {
            if (   pChild->bObjType != KFSOBJ_TYPE_MISSING
                || pChild->uCacheGen == KFSOBJ_CACHE_GEN_IGNORE
                || pChild->uCacheGen == pCache->auGenerationsMissing[pChild->fFlags & KFSOBJ_F_USE_CUSTOM_GEN]
                || (fFlags & KFSCACHE_LOOKUP_F_NO_REFRESH)
                || kFsCacheRefreshMissing(pCache, pChild, penmError) )
            { /* likely */ }
            else
            {
                if (ppLastAncestor)
                    *ppLastAncestor = kFsCacheObjRetainInternal(&pParent->Obj);
                KFSCACHE_UNLOCK(pCache);
                return NULL;
            }
            kFsCacheObjRetainInternal(pChild);
            KFSCACHE_UNLOCK(pCache);
            return pChild;
        }

        /*
         * Check that it's a directory.  If a missing entry, we may have to
         * refresh it and re-examin it.
         */
        if (pChild->bObjType == KFSOBJ_TYPE_DIR)
            pParent = (PKFSDIR)pChild;
        else if (pChild->bObjType != KFSOBJ_TYPE_MISSING)
        {
            *penmError = KFSLOOKUPERROR_PATH_COMP_NOT_DIR;
            if (ppLastAncestor)
                *ppLastAncestor = kFsCacheObjRetainInternal(&pParent->Obj);
            KFSCACHE_UNLOCK(pCache);
            return NULL;
        }
        else if (   pChild->uCacheGen == KFSOBJ_CACHE_GEN_IGNORE
                 || pChild->uCacheGen == pCache->auGenerationsMissing[pChild->fFlags & KFSOBJ_F_USE_CUSTOM_GEN]
                 || (fFlags & KFSCACHE_LOOKUP_F_NO_REFRESH))
        {
            *penmError = KFSLOOKUPERROR_PATH_COMP_NOT_FOUND;
            if (ppLastAncestor)
                *ppLastAncestor = kFsCacheObjRetainInternal(&pParent->Obj);
            KFSCACHE_UNLOCK(pCache);
            return NULL;
        }
        else if (kFsCacheRefreshMissingIntermediateDir(pCache, pChild, penmError))
            pParent = (PKFSDIR)pChild;
        else
        {
            if (ppLastAncestor)
                *ppLastAncestor = kFsCacheObjRetainInternal(&pParent->Obj);
            KFSCACHE_UNLOCK(pCache);
            return NULL;
        }
    }

    /* not reached */
    KFSCACHE_UNLOCK(pCache);
    return NULL;
}


/**
 * Walks an full path relative to the given directory, UTF-16 version.
 *
 * This will create any missing nodes while walking.
 *
 * The caller will have to do the path hash table insertion of the result.
 *
 * @returns Pointer to the tree node corresponding to @a pszPath.
 *          NULL on lookup failure, see @a penmError for details.
 * @param   pCache              The cache.
 * @param   pParent             The directory to start the lookup in.
 * @param   pszPath             The path to walk.  No dot-dot bits allowed!
 * @param   cchPath             The length of the path.
 * @param   fFlags              Lookup flags, KFSCACHE_LOOKUP_F_XXX.
 * @param   penmError           Where to return details as to why the lookup
 *                              failed.
 * @param   ppLastAncestor      Where to return the last parent element found
 *                              (referenced) in case of error like an path/file
 *                              not found problem.  Optional.
 */
PKFSOBJ kFsCacheLookupRelativeToDirW(PKFSCACHE pCache, PKFSDIR pParent, const wchar_t *pwszPath, KU32 cwcPath, KU32 fFlags,
                                     KFSLOOKUPERROR *penmError, PKFSOBJ *ppLastAncestor)
{
    /*
     * Walk loop.
     */
    KU32 off = 0;
    if (ppLastAncestor)
        *ppLastAncestor = NULL;
    KFSCACHE_LOCK(pCache);
    for (;;)
    {
        PKFSOBJ pChild;

        /*
         * Find the end of the component, counting trailing slashes.
         */
        wchar_t wc;
        KU32    cwcSlashes = 0;
        KU32    offEnd     = off + 1;
        while ((wc = pwszPath[offEnd]) != '\0')
        {
            if (!IS_SLASH(wc))
                offEnd++;
            else
            {
                do
                    cwcSlashes++;
                while (IS_SLASH(pwszPath[offEnd + cwcSlashes]));
                break;
            }
        }

        /*
         * Do we need to populate or refresh this directory first?
         */
        if (   !pParent->fNeedRePopulating
            && pParent->fPopulated
            && (   pParent->Obj.uCacheGen == KFSOBJ_CACHE_GEN_IGNORE
                || pParent->Obj.uCacheGen == pCache->auGenerations[pParent->Obj.fFlags & KFSOBJ_F_USE_CUSTOM_GEN]) )
        { /* likely */ }
        else if (   (fFlags & (KFSCACHE_LOOKUP_F_NO_INSERT | KFSCACHE_LOOKUP_F_NO_REFRESH))
                 || kFsCachePopuplateOrRefreshDir(pCache, pParent, penmError))
        { /* likely */ }
        else
        {
            if (ppLastAncestor)
                *ppLastAncestor = kFsCacheObjRetainInternal(&pParent->Obj);
            KFSCACHE_UNLOCK(pCache);
            return NULL;
        }

        /*
         * Search the current node for the name.
         *
         * If we don't find it, we may insert a missing node depending on
         * the cache configuration.
         */
        pChild = kFsCacheFindChildW(pCache, pParent, &pwszPath[off], offEnd - off);
        if (pChild != NULL)
        { /* probably likely */ }
        else
        {
            if (    (pCache->fFlags & KFSCACHE_F_MISSING_OBJECTS)
                && !(fFlags & KFSCACHE_LOOKUP_F_NO_INSERT))
                pChild = kFsCacheCreateMissingW(pCache, pParent, &pwszPath[off], offEnd - off, penmError);
            if (cwcSlashes == 0 || offEnd + cwcSlashes >= cwcPath)
            {
                if (pChild)
                {
                    kFsCacheObjRetainInternal(pChild);
                    KFSCACHE_UNLOCK(pCache);
                    return pChild;
                }
                *penmError = KFSLOOKUPERROR_NOT_FOUND;
            }
            else
                *penmError = KFSLOOKUPERROR_PATH_COMP_NOT_FOUND;
            if (ppLastAncestor)
                *ppLastAncestor = kFsCacheObjRetainInternal(&pParent->Obj);
            KFSCACHE_UNLOCK(pCache);
            return NULL;
        }

        /* Advance off and check if we're done already. */
        off = offEnd + cwcSlashes;
        if (   cwcSlashes == 0
            || off >= cwcPath)
        {
            if (   pChild->bObjType != KFSOBJ_TYPE_MISSING
                || pChild->uCacheGen == KFSOBJ_CACHE_GEN_IGNORE
                || pChild->uCacheGen == pCache->auGenerationsMissing[pChild->fFlags & KFSOBJ_F_USE_CUSTOM_GEN]
                || (fFlags & KFSCACHE_LOOKUP_F_NO_REFRESH)
                || kFsCacheRefreshMissing(pCache, pChild, penmError) )
            { /* likely */ }
            else
            {
                if (ppLastAncestor)
                    *ppLastAncestor = kFsCacheObjRetainInternal(&pParent->Obj);
                KFSCACHE_UNLOCK(pCache);
                return NULL;
            }
            kFsCacheObjRetainInternal(pChild);
            KFSCACHE_UNLOCK(pCache);
            return pChild;
        }

        /*
         * Check that it's a directory.  If a missing entry, we may have to
         * refresh it and re-examin it.
         */
        if (pChild->bObjType == KFSOBJ_TYPE_DIR)
            pParent = (PKFSDIR)pChild;
        else if (pChild->bObjType != KFSOBJ_TYPE_MISSING)
        {
            *penmError = KFSLOOKUPERROR_PATH_COMP_NOT_DIR;
            if (ppLastAncestor)
                *ppLastAncestor = kFsCacheObjRetainInternal(&pParent->Obj);
            KFSCACHE_UNLOCK(pCache);
            return NULL;
        }
        else if (   pChild->uCacheGen == KFSOBJ_CACHE_GEN_IGNORE
                 || pChild->uCacheGen == pCache->auGenerationsMissing[pChild->fFlags & KFSOBJ_F_USE_CUSTOM_GEN]
                 || (fFlags & KFSCACHE_LOOKUP_F_NO_REFRESH) )

        {
            *penmError = KFSLOOKUPERROR_PATH_COMP_NOT_FOUND;
            if (ppLastAncestor)
                *ppLastAncestor = kFsCacheObjRetainInternal(&pParent->Obj);
            KFSCACHE_UNLOCK(pCache);
            return NULL;
        }
        else if (kFsCacheRefreshMissingIntermediateDir(pCache, pChild, penmError))
            pParent = (PKFSDIR)pChild;
        else
        {
            if (ppLastAncestor)
                *ppLastAncestor = kFsCacheObjRetainInternal(&pParent->Obj);
            KFSCACHE_UNLOCK(pCache);
            return NULL;
        }
    }

    KFSCACHE_UNLOCK(pCache);
    return NULL;
}

/**
 * Walk the file system tree for the given absolute path, entering it into the
 * hash table.
 *
 * This will create any missing nodes while walking.
 *
 * The caller will have to do the path hash table insertion of the result.
 *
 * @returns Pointer to the tree node corresponding to @a pszPath.
 *          NULL on lookup failure, see @a penmError for details.
 * @param   pCache              The cache.
 * @param   pszPath             The path to walk. No dot-dot bits allowed!
 * @param   cchPath             The length of the path.
 * @param   fFlags              Lookup flags, KFSCACHE_LOOKUP_F_XXX.
 * @param   penmError           Where to return details as to why the lookup
 *                              failed.
 * @param   ppLastAncestor      Where to return the last parent element found
 *                              (referenced) in case of error an path/file not
 *                              found problem.  Optional.
 */
static PKFSOBJ kFsCacheLookupAbsoluteA(PKFSCACHE pCache, const char *pszPath, KU32 cchPath, KU32 fFlags,
                                       KFSLOOKUPERROR *penmError, PKFSOBJ *ppLastAncestor)
{
    PKFSOBJ     pRoot;
    KU32        cchSlashes;
    KU32        offEnd;

    KFSCACHE_LOG2(("kFsCacheLookupAbsoluteA(%s)\n", pszPath));

    /*
     * The root "directory" needs special handling, so we keep it outside the
     * main search loop. (Special: Cannot enumerate it, UNCs, ++.)
     */
    cchSlashes = 0;
    if (   pszPath[1] == ':'
        && IS_ALPHA(pszPath[0]))
    {
        /* Drive letter. */
        offEnd = 2;
        kHlpAssert(IS_SLASH(pszPath[2]));
        pRoot = kFsCacheLookupDrive(pCache, toupper(pszPath[0]), fFlags, penmError);
    }
    else if (   IS_SLASH(pszPath[0])
             && IS_SLASH(pszPath[1]) )
        pRoot = kFsCacheLookupUncShareA(pCache, pszPath, fFlags, &offEnd, penmError);
    else
    {
        *penmError = KFSLOOKUPERROR_UNSUPPORTED;
        return NULL;
    }
    if (pRoot)
    { /* likely */ }
    else
        return NULL;

    /* Count slashes trailing the root spec. */
    if (offEnd < cchPath)
    {
        kHlpAssert(IS_SLASH(pszPath[offEnd]));
        do
            cchSlashes++;
        while (IS_SLASH(pszPath[offEnd + cchSlashes]));
    }

    /* Done already? */
    if (offEnd >= cchPath)
    {
        if (   pRoot->uCacheGen == KFSOBJ_CACHE_GEN_IGNORE
            || pRoot->uCacheGen == (  pRoot->bObjType != KFSOBJ_TYPE_MISSING
                                    ? pCache->auGenerations[       pRoot->fFlags & KFSOBJ_F_USE_CUSTOM_GEN]
                                    : pCache->auGenerationsMissing[pRoot->fFlags & KFSOBJ_F_USE_CUSTOM_GEN])
            || (fFlags & KFSCACHE_LOOKUP_F_NO_REFRESH)
            || kFsCacheRefreshObj(pCache, pRoot, penmError))
            return kFsCacheObjRetainInternal(pRoot);
        if (ppLastAncestor)
            *ppLastAncestor = kFsCacheObjRetainInternal(pRoot);
        return NULL;
    }

    /* Check that we've got a valid result and not a cached negative one. */
    if (pRoot->bObjType == KFSOBJ_TYPE_DIR)
    { /* likely */ }
    else
    {
        kHlpAssert(pRoot->bObjType == KFSOBJ_TYPE_MISSING);
        kHlpAssert(   pRoot->uCacheGen == KFSOBJ_CACHE_GEN_IGNORE
                   || pRoot->uCacheGen == pCache->auGenerationsMissing[pRoot->fFlags & KFSOBJ_F_USE_CUSTOM_GEN]);
        return pRoot;
    }

    /*
     * Now that we've found a valid root directory, lookup the
     * remainder of the path starting with it.
     */
    return kFsCacheLookupRelativeToDirA(pCache, (PKFSDIR)pRoot, &pszPath[offEnd + cchSlashes],
                                        cchPath - offEnd - cchSlashes, fFlags, penmError, ppLastAncestor);
}


/**
 * Walk the file system tree for the given absolute path, UTF-16 version.
 *
 * This will create any missing nodes while walking.
 *
 * The caller will have to do the path hash table insertion of the result.
 *
 * @returns Pointer to the tree node corresponding to @a pszPath.
 *          NULL on lookup failure, see @a penmError for details.
 * @param   pCache              The cache.
 * @param   pwszPath            The path to walk.
 * @param   cwcPath             The length of the path (in wchar_t's).
 * @param   fFlags              Lookup flags, KFSCACHE_LOOKUP_F_XXX.
 * @param   penmError           Where to return details as to why the lookup
 *                              failed.
 * @param   ppLastAncestor      Where to return the last parent element found
 *                              (referenced) in case of error an path/file not
 *                              found problem.  Optional.
 */
static PKFSOBJ kFsCacheLookupAbsoluteW(PKFSCACHE pCache, const wchar_t *pwszPath, KU32 cwcPath, KU32 fFlags,
                                       KFSLOOKUPERROR *penmError, PKFSOBJ *ppLastAncestor)
{
    PKFSDIR     pParent = &pCache->RootDir;
    PKFSOBJ     pRoot;
    KU32        off;
    KU32        cwcSlashes;
    KU32        offEnd;

    KFSCACHE_LOG2(("kFsCacheLookupAbsoluteW(%ls)\n", pwszPath));

    /*
     * The root "directory" needs special handling, so we keep it outside the
     * main search loop. (Special: Cannot enumerate it, UNCs, ++.)
     */
    cwcSlashes = 0;
    off        = 0;
    if (   pwszPath[1] == ':'
        && IS_ALPHA(pwszPath[0]))
    {
        /* Drive letter. */
        offEnd = 2;
        kHlpAssert(IS_SLASH(pwszPath[2]));
        pRoot = kFsCacheLookupDrive(pCache, toupper(pwszPath[0]), fFlags, penmError);
    }
    else if (   IS_SLASH(pwszPath[0])
             && IS_SLASH(pwszPath[1]) )
        pRoot = kFsCacheLookupUncShareW(pCache, pwszPath, fFlags, &offEnd, penmError);
    else
    {
        *penmError = KFSLOOKUPERROR_UNSUPPORTED;
        return NULL;
    }
    if (pRoot)
    { /* likely */ }
    else
        return NULL;

    /* Count slashes trailing the root spec. */
    if (offEnd < cwcPath)
    {
        kHlpAssert(IS_SLASH(pwszPath[offEnd]));
        do
            cwcSlashes++;
        while (IS_SLASH(pwszPath[offEnd + cwcSlashes]));
    }

    /* Done already? */
    if (offEnd >= cwcPath)
    {
        if (   pRoot->uCacheGen == KFSOBJ_CACHE_GEN_IGNORE
            || pRoot->uCacheGen == (pRoot->bObjType != KFSOBJ_TYPE_MISSING
                                    ? pCache->auGenerations[       pRoot->fFlags & KFSOBJ_F_USE_CUSTOM_GEN]
                                    : pCache->auGenerationsMissing[pRoot->fFlags & KFSOBJ_F_USE_CUSTOM_GEN])
            || (fFlags & KFSCACHE_LOOKUP_F_NO_REFRESH)
            || kFsCacheRefreshObj(pCache, pRoot, penmError))
            return kFsCacheObjRetainInternal(pRoot);
        if (ppLastAncestor)
            *ppLastAncestor = kFsCacheObjRetainInternal(pRoot);
        return NULL;
    }

    /* Check that we've got a valid result and not a cached negative one. */
    if (pRoot->bObjType == KFSOBJ_TYPE_DIR)
    { /* likely */ }
    else
    {
        kHlpAssert(pRoot->bObjType == KFSOBJ_TYPE_MISSING);
        kHlpAssert(   pRoot->uCacheGen == KFSOBJ_CACHE_GEN_IGNORE
                   || pRoot->uCacheGen == pCache->auGenerationsMissing[pRoot->fFlags & KFSOBJ_F_USE_CUSTOM_GEN]);
        return pRoot;
    }

    /*
     * Now that we've found a valid root directory, lookup the
     * remainder of the path starting with it.
     */
    return kFsCacheLookupRelativeToDirW(pCache, (PKFSDIR)pRoot, &pwszPath[offEnd + cwcSlashes],
                                        cwcPath - offEnd - cwcSlashes, fFlags, penmError, ppLastAncestor);
}


/**
 * This deals with paths that are relative and paths that contains '..'
 * elements, ANSI version.
 *
 * @returns Pointer to object corresponding to @a pszPath on success.
 *          NULL if this isn't a path we care to cache.
 *
 * @param   pCache              The cache.
 * @param   pszPath             The path.
 * @param   cchPath             The length of the path.
 * @param   fFlags              Lookup flags, KFSCACHE_LOOKUP_F_XXX.
 * @param   penmError           Where to return details as to why the lookup
 *                              failed.
 * @param   ppLastAncestor      Where to return the last parent element found
 *                              (referenced) in case of error an path/file not
 *                              found problem.  Optional.
 */
static PKFSOBJ kFsCacheLookupSlowA(PKFSCACHE pCache, const char *pszPath, KU32 cchPath, KU32 fFlags,
                                   KFSLOOKUPERROR *penmError, PKFSOBJ *ppLastAncestor)
{
    /*
     * We just call GetFullPathNameA here to do the job as getcwd and _getdcwd
     * ends up calling it anyway.
     */
    char szFull[KFSCACHE_CFG_MAX_PATH];
    UINT cchFull = GetFullPathNameA(pszPath, sizeof(szFull), szFull, NULL);
    if (   cchFull >= 3
        && cchFull < sizeof(szFull))
    {
        KFSCACHE_LOG2(("kFsCacheLookupSlowA(%s)\n", pszPath));
        return kFsCacheLookupAbsoluteA(pCache, szFull, cchFull, fFlags, penmError, ppLastAncestor);
    }

    /* The path is too long! */
    kHlpAssertMsgFailed(("'%s' -> cchFull=%u\n", pszPath, cchFull));
    *penmError = cchFull >= 3 ? KFSLOOKUPERROR_PATH_TOO_LONG : KFSLOOKUPERROR_PATH_TOO_SHORT;
    return NULL;
}


/**
 * This deals with paths that are relative and paths that contains '..'
 * elements, UTF-16 version.
 *
 * @returns Pointer to object corresponding to @a pszPath on success.
 *          NULL if this isn't a path we care to cache.
 *
 * @param   pCache              The cache.
 * @param   pwszPath            The path.
 * @param   cwcPath             The length of the path (in wchar_t's).
 * @param   fFlags              Lookup flags, KFSCACHE_LOOKUP_F_XXX.
 * @param   penmError           Where to return details as to why the lookup
 *                              failed.
 * @param   ppLastAncestor      Where to return the last parent element found
 *                              (referenced) in case of error an path/file not
 *                              found problem.  Optional.
 */
static PKFSOBJ kFsCacheLookupSlowW(PKFSCACHE pCache, const wchar_t *pwszPath, KU32 wcwPath, KU32 fFlags,
                                   KFSLOOKUPERROR *penmError, PKFSOBJ *ppLastAncestor)
{
    /*
     * We just call GetFullPathNameA here to do the job as getcwd and _getdcwd
     * ends up calling it anyway.
     */
    wchar_t wszFull[KFSCACHE_CFG_MAX_PATH];
    UINT cwcFull = GetFullPathNameW(pwszPath, KFSCACHE_CFG_MAX_PATH, wszFull, NULL);
    if (   cwcFull >= 3
        && cwcFull < KFSCACHE_CFG_MAX_PATH)
    {
        KFSCACHE_LOG2(("kFsCacheLookupSlowA(%ls)\n", pwszPath));
        return kFsCacheLookupAbsoluteW(pCache, wszFull, cwcFull, fFlags, penmError, ppLastAncestor);
    }

    /* The path is too long! */
    kHlpAssertMsgFailed(("'%ls' -> cwcFull=%u\n", pwszPath, cwcFull));
    *penmError = cwcFull >= 3 ? KFSLOOKUPERROR_PATH_TOO_LONG : KFSLOOKUPERROR_PATH_TOO_SHORT;
    return NULL;
}


/**
 * Refreshes a path hash that has expired, ANSI version.
 *
 * @returns pHash on success, NULL if removed.
 * @param   pCache              The cache.
 * @param   pHashEntry          The path hash.
 * @param   idxHashTab          The hash table entry.
 */
static PKFSHASHA kFsCacheRefreshPathA(PKFSCACHE pCache, PKFSHASHA pHashEntry, KU32 idxHashTab)
{
    PKFSOBJ pLastAncestor = NULL;
    if (!pHashEntry->pFsObj)
    {
        if (pHashEntry->fAbsolute)
            pHashEntry->pFsObj = kFsCacheLookupAbsoluteA(pCache, pHashEntry->pszPath, pHashEntry->cchPath, 0 /*fFlags*/,
                                                         &pHashEntry->enmError, &pLastAncestor);
        else
            pHashEntry->pFsObj = kFsCacheLookupSlowA(pCache, pHashEntry->pszPath, pHashEntry->cchPath, 0 /*fFlags*/,
                                                     &pHashEntry->enmError, &pLastAncestor);
    }
    else
    {
        KU8             bOldType = pHashEntry->pFsObj->bObjType;
        KFSLOOKUPERROR  enmError;
        if (kFsCacheRefreshObj(pCache, pHashEntry->pFsObj, &enmError))
        {
            if (pHashEntry->pFsObj->bObjType == bOldType)
            { }
            else
            {
                pHashEntry->pFsObj->cPathHashRefs -= 1;
                kFsCacheObjRelease(pCache, pHashEntry->pFsObj);
                if (pHashEntry->fAbsolute)
                    pHashEntry->pFsObj = kFsCacheLookupAbsoluteA(pCache, pHashEntry->pszPath, pHashEntry->cchPath, 0 /*fFlags*/,
                                                                 &pHashEntry->enmError, &pLastAncestor);
                else
                    pHashEntry->pFsObj = kFsCacheLookupSlowA(pCache, pHashEntry->pszPath, pHashEntry->cchPath, 0 /*fFlags*/,
                                                             &pHashEntry->enmError, &pLastAncestor);
            }
        }
        else
        {
            fprintf(stderr, "kFsCacheRefreshPathA - refresh failure handling not implemented!\n");
            __debugbreak();
            /** @todo just remove this entry.   */
            return NULL;
        }
    }

    if (pLastAncestor && !pHashEntry->pFsObj)
        pHashEntry->idxMissingGen = pLastAncestor->fFlags & KFSOBJ_F_USE_CUSTOM_GEN;
    pHashEntry->uCacheGen = !pHashEntry->pFsObj
                          ? pCache->auGenerationsMissing[pHashEntry->idxMissingGen]
                          : pHashEntry->pFsObj->bObjType == KFSOBJ_TYPE_MISSING
                          ? pCache->auGenerationsMissing[pHashEntry->pFsObj->fFlags & KFSOBJ_F_USE_CUSTOM_GEN]
                          : pCache->auGenerations[       pHashEntry->pFsObj->fFlags & KFSOBJ_F_USE_CUSTOM_GEN];
    if (pLastAncestor)
        kFsCacheObjRelease(pCache, pLastAncestor);
    return pHashEntry;
}


/**
 * Refreshes a path hash that has expired, UTF-16 version.
 *
 * @returns pHash on success, NULL if removed.
 * @param   pCache              The cache.
 * @param   pHashEntry          The path hash.
 * @param   idxHashTab          The hash table entry.
 */
static PKFSHASHW kFsCacheRefreshPathW(PKFSCACHE pCache, PKFSHASHW pHashEntry, KU32 idxHashTab)
{
    PKFSOBJ pLastAncestor = NULL;
    if (!pHashEntry->pFsObj)
    {
        if (pHashEntry->fAbsolute)
            pHashEntry->pFsObj = kFsCacheLookupAbsoluteW(pCache, pHashEntry->pwszPath, pHashEntry->cwcPath, 0 /*fFlags*/,
                                                         &pHashEntry->enmError, &pLastAncestor);
        else
            pHashEntry->pFsObj = kFsCacheLookupSlowW(pCache, pHashEntry->pwszPath, pHashEntry->cwcPath, 0 /*fFlags*/,
                                                     &pHashEntry->enmError, &pLastAncestor);
    }
    else
    {
        KU8             bOldType = pHashEntry->pFsObj->bObjType;
        KFSLOOKUPERROR  enmError;
        if (kFsCacheRefreshObj(pCache, pHashEntry->pFsObj, &enmError))
        {
            if (pHashEntry->pFsObj->bObjType == bOldType)
            { }
            else
            {
                pHashEntry->pFsObj->cPathHashRefs -= 1;
                kFsCacheObjRelease(pCache, pHashEntry->pFsObj);
                if (pHashEntry->fAbsolute)
                    pHashEntry->pFsObj = kFsCacheLookupAbsoluteW(pCache, pHashEntry->pwszPath, pHashEntry->cwcPath, 0 /*fFlags*/,
                                                                 &pHashEntry->enmError, &pLastAncestor);
                else
                    pHashEntry->pFsObj = kFsCacheLookupSlowW(pCache, pHashEntry->pwszPath, pHashEntry->cwcPath, 0 /*fFlags*/,
                                                             &pHashEntry->enmError, &pLastAncestor);
            }
        }
        else
        {
            fprintf(stderr, "kFsCacheRefreshPathW - refresh failure handling not implemented!\n");
            fflush(stderr);
            __debugbreak();
            /** @todo just remove this entry.   */
            return NULL;
        }
    }
    if (pLastAncestor && !pHashEntry->pFsObj)
        pHashEntry->idxMissingGen = pLastAncestor->fFlags & KFSOBJ_F_USE_CUSTOM_GEN;
    pHashEntry->uCacheGen = !pHashEntry->pFsObj
                          ? pCache->auGenerationsMissing[pHashEntry->idxMissingGen]
                          : pHashEntry->pFsObj->bObjType == KFSOBJ_TYPE_MISSING
                          ? pCache->auGenerationsMissing[pHashEntry->pFsObj->fFlags & KFSOBJ_F_USE_CUSTOM_GEN]
                          : pCache->auGenerations[       pHashEntry->pFsObj->fFlags & KFSOBJ_F_USE_CUSTOM_GEN];
    if (pLastAncestor)
        kFsCacheObjRelease(pCache, pLastAncestor);
    return pHashEntry;
}


/**
 * Internal lookup worker that looks up a KFSOBJ for the given ANSI path with
 * length and hash.
 *
 * This will first try the hash table.  If not in the hash table, the file
 * system cache tree is walked, missing bits filled in and finally a hash table
 * entry is created.
 *
 * Only drive letter paths are cachable.  We don't do any UNC paths at this
 * point.
 *
 * @returns Reference to object corresponding to @a pszPath on success, this
 *          must be released by kFsCacheObjRelease.
 *          NULL if not a path we care to cache.
 * @param   pCache              The cache.
 * @param   pchPath             The path to lookup.
 * @param   cchPath             The path length.
 * @param   uHashPath           The hash of the path.
 * @param   penmError           Where to return details as to why the lookup
 *                              failed.
 */
static PKFSOBJ kFsCacheLookupHashedA(PKFSCACHE pCache, const char *pchPath, KU32 cchPath, KU32 uHashPath,
                                     KFSLOOKUPERROR *penmError)
{
    /*
     * Do hash table lookup of the path.
     */
    KU32        idxHashTab = uHashPath % K_ELEMENTS(pCache->apAnsiPaths);
    PKFSHASHA   pHashEntry = pCache->apAnsiPaths[idxHashTab];
    kHlpAssert(pCache->u32Magic == KFSCACHE_MAGIC);
    if (pHashEntry)
    {
        do
        {
            if (   pHashEntry->uHashPath == uHashPath
                && pHashEntry->cchPath   == cchPath
                && kHlpMemComp(pHashEntry->pszPath, pchPath, cchPath) == 0)
            {
                PKFSOBJ pFsObj;
                if (   pHashEntry->uCacheGen == KFSOBJ_CACHE_GEN_IGNORE
                    || pHashEntry->uCacheGen == (  (pFsObj = pHashEntry->pFsObj) != NULL
                                                 ? pFsObj->bObjType != KFSOBJ_TYPE_MISSING
                                                   ? pCache->auGenerations[       pFsObj->fFlags & KFSOBJ_F_USE_CUSTOM_GEN]
                                                   : pCache->auGenerationsMissing[pFsObj->fFlags & KFSOBJ_F_USE_CUSTOM_GEN]
                                                 : pCache->auGenerationsMissing[pHashEntry->idxMissingGen])
                    || (pHashEntry = kFsCacheRefreshPathA(pCache, pHashEntry, idxHashTab)) )
                {
                    pCache->cLookups++;
                    pCache->cPathHashHits++;
                    KFSCACHE_LOG2(("kFsCacheLookupA(%*.*s) - hit %p\n", cchPath, cchPath, pchPath, pHashEntry->pFsObj));
                    *penmError = pHashEntry->enmError;
                    if (pHashEntry->pFsObj)
                        return kFsCacheObjRetainInternal(pHashEntry->pFsObj);
                    return NULL;
                }
                break;
            }
            pHashEntry = pHashEntry->pNext;
        } while (pHashEntry);
    }

    /*
     * Create an entry for it by walking the file system cache and filling in the blanks.
     */
    if (   cchPath > 0
        && cchPath < KFSCACHE_CFG_MAX_PATH)
    {
        PKFSOBJ pFsObj;
        KBOOL   fAbsolute;
        PKFSOBJ pLastAncestor = NULL;

        /* Is absolute without any '..' bits? */
        if (   cchPath >= 3
            && (   (   pchPath[1] == ':'    /* Drive letter */
                    && IS_SLASH(pchPath[2])
                    && IS_ALPHA(pchPath[0]) )
                || (   IS_SLASH(pchPath[0]) /* UNC */
                    && IS_SLASH(pchPath[1]) ) )
            && !kFsCacheHasDotDotA(pchPath, cchPath) )
        {
            pFsObj = kFsCacheLookupAbsoluteA(pCache, pchPath, cchPath, 0 /*fFlags*/, penmError, &pLastAncestor);
            fAbsolute = K_TRUE;
        }
        else
        {
            pFsObj = kFsCacheLookupSlowA(pCache, pchPath, cchPath, 0 /*fFlags*/, penmError, &pLastAncestor);
            fAbsolute = K_FALSE;
        }
        if (   pFsObj
            || (   (pCache->fFlags & KFSCACHE_F_MISSING_PATHS)
                && *penmError != KFSLOOKUPERROR_PATH_TOO_LONG)
            || *penmError == KFSLOOKUPERROR_UNSUPPORTED )
            kFsCacheCreatePathHashTabEntryA(pCache, pFsObj, pchPath, cchPath, uHashPath, idxHashTab, fAbsolute,
                                            pLastAncestor ? pLastAncestor->fFlags & KFSOBJ_F_USE_CUSTOM_GEN : 0, *penmError);
        if (pLastAncestor)
            kFsCacheObjRelease(pCache, pLastAncestor);

        pCache->cLookups++;
        if (pFsObj)
            pCache->cWalkHits++;
        return pFsObj;
    }

    *penmError = cchPath > 0 ? KFSLOOKUPERROR_PATH_TOO_LONG : KFSLOOKUPERROR_PATH_TOO_SHORT;
    return NULL;
}


/**
 * Internal lookup worker that looks up a KFSOBJ for the given UTF-16 path with
 * length and hash.
 *
 * This will first try the hash table.  If not in the hash table, the file
 * system cache tree is walked, missing bits filled in and finally a hash table
 * entry is created.
 *
 * Only drive letter paths are cachable.  We don't do any UNC paths at this
 * point.
 *
 * @returns Reference to object corresponding to @a pwcPath on success, this
 *          must be released by kFsCacheObjRelease.
 *          NULL if not a path we care to cache.
 * @param   pCache              The cache.
 * @param   pwcPath             The path to lookup.
 * @param   cwcPath             The length of the path (in wchar_t's).
 * @param   uHashPath           The hash of the path.
 * @param   penmError           Where to return details as to why the lookup
 *                              failed.
 */
static PKFSOBJ kFsCacheLookupHashedW(PKFSCACHE pCache, const wchar_t *pwcPath, KU32 cwcPath, KU32 uHashPath,
                                     KFSLOOKUPERROR *penmError)
{
    /*
     * Do hash table lookup of the path.
     */
    KU32        idxHashTab = uHashPath % K_ELEMENTS(pCache->apAnsiPaths);
    PKFSHASHW   pHashEntry = pCache->apUtf16Paths[idxHashTab];
    kHlpAssert(pCache->u32Magic == KFSCACHE_MAGIC);
    if (pHashEntry)
    {
        do
        {
            if (   pHashEntry->uHashPath == uHashPath
                && pHashEntry->cwcPath   == cwcPath
                && kHlpMemComp(pHashEntry->pwszPath, pwcPath, cwcPath) == 0)
            {
                PKFSOBJ pFsObj;
                if (   pHashEntry->uCacheGen == KFSOBJ_CACHE_GEN_IGNORE
                    || pHashEntry->uCacheGen == ((pFsObj = pHashEntry->pFsObj) != NULL
                                                 ? pFsObj->bObjType != KFSOBJ_TYPE_MISSING
                                                   ? pCache->auGenerations[       pFsObj->fFlags & KFSOBJ_F_USE_CUSTOM_GEN]
                                                   : pCache->auGenerationsMissing[pFsObj->fFlags & KFSOBJ_F_USE_CUSTOM_GEN]
                                                 : pCache->auGenerationsMissing[pHashEntry->idxMissingGen])
                    || (pHashEntry = kFsCacheRefreshPathW(pCache, pHashEntry, idxHashTab)) )
                {
                    pCache->cLookups++;
                    pCache->cPathHashHits++;
                    KFSCACHE_LOG2(("kFsCacheLookupW(%*.*ls) - hit %p\n", cwcPath, cwcPath, pwcPath, pHashEntry->pFsObj));
                    *penmError = pHashEntry->enmError;
                    if (pHashEntry->pFsObj)
                        return kFsCacheObjRetainInternal(pHashEntry->pFsObj);
                    return NULL;
                }
                break;
            }
            pHashEntry = pHashEntry->pNext;
        } while (pHashEntry);
    }

    /*
     * Create an entry for it by walking the file system cache and filling in the blanks.
     */
    if (   cwcPath > 0
        && cwcPath < KFSCACHE_CFG_MAX_PATH)
    {
        PKFSOBJ pFsObj;
        KBOOL   fAbsolute;
        PKFSOBJ pLastAncestor = NULL;

        /* Is absolute without any '..' bits? */
        if (   cwcPath >= 3
            && (   (   pwcPath[1] == ':'    /* Drive letter */
                    && IS_SLASH(pwcPath[2])
                    && IS_ALPHA(pwcPath[0]) )
                || (   IS_SLASH(pwcPath[0]) /* UNC */
                    && IS_SLASH(pwcPath[1]) ) )
            && !kFsCacheHasDotDotW(pwcPath, cwcPath) )
        {
            pFsObj = kFsCacheLookupAbsoluteW(pCache, pwcPath, cwcPath, 0 /*fFlags*/, penmError, &pLastAncestor);
            fAbsolute = K_TRUE;
        }
        else
        {
            pFsObj = kFsCacheLookupSlowW(pCache, pwcPath, cwcPath, 0 /*fFlags*/, penmError, &pLastAncestor);
            fAbsolute = K_FALSE;
        }
        if (   pFsObj
            || (   (pCache->fFlags & KFSCACHE_F_MISSING_PATHS)
                && *penmError != KFSLOOKUPERROR_PATH_TOO_LONG)
            || *penmError == KFSLOOKUPERROR_UNSUPPORTED )
            kFsCacheCreatePathHashTabEntryW(pCache, pFsObj, pwcPath, cwcPath, uHashPath, idxHashTab, fAbsolute,
                                            pLastAncestor ? pLastAncestor->fFlags & KFSOBJ_F_USE_CUSTOM_GEN : 0, *penmError);
        if (pLastAncestor)
            kFsCacheObjRelease(pCache, pLastAncestor);

        pCache->cLookups++;
        if (pFsObj)
            pCache->cWalkHits++;
        return pFsObj;
    }

    *penmError = cwcPath > 0 ? KFSLOOKUPERROR_PATH_TOO_LONG : KFSLOOKUPERROR_PATH_TOO_SHORT;
    return NULL;
}



/**
 * Looks up a KFSOBJ for the given ANSI path.
 *
 * This will first try the hash table.  If not in the hash table, the file
 * system cache tree is walked, missing bits filled in and finally a hash table
 * entry is created.
 *
 * Only drive letter paths are cachable.  We don't do any UNC paths at this
 * point.
 *
 * @returns Reference to object corresponding to @a pszPath on success, this
 *          must be released by kFsCacheObjRelease.
 *          NULL if not a path we care to cache.
 * @param   pCache              The cache.
 * @param   pszPath             The path to lookup.
 * @param   penmError           Where to return details as to why the lookup
 *                              failed.
 */
PKFSOBJ kFsCacheLookupA(PKFSCACHE pCache, const char *pszPath, KFSLOOKUPERROR *penmError)
{
    KU32    uHashPath;
    KU32    cchPath = (KU32)kFsCacheStrHashEx(pszPath, &uHashPath);
    PKFSOBJ pObj;
    KFSCACHE_LOCK(pCache);
    pObj = kFsCacheLookupHashedA(pCache, pszPath, cchPath, uHashPath, penmError);
    KFSCACHE_UNLOCK(pCache);
    return pObj;
}


/**
 * Looks up a KFSOBJ for the given UTF-16 path.
 *
 * This will first try the hash table.  If not in the hash table, the file
 * system cache tree is walked, missing bits filled in and finally a hash table
 * entry is created.
 *
 * Only drive letter paths are cachable.  We don't do any UNC paths at this
 * point.
 *
 * @returns Reference to object corresponding to @a pwszPath on success, this
 *          must be released by kFsCacheObjRelease.
 *          NULL if not a path we care to cache.
 * @param   pCache              The cache.
 * @param   pwszPath            The path to lookup.
 * @param   penmError           Where to return details as to why the lookup
 *                              failed.
 */
PKFSOBJ kFsCacheLookupW(PKFSCACHE pCache, const wchar_t *pwszPath, KFSLOOKUPERROR *penmError)
{
    KU32    uHashPath;
    KU32    cwcPath = (KU32)kFsCacheUtf16HashEx(pwszPath, &uHashPath);
    PKFSOBJ pObj;
    KFSCACHE_LOCK(pCache);
    pObj = kFsCacheLookupHashedW(pCache, pwszPath, cwcPath, uHashPath, penmError);
    KFSCACHE_UNLOCK(pCache);
    return pObj;
}


/**
 * Looks up a KFSOBJ for the given ANSI path.
 *
 * This will first try the hash table.  If not in the hash table, the file
 * system cache tree is walked, missing bits filled in and finally a hash table
 * entry is created.
 *
 * Only drive letter paths are cachable.  We don't do any UNC paths at this
 * point.
 *
 * @returns Reference to object corresponding to @a pchPath on success, this
 *          must be released by kFsCacheObjRelease.
 *          NULL if not a path we care to cache.
 * @param   pCache              The cache.
 * @param   pchPath             The path to lookup (does not need to be nul
 *                              terminated).
 * @param   cchPath             The path length.
 * @param   penmError           Where to return details as to why the lookup
 *                              failed.
 */
PKFSOBJ kFsCacheLookupWithLengthA(PKFSCACHE pCache, const char *pchPath, KSIZE cchPath, KFSLOOKUPERROR *penmError)
{
    KU32    uHashPath = kFsCacheStrHashN(pchPath, cchPath);
    PKFSOBJ pObj;
    KFSCACHE_LOCK(pCache);
    pObj = kFsCacheLookupHashedA(pCache, pchPath, (KU32)cchPath, uHashPath, penmError);
    KFSCACHE_UNLOCK(pCache);
    return pObj;
}


/**
 * Looks up a KFSOBJ for the given UTF-16 path.
 *
 * This will first try the hash table.  If not in the hash table, the file
 * system cache tree is walked, missing bits filled in and finally a hash table
 * entry is created.
 *
 * Only drive letter paths are cachable.  We don't do any UNC paths at this
 * point.
 *
 * @returns Reference to object corresponding to @a pwchPath on success, this
 *          must be released by kFsCacheObjRelease.
 *          NULL if not a path we care to cache.
 * @param   pCache              The cache.
 * @param   pwcPath             The path to lookup (does not need to be nul
 *                              terminated).
 * @param   cwcPath             The path length (in wchar_t's).
 * @param   penmError           Where to return details as to why the lookup
 *                              failed.
 */
PKFSOBJ kFsCacheLookupWithLengthW(PKFSCACHE pCache, const wchar_t *pwcPath, KSIZE cwcPath, KFSLOOKUPERROR *penmError)
{
    KU32    uHashPath = kFsCacheUtf16HashN(pwcPath, cwcPath);
    PKFSOBJ pObj;
    KFSCACHE_LOCK(pCache);
    pObj = kFsCacheLookupHashedW(pCache, pwcPath, (KU32)cwcPath, uHashPath, penmError);
    KFSCACHE_UNLOCK(pCache);
    return pObj;
}


/**
 * Wrapper around kFsCacheLookupA that drops KFSOBJ_TYPE_MISSING and returns
 * KFSLOOKUPERROR_NOT_FOUND instead.
 *
 * @returns Reference to object corresponding to @a pszPath on success, this
 *          must be released by kFsCacheObjRelease.
 *          NULL if not a path we care to cache.
 * @param   pCache              The cache.
 * @param   pszPath             The path to lookup.
 * @param   penmError           Where to return details as to why the lookup
 *                              failed.
 */
PKFSOBJ kFsCacheLookupNoMissingA(PKFSCACHE pCache, const char *pszPath, KFSLOOKUPERROR *penmError)
{
    PKFSOBJ pObj;
    KFSCACHE_LOCK(pCache); /* probably not necessary */
    pObj = kFsCacheLookupA(pCache, pszPath, penmError);
    if (pObj)
    {
        if (pObj->bObjType != KFSOBJ_TYPE_MISSING)
        {
            KFSCACHE_UNLOCK(pCache);
            return pObj;
        }

        kFsCacheObjRelease(pCache, pObj);
        *penmError = KFSLOOKUPERROR_NOT_FOUND;
    }
    KFSCACHE_UNLOCK(pCache);
    return NULL;
}


/**
 * Wrapper around kFsCacheLookupW that drops KFSOBJ_TYPE_MISSING and returns
 * KFSLOOKUPERROR_NOT_FOUND instead.
 *
 * @returns Reference to object corresponding to @a pszPath on success, this
 *          must be released by kFsCacheObjRelease.
 *          NULL if not a path we care to cache.
 * @param   pCache              The cache.
 * @param   pwszPath            The path to lookup.
 * @param   penmError           Where to return details as to why the lookup
 *                              failed.
 */
PKFSOBJ kFsCacheLookupNoMissingW(PKFSCACHE pCache, const wchar_t *pwszPath, KFSLOOKUPERROR *penmError)
{
    PKFSOBJ pObj;
    KFSCACHE_LOCK(pCache); /* probably not necessary */
    pObj = kFsCacheLookupW(pCache, pwszPath, penmError);
    if (pObj)
    {
        if (pObj->bObjType != KFSOBJ_TYPE_MISSING)
        {
            KFSCACHE_UNLOCK(pCache);
            return pObj;
        }

        kFsCacheObjRelease(pCache, pObj);
        *penmError = KFSLOOKUPERROR_NOT_FOUND;
    }
    KFSCACHE_UNLOCK(pCache);
    return NULL;
}


/**
 * Destroys a cache object which has a zero reference count.
 *
 * @returns 0
 * @param   pCache              The cache.
 * @param   pObj                The object.
 * @param   pszWhere            Where it was released from.
 */
KU32 kFsCacheObjDestroy(PKFSCACHE pCache, PKFSOBJ pObj, const char *pszWhere)
{
    kHlpAssert(pObj->cRefs == 0);
    kHlpAssert(pObj->pParent == NULL);
    kHlpAssert(pObj->u32Magic == KFSOBJ_MAGIC);
    KFSCACHE_LOCK(pCache);

    KFSCACHE_LOG(("Destroying %s/%s, type=%d, pObj=%p, pszWhere=%s\n",
                  pObj->pParent ? pObj->pParent->Obj.pszName : "", pObj->pszName, pObj->bObjType, pObj, pszWhere));
    if (pObj->cPathHashRefs != 0)
    {
        fprintf(stderr, "Destroying %s/%s, type=%d, path hash entries: %d!\n", pObj->pParent ? pObj->pParent->Obj.pszName : "",
                pObj->pszName, pObj->bObjType, pObj->cPathHashRefs);
        fflush(stderr);
        __debugbreak();
    }

    /*
     * Invalidate the structure.
     */
    pObj->u32Magic = ~KFSOBJ_MAGIC;

    /*
     * Destroy any user data first.
     */
    while (pObj->pUserDataHead != NULL)
    {
        PKFSUSERDATA pUserData = pObj->pUserDataHead;
        pObj->pUserDataHead = pUserData->pNext;
        if (pUserData->pfnDestructor)
            pUserData->pfnDestructor(pCache, pObj, pUserData);
        kHlpFree(pUserData);
    }

    /*
     * Do type specific destruction
     */
    switch (pObj->bObjType)
    {
        case KFSOBJ_TYPE_MISSING:
            /* nothing else to do here */
            pCache->cbObjects -= sizeof(KFSDIR);
            break;

        case KFSOBJ_TYPE_DIR:
        {
            PKFSDIR pDir = (PKFSDIR)pObj;
            KU32    cChildren = pDir->cChildren;
            pCache->cbObjects -= sizeof(*pDir)
                               + K_ALIGN_Z(cChildren, 16) * sizeof(pDir->papChildren)
                               + (pDir->fHashTabMask + !!pDir->fHashTabMask) * sizeof(pDir->papHashTab[0]);

            pDir->cChildren   = 0;
            while (cChildren-- > 0)
                kFsCacheObjRelease(pCache, pDir->papChildren[cChildren]);
            kHlpFree(pDir->papChildren);
            pDir->papChildren = NULL;

            kHlpFree(pDir->papHashTab);
            pDir->papHashTab = NULL;
            break;
        }

        case KFSOBJ_TYPE_FILE:
        case KFSOBJ_TYPE_OTHER:
            pCache->cbObjects -= sizeof(*pObj);
            break;

        default:
            KFSCACHE_UNLOCK(pCache);
            return 0;
    }

    /*
     * Common bits.
     */
    pCache->cbObjects -= pObj->cchName + 1;
#ifdef KFSCACHE_CFG_UTF16
    pCache->cbObjects -= (pObj->cwcName + 1) * sizeof(wchar_t);
#endif
#ifdef KFSCACHE_CFG_SHORT_NAMES
    if (pObj->pszName != pObj->pszShortName)
    {
        pCache->cbObjects -= pObj->cchShortName + 1;
# ifdef KFSCACHE_CFG_UTF16
        pCache->cbObjects -= (pObj->cwcShortName + 1) * sizeof(wchar_t);
# endif
    }
#endif
    pCache->cObjects--;

    if (pObj->pNameAlloc)
    {
        pCache->cbObjects -= pObj->pNameAlloc->cb;
        kHlpFree(pObj->pNameAlloc);
    }

    KFSCACHE_UNLOCK(pCache);

    kHlpFree(pObj);
    return 0;
}


/**
 * Releases a reference to a cache object.
 *
 * @returns New reference count.
 * @param   pCache              The cache.
 * @param   pObj                The object.
 */
#undef kFsCacheObjRelease
KU32 kFsCacheObjRelease(PKFSCACHE pCache, PKFSOBJ pObj)
{
    if (pObj)
    {
        KU32 cRefs;
        kHlpAssert(pCache->u32Magic == KFSCACHE_MAGIC);
        kHlpAssert(pObj->u32Magic == KFSOBJ_MAGIC);

        cRefs = _InterlockedDecrement(&pObj->cRefs);
        if (cRefs)
            return cRefs;
        return kFsCacheObjDestroy(pCache, pObj, "kFsCacheObjRelease");
    }
    return 0;
}


/**
 * Debug version of kFsCacheObjRelease
 *
 * @returns New reference count.
 * @param   pCache              The cache.
 * @param   pObj                The object.
 * @param   pszWhere            Where it's invoked from.
 */
KU32 kFsCacheObjReleaseTagged(PKFSCACHE pCache, PKFSOBJ pObj, const char *pszWhere)
{
    if (pObj)
    {
        KU32 cRefs;
        kHlpAssert(pCache->u32Magic == KFSCACHE_MAGIC);
        kHlpAssert(pObj->u32Magic == KFSOBJ_MAGIC);

        cRefs = _InterlockedDecrement(&pObj->cRefs);
        if (cRefs)
            return cRefs;
        return kFsCacheObjDestroy(pCache, pObj, pszWhere);
    }
    return 0;
}


/**
 * Retains a reference to a cahce object.
 *
 * @returns New reference count.
 * @param   pObj                The object.
 */
KU32 kFsCacheObjRetain(PKFSOBJ pObj)
{
    KU32 cRefs;
    kHlpAssert(pCache->u32Magic == KFSCACHE_MAGIC);
    kHlpAssert(pObj->u32Magic == KFSOBJ_MAGIC);

    cRefs = _InterlockedIncrement(&pObj->cRefs);
    kHlpAssert(cRefs < 16384);
    return cRefs;
}


/**
 * Associates an item of user data with the given object.
 *
 * If the data needs cleaning up before being free, set the
 * PKFSUSERDATA::pfnDestructor member of the returned structure.
 *
 * @returns Pointer to the user data on success.
 *          NULL if out of memory or key already in use.
 *
 * @param   pCache              The cache.
 * @param   pObj                The object.
 * @param   uKey                The user data key.
 * @param   cbUserData          The size of the user data.
 */
PKFSUSERDATA kFsCacheObjAddUserData(PKFSCACHE pCache, PKFSOBJ pObj, KUPTR uKey, KSIZE cbUserData)
{
    kHlpAssert(cbUserData >= sizeof(*pNew));
    KFSCACHE_OBJUSERDATA_LOCK(pCache, pObj);

    if (kFsCacheObjGetUserData(pCache, pObj, uKey) == NULL)
    {
        PKFSUSERDATA pNew = (PKFSUSERDATA)kHlpAllocZ(cbUserData);
        if (pNew)
        {
            pNew->uKey          = uKey;
            pNew->pfnDestructor = NULL;
            pNew->pNext         = pObj->pUserDataHead;
            pObj->pUserDataHead = pNew;
            KFSCACHE_OBJUSERDATA_UNLOCK(pCache, pObj);
            return pNew;
        }
    }

    KFSCACHE_OBJUSERDATA_UNLOCK(pCache, pObj);
    return NULL;
}


/**
 * Retrieves an item of user data associated with the given object.
 *
 * @returns Pointer to the associated user data if found, otherwise NULL.
 * @param   pCache              The cache.
 * @param   pObj                The object.
 * @param   uKey                The user data key.
 */
PKFSUSERDATA kFsCacheObjGetUserData(PKFSCACHE pCache, PKFSOBJ pObj, KUPTR uKey)
{
    PKFSUSERDATA pCur;

    kHlpAssert(pCache->u32Magic == KFSCACHE_MAGIC);
    kHlpAssert(pObj->u32Magic == KFSOBJ_MAGIC);
    KFSCACHE_OBJUSERDATA_LOCK(pCache, pObj);

    for (pCur = pObj->pUserDataHead; pCur; pCur = pCur->pNext)
        if (pCur->uKey == uKey)
        {
            KFSCACHE_OBJUSERDATA_UNLOCK(pCache, pObj);
            return pCur;
        }

    KFSCACHE_OBJUSERDATA_UNLOCK(pCache, pObj);
    return NULL;
}


/**
 * Determins the idxUserDataLock value.
 *
 * Called by KFSCACHE_OBJUSERDATA_LOCK when idxUserDataLock is set to KU8_MAX.
 *
 * @returns The proper idxUserDataLock value.
 * @param   pCache              The cache.
 * @param   pObj                The object.
 */
KU8 kFsCacheObjGetUserDataLockIndex(PKFSCACHE pCache, PKFSOBJ pObj)
{
    KU8 idxUserDataLock = pObj->idxUserDataLock;
    if (idxUserDataLock == KU8_MAX)
    {
        KFSCACHE_LOCK(pCache);
        idxUserDataLock = pObj->idxUserDataLock;
        if (idxUserDataLock == KU8_MAX)
        {
            idxUserDataLock = pCache->idxUserDataNext++;
            idxUserDataLock %= K_ELEMENTS(pCache->auUserDataLocks);
            pObj->idxUserDataLock = idxUserDataLock;
        }
        KFSCACHE_UNLOCK(pCache);
    }
    return idxUserDataLock;
}

/**
 * Gets the full path to @a pObj, ANSI version.
 *
 * @returns K_TRUE on success, K_FALSE on buffer overflow (nothing stored).
 * @param   pObj                The object to get the full path to.
 * @param   pszPath             Where to return the path
 * @param   cbPath              The size of the output buffer.
 * @param   chSlash             The slash to use.
 */
KBOOL kFsCacheObjGetFullPathA(PKFSOBJ pObj, char *pszPath, KSIZE cbPath, char chSlash)
{
    /** @todo No way of to do locking here w/o pCache parameter; need to verify
     *        that we're only access static data! */
    KSIZE off = pObj->cchParent;
    kHlpAssert(pObj->u32Magic == KFSOBJ_MAGIC);
    if (off > 0)
    {
        KSIZE offEnd = off + pObj->cchName;
        if (offEnd < cbPath)
        {
            PKFSDIR pAncestor;

            pszPath[off + pObj->cchName] = '\0';
            memcpy(&pszPath[off], pObj->pszName, pObj->cchName);

            for (pAncestor = pObj->pParent; off > 0; pAncestor = pAncestor->Obj.pParent)
            {
                kHlpAssert(off > 1);
                kHlpAssert(pAncestor != NULL);
                kHlpAssert(pAncestor->Obj.cchName > 0);
                pszPath[--off] = chSlash;
                off -= pAncestor->Obj.cchName;
                kHlpAssert(pAncestor->Obj.cchParent == off);
                memcpy(&pszPath[off], pAncestor->Obj.pszName, pAncestor->Obj.cchName);
            }
            return K_TRUE;
        }
    }
    else
    {
        KBOOL const fDriveLetter = pObj->cchName == 2 && pObj->pszName[2] == ':';
        off = pObj->cchName;
        if (off + fDriveLetter < cbPath)
        {
            memcpy(pszPath, pObj->pszName, off);
            if (fDriveLetter)
                pszPath[off++] = chSlash;
            pszPath[off] = '\0';
            return K_TRUE;
        }
    }

    return K_FALSE;
}


/**
 * Gets the full path to @a pObj, UTF-16 version.
 *
 * @returns K_TRUE on success, K_FALSE on buffer overflow (nothing stored).
 * @param   pObj                The object to get the full path to.
 * @param   pszPath             Where to return the path
 * @param   cbPath              The size of the output buffer.
 * @param   wcSlash             The slash to use.
 */
KBOOL kFsCacheObjGetFullPathW(PKFSOBJ pObj, wchar_t *pwszPath, KSIZE cwcPath, wchar_t wcSlash)
{
    /** @todo No way of to do locking here w/o pCache parameter; need to verify
     *        that we're only access static data! */
    KSIZE off = pObj->cwcParent;
    kHlpAssert(pObj->u32Magic == KFSOBJ_MAGIC);
    if (off > 0)
    {
        KSIZE offEnd = off + pObj->cwcName;
        if (offEnd < cwcPath)
        {
            PKFSDIR pAncestor;

            pwszPath[off + pObj->cwcName] = '\0';
            memcpy(&pwszPath[off], pObj->pwszName, pObj->cwcName * sizeof(wchar_t));

            for (pAncestor = pObj->pParent; off > 0; pAncestor = pAncestor->Obj.pParent)
            {
                kHlpAssert(off > 1);
                kHlpAssert(pAncestor != NULL);
                kHlpAssert(pAncestor->Obj.cwcName > 0);
                pwszPath[--off] = wcSlash;
                off -= pAncestor->Obj.cwcName;
                kHlpAssert(pAncestor->Obj.cwcParent == off);
                memcpy(&pwszPath[off], pAncestor->Obj.pwszName, pAncestor->Obj.cwcName * sizeof(wchar_t));
            }
            return K_TRUE;
        }
    }
    else
    {
        KBOOL const fDriveLetter = pObj->cchName == 2 && pObj->pszName[2] == ':';
        off = pObj->cwcName;
        if (off + fDriveLetter < cwcPath)
        {
            memcpy(pwszPath, pObj->pwszName, off * sizeof(wchar_t));
            if (fDriveLetter)
                pwszPath[off++] = wcSlash;
            pwszPath[off] = '\0';
            return K_TRUE;
        }
    }

    return K_FALSE;
}


#ifdef KFSCACHE_CFG_SHORT_NAMES

/**
 * Gets the full short path to @a pObj, ANSI version.
 *
 * @returns K_TRUE on success, K_FALSE on buffer overflow (nothing stored).
 * @param   pObj                The object to get the full path to.
 * @param   pszPath             Where to return the path
 * @param   cbPath              The size of the output buffer.
 * @param   chSlash             The slash to use.
 */
KBOOL kFsCacheObjGetFullShortPathA(PKFSOBJ pObj, char *pszPath, KSIZE cbPath, char chSlash)
{
    /** @todo No way of to do locking here w/o pCache parameter; need to verify
     *        that we're only access static data! */
    KSIZE off = pObj->cchShortParent;
    kHlpAssert(pObj->u32Magic == KFSOBJ_MAGIC);
    if (off > 0)
    {
        KSIZE offEnd = off + pObj->cchShortName;
        if (offEnd < cbPath)
        {
            PKFSDIR pAncestor;

            pszPath[off + pObj->cchShortName] = '\0';
            memcpy(&pszPath[off], pObj->pszShortName, pObj->cchShortName);

            for (pAncestor = pObj->pParent; off > 0; pAncestor = pAncestor->Obj.pParent)
            {
                kHlpAssert(off > 1);
                kHlpAssert(pAncestor != NULL);
                kHlpAssert(pAncestor->Obj.cchShortName > 0);
                pszPath[--off] = chSlash;
                off -= pAncestor->Obj.cchShortName;
                kHlpAssert(pAncestor->Obj.cchShortParent == off);
                memcpy(&pszPath[off], pAncestor->Obj.pszShortName, pAncestor->Obj.cchShortName);
            }
            return K_TRUE;
        }
    }
    else
    {
        KBOOL const fDriveLetter = pObj->cchShortName == 2 && pObj->pszShortName[2] == ':';
        off = pObj->cchShortName;
        if (off + fDriveLetter < cbPath)
        {
            memcpy(pszPath, pObj->pszShortName, off);
            if (fDriveLetter)
                pszPath[off++] = chSlash;
            pszPath[off] = '\0';
            return K_TRUE;
        }
    }

    return K_FALSE;
}


/**
 * Gets the full short path to @a pObj, UTF-16 version.
 *
 * @returns K_TRUE on success, K_FALSE on buffer overflow (nothing stored).
 * @param   pObj                The object to get the full path to.
 * @param   pszPath             Where to return the path
 * @param   cbPath              The size of the output buffer.
 * @param   wcSlash             The slash to use.
 */
KBOOL kFsCacheObjGetFullShortPathW(PKFSOBJ pObj, wchar_t *pwszPath, KSIZE cwcPath, wchar_t wcSlash)
{
    /** @todo No way of to do locking here w/o pCache parameter; need to verify
     *        that we're only access static data! */
    KSIZE off = pObj->cwcShortParent;
    kHlpAssert(pObj->u32Magic == KFSOBJ_MAGIC);
    if (off > 0)
    {
        KSIZE offEnd = off + pObj->cwcShortName;
        if (offEnd < cwcPath)
        {
            PKFSDIR pAncestor;

            pwszPath[off + pObj->cwcShortName] = '\0';
            memcpy(&pwszPath[off], pObj->pwszShortName, pObj->cwcShortName * sizeof(wchar_t));

            for (pAncestor = pObj->pParent; off > 0; pAncestor = pAncestor->Obj.pParent)
            {
                kHlpAssert(off > 1);
                kHlpAssert(pAncestor != NULL);
                kHlpAssert(pAncestor->Obj.cwcShortName > 0);
                pwszPath[--off] = wcSlash;
                off -= pAncestor->Obj.cwcShortName;
                kHlpAssert(pAncestor->Obj.cwcShortParent == off);
                memcpy(&pwszPath[off], pAncestor->Obj.pwszShortName, pAncestor->Obj.cwcShortName * sizeof(wchar_t));
            }
            return K_TRUE;
        }
    }
    else
    {
        KBOOL const fDriveLetter = pObj->cchShortName == 2 && pObj->pszShortName[2] == ':';
        off = pObj->cwcShortName;
        if (off + fDriveLetter < cwcPath)
        {
            memcpy(pwszPath, pObj->pwszShortName, off * sizeof(wchar_t));
            if (fDriveLetter)
                pwszPath[off++] = wcSlash;
            pwszPath[off] = '\0';
            return K_TRUE;
        }
    }

    return K_FALSE;
}

#endif /* KFSCACHE_CFG_SHORT_NAMES */



/**
 * Read the specified bits from the files into the given buffer, simple version.
 *
 * @returns K_TRUE on success (all requested bytes read),
 *          K_FALSE on any kind of failure.
 *
 * @param   pCache              The cache.
 * @param   pFileObj            The file object.
 * @param   offStart            Where to start reading.
 * @param   pvBuf               Where to store what we read.
 * @param   cbToRead            How much to read (exact).
 */
KBOOL kFsCacheFileSimpleOpenReadClose(PKFSCACHE pCache, PKFSOBJ pFileObj, KU64 offStart, void *pvBuf, KSIZE cbToRead)
{
    /*
     * Open the file relative to the parent directory.
     */
    MY_NTSTATUS             rcNt;
    HANDLE                  hFile;
    MY_IO_STATUS_BLOCK      Ios;
    MY_OBJECT_ATTRIBUTES    ObjAttr;
    MY_UNICODE_STRING       UniStr;

    kHlpAssertReturn(pFileObj->bObjType == KFSOBJ_TYPE_FILE, K_FALSE);
    kHlpAssert(pFileObj->pParent);
    kHlpAssertReturn(pFileObj->pParent->hDir != INVALID_HANDLE_VALUE, K_FALSE);
    kHlpAssertReturn(offStart == 0, K_FALSE); /** @todo when needed */

    Ios.Information = -1;
    Ios.u.Status    = -1;

    UniStr.Buffer        = (wchar_t *)pFileObj->pwszName;
    UniStr.Length        = (USHORT)(pFileObj->cwcName * sizeof(wchar_t));
    UniStr.MaximumLength = UniStr.Length + sizeof(wchar_t);

/** @todo potential race against kFsCacheInvalidateDeletedDirectoryA   */
    MyInitializeObjectAttributes(&ObjAttr, &UniStr, OBJ_CASE_INSENSITIVE, pFileObj->pParent->hDir, NULL /*pSecAttr*/);

    rcNt = g_pfnNtCreateFile(&hFile,
                             GENERIC_READ | SYNCHRONIZE,
                             &ObjAttr,
                             &Ios,
                             NULL, /*cbFileInitialAlloc */
                             FILE_ATTRIBUTE_NORMAL,
                             FILE_SHARE_READ,
                             FILE_OPEN,
                             FILE_NON_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT,
                             NULL, /*pEaBuffer*/
                             0);   /*cbEaBuffer*/
    if (MY_NT_SUCCESS(rcNt))
    {
        LARGE_INTEGER offFile;
        offFile.QuadPart = offStart;

        Ios.Information = -1;
        Ios.u.Status    = -1;
        rcNt = g_pfnNtReadFile(hFile, NULL /*hEvent*/, NULL /*pfnApcComplete*/, NULL /*pvApcCtx*/, &Ios,
                               pvBuf, (KU32)cbToRead, !offStart ? &offFile : NULL, NULL /*puKey*/);
        if (MY_NT_SUCCESS(rcNt))
            rcNt = Ios.u.Status;
        if (MY_NT_SUCCESS(rcNt))
        {
            if (Ios.Information == cbToRead)
            {
                g_pfnNtClose(hFile);
                return K_TRUE;
            }
            KFSCACHE_LOG(("Error reading %#x bytes from '%ls': Information=%p\n", pFileObj->pwszName, Ios.Information));
        }
        else
            KFSCACHE_LOG(("Error reading %#x bytes from '%ls': %#x\n", pFileObj->pwszName, rcNt));
        g_pfnNtClose(hFile);
    }
    else
        KFSCACHE_LOG(("Error opening '%ls' for caching: %#x\n", pFileObj->pwszName, rcNt));
    return K_FALSE;
}


/**
 * Invalidate all cache entries of missing files.
 *
 * @param   pCache      The cache.
 */
void kFsCacheInvalidateMissing(PKFSCACHE pCache)
{
    kHlpAssert(pCache->u32Magic == KFSOBJ_MAGIC);
    KFSCACHE_LOCK(pCache);

    pCache->auGenerationsMissing[0]++;
    kHlpAssert(pCache->uGenerationMissing < KU32_MAX);

    KFSCACHE_LOG(("Invalidate missing %#x\n", pCache->auGenerationsMissing[0]));
    KFSCACHE_UNLOCK(pCache);
}


/** 
 * Recursively close directories. 
 */ 
static void kFsCacheCloseDirs(PKFSOBJ *papChildren, KU32 cChildren)
{
    while (cChildren-- > 0)
    {
        PKFSDIR pDir = (PKFSDIR)papChildren[cChildren];
        if (pDir && pDir->Obj.bObjType == KFSOBJ_TYPE_DIR)
        {
            if (pDir->hDir != INVALID_HANDLE_VALUE)
            {
                g_pfnNtClose(pDir->hDir);
                pDir->hDir = INVALID_HANDLE_VALUE;
            }
            kFsCacheCloseDirs(pDir->papChildren, pDir->cChildren);
        }
    }
}


/**
 * Worker for kFsCacheInvalidateAll and kFsCacheInvalidateAllAndCloseDirs
 */
static void kFsCacheInvalidateAllWorker(PKFSCACHE pCache, KBOOL fCloseDirs, KBOOL fIncludingRoot)
{
    kHlpAssert(pCache->u32Magic == KFSOBJ_MAGIC);
    KFSCACHE_LOCK(pCache);

    pCache->auGenerationsMissing[0]++;
    kHlpAssert(pCache->auGenerationsMissing[0] < KU32_MAX);
    pCache->auGenerationsMissing[1]++;
    kHlpAssert(pCache->auGenerationsMissing[1] < KU32_MAX);

    pCache->auGenerations[0]++;
    kHlpAssert(pCache->auGenerations[0] < KU32_MAX);
    pCache->auGenerations[1]++;
    kHlpAssert(pCache->auGenerations[1] < KU32_MAX);

    if (fCloseDirs)
    {
        kFsCacheCloseDirs(pCache->RootDir.papChildren, pCache->RootDir.cChildren);
        if (fCloseDirs && pCache->RootDir.hDir != INVALID_HANDLE_VALUE)
        {
            g_pfnNtClose(pCache->RootDir.hDir);
            pCache->RootDir.hDir = INVALID_HANDLE_VALUE;
        }
    }

    KFSCACHE_LOG(("Invalidate all - default: %#x/%#x,  custom: %#x/%#x\n",
                  pCache->auGenerationsMissing[0], pCache->auGenerations[0],
                  pCache->auGenerationsMissing[1], pCache->auGenerations[1]));
    KFSCACHE_UNLOCK(pCache);
}


/**
 * Invalidate all cache entries (regular, custom & missing).
 *
 * @param   pCache      The cache.
 */
void kFsCacheInvalidateAll(PKFSCACHE pCache)
{
    kHlpAssert(pCache->u32Magic == KFSOBJ_MAGIC);
    kFsCacheInvalidateAllWorker(pCache, K_FALSE, K_FALSE);
}


/**
 * Invalidate all cache entries (regular, custom & missing) and close all the
 * directory handles.
 *
 * @param   pCache          The cache.
 * @param   fIncludingRoot  Close the root directory handle too.
 */
void kFsCacheInvalidateAllAndCloseDirs(PKFSCACHE pCache, KBOOL fIncludingRoot)
{
    kHlpAssert(pCache->u32Magic == KFSOBJ_MAGIC);
    kFsCacheInvalidateAllWorker(pCache, K_TRUE, fIncludingRoot);
}


/**
 * Invalidate all cache entries with custom generation handling set.
 *
 * @see     kFsCacheSetupCustomRevisionForTree, KFSOBJ_F_USE_CUSTOM_GEN
 * @param   pCache      The cache.
 */
void kFsCacheInvalidateCustomMissing(PKFSCACHE pCache)
{
    kHlpAssert(pCache->u32Magic == KFSOBJ_MAGIC);
    KFSCACHE_LOCK(pCache);

    pCache->auGenerationsMissing[1]++;
    kHlpAssert(pCache->auGenerationsMissing[1] < KU32_MAX);

    KFSCACHE_LOG(("Invalidate missing custom %#x\n", pCache->auGenerationsMissing[1]));
    KFSCACHE_UNLOCK(pCache);
}


/**
 * Invalidate all cache entries with custom generation handling set, both
 * missing and regular present entries.
 *
 * @see     kFsCacheSetupCustomRevisionForTree, KFSOBJ_F_USE_CUSTOM_GEN
 * @param   pCache      The cache.
 */
void kFsCacheInvalidateCustomBoth(PKFSCACHE pCache)
{
    kHlpAssert(pCache->u32Magic == KFSOBJ_MAGIC);
    KFSCACHE_LOCK(pCache);

    pCache->auGenerations[1]++;
    kHlpAssert(pCache->auGenerations[1] < KU32_MAX);
    pCache->auGenerationsMissing[1]++;
    kHlpAssert(pCache->auGenerationsMissing[1] < KU32_MAX);

    KFSCACHE_LOG(("Invalidate both custom %#x/%#x\n", pCache->auGenerationsMissing[1], pCache->auGenerations[1]));
    KFSCACHE_UNLOCK(pCache);
}



/**
 * Applies the given flags to all the objects in a tree.
 *
 * @param   pRoot               Where to start applying the flag changes.
 * @param   fAndMask            The AND mask.
 * @param   fOrMask             The OR mask.
 */
static void kFsCacheApplyFlagsToTree(PKFSDIR pRoot, KU32 fAndMask, KU32 fOrMask)
{
    PKFSOBJ    *ppCur = ((PKFSDIR)pRoot)->papChildren;
    KU32        cLeft = ((PKFSDIR)pRoot)->cChildren;
    while (cLeft-- > 0)
    {
        PKFSOBJ pCur = *ppCur++;
        if (pCur->bObjType != KFSOBJ_TYPE_DIR)
            pCur->fFlags = (fAndMask & pCur->fFlags) | fOrMask;
        else
            kFsCacheApplyFlagsToTree((PKFSDIR)pCur, fAndMask, fOrMask);
    }

    pRoot->Obj.fFlags = (fAndMask & pRoot->Obj.fFlags) | fOrMask;
}


/**
 * Sets up using custom revisioning for the specified directory tree or file.
 *
 * There are some restrictions of the current implementation:
 *      - If the root of the sub-tree is ever deleted from the cache (i.e.
 *        deleted in real life and reflected in the cache), the setting is lost.
 *      - It is not automatically applied to the lookup paths caches.
 *
 * @returns K_TRUE on success, K_FALSE on failure.
 * @param   pCache              The cache.
 * @param   pRoot               The root of the subtree.  A non-directory is
 *                              fine, like a missing node.
 */
KBOOL kFsCacheSetupCustomRevisionForTree(PKFSCACHE pCache, PKFSOBJ pRoot)
{
    if (pRoot)
    {
        KFSCACHE_LOCK(pCache);
        if (pRoot->bObjType == KFSOBJ_TYPE_DIR)
            kFsCacheApplyFlagsToTree((PKFSDIR)pRoot, KU32_MAX, KFSOBJ_F_USE_CUSTOM_GEN);
        else
            pRoot->fFlags |= KFSOBJ_F_USE_CUSTOM_GEN;
        KFSCACHE_UNLOCK(pCache);
        return K_TRUE;
    }
    return K_FALSE;
}


/**
 * Invalidates a deleted directory, ANSI version.
 *
 * @returns K_TRUE if found and is a non-root directory. Otherwise K_FALSE.
 * @param   pCache              The cache.
 * @param   pszDir              The directory.
 */
KBOOL kFsCacheInvalidateDeletedDirectoryA(PKFSCACHE pCache, const char *pszDir)
{
    KU32            cchDir = (KU32)kHlpStrLen(pszDir);
    KFSLOOKUPERROR  enmError;
    PKFSOBJ         pFsObj;

    KFSCACHE_LOCK(pCache);

    /* Is absolute without any '..' bits? */
    if (   cchDir >= 3
        && (   (   pszDir[1] == ':'    /* Drive letter */
                && IS_SLASH(pszDir[2])
                && IS_ALPHA(pszDir[0]) )
            || (   IS_SLASH(pszDir[0]) /* UNC */
                && IS_SLASH(pszDir[1]) ) )
        && !kFsCacheHasDotDotA(pszDir, cchDir) )
        pFsObj = kFsCacheLookupAbsoluteA(pCache, pszDir, cchDir, KFSCACHE_LOOKUP_F_NO_INSERT | KFSCACHE_LOOKUP_F_NO_REFRESH,
                                         &enmError, NULL);
    else
        pFsObj = kFsCacheLookupSlowA(pCache, pszDir, cchDir, KFSCACHE_LOOKUP_F_NO_INSERT | KFSCACHE_LOOKUP_F_NO_REFRESH,
                                     &enmError, NULL);
    if (pFsObj)
    {
        /* Is directory? */
        if (pFsObj->bObjType == KFSOBJ_TYPE_DIR)
        {
            if (pFsObj->pParent != &pCache->RootDir)
            {
                PKFSDIR pDir = (PKFSDIR)pFsObj;
                KFSCACHE_LOG(("kFsCacheInvalidateDeletedDirectoryA: %s hDir=%p\n", pszDir, pDir->hDir));
                if (pDir->hDir != INVALID_HANDLE_VALUE)
                {
                    g_pfnNtClose(pDir->hDir);
                    pDir->hDir = INVALID_HANDLE_VALUE;
                }
                pDir->fNeedRePopulating = K_TRUE;
                pDir->Obj.uCacheGen = pCache->auGenerations[pDir->Obj.fFlags & KFSOBJ_F_USE_CUSTOM_GEN] - 1;
                kFsCacheObjRelease(pCache, &pDir->Obj);
                KFSCACHE_UNLOCK(pCache);
                return K_TRUE;
            }
            KFSCACHE_LOG(("kFsCacheInvalidateDeletedDirectoryA: Trying to invalidate a root directory was deleted! %s\n", pszDir));
        }
        else
            KFSCACHE_LOG(("kFsCacheInvalidateDeletedDirectoryA: Trying to invalidate a non-directory: bObjType=%d %s\n",
                          pFsObj->bObjType, pszDir));
        kFsCacheObjRelease(pCache, pFsObj);
    }
    else
        KFSCACHE_LOG(("kFsCacheInvalidateDeletedDirectoryA: '%s' was not found\n", pszDir));
    KFSCACHE_UNLOCK(pCache);
    return K_FALSE;
}


PKFSCACHE kFsCacheCreate(KU32 fFlags)
{
    PKFSCACHE pCache;
    birdResolveImports();

    pCache = (PKFSCACHE)kHlpAllocZ(sizeof(*pCache));
    if (pCache)
    {
        /* Dummy root dir entry. */
        pCache->RootDir.Obj.u32Magic        = KFSOBJ_MAGIC;
        pCache->RootDir.Obj.cRefs           = 1;
        pCache->RootDir.Obj.uCacheGen       = KFSOBJ_CACHE_GEN_IGNORE;
        pCache->RootDir.Obj.bObjType        = KFSOBJ_TYPE_DIR;
        pCache->RootDir.Obj.fHaveStats      = K_FALSE;
        pCache->RootDir.Obj.pParent         = NULL;
        pCache->RootDir.Obj.pszName         = "";
        pCache->RootDir.Obj.cchName         = 0;
        pCache->RootDir.Obj.cchParent       = 0;
#ifdef KFSCACHE_CFG_UTF16
        pCache->RootDir.Obj.cwcName         = 0;
        pCache->RootDir.Obj.cwcParent       = 0;
        pCache->RootDir.Obj.pwszName        = L"";
#endif

#ifdef KFSCACHE_CFG_SHORT_NAMES
        pCache->RootDir.Obj.pszShortName    = NULL;
        pCache->RootDir.Obj.cchShortName    = 0;
        pCache->RootDir.Obj.cchShortParent  = 0;
# ifdef KFSCACHE_CFG_UTF16
        pCache->RootDir.Obj.cwcShortName;
        pCache->RootDir.Obj.cwcShortParent;
        pCache->RootDir.Obj.pwszShortName;
# endif
#endif
        pCache->RootDir.cChildren           = 0;
        pCache->RootDir.cChildrenAllocated  = 0;
        pCache->RootDir.papChildren         = NULL;
        pCache->RootDir.hDir                = INVALID_HANDLE_VALUE;
        pCache->RootDir.fHashTabMask        = 255; /* 256: 26 drive letters and 102 UNCs before we're half ways. */
        pCache->RootDir.papHashTab          = (PKFSOBJ *)kHlpAllocZ(256 * sizeof(pCache->RootDir.papHashTab[0]));
        if (pCache->RootDir.papHashTab)
        {
            /* The cache itself. */
            pCache->u32Magic                = KFSCACHE_MAGIC;
            pCache->fFlags                  = fFlags;
            pCache->auGenerations[0]        = KU32_MAX / 4;
            pCache->auGenerations[1]        = KU32_MAX / 32;
            pCache->auGenerationsMissing[0] = KU32_MAX / 256;
            pCache->auGenerationsMissing[1] = 1;
            pCache->cObjects                = 1;
            pCache->cbObjects               = sizeof(pCache->RootDir)
                                            + (pCache->RootDir.fHashTabMask + 1) * sizeof(pCache->RootDir.papHashTab[0]);
            pCache->cPathHashHits           = 0;
            pCache->cWalkHits               = 0;
            pCache->cChildSearches          = 0;
            pCache->cChildHashHits          = 0;
            pCache->cChildHashed            = 0;
            pCache->cChildHashTabs          = 1;
            pCache->cChildHashEntriesTotal  = pCache->RootDir.fHashTabMask + 1;
            pCache->cChildHashCollisions    = 0;
            pCache->cNameChanges            = 0;
            pCache->cNameGrowths            = 0;
            pCache->cAnsiPaths              = 0;
            pCache->cAnsiPathCollisions     = 0;
            pCache->cbAnsiPaths             = 0;
#ifdef KFSCACHE_CFG_UTF16
            pCache->cUtf16Paths             = 0;
            pCache->cUtf16PathCollisions    = 0;
            pCache->cbUtf16Paths            = 0;
#endif

#ifdef KFSCACHE_CFG_LOCKING
            {
                KSIZE idx = K_ELEMENTS(pCache->auUserDataLocks);
                while (idx-- > 0)
                    InitializeCriticalSection(&pCache->auUserDataLocks[idx].CritSect);
                InitializeCriticalSection(&pCache->u.CritSect);
            }
#endif
            return pCache;
        }

        kHlpFree(pCache);
    }
    return NULL;
}