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

Copyright (c) 1995  Microsoft Corporation

Module Name:

    Tunnel.c

Abstract:

    The tunnel package provides a set of routines that allow compatibility
    with applications that rely on filesystems being able to "hold onto"
    file meta-info for a short period of time after deletion/renaming and
    reinstantiating a new directory entry with that meta-info if a
    create/rename occurs to cause a file of that name to appear again in a
    short period of time.

    Note that this violates POSIX rules. This package should not be used
    on POSIX fileobjects, i.e. fileobjects that have case-sensitive names.

    Entries are keyed by directory and one of the short/long names. An opaque
    rock of information is also associated (create time, last write time, etc.).
    This is expected to vary on a per-filesystem basis.

    A TUNNEL variable should be initialized for every volume in the system
    at mount time. Thereafter, each delete/rename-out should add to the tunnel
    and each create/rename-in should read from the tunnel. Each directory
    deletion should also notify the package so that all associated entries can
    be flushed. The package is responsible for cleaning out aged entries.

    Tunneled information is in the paged pool.

    Concurrent access to the TUNNEL variable is controlled by this package.
    Callers are responsible for synchronizing access to the FsRtlDeleteTunnelCache
    call.

    The functions provided in this package are as follows:

      o  FsRtlInitializeTunnel - Initializes the TUNNEL package (called once per boot)

      o  FsRtlInitializeTunnelCache - Initializes a TUNNEL structure (called once on mount)

      o  FsRtlAddToTunnelCache - Adds a new key/value pair to the tunnel

      o  FsRtlFindInTunnelCache - Finds and returns a key/value from the tunnel

      o  FsRtlDeleteKeyFromTunnelCache - Deletes all entries with a given
           directory key from the tunnel

      o  FsRtlDeleteTunnelCache - Deletes a TUNNEL structure

Author:

    Dan Lovinger     [DanLo]    8-Aug-1995

Revision History:

--*/

#include "FsRtlP.h"

//
//  Registry keys/values for controlling tunneling
//

#define TUNNEL_KEY_NAME           L"\\Registry\\Machine\\System\\CurrentControlSet\\Control\\FileSystem"
#define TUNNEL_AGE_VALUE_NAME     L"MaximumTunnelEntryAgeInSeconds"
#define TUNNEL_SIZE_VALUE_NAME    L"MaximumTunnelEntries"
#define KEY_WORK_AREA ((sizeof(KEY_VALUE_FULL_INFORMATION) + sizeof(ULONG)) + 64)

//
//  Tunnel expiration paramters (cached once at startup)
//

ULONG   TunnelMaxEntries;
ULONG   TunnelMaxAge;

//
//  We use a lookaside list to manage the common size tunnel entry. The common size
//  is contrived to be 128 bytes by adjusting the size we defer for the long name
//  to 16 characters, which is pretty reasonable. If we ever expect to get more than
//  a ULONGLONG data element or common names are observed to become larger, adjusting
//  this may be required.
//

PAGED_LOOKASIDE_LIST    TunnelLookasideList;
#define MAX_LOOKASIDE_DEPTH     256

#define LOOKASIDE_NODE_SIZE     ( sizeof(TUNNEL_NODE) +     \
                                  sizeof(WCHAR)*(8+1+3) +   \
                                  sizeof(WCHAR)*(16) +      \
                                  sizeof(ULONGLONG) )

//
//  Flag bits in the TUNNEL_NODE
//

#define TUNNEL_FLAG_NON_LOOKASIDE    0x1
#define TUNNEL_FLAG_KEY_SHORT        0x2

//
//  A node of tunneled information in the cache
//
//  A TUNNEL is allocated in each VCB and initialized at mount time.
//
//  TUNNEL_NODES are then arranged off of the TUNNEL in a splay tree keyed
//  by DirKey ## Name, where Name is whichever of the names was removed from
//  the directory (short or long). Each node is also timestamped and inserted
//  into a timer queue for age expiration.
//

typedef struct {

    //
    //  Splay links in the Cache tree
    //

    RTL_SPLAY_LINKS      CacheLinks;

    //
    //  List links in the timer queue
    //

    LIST_ENTRY           ListLinks;

    //
    //  Time this entry was created (for constant time insert)
    //

    LARGE_INTEGER        CreateTime;

    //
    //  Directory these names are associated with
    //

    ULONGLONG            DirKey;

    //
    //  Flags for the entry
    //

    ULONG                Flags;

    //
    //  Long/Short names of the file
    //

    UNICODE_STRING       LongName;
    UNICODE_STRING       ShortName;

    //
    //  Opaque tunneled data
    //

    PVOID                TunnelData;
    ULONG                TunnelDataLength;

} TUNNEL_NODE, *PTUNNEL_NODE;

//
//  Internal utility functions
//

NTSTATUS
FsRtlGetTunnelParameterValue (
    IN PUNICODE_STRING ValueName,
    IN OUT PULONG Value);

VOID
FsRtlPruneTunnelCache (
    IN PTUNNEL Cache,
    IN OUT PLIST_ENTRY FreePoolList);

#ifdef ALLOC_PRAGMA
#pragma alloc_text(PAGE, FsRtlInitializeTunnel)
#pragma alloc_text(PAGE, FsRtlInitializeTunnelCache)
#pragma alloc_text(PAGE, FsRtlAddToTunnelCache)
#pragma alloc_text(PAGE, FsRtlFindInTunnelCache)
#pragma alloc_text(PAGE, FsRtlDeleteKeyFromTunnelCache)
#pragma alloc_text(PAGE, FsRtlDeleteTunnelCache)
#pragma alloc_text(PAGE, FsRtlPruneTunnelCache)
#pragma alloc_text(PAGE, FsRtlGetTunnelParameterValue)
#endif

//
//  Testing and usermode rig support. Define TUNNELTEST to get verbose debugger
//  output on various operations. Define USERTEST to transform the code into
//  a form which can be compiled in usermode for more efficient debugging.
//

#if defined(TUNNELTEST) || defined(KEYVIEW)
VOID DumpUnicodeString(UNICODE_STRING *s);
VOID DumpNode( TUNNEL_NODE *Node, ULONG Indent );
VOID DumpTunnel( TUNNEL *Tunnel );
#define DblHex64(a) (ULONG)((a >> 32) & 0xffffffff),(ULONG)(a & 0xffffffff)
#endif // TUNNELTEST

#ifdef USERTEST
#include <stdio.h>
#undef KeQuerySystemTime
#define KeQuerySystemTime NtQuerySystemTime
#undef ExInitializeFastMutex
#define ExInitializeFastMutex(arg)
#define ExAcquireFastMutex(arg)
#define ExReleaseFastMutex(arg)
#define DbgPrint printf
#undef PAGED_CODE
#define PAGED_CODE()
#endif


__inline LONG
FsRtlCompareNodeAndKey (
    TUNNEL_NODE *Node,
    ULONGLONG DirectoryKey,
    PUNICODE_STRING Name
    )
/*++

Routine Description:

    Compare a tunnel node with a key/name pair

Arguments:

    Node              - a tunnel node

    DirectoryKey      - a key value

    Name              - a filename

Return Value:

    Signed comparison result

--*/

{
    return  (Node->DirKey > DirectoryKey ?  1 :
            (Node->DirKey < DirectoryKey ? -1 :
            RtlCompareUnicodeString((FlagOn(Node->Flags, TUNNEL_FLAG_KEY_SHORT) ?
                                        &Node->ShortName : &Node->LongName),
                                    Name,
                                    TRUE)));
}


__inline VOID
FsRtlQueryNormalizedSystemTime (
    PLARGE_INTEGER PTime
    )
/*++

Routine Description:

    Query system time normalized to ~.5 sec boundaries. Time is kept in .1 msec quanta,
    so masking off the low 22 bits (2^22 = 4,194,304) will yield normalized quantities.

Arguments:

    PTime     - pointer to a timestamp to write into   

Return Value:

    None

-*/
{
    KeQuerySystemTime(PTime);
    PTime->LowPart &= ~0x3fffff;
}


__inline VOID
FsRtlFreeTunnelNode (
    PTUNNEL_NODE Node,
    PLIST_ENTRY FreePoolList OPTIONAL
    )
/*++

Routine Description:

    Free a node

Arguments:

    Node            - a tunnel node to free

    FreePoolList    - optional list to hold freeable pool memory

Return Value:

    None

-*/
{
    if (FreePoolList) {

        InsertHeadList(FreePoolList, &Node->ListLinks);

    } else {

        if (FlagOn(Node->Flags, TUNNEL_FLAG_NON_LOOKASIDE)) {
    
            ExFreePool(Node);
    
        } else {
    
            ExFreeToPagedLookasideList(&TunnelLookasideList, Node);
        }
    }
}


__inline VOID
FsRtlEmptyFreePoolList (
    PLIST_ENTRY FreePoolList
    )
/*++

Routine Description:

    Free all pool memory that has been delayed onto a free list.

Arguments:

    FreePoolList    - a list of freeable pool memory

Return Value:

    None

-*/
{
    PTUNNEL_NODE FreeNode;

    while (!IsListEmpty(FreePoolList)) {

        FreeNode = CONTAINING_RECORD(FreePoolList->Flink, TUNNEL_NODE, ListLinks);
        RemoveEntryList(FreePoolList->Flink);

        FsRtlFreeTunnelNode(FreeNode, NULL);
    }
}


__inline VOID
FsRtlRemoveNodeFromTunnel (
    IN PTUNNEL Cache,
    IN PTUNNEL_NODE Node,
    IN PLIST_ENTRY FreePoolList,
    IN PBOOLEAN Splay OPTIONAL
    )
/*++

Routine Description:

    Performs the common work of deleting a node from a tunnel cache. Pool memory
    is not deleted immediately but is saved aside on a list for deletion later
    by the calling routine.

Arguments:

    Cache - the tunnel cache the node is in

    Node - the node being removed

    FreePoolList - an initialized list to take the node if it was allocated from
        pool

    Splay - an optional flag to indicate whether the tree should be splayed on
        the delete. Set to FALSE if splaying was performed.

Return Value:

    None.

--*/
{
    if (Splay && *Splay) {

        Cache->Cache = RtlDelete(&Node->CacheLinks);

        *Splay = FALSE;

    } else {

        RtlDeleteNoSplay(&Node->CacheLinks, &Cache->Cache);
    }

    RemoveEntryList(&Node->ListLinks);

    Cache->NumEntries--;

    FsRtlFreeTunnelNode(Node, FreePoolList);
}


VOID
FsRtlInitializeTunnel (
    VOID
    )
/*++

Routine Description:

    Initializes the global part of the tunneling package.

Arguments:

    None

Return Value:

    None

--*/
{
    UNICODE_STRING  ValueName;
    USHORT          LookasideDepth;

    PAGED_CODE();

    if (MmIsThisAnNtAsSystem()) {

        TunnelMaxEntries = 1024;

    } else {

        TunnelMaxEntries = 256;
    }

    TunnelMaxAge = 15;

    //
    //  Query our configurable parameters
    //
    //  Don't worry about failure in retrieving from the registry. We've gotten
    //  this far so fall back on defaults even if there was a problem with resources.
    //


    ValueName.Buffer = TUNNEL_SIZE_VALUE_NAME;
    ValueName.Length = sizeof(TUNNEL_SIZE_VALUE_NAME) - sizeof(WCHAR);
    ValueName.MaximumLength = sizeof(TUNNEL_SIZE_VALUE_NAME);
    (VOID) FsRtlGetTunnelParameterValue(&ValueName, &TunnelMaxEntries);

    ValueName.Buffer = TUNNEL_AGE_VALUE_NAME;
    ValueName.Length = sizeof(TUNNEL_AGE_VALUE_NAME) - sizeof(WCHAR);
    ValueName.MaximumLength = sizeof(TUNNEL_AGE_VALUE_NAME);
    (VOID) FsRtlGetTunnelParameterValue(&ValueName, &TunnelMaxAge);

    if (TunnelMaxAge == 0) {

        //
        //  If the registry has been set so the timeout is zero, we should force
        //  the number of entries to zero also. This preserves expectations and lets
        //  us key off of max entries alone in performing the hard disabling of the
        //  caching code.
        //

        TunnelMaxEntries = 0;
    }

    //
    //  Convert from seconds to 10ths of msecs, the internal resolution
    //

    TunnelMaxAge *= 10000000;

    //
    //  Build the lookaside list for common node allocation
    //

    if (TunnelMaxEntries > MAXUSHORT) {

        //
        //  User is hinting a big need to us
        //

        LookasideDepth = MAX_LOOKASIDE_DEPTH;

    } else {

        LookasideDepth = ((USHORT)TunnelMaxEntries)/16;
    }

    if (LookasideDepth == 0 && TunnelMaxEntries) {

        //
        //  Miniscule number of entries allowed. Lookaside 'em all.
        //

        LookasideDepth = (USHORT)TunnelMaxEntries + 1;
    }

    if (LookasideDepth > MAX_LOOKASIDE_DEPTH) {

        //
        //  Finally, restrict the depth to something reasonable.
        //

        LookasideDepth = MAX_LOOKASIDE_DEPTH;
    }

    ExInitializePagedLookasideList( &TunnelLookasideList,
                                    NULL,
                                    NULL,
                                    0,
                                    LOOKASIDE_NODE_SIZE,
                                    'LnuT',
                                    LookasideDepth );

    return;
}


//
//  *** SPEC
//
//    FsRtlInitializeTunnelCache - Initialize a tunneling cache for a volume
//
//    FsRtlInitializeTunnelCache will allocate a default cache (resizing policy is common
//    to all file systems) and initialize it to be empty.  File systems will store a pointer to
//    this cache in their per-volume structures.
//
//    Information is retained in the tunnel cache for a fixed period of time.  MarkZ would
//    assume that a value of 10 seconds would satisfy the vast majority of situations.  This
//    could be controlled by the registry or could be a compilation constant.
//
//  Change: W95 times out at 15 seconds. Would be a registry value initialized at tunnel
//  creation time, with a proposed default of 15 seconds.
//

VOID
FsRtlInitializeTunnelCache (
    IN PTUNNEL Cache
    )
/*++

Routine Description:

    Initialize a new tunnel cache.

Arguments:

    None

Return Value:

    None

--*/
{
    PAGED_CODE();

    ExInitializeFastMutex(&Cache->Mutex);

    Cache->Cache = NULL;
    InitializeListHead(&Cache->TimerQueue);
    Cache->NumEntries = 0;

    return;
}


//
//  *** SPEC
//
//    FsRtlAddToTunnelCache - add information to a tunnel cache
//
//    FsRtlAddToTunnelCache is called by file systems when a name disappears from a
//    directory.  This typically occurs in both the delete and the rename paths.  When
//    a name is deleted, all information needed to be cached is extracted from the file
//    and passed in a single buffer.  This information is stored keyed by the directory key
//    (a ULONG that is unique to the directory) and the short-name of the file.
//
//    The caller is required to synchronize this call against FsRtlDeleteTunnelCache.
//
//    Arguments:
//        Cache        pointer to cache initialized by FsRtlInitializeTunnelCache
//        DirectoryKey    ULONG unique ID of the directory containing the deleted file
//        ShortName    UNICODE_STRING* short (8.3) name of the file
//        LongName    UNICODE_STRING* full name of the file
//        DataLength    ULONG length of data to be cached with these names
//        Data        VOID* data that will be cached.
//
//    It is acceptable for the Cache to ignore this request based upon memory constraints.
//
//  Change: W95 maintains 10 items in the tunnel cache. Since we are a potential server
//  this should be much higher. The max count would be initialized from the registry with
//  a proposed default of 1024. Adds which run into the limit would cause least recently
//  inserted recycling (i.e., off of the top of the timer queue).
//
//  Change: Key should be by the name removed, not neccesarily the short name. If a long name
//  is removed, it would be incorrect to miss the tunnel. Use KeyByShortName boolean to specify
//  which.
//
//  Change: Specify that Data, ShortName, and LongName are copied for storage.
//

VOID
FsRtlAddToTunnelCache (
    IN PTUNNEL Cache,
    IN ULONGLONG DirKey,
    IN PUNICODE_STRING ShortName,
    IN PUNICODE_STRING LongName,
    IN BOOLEAN KeyByShortName,
    IN ULONG DataLength,
    IN PVOID Data
    )
/*++

Routine Description:

    Adds an entry to the tunnel cache keyed by

        DirectoryKey ## (KeyByShortName ? ShortName : LongName)

    ShortName, LongName, and Data are copied and stored in the tunnel. As a side
    effect, if there are too many entries in the tunnel cache, this routine will
    initiate expiration in the tunnel cache.

Arguments:

    Cache - a tunnel cache initialized by FsRtlInitializeTunnelCache()

    DirKey - the key value of the directory the name appeared in

    ShortName - (optional if !KeyByShortName) the 8.3 name of the file

    LongName - (optional if KeyByShortName) the long name of the file

    KeyByShortName - specifies which name is keyed in the tunnel cache

    DataLength - specifies the length of the opaque data segment (file
    system specific) which contains the tunnelling information for this
    file

    Data - pointer to the opaque tunneling data segment

Return Value:

    None

--*/
{
    LONG Compare;
    ULONG NodeSize;
    PUNICODE_STRING NameKey;
    PRTL_SPLAY_LINKS *Links;
    LIST_ENTRY FreePoolList;

    PTUNNEL_NODE Node = NULL;
    PTUNNEL_NODE NewNode = NULL;
    BOOLEAN FreeOldNode = FALSE;
    BOOLEAN AllocatedFromPool = FALSE;

    PAGED_CODE();

    //
    //  If MaxEntries is 0 then tunneling is disabled.
    //

    if (TunnelMaxEntries == 0) return;

    InitializeListHead(&FreePoolList);

    //
    //  Grab a new node for this data
    //

    NodeSize = sizeof(TUNNEL_NODE) + ShortName->Length + LongName->Length + DataLength;

    if (LOOKASIDE_NODE_SIZE >= NodeSize) {

        NewNode = ExAllocateFromPagedLookasideList(&TunnelLookasideList);
    }

    if (NewNode == NULL) {

        //
        //  Data doesn't fit in lookaside nodes
        //

        NewNode = ExAllocatePoolWithTag(PagedPool, NodeSize, 'PnuT');

        if (NewNode == NULL) {

            //
            //  Give up tunneling this entry
            //

            return;
        }

        AllocatedFromPool = TRUE;
    }

    //
    //  Traverse the cache to find our insertion point
    //

    NameKey = (KeyByShortName ? ShortName : LongName);

    ExAcquireFastMutex(&Cache->Mutex);

    Links = &Cache->Cache;

    while (*Links) {

        Node = CONTAINING_RECORD(*Links, TUNNEL_NODE, CacheLinks);

        Compare = FsRtlCompareNodeAndKey(Node, DirKey, NameKey);

        if (Compare > 0) {

            Links = &RtlLeftChild(&Node->CacheLinks);

        } else {

            if (Compare < 0) {

                Links = &RtlRightChild(&Node->CacheLinks);

            } else {

                break;
            }
        }
    }

    //
    //  Thread new data into the splay tree
    //

    RtlInitializeSplayLinks(&NewNode->CacheLinks);

    if (Node) {

        //
        //  Not inserting first node in tree
        //

        if (*Links) {

            //
            //  Entry exists in the cache, so replace by swapping all splay links
            //

            RtlRightChild(&NewNode->CacheLinks) = RtlRightChild(*Links);
            RtlLeftChild(&NewNode->CacheLinks) = RtlLeftChild(*Links);

            if (RtlRightChild(*Links)) RtlParent(RtlRightChild(*Links)) = &NewNode->CacheLinks;
            if (RtlLeftChild(*Links)) RtlParent(RtlLeftChild(*Links)) = &NewNode->CacheLinks;

            if (!RtlIsRoot(*Links)) {

                //
                //  Change over the parent links. Note that we've messed with *Links now
                //  since it is pointing at the parent member.
                //

                RtlParent(&NewNode->CacheLinks) = RtlParent(*Links);

                if (RtlIsLeftChild(*Links)) {

                    RtlLeftChild(RtlParent(*Links)) = &NewNode->CacheLinks;

                } else {

                    RtlRightChild(RtlParent(*Links)) = &NewNode->CacheLinks;
                }

            } else {

                //
                //  Set root of the cache
                //

                Cache->Cache = &NewNode->CacheLinks;
            }

            //
            //  Free old node
            //

            RemoveEntryList(&Node->ListLinks);

            FsRtlFreeTunnelNode(Node, &FreePoolList);

            Cache->NumEntries--;

        } else {

            //
            //  Simple insertion as a leaf
            //

            NewNode->CacheLinks.Parent = &Node->CacheLinks;
            *Links = &NewNode->CacheLinks;
        }

    } else {

        Cache->Cache = &NewNode->CacheLinks;
    }

    //
    //  Thread onto the timer list
    //

    FsRtlQueryNormalizedSystemTime(&NewNode->CreateTime);
    InsertTailList(&Cache->TimerQueue, &NewNode->ListLinks);

    Cache->NumEntries++;

    //
    //  Stash tunneling information
    //

    NewNode->DirKey = DirKey;

    if (KeyByShortName) {

        NewNode->Flags = TUNNEL_FLAG_KEY_SHORT;

    } else {

        NewNode->Flags = 0;
    }

    //
    //  Initialize the internal UNICODE_STRINGS to point at the buffer segments. For various
    //  reasons (UNICODE APIs are incomplete, we're avoiding calling any allocate routine more
    //  than once, UNICODE strings are not guaranteed to be null terminated) we have to do a lot
    //  of this by hand.
    //
    //  The data is layed out like this in the allocated block:
    //
    //  -----------------------------------------------------------------------------------
    //  | TUNNEL_NODE | Node->ShortName.Buffer | Node->LongName.Buffer | Node->TunnelData |
    //  -----------------------------------------------------------------------------------
    //

    NewNode->ShortName.Buffer = (PWCHAR)((PCHAR)NewNode + sizeof(TUNNEL_NODE));
    NewNode->LongName.Buffer = (PWCHAR)((PCHAR)NewNode + sizeof(TUNNEL_NODE) + ShortName->Length);

    NewNode->ShortName.Length = NewNode->ShortName.MaximumLength = ShortName->Length;
    NewNode->LongName.Length = NewNode->LongName.MaximumLength = LongName->Length;

    if (ShortName->Length) {

        RtlCopyMemory(NewNode->ShortName.Buffer, ShortName->Buffer, ShortName->Length);
    }

    if (LongName->Length) {

        RtlCopyMemory(NewNode->LongName.Buffer, LongName->Buffer, LongName->Length);
    }

    NewNode->TunnelData = (PVOID)((PCHAR)NewNode + sizeof(TUNNEL_NODE) + ShortName->Length + LongName->Length);

    NewNode->TunnelDataLength = DataLength;

    RtlCopyMemory(NewNode->TunnelData, Data, DataLength);

    if (AllocatedFromPool) {

        SetFlag(NewNode->Flags, TUNNEL_FLAG_NON_LOOKASIDE);
    }

#if defined(TUNNELTEST) || defined (KEYVIEW)
    DbgPrint("FsRtlAddToTunnelCache:\n");
    DumpNode(NewNode, 1);
#ifndef KEYVIEW
    DumpTunnel(Cache);
#endif
#endif // TUNNELTEST

    //
    //  Clean out the cache, release, and then drop any pool memory we need to
    //

    FsRtlPruneTunnelCache(Cache, &FreePoolList);

    ExReleaseFastMutex(&Cache->Mutex);

    FsRtlEmptyFreePoolList(&FreePoolList);

    return;
}


//
//  *** SPEC
//
//    FsRtlFindInTunnelCache - retrieve information from tunnel cache
//
//    FsRtlFindInTunnelCache consults the cache to see if an entry with the same
//    DirectoryKey and ShortName exist.  If so, it returns the data associated with the
//    cache entry.  The entry may or may not be freed from the cache.  Information that is
//    stale but not yet purged (older than the retention threshold but not yet cleaned out)
//    may be returned.
//
//    File systems call FsRtlFindInTunnel cache in the create path when a new file is
//    being created and in the rename path when a new name is appearing in a directory.
//
//    The caller is required to synchronize this call against FsRtlDeleteTunnelCache.
//
//    Arguments:
//        Cache        a tunnel cache initialized by FsRtlInitializeTunnelCache()
//        DirectoryKey    ULONG unique ID of the directory where a name is appearing
//        Name        UNICODE_STRING* name that is being created
//        DataLength     in length of buffer, out returned length of data found
//        Data        pointer to buffer
//
//    Returns:
//        TRUE iff a matching DirectoryKey/Name pair are found, FALSE otherwise
//
//  Change: Add out parameters ShortName and LongName to capture the file naming information.
//  Plus: this avoids the need for marshalling/unmarshalling steps for the current desired use of
//  this code since otherwise we'd have variable length unaligned structures to contain the
//  strings along with the other meta-info.
//  Minus: Possibly a bad precedent.
//
//  Change: spec reads "may or may not be freed from cache" on a hit. This complicates unwinding
//  from aborted operations. Data will not be freed on a hit, but will expire like normal entries.
//

BOOLEAN
FsRtlFindInTunnelCache (
    IN PTUNNEL Cache,
    IN ULONGLONG DirKey,
    IN PUNICODE_STRING Name,
    OUT PUNICODE_STRING ShortName,
    OUT PUNICODE_STRING LongName,
    IN OUT PULONG  DataLength,
    OUT PVOID Data
    )
/*++

Routine Description:

    Looks up the key

        DirKey ## Name

    in the tunnel cache and removes it. As a side effect, this routine will initiate
    expiration of the aged entries in the tunnel cache.

Arguments:

    Cache - a tunnel cache initialized by FsRtlInitializeTunnelCache()

    DirKey - the key value of the directory the name will appear in

    Name - the name of the entry

    ShortName - return string to hold the short name of the tunneled file. Must
        already be allocated and large enough for max 8.3 name

    LongName -  return string to hold the long name of the tunneled file. If
        already allocated, may be grown if not large enough. Caller is
        responsible for noticing this and freeing data regardless of return value.

    DataLength - provides the length of the buffer avaliable to hold the
        tunneling information, returns the size of the tunneled information
        read out

Return Value:

    Boolean true if found, false otherwise

--*/
{
    PRTL_SPLAY_LINKS Links;
    PTUNNEL_NODE Node;
    LONG Compare;
    LIST_ENTRY FreePoolList;

    BOOLEAN Status = FALSE;

    PAGED_CODE();

    //
    //  If MaxEntries is 0 then tunneling is disabled.
    //

    if (TunnelMaxEntries == 0) return FALSE;

    InitializeListHead(&FreePoolList);

#ifdef KEYVIEW
    DbgPrint("++\nSearching for %wZ , %08x%08x\n--\n", Name, DblHex64(DirKey));
#endif

    ExAcquireFastMutex(&Cache->Mutex);

    //
    //  Expire aged entries first so we don't grab old data
    //

    FsRtlPruneTunnelCache(Cache, &FreePoolList);

    Links = Cache->Cache;

    while (Links) {

        Node = CONTAINING_RECORD(Links, TUNNEL_NODE, CacheLinks);

        Compare = FsRtlCompareNodeAndKey(Node, DirKey, Name);

        if (Compare > 0) {

            Links = RtlLeftChild(&Node->CacheLinks);

        } else {

            if (Compare < 0) {

                Links = RtlRightChild(&Node->CacheLinks);

            } else {

                //
                //  Found tunneling information
                //

#if defined(TUNNELTEST) || defined(KEYVIEW)
                DbgPrint("FsRtlFindInTunnelCache:\n");
                DumpNode(Node, 1);
#ifndef KEYVIEW
                DumpTunnel(Cache);
#endif
#endif // TUNNELTEST

                break;
            }
        }
    }

    try {

        if (Links) {
    
            //
            //  Copy node data into caller's area
            //
    
            ASSERT(ShortName->MaximumLength >= (8+1+3)*sizeof(WCHAR));
            RtlCopyUnicodeString(ShortName, &Node->ShortName);
    
            if (LongName->MaximumLength >= Node->LongName.Length) {
    
                RtlCopyUnicodeString(LongName, &Node->LongName);
    
            } else {
    
                //
                //  Need to allocate more memory for the long name
                //
    
                LongName->Buffer = FsRtlAllocatePoolWithTag(PagedPool, Node->LongName.Length, '4nuT');
                LongName->Length = LongName->MaximumLength = Node->LongName.Length;
    
                RtlCopyMemory(LongName->Buffer, Node->LongName.Buffer, Node->LongName.Length);
            }
    
            ASSERT(*DataLength >= Node->TunnelDataLength);
            RtlCopyMemory(Data, Node->TunnelData, Node->TunnelDataLength);
            *DataLength = Node->TunnelDataLength;
    
            Status = TRUE;
        }

    } finally {

        ExReleaseFastMutex(&Cache->Mutex);
    
        FsRtlEmptyFreePoolList(&FreePoolList);
    }
    
    return Status;
}


//
//  *** SPEC
//
//    FsRtlDeleteKeyFromTunnelCache - delete all cached information associated with
//    a DirectoryKey
//
//    When file systems delete a directory, all cached information relating to that directory
//    must be purged.  File systems call FsRtlDeleteKeyFromTunnelCache in the rmdir path.
//
//    The caller is required to synchronize this call against FsRtlDeleteTunnelCache.
//
//    Arguments:
//        Cache        a tunnel cache initialized by FsRtlInitializeTunnelCache()
//        DirectoryKey    ULONGLONG unique ID of the directory that is being deleted
//

VOID
FsRtlDeleteKeyFromTunnelCache (
    IN PTUNNEL Cache,
    IN ULONGLONG DirKey
    )
/*++

Routine Description:

    Deletes all entries in the cache associated with a specific directory

Arguments:

    Cache - a tunnel cache initialized by FsRtlInitializeTunnelCache()

    DirKey - the key value of the directory (presumeably being removed)

Return Value:

    None

--*/
{
    PRTL_SPLAY_LINKS Links;
    PRTL_SPLAY_LINKS SuccessorLinks;
    PTUNNEL_NODE Node;
    LIST_ENTRY FreePoolList;

    PRTL_SPLAY_LINKS LastLinks = NULL;
    BOOLEAN Splay = TRUE;

    PAGED_CODE();

    //
    //  If MaxEntries is 0 then tunneling is disabled.
    //

    if (TunnelMaxEntries == 0) return;

    InitializeListHead(&FreePoolList);

#ifdef KEYVIEW
    DbgPrint("++\nDeleting key %08x%08x\n--\n", DblHex64(DirKey));
#endif

    ExAcquireFastMutex(&Cache->Mutex);

    Links = Cache->Cache;

    while (Links) {

        Node = CONTAINING_RECORD(Links, TUNNEL_NODE, CacheLinks);

        if (Node->DirKey > DirKey) {

            //
            //  All nodes to the right are bigger, go left
            //

            Links = RtlLeftChild(&Node->CacheLinks);

        } else {

            if (Node->DirKey < DirKey) {

                if (LastLinks) {

                    //
                    //  If we have previously seen a candidate node to delete
                    //  and we have now gone too far left - we know where to start.
                    //

                    break;
                }

                Links = RtlRightChild(&Node->CacheLinks);

            } else {

                //
                //  Node is a candidate to be deleted, but we might have more nodes
                //  to the left in the tree. Note this location and go on.
                //

                LastLinks = Links;
                Links = RtlLeftChild(&Node->CacheLinks);
            }
        }
    }

    for (Links = LastLinks;
         Links;
         Links = SuccessorLinks) {

        SuccessorLinks = RtlRealSuccessor(Links);
        Node = CONTAINING_RECORD(Links, TUNNEL_NODE, CacheLinks);

        if (Node->DirKey != DirKey) {

            //
            //  Reached nodes which have a different key, so we're done
            //

            break;
        }

        FsRtlRemoveNodeFromTunnel(Cache, Node, &FreePoolList, &Splay);
    }

#ifdef TUNNELTEST
    DbgPrint("FsRtlDeleteKeyFromTunnelCache:\n");
#ifndef KEYVIEW
    DumpTunnel(Cache);
#endif
#endif // TUNNELTEST

    ExReleaseFastMutex(&Cache->Mutex);

    //
    //  Free delayed pool
    //

    FsRtlEmptyFreePoolList(&FreePoolList);

    return;
}


//
//  *** SPEC
//
//    FsRtlDeleteTunnelCache - free a tunnel cache
//
//    FsRtlDeleteTunnelCache deletes all cached information.  The Cache is no longer
//    valid.
//
//    Arguments:
//        Cache        a tunnel cache initialized by FsRtlInitializeTunnelCache()
//

VOID
FsRtlDeleteTunnelCache (
    IN PTUNNEL Cache
    )
/*++

Routine Description:

    Deletes a tunnel cache

Arguments:

    Cache - the cache to delete, initialized by FsRtlInitializeTunnelCache()

Return Value:

    None

--*/
{
    PTUNNEL_NODE Node;
    PLIST_ENTRY Link, Next;

    PAGED_CODE();

    //
    //  If MaxEntries is 0 then tunneling is disabled.
    //

    if (TunnelMaxEntries == 0) return;

    //
    //  Zero out the cache and delete everything on the timer list
    //

    Cache->Cache = NULL;
    Cache->NumEntries = 0;

    for (Link = Cache->TimerQueue.Flink;
         Link != &Cache->TimerQueue;
         Link = Next) {

        Next = Link->Flink;

        Node = CONTAINING_RECORD(Link, TUNNEL_NODE, ListLinks);

        FsRtlFreeTunnelNode(Node, NULL);
    }

    InitializeListHead(&Cache->TimerQueue);

    return;
}


VOID
FsRtlPruneTunnelCache (
    IN PTUNNEL Cache,
    IN OUT PLIST_ENTRY FreePoolList
    )
/*++

Routine Description:

    Removes deadwood entries from the tunnel cache as defined by TunnelMaxAge and TunnelMaxEntries.
    Pool memory is returned on a list for deletion by the calling routine at a time of
    its choosing.

    For performance reasons we don't want to force freeing of memory inside a mutex.

Arguments:

    Cache - the tunnel cache to prune

    FreePoolList - a list to queue pool memory on to

Return Value:

    None
--*/
{
    PTUNNEL_NODE Node;
    LARGE_INTEGER ExpireTime;
    BOOLEAN Splay = TRUE;

    PAGED_CODE();

    //
    //  Calculate the age of the oldest entry we want to keep
    //

    FsRtlQueryNormalizedSystemTime(&ExpireTime);
    ExpireTime.QuadPart -= TunnelMaxAge;

    //
    //  Expire old entries off of the timer queue
    //

    while (!IsListEmpty(&Cache->TimerQueue)) {

        Node = CONTAINING_RECORD(Cache->TimerQueue.Flink, TUNNEL_NODE, ListLinks);

        if (Node->CreateTime.QuadPart < ExpireTime.QuadPart) {

#if defined(TUNNELTEST) || defined(KEYVIEW)
            DbgPrint("Expiring node %x (%ud%ud 1/10 msec too old)\n", Node, DblHex64(ExpireTime.QuadPart - Node->CreateTime.QuadPart));
#endif // TUNNELTEST

            FsRtlRemoveNodeFromTunnel(Cache, Node, FreePoolList, &Splay);

        } else {

            //
            //  No more nodes to be expired
            //

            break;
        }
    }

    //
    //  Remove entries until we're under the TunnelMaxEntries limit
    //

    while (Cache->NumEntries > TunnelMaxEntries) {

        Node = CONTAINING_RECORD(Cache->TimerQueue.Flink, TUNNEL_NODE, ListLinks);

#if defined(TUNNELTEST) || defined(KEYVIEW)
            DbgPrint("Dumping node %x (%d > %d)\n", Node, Cache->NumEntries, TunnelMaxEntries);
#endif // TUNNELTEST

        FsRtlRemoveNodeFromTunnel(Cache, Node, FreePoolList, &Splay);
    }

    return;
}


NTSTATUS
FsRtlGetTunnelParameterValue (
    IN PUNICODE_STRING ValueName,
    IN OUT PULONG Value
    )

/*++

Routine Description:

    Given a unicode value name this routine will go into the registry
    location for the Tunnel parameter information and get the
    value.

Arguments:

    ValueName - the unicode name for the registry value located in the
                double space configuration location of the registry.
    Value   - a pointer to the ULONG for the result.

Return Value:

    NTSTATUS

    If STATUS_SUCCESSFUL is returned, the location *Value will be
    updated with the DWORD value from the registry.  If any failing
    status is returned, this value is untouched.

--*/

{
    HANDLE Handle;
    NTSTATUS Status;
    ULONG RequestLength;
    ULONG ResultLength;
    UCHAR Buffer[KEY_WORK_AREA];
    UNICODE_STRING KeyName;
    OBJECT_ATTRIBUTES ObjectAttributes;
    PKEY_VALUE_FULL_INFORMATION KeyValueInformation;

    KeyName.Buffer = TUNNEL_KEY_NAME;
    KeyName.Length = sizeof(TUNNEL_KEY_NAME) - sizeof(WCHAR);
    KeyName.MaximumLength = sizeof(TUNNEL_KEY_NAME);

    InitializeObjectAttributes(&ObjectAttributes,
                               &KeyName,
                               OBJ_CASE_INSENSITIVE,
                               NULL,
                               NULL);

    Status = ZwOpenKey(&Handle,
                       KEY_READ,
                       &ObjectAttributes);

    if (!NT_SUCCESS(Status)) {

        return Status;
    }

    RequestLength = KEY_WORK_AREA;

    KeyValueInformation = (PKEY_VALUE_FULL_INFORMATION)Buffer;

    while (1) {

        Status = ZwQueryValueKey(Handle,
                                 ValueName,
                                 KeyValueFullInformation,
                                 KeyValueInformation,
                                 RequestLength,
                                 &ResultLength);

        ASSERT( Status != STATUS_BUFFER_OVERFLOW );

        if (Status == STATUS_BUFFER_OVERFLOW) {

            //
            // Try to get a buffer big enough.
            //

            if (KeyValueInformation != (PKEY_VALUE_FULL_INFORMATION)Buffer) {

                ExFreePool(KeyValueInformation);
            }

            RequestLength += 256;

            KeyValueInformation = (PKEY_VALUE_FULL_INFORMATION)
                                  ExAllocatePoolWithTag(PagedPool,
                                                        RequestLength,
                                                        'KnuT');

            if (!KeyValueInformation) {
                return STATUS_NO_MEMORY;
            }

        } else {

            break;
        }
    }

    ZwClose(Handle);

    if (NT_SUCCESS(Status)) {

        if (KeyValueInformation->DataLength != 0) {

            PULONG DataPtr;

            //
            // Return contents to the caller.
            //

            DataPtr = (PULONG)
              ((PUCHAR)KeyValueInformation + KeyValueInformation->DataOffset);
            *Value = *DataPtr;

        } else {

            //
            // Treat as if no value was found
            //

            Status = STATUS_OBJECT_NAME_NOT_FOUND;
        }
    }

    if (KeyValueInformation != (PKEY_VALUE_FULL_INFORMATION)Buffer) {

        ExFreePool(KeyValueInformation);
    }

    return Status;
}


#if defined(TUNNELTEST) || defined(KEYVIEW)

VOID
DumpTunnel (
    PTUNNEL Tunnel
    )
{
    PRTL_SPLAY_LINKS SplayLinks, Ptr;
    PTUNNEL_NODE Node;
    PLIST_ENTRY Link;
    ULONG Indent = 1, i;
    ULONG EntryCount = 0;
    BOOLEAN CountOff = FALSE;

    DbgPrint("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n");

    DbgPrint("NumEntries = %d\n", Tunnel->NumEntries);
    DbgPrint("****** Cache Tree\n");

    SplayLinks = Tunnel->Cache;

    if (SplayLinks == NULL) {

        goto end;
    }

    while (RtlLeftChild(SplayLinks) != NULL) {

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

    while (SplayLinks) {

        Node = CONTAINING_RECORD( SplayLinks, TUNNEL_NODE, CacheLinks );

        EntryCount++;

        DumpNode(Node, Indent);

        Ptr = SplayLinks;

        /*
          first check to see if there is a right subtree to the input link
          if there is then the real successor is the left most node in
          the right subtree.  That is find and return P in the following diagram

                      Links
                         \
                          .
                         .
                        .
                       /
                      P
                       \
        */

        if ((Ptr = RtlRightChild(SplayLinks)) != NULL) {

            Indent++;
            while (RtlLeftChild(Ptr) != NULL) {

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

            SplayLinks = Ptr;

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

                               P
                              /
                             .
                              .
                               .
                              Links
            */

            Ptr = SplayLinks;
            while (RtlIsRightChild(Ptr)) {

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

            if (!RtlIsLeftChild(Ptr)) {

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

            } else {

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

    end:

    if (CountOff = (EntryCount != Tunnel->NumEntries)) {

        DbgPrint("!!!!!!!!!! Splay Tree Count Mismatch (%d != %d)\n", EntryCount, Tunnel->NumEntries);
    }

    EntryCount = 0;

    DbgPrint("****** Timer Queue\n");

    for (Link = Tunnel->TimerQueue.Flink;
         Link != &Tunnel->TimerQueue;
         Link = Link->Flink) {

        Node = CONTAINING_RECORD( Link, TUNNEL_NODE, ListLinks );

        EntryCount++;

        DumpNode(Node, 1);
    }

    if (CountOff |= (EntryCount != Tunnel->NumEntries)) {

        DbgPrint("!!!!!!!!!! Timer Queue Count Mismatch (%d != %d)\n", EntryCount, Tunnel->NumEntries);
    }

    ASSERT(!CountOff);

    DbgPrint("------------------------------------------------------------------\n");
}

#define MAXINDENT  128
#define INDENTSTEP 3

VOID
DumpNode (
    PTUNNEL_NODE Node,
    ULONG Indent
    )
{
    ULONG i;
    CHAR  SpaceBuf[MAXINDENT*INDENTSTEP + 1];

    Indent--;
    if (Indent > MAXINDENT) {
        Indent = MAXINDENT;
    }

    //
    //  DbgPrint is really expensive to iteratively call to do the indenting,
    //  so just build up the indentation all at once on the stack.
    //

    RtlFillMemory(SpaceBuf, Indent*INDENTSTEP, ' ');
    SpaceBuf[Indent*INDENTSTEP] = '\0';

    DbgPrint("%sNode 0x%x  CreateTime = %08x%08x, DirKey = %08x%08x, Flags = %d\n",
             SpaceBuf,
             Node,
             DblHex64(Node->CreateTime.QuadPart),
             DblHex64(Node->DirKey),
             Node->Flags );

    DbgPrint("%sShort = %wZ, Long = %wZ\n", SpaceBuf,
                                            &Node->ShortName,
                                            &Node->LongName );

    DbgPrint("%sP = %x, R = %x, L = %x\n", SpaceBuf,
                                           RtlParent(&Node->CacheLinks),
                                           RtlRightChild(&Node->CacheLinks),
                                           RtlLeftChild(&Node->CacheLinks) );
}
#endif // TUNNELTEST