summaryrefslogtreecommitdiffstats
path: root/private/ntos/smbtrsup/smbtrsup.c
blob: 79a4b5e49df0d8fbf65b3a466aa2cd5865d5f88b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
/*++

Copyright (c) 1992  Microsoft Corporation

Module Name:

    smbtrsup.c

Abstract:

    This module contains the code to implement the kernel mode SmbTrace
    component within the LanMan server and redirector.
    The interface between the kernel mode component and the
    server/redirector is found in nt\private\inc\smbtrsup.h
    The interface providing user-level access to SmbTrace is found in
    nt\private\inc\smbtrace.h

Author:

    Peter Gray (w-peterg)   23-March-1992

Revision History:

    Stephan Mueller (t-stephm)   21-July-1992

        Completed, fixed bugs, moved all associated declarations here
        from various places in the server, ported to the redirector
        and converted to a kernel DLL.

--*/

#include <ntifs.h>
#include <smbtrace.h>     // for names and structs shared with user-mode app

#define _SMBTRSUP_SYS_ 1  // to get correct definitions for exported variables
#include <smbtrsup.h>     // for functions exported to server/redirector

#if DBG
ULONG SmbtrsupDebug = 0;
#define TrPrint(x) if (SmbtrsupDebug) KdPrint(x)
#else
#define TrPrint(x)
#endif

//
// we assume all well-known names are #defined in Unicode, and require
// them to be so: in the SmbTrace application and the smbtrsup.sys package
//
#ifndef UNICODE
#error "UNICODE build required"
#endif


#if DBG
#define PAGED_DBG 1
#endif
#ifdef PAGED_DBG
#undef PAGED_CODE
#define PAGED_CODE() \
    struct { ULONG bogus; } ThisCodeCantBePaged; \
    ThisCodeCantBePaged; \
    if (KeGetCurrentIrql() > APC_LEVEL) { \
        KdPrint(( "SMBTRSUP: Pageable code called at IRQL %d.  File %s, Line %d\n", KeGetCurrentIrql(), __FILE__, __LINE__ )); \
        ASSERT(FALSE); \
        }
#define PAGED_CODE_CHECK() if (ThisCodeCantBePaged) ;
ULONG ThisCodeCantBePaged;
#else
#define PAGED_CODE_CHECK()
#endif


#if PAGED_DBG
#define ACQUIRE_SPIN_LOCK(a, b) {               \
    PAGED_CODE_CHECK();                         \
    KeAcquireSpinLock(a, b);                    \
    }
#define RELEASE_SPIN_LOCK(a, b) {               \
    PAGED_CODE_CHECK();                         \
    KeReleaseSpinLock(a, b);                    \
    }

#else
#define ACQUIRE_SPIN_LOCK(a, b) KeAcquireSpinLock(a, b)
#define RELEASE_SPIN_LOCK(a, b) KeReleaseSpinLock(a, b)
#endif

//
// Increment shared variable in instance data using appropriate interlock
//
#define LOCK_INC_ID(var)                                     \
     ExInterlockedAddUlong( (PULONG)&ID(var),                \
                            1, &ID(var##Interlock) )

//
// Zero shared variable in instance data using appropriate interlock
//
#define LOCK_ZERO_ID(var) {                                  \
     ID(var) = 0;                                            \
     }


//
// The various states SmbTrace can be in.  These states are internal
// only.  The external SmbTraceActive variable contains much less
// detailed information:  it is TRUE when TraceRunning, FALSE in any other
// state.
//
typedef enum _SMBTRACE_STATE {
    TraceStopped,          // not running
    TraceStarting,         // preparing to run
    TraceStartStopFile,    // starting, but want to shut down immediately
                           // because the FileObject closed
    TraceStartStopNull,    // starting, but want to shut down immediately
                           // because a new fsctl came in
    TraceAppWaiting,       // waiting for application to die
    TraceRunning,          // processing SMBs
    TraceStopping          // waiting for smbtrace thread to stop
} SMBTRACE_STATE;


//
// Structure used to hold information regarding an SMB which is put into
// the SmbTrace thread queue.
//
typedef struct _SMBTRACE_QUEUE_ENTRY {
    LIST_ENTRY  ListEntry;      // usual doubly-linked list
    ULONG       SmbLength;      // the length of this SMB
    PVOID       Buffer;         // pointer into SmbTracePortMemoryHeap
                                // or non-paged pool
    PVOID       SmbAddress;     // address of real SMB, if SMB still
                                // available (i.e. if slow mode)
    BOOLEAN     BufferNonPaged; // TRUE if Buffer in non-paged pool, FALSE if
                                // Buffer in SmbTracePortMemoryHeap
                                // Redirector-specific
    PKEVENT     WaitEvent;      // pointer to worker thread event to be
                                // signalled when SMB has been processed
                                // slow mode specific
} SMBTRACE_QUEUE_ENTRY, *PSMBTRACE_QUEUE_ENTRY;


//
// Instance data is specific to the component being traced.  In order
// to unclutter the source code, use the following macro to access
// instance specific data.
// Every exported function either has an explicit parameter (named
// Component) which the caller provides, or is implicitly applicable
// only to one component, and has a local variable named Component
// which is always set to the appropriate value.
//
#define ID(field) (SmbTraceData[Component].field)

//
// Instance data.  The fields which need to be statically initialized
// are declared before those that we don't care to initialize.
//
typedef struct _INSTANCE_DATA {

    //
    // Statically initialized fields.
    //

    //
    // Names for identifying the component being traced in KdPrint messages,
    // and global objects
    //
    PCHAR ComponentName;
    PWSTR SharedMemoryName;
    PWSTR NewSmbEventName;
    PWSTR DoneSmbEventName;

    //
    //  Prevent reinitializing resources if rdr/srv reloaded
    //
    BOOLEAN InstanceInitialized;

    //
    // some tracing parameters, from SmbTrace application
    //
    BOOLEAN SingleSmbMode;
    CLONG   Verbosity;

    //
    // State of the current trace.
    //
    SMBTRACE_STATE TraceState;

    //
    // Pointer to file object of client who started the current trace.
    //
    PFILE_OBJECT StartersFileObject;

    //
    // Fsp process of the component we're tracing in.
    //
    PEPROCESS FspProcess;

    //
    // All subsequent fields are not expliticly statically initiliazed.
    //

    //
    // Current count of number of SMBs lost since last one output.
    // Use an interlock to access, cleared when an SMB is sent to
    // the client successfully.  This lock is used with ExInterlockedXxx
    // routines, so it cannot be treated as a real spin lock (i.e.
    // don't use KeAcquireSpinLock.)
    //
    KSPIN_LOCK SmbsLostInterlock;
    ULONG      SmbsLost;

    //
    // some events, only accessed within the kernel
    //
    KEVENT ActiveEvent;
    KEVENT TerminatedEvent;
    KEVENT TerminationEvent;
    KEVENT AppTerminationEvent;
    KEVENT NeedMemoryEvent;

    //
    // some events, shared with the outside world
    //
    HANDLE NewSmbEvent;
    HANDLE DoneSmbEvent;

    //
    // Handle to the shared memory used for communication between
    // the server/redirector and SmbTrace.
    //
    HANDLE SectionHandle;

    //
    // Pointers to control the shared memory for the SmbTrace application.
    // The port memory heap handle is initialized to NULL to indicate that
    // there is no connection with SmbTrace yet.
    //
    PVOID PortMemoryBase;
    ULONG PortMemorySize;
    ULONG TableSize;
    PVOID PortMemoryHeap;

    //
    // serialized access to the heap,
    // to allow clean shutdown (StateInterlock)
    //
    KSPIN_LOCK  HeapReferenceCountLock;
    PERESOURCE StateInterlock;
    PERESOURCE HeapInterlock;
    ULONG     HeapReferenceCount;

    //
    // Pointers to the structured data, located in the shared memory.
    //
    PSMBTRACE_TABLE_HEADER  TableHeader;
    PSMBTRACE_TABLE_ENTRY   Table;

    //
    // Fields for the SmbTrace queue.  The server/redirector puts
    // incoming and outgoing SMBs into this queue (when
    // SmbTraceActive[Component] is TRUE and they are processed
    // by the SmbTrace thread.
    //
    LIST_ENTRY Queue;            // The queue itself
    KSPIN_LOCK QueueInterlock;   // Synchronizes access to queue
    KSEMAPHORE QueueSemaphore;   // Counts elements in queue

} INSTANCE_DATA;


#ifdef  ALLOC_DATA_PRAGMA
#pragma data_seg("PAGESMBD")
#endif
//
// Global variables for SmbTrace support
//

INSTANCE_DATA SmbTraceData[] = {

    //
    // Server data
    //

    {
        "Srv",                                 // ComponentName
        SMBTRACE_SRV_SHARED_MEMORY_NAME,       // SharedMemoryName
        SMBTRACE_SRV_NEW_SMB_EVENT_NAME,       // NewSmbEventName
        SMBTRACE_SRV_DONE_SMB_EVENT_NAME,      // DoneSmbEventName

        FALSE,                                 // InstanceInitialized

        FALSE,                                 // SingleSmbMode
        SMBTRACE_VERBOSITY_ERROR,              // Verbosity

        TraceStopped,                          // TraceState

        NULL,                                  // StartersFileObject
        NULL                                   // FspProcess

        // rest of fields expected to get 'all-zeroes'
    },

    //
    // Redirector data
    //

    {
        "Rdr",                                 // ComponentName
        SMBTRACE_LMR_SHARED_MEMORY_NAME,       // SharedMemoryName
        SMBTRACE_LMR_NEW_SMB_EVENT_NAME,       // NewSmbEventName
        SMBTRACE_LMR_DONE_SMB_EVENT_NAME,      // DoneSmbEventName

        FALSE,                                 // InstanceInitialized

        FALSE,                                 // SingleSmbMode
        SMBTRACE_VERBOSITY_ERROR,              // Verbosity

        TraceStopped,                          // TraceState

        NULL,                                  // StartersFileObject
        NULL                                   // FspProcess

        // rest of fields expected to get 'all-zeroes'
    }
};


//
// some state booleans, exported to clients.  For this reason,
// they're stored separately from the rest of the instance data.
// Initially, SmbTrace is neither active nor transitioning.
//
BOOLEAN SmbTraceActive[] = {FALSE, FALSE};
BOOLEAN SmbTraceTransitioning[] = {FALSE, FALSE};

HANDLE
SmbTraceDiscardableCodeHandle = 0;

HANDLE
SmbTraceDiscardableDataHandle = 0;

#ifdef  ALLOC_DATA_PRAGMA
#pragma data_seg()
#endif

//
// Forward declarations of internal routines
//

BOOLEAN
SmbTraceReferenceHeap(
    IN SMBTRACE_COMPONENT Component
    );

VOID
SmbTraceDereferenceHeap(
    IN SMBTRACE_COMPONENT Component
    );

VOID
SmbTraceDisconnect(
    IN SMBTRACE_COMPONENT Component
    );

VOID
SmbTraceEmptyQueue (
    IN SMBTRACE_COMPONENT Component
    );

VOID
SmbTraceThreadEntry(
    IN PVOID Context
    );

NTSTATUS
SmbTraceFreeMemory (
    IN SMBTRACE_COMPONENT Component
    );

VOID
SmbTraceToClient(
    IN PVOID Smb,
    IN CLONG SmbLength,
    IN PVOID SmbAddress,
    IN SMBTRACE_COMPONENT Component
    );

ULONG
SmbTraceMdlLength(
    IN PMDL Mdl
    );

VOID
SmbTraceCopyMdlContiguous(
    OUT PVOID Destination,
    IN  PMDL Mdl,
    IN  ULONG Length
    );

//NTSTATUS
//DriverEntry(
//    IN PDRIVER_OBJECT DriverObject,
//    IN PUNICODE_STRING RegistryPath
//    );

VOID
SmbTraceDeferredDereferenceHeap(
    IN PVOID Context
    );

#ifdef  ALLOC_PRAGMA
#pragma alloc_text(PAGE, SmbTraceInitialize)
#pragma alloc_text(PAGE, SmbTraceTerminate)
#pragma alloc_text(PAGE, SmbTraceStart)
#pragma alloc_text(PAGE, SmbTraceStop)
#pragma alloc_text(PAGE, SmbTraceCompleteSrv)
#pragma alloc_text(PAGE, SmbTraceDisconnect)
#pragma alloc_text(PAGE, SmbTraceEmptyQueue)
#pragma alloc_text(PAGE, SmbTraceThreadEntry)
#pragma alloc_text(PAGE, SmbTraceFreeMemory)
#pragma alloc_text(PAGE, SmbTraceToClient)
#pragma alloc_text(PAGE, SmbTraceDeferredDereferenceHeap)
#pragma alloc_text(PAGESMBC, SmbTraceCompleteRdr)
#pragma alloc_text(PAGESMBC, SmbTraceReferenceHeap)
#pragma alloc_text(PAGESMBC, SmbTraceDereferenceHeap)
#pragma alloc_text(PAGESMBC, SmbTraceMdlLength)
#pragma alloc_text(PAGESMBC, SmbTraceCopyMdlContiguous)
#endif



//
// Exported routines
//


NTSTATUS
SmbTraceInitialize (
    IN SMBTRACE_COMPONENT Component
    )

/*++

Routine Description:

    This routine initializes the SmbTrace component-specific instance
    globals.  On first-ever invocation, it performs truly global
    initialization.

Arguments:

    Component - Context from which we're called: server or redirector

Return Value:

    NTSTATUS - Indicates failure if unable to allocate resources

--*/

{
    PAGED_CODE();

    if ( ID(InstanceInitialized) == FALSE ) {
        //
        // Component specific initialization -- events and locks.
        //

        KeInitializeEvent( &ID(ActiveEvent), NotificationEvent, FALSE);
        KeInitializeEvent( &ID(TerminatedEvent), NotificationEvent, FALSE);
        KeInitializeEvent( &ID(TerminationEvent), NotificationEvent, FALSE);
        KeInitializeEvent( &ID(AppTerminationEvent), NotificationEvent, FALSE);
        KeInitializeEvent( &ID(NeedMemoryEvent), NotificationEvent, FALSE);

        KeInitializeSpinLock( &ID(SmbsLostInterlock) );
        KeInitializeSpinLock( &ID(HeapReferenceCountLock) );

        ID(StateInterlock) = ExAllocatePoolWithTag(
                                NonPagedPool,
                                sizeof(ERESOURCE),
                                'tbmS'
                                );
        if ( ID(StateInterlock) == NULL ) {
            return STATUS_INSUFFICIENT_RESOURCES;
        }
        ExInitializeResource( ID(StateInterlock) );

        ID(HeapInterlock) = ExAllocatePoolWithTag(
                                NonPagedPool,
                                sizeof(ERESOURCE),
                                'tbmS'
                                );
        if ( ID(HeapInterlock) == NULL ) {
            ExDeleteResource( ID(StateInterlock) );
            ExFreePool( ID(StateInterlock) );
            ID(StateInterlock) = NULL;
            return STATUS_INSUFFICIENT_RESOURCES;
        }
        ExInitializeResource( ID(HeapInterlock) );

        ID(InstanceInitialized) = TRUE;
    }

    return STATUS_SUCCESS;

} // SmbTraceInitialize


VOID
SmbTraceTerminate (
    IN SMBTRACE_COMPONENT Component
    )

/*++

Routine Description:

    This routine cleans up the SmbTrace component-specific instance
    globals.  It should be called by the component when the component
    is unloaded.

Arguments:

    Component - Context from which we're called: server or redirector

Return Value:

    None

--*/

{
    PAGED_CODE();

    if ( ID(InstanceInitialized) ) {

        ExDeleteResource( ID(StateInterlock) );
        ExFreePool( ID(StateInterlock) );

        ExDeleteResource( ID(HeapInterlock) );
        ExFreePool( ID(HeapInterlock) );

        ID(InstanceInitialized) = FALSE;
    }

    return;

} // SmbTraceTerminate


NTSTATUS
SmbTraceStart (
    IN ULONG InputBufferLength,
    IN ULONG OutputBufferLength,
    IN OUT PVOID ConfigInOut,
    IN PFILE_OBJECT FileObject,
    IN SMBTRACE_COMPONENT Component
    )

/*++

Routine Description:

    This routine performs all the work necessary to connect the server/
    redirector to SmbTrace.  It creates the section of shared memory to
    be used, then creates the events needed. All these objects are then
    opened by the client (smbtrace) program. This code initializes the
    table, the heap stored in the section and table header.  This routine
    must be called from an Fsp process.

Arguments:

    InputBufferLength - Length of the ConfigInOut packet

    OutputBufferLength - Length expected for the ConfigInOut packet returned

    ConfigInOut - A structure that has configuration information.

    FileObject - FileObject of the process requesting that SmbTrace be started,
                 used to automatically shut down when the app dies.

    Component - Context from which we're called: server or redirector

Return Value:

    NTSTATUS - result of operation.

--*/

// size of our one, particular, ACL
#define ACL_LENGTH  (ULONG)sizeof(ACL) +                 \
                    (ULONG)sizeof(ACCESS_ALLOWED_ACE) +  \
                    sizeof(LUID) +                       \
                    8

{
    NTSTATUS status;
    UNICODE_STRING memoryNameU;

    SID_IDENTIFIER_AUTHORITY NtAuthority = SECURITY_NT_AUTHORITY;
    UCHAR Buffer[ACL_LENGTH];
    PACL AdminAcl = (PACL)(&Buffer[0]);
    SECURITY_DESCRIPTOR securityDescriptor;

    UNICODE_STRING eventNameU;
    OBJECT_ATTRIBUTES objectAttributes;
    ULONG i;
    LARGE_INTEGER sectionSize;
    PSMBTRACE_CONFIG_PACKET_REQ  ConfigPacket;
    PSMBTRACE_CONFIG_PACKET_RESP ConfigPacketResp;
    HANDLE threadHandle;

    PAGED_CODE();

    ASSERT( ID(InstanceInitialized) );

    //
    // Validate the buffer lengths passed in.
    //

    if ( ( InputBufferLength  != sizeof( SMBTRACE_CONFIG_PACKET_REQ ) )
      || ( OutputBufferLength != sizeof( SMBTRACE_CONFIG_PACKET_RESP ) )
    ) {

        TrPrint(( "%s!SmbTraceStart: config packet(s) of wrong size!\n",
                  ID(ComponentName) ));

        return STATUS_INFO_LENGTH_MISMATCH;

    }

    ExAcquireResourceExclusive( ID(StateInterlock), TRUE );

    if ( ID(TraceState) != TraceStopped ) {
        ExReleaseResource( ID(StateInterlock) );
        return STATUS_INVALID_DEVICE_STATE;
    }

    ASSERT(!SmbTraceActive[Component]);

    ASSERT (SmbTraceDiscardableDataHandle == NULL);

    ASSERT (SmbTraceDiscardableCodeHandle == NULL);

    SmbTraceDiscardableCodeHandle = MmLockPagableCodeSection(SmbTraceReferenceHeap);

    SmbTraceDiscardableDataHandle = MmLockPagableDataSection(SmbTraceData);

    ID(TraceState) = TraceStarting;

    //
    // Initialize global variables so that we know what to close on errexit
    //

    ID(SectionHandle) = NULL;
    ID(PortMemoryHeap) = NULL;
    ID(NewSmbEvent) = NULL;
    ID(DoneSmbEvent) = NULL;

    //
    // Caution! Both input and output packets are the same, we must
    // read all of the input before we write any output.
    //

    ConfigPacket = (PSMBTRACE_CONFIG_PACKET_REQ) ConfigInOut;
    ConfigPacketResp = (PSMBTRACE_CONFIG_PACKET_RESP) ConfigInOut;

    //
    // Set the mode of operation (read all values).
    //

    ID(SingleSmbMode)  = ConfigPacket->SingleSmbMode;
    ID(Verbosity)      = ConfigPacket->Verbosity;
    ID(PortMemorySize) = ConfigPacket->BufferSize;
    ID(TableSize)      = ConfigPacket->TableSize;

    //
    // Create a security descriptor containing a discretionary Acl
    // allowing administrator access.  This SD will be used to allow
    // Smbtrace access to the shared memory and the notification events.
    //

    // Create Acl allowing administrator access using well-known Sid.

    status = RtlCreateAcl( AdminAcl, ACL_LENGTH, ACL_REVISION2 );
    if ( !NT_SUCCESS(status) ) {
        TrPrint((
            "%s!SmbTraceStart: RtlCreateAcl failed: %X\n",
            ID(ComponentName), status ));
        goto errexit;
    }

    status = RtlAddAccessAllowedAce(
             AdminAcl,
             ACL_REVISION2,
             GENERIC_ALL,
             SeExports->SeAliasAdminsSid
             );
    if ( !NT_SUCCESS(status) ) {
        TrPrint((
            "%s!SmbTraceStart: RtlAddAccessAllowedAce failed: %X\n",
            ID(ComponentName), status ));
        goto errexit;
    }

    // Create SecurityDescriptor containing AdminAcl as a discrectionary ACL.

    RtlCreateSecurityDescriptor(
             &securityDescriptor,
             SECURITY_DESCRIPTOR_REVISION1
             );
    if ( !NT_SUCCESS(status) ) {
        TrPrint((
            "%s!SmbTraceStart: RtlCreateSecurityDescriptor failed: %X\n",
            ID(ComponentName), status ));
        goto errexit;
    }

    status = RtlSetDaclSecurityDescriptor(
             &securityDescriptor,
             TRUE,
             AdminAcl,
             FALSE
             );
    if ( !NT_SUCCESS(status) ) {
        TrPrint((
            "%s!SmbTraceStart: "
            "RtlSetDAclAllowedSecurityDescriptor failed: %X\n",
            ID(ComponentName), status ));
        goto errexit;
    }

    //
    // Create the section to be used for communication between the
    // server/redirector and SmbTrace.
    //

    // Define the object name.

    RtlInitUnicodeString( &memoryNameU, ID(SharedMemoryName) );

    // Define the object information, including security descriptor and name.

    InitializeObjectAttributes(
        &objectAttributes,
        &memoryNameU,
        OBJ_CASE_INSENSITIVE,
        NULL,
        &securityDescriptor
        );

    // Setup the section size.

    sectionSize.LowPart = ID(PortMemorySize);
    sectionSize.HighPart = 0L;

    // Create the named section of memory with all of our attributes.

    status = ZwCreateSection(
                &ID(SectionHandle),
                SECTION_MAP_READ | SECTION_MAP_WRITE,
                &objectAttributes,
                &sectionSize,
                PAGE_READWRITE,
                SEC_RESERVE,
                NULL                        // file handle
                );

    if ( !NT_SUCCESS(status) ) {
        TrPrint(( "%s!SmbTraceStart: ZwCreateSection failed: %X\n",
                  ID(ComponentName), status ));
        goto errexit;
    }

    // Now, map it into our address space.

    ID(PortMemoryBase) = NULL;

    status = ZwMapViewOfSection(
                    ID(SectionHandle),
                    NtCurrentProcess(),
                    &ID(PortMemoryBase),
                    0,                        // zero bits (don't care)
                    0,                        // commit size
                    NULL,                     // SectionOffset
                    &ID(PortMemorySize),      // viewSize
                    ViewUnmap,                // inheritDisposition
                    0L,                       // allocation type
                    PAGE_READWRITE            // protection
                    );

    if ( !NT_SUCCESS(status) ) {
        TrPrint(( "%s!SmbTraceStart: NtMapViewOfSection failed: %X\n",
                  ID(ComponentName), status ));
        goto errexit;
    }

    //
    // Set up the shared section memory as a heap.
    //
    // *** Note that the HeapInterlock for the client instance is passed
    //     to the heap manager to be used for serialization of
    //     allocation and deallocation.  It is necessary for the
    //     resource to be allocated FROM NONPAGED POOL externally to the
    //     heap manager, because if we let the heap manager allocate
    //     the resource, if would allocate it from process virtual
    //     memory.
    //

    ID(PortMemoryHeap) = RtlCreateHeap(
                              0,                            // Flags
                              ID(PortMemoryBase),           // HeapBase
                              ID(PortMemorySize),           // ReserveSize
                              PAGE_SIZE,                    // CommitSize
                              ID(HeapInterlock),            // Lock
                              0                             // Reserved
                              );

    //
    // Allocate and initialize the table and its header.
    //

    ID(TableHeader) = RtlAllocateHeap(
                                    ID(PortMemoryHeap), 0,
                                    sizeof( SMBTRACE_TABLE_HEADER )
                                    );

    ID(Table) = RtlAllocateHeap(
                        ID(PortMemoryHeap), 0,
                        sizeof( SMBTRACE_TABLE_ENTRY ) * ID(TableSize)
                        );

    if ( (ID(TableHeader) == NULL) || (ID(Table) == NULL) ) {
        TrPrint((
            "%s!SmbTraceStart: Not enough memory!\n",
            ID(ComponentName) ));

        status = STATUS_NO_MEMORY;

        goto errexit;
    }

    // Initialize the values inside.

    ID(TableHeader)->HighestConsumed = 0;
    ID(TableHeader)->NextFree = 1;
    ID(TableHeader)->ApplicationStop = FALSE;

    for ( i = 0; i < ID(TableSize); i++) {
        ID(Table)[i].BufferOffset = 0L;
        ID(Table)[i].SmbLength = 0L;
    }

    //
    // Create the required event handles.
    //

    // Define the object information.

    RtlInitUnicodeString( &eventNameU, ID(NewSmbEventName) );

    InitializeObjectAttributes(
        &objectAttributes,
        &eventNameU,
        OBJ_CASE_INSENSITIVE,
        NULL,
        &securityDescriptor
        );

    // Open the named object.

    status = ZwCreateEvent(
                &ID(NewSmbEvent),
                EVENT_ALL_ACCESS,
                &objectAttributes,
                NotificationEvent,
                FALSE                        // initial state
                );

    if ( !NT_SUCCESS(status) ) {
        TrPrint(( "%s!SmbTraceStart: ZwCreateEvent (1st) failed: %X\n",
                  ID(ComponentName), status ));

        goto errexit;
    }

    if ( ID(SingleSmbMode) ) {    // this event may not be required.

        // Define the object information.

        RtlInitUnicodeString( &eventNameU, ID(DoneSmbEventName) );

        InitializeObjectAttributes(
            &objectAttributes,
            &eventNameU,
            OBJ_CASE_INSENSITIVE,
            NULL,
            &securityDescriptor
            );

        // Create the named object.

        status = ZwCreateEvent(
                    &ID(DoneSmbEvent),
                    EVENT_ALL_ACCESS,
                    &objectAttributes,
                    NotificationEvent,
                    FALSE                    // initial state
                    );

        if ( !NT_SUCCESS(status) ) {
            TrPrint((
                "%s!SmbTraceStart: NtCreateEvent (2nd) failed: %X\n",
                 ID(ComponentName), status ));
            goto errexit;
        }
        TrPrint(( "%s!SmbTraceStart: DoneSmbEvent handle %x in process %x\n",
                ID(ComponentName), ID(DoneSmbEvent), PsGetCurrentProcess()));

    }

    //
    //  Reset any events that may be in the wrong state from a previous run.
    //

    KeResetEvent(&ID(TerminationEvent));
    KeResetEvent(&ID(TerminatedEvent));

    //
    // Connection was successful, now start the SmbTrace thread.
    //

    //
    // Create the SmbTrace thread and wait for it to finish
    // initializing (at which point SmbTraceActiveEvent is set)
    //

    status = PsCreateSystemThread(
        &threadHandle,
        THREAD_ALL_ACCESS,
        NULL,
        NtCurrentProcess(),
        NULL,
        (PKSTART_ROUTINE) SmbTraceThreadEntry,
        (PVOID)Component
        );

    if ( !NT_SUCCESS(status) ) {

        TrPrint((
            "%s!SmbTraceStart: PsCreateSystemThread failed: %X\n",
            ID(ComponentName), status ));

        goto errexit;
    }

    //
    // Wait until SmbTraceThreadEntry has finished initializing
    //

    (VOID)KeWaitForSingleObject(
            &ID(ActiveEvent),
            UserRequest,
            KernelMode,
            FALSE,
            NULL
            );

    //
    // Close the handle to the process so the object will be
    // destroyed when the thread dies.
    //

    ZwClose( threadHandle );


    //
    // Record who started SmbTrace so we can stop if he dies or otherwise
    // closes this handle to us.
    //

    ID(StartersFileObject) = FileObject;

    //
    // Record caller's process; which is always the appropriate Fsp
    // process.
    //

    ID(FspProcess) = PsGetCurrentProcess();


    //
    // Setup the response packet, since everything worked (write all values).
    //

    ConfigPacketResp->HeaderOffset =
                                ( (ULONG)ID(TableHeader)
                                - (ULONG)ID(PortMemoryBase) );

    ConfigPacketResp->TableOffset =
                                ( (ULONG)ID(Table)
                                - (ULONG)ID(PortMemoryBase) );

    TrPrint(( "%s!SmbTraceStart: SmbTrace started.\n", ID(ComponentName) ));

    ExReleaseResource( ID(StateInterlock) );

    //
    // if someone wanted it shut down while it was starting, shut it down
    //

    switch ( ID(TraceState) ) {

    case TraceStartStopFile :
        SmbTraceStop( ID(StartersFileObject), Component );
        return STATUS_UNSUCCESSFUL;  // app closed, so we should shut down
        break;

    case TraceStartStopNull :
        SmbTraceStop( NULL, Component );
        return STATUS_UNSUCCESSFUL;  // someone requested a shut down
        break;

    default :
        ID(TraceState) = TraceRunning;
        SmbTraceActive[Component] = TRUE;
        return STATUS_SUCCESS;
    }

errexit:

    SmbTraceDisconnect( Component );

    ID(TraceState) = TraceStopped;

    ExReleaseResource( ID(StateInterlock) );

    //
    // return original failure status code, not success of cleanup
    //

    return status;

} // SmbTraceStart

// constant only of interest while constructing the particular Acl
// in SmbTraceStart
#undef ACL_LENGTH


NTSTATUS
SmbTraceStop(
    IN PFILE_OBJECT FileObject OPTIONAL,
    IN SMBTRACE_COMPONENT Component
    )

/*++

Routine Description:

    This routine stops tracing in the server/redirector.  If no
    FileObject is provided, the SmbTrace application is stopped.
    If a FileObject is provided, SmbTrace is stopped if the
    FileObject refers to the one who started it.

Arguments:

    FileObject - FileObject of a process that terminated.  If it's the process
                 that requested SmbTracing, we shut down automatically.

    Component - Context from which we're called: server or redirector

Return Value:

    NTSTATUS - result of operation.  Possible results are:
        STATUS_SUCCESS - SmbTrace was stopped
        STATUS_UNSUCCESSFUL - SmbTrace was not stopped because the
            provided FileObject did not refer to the SmbTrace starter
            or because SmbTrace was not running.

--*/

{
    PAGED_CODE();

    //
    // If we haven't been initialized, there's nothing to stop.  (And no
    // resource to acquire!)
    //

    if ( !ID(InstanceInitialized) ) {
        return STATUS_UNSUCCESSFUL;
    }

    //
    // If it's not the FileObject that started SmbTrace, we don't care.
    // From then on, if ARGUMENT_PRESENT(FileObject) it's the right one.
    //

    if ( ARGUMENT_PRESENT(FileObject) &&
         FileObject != ID(StartersFileObject)
    ) {
       return STATUS_UNSUCCESSFUL;
    }

    ExAcquireResourceExclusive( ID(StateInterlock), TRUE );

    //
    // Depending on the current state of SmbTrace and whether this is
    // a FileObject or unconditional shutdown request, we do different
    // things.  It is always clear at this point, though, that
    // SmbTraceActive should be set to FALSE.
    //

    SmbTraceActive[Component] = FALSE;

    switch ( ID(TraceState) ) {
    case TraceStopped :
    case TraceStopping :
    case TraceStartStopFile :
    case TraceStartStopNull :

        // if we're not running or already in a mode where we know we'll
        // soon be shut down, ignore the request.
        ExReleaseResource( ID(StateInterlock) );
        return STATUS_UNSUCCESSFUL;
        break;

    case TraceStarting :

        // inform starting SmbTrace that it should shut down immediately
        // upon finishing initialization.  It needs to know whether this
        // is a FileObject or unconditional shutdown request.

        ID(TraceState) = ARGUMENT_PRESENT(FileObject)
                       ? TraceStartStopFile
                       : TraceStartStopNull;
        ExReleaseResource( ID(StateInterlock) );
        return STATUS_SUCCESS;
        break;

    case TraceAppWaiting :

        // we're waiting for the application to die already, so ignore
        // new unconditional requests.  But FileObject requests are
        // welcomed.  We cause the SmbTrace thread to kill itself.
        if ( ARGUMENT_PRESENT(FileObject) ) {
            break;  // thread kill code follows switch
        } else {
            ExReleaseResource( ID(StateInterlock) );
            return STATUS_UNSUCCESSFUL;
        }
        break;

    case TraceRunning :

        // if it's a FileObject request, the app is dead, so we cause
        // the SmbTrace thread to kill itself.  Otherwise, we need to
        // signal the app to stop and return.  When the app is gone, we
        // will be called again; this time with a FileObject.

        if ( ARGUMENT_PRESENT(FileObject) ) {
            break;  // thread kill code follows switch
        } else {
            KeSetEvent( &ID(AppTerminationEvent), 2, FALSE );
            ID(TraceState) = TraceAppWaiting;
            ExReleaseResource( ID(StateInterlock) );
            return STATUS_SUCCESS;
        }

        break;

    default :
        ASSERT(!"SmbTraceStop: invalid TraceState");
        break;
    }

    //
    // We reach here from within the switch only in the case where
    // we actually want to kill the SmbTrace thread.  Signal it to
    // wake up, and wait until it terminates.  Signal DoneSmbEvent
    // in case it is currently waiting for the application to signal
    // it in slow mode.
    //

    ID(StartersFileObject) = NULL;

    if ( ID(SingleSmbMode)) {

        BOOLEAN ProcessAttached = FALSE;

        if (PsGetCurrentProcess() != ID(FspProcess)) {
            KeAttachProcess(ID(FspProcess));
            ProcessAttached = TRUE;
        }

        TrPrint(( "%s!SmbTraceStop: Signal DoneSmbEvent, handle %x, process %x.\n",
                    ID(ComponentName), ID(DoneSmbEvent), PsGetCurrentProcess()));
        ZwSetEvent( ID(DoneSmbEvent), NULL );

        if (ProcessAttached) {
            KeDetachProcess();
        }

    }

    TrPrint(( "%s!SmbTraceStop: Signal Termination Event.\n", ID(ComponentName) ));
    ID(TraceState) = TraceStopping;
    KeSetEvent( &ID(TerminationEvent), 2, FALSE );

    ExReleaseResource( ID(StateInterlock) );

    KeWaitForSingleObject(
        &ID(TerminatedEvent),
        UserRequest,
        KernelMode,
        FALSE,
        NULL
        );

    TrPrint(( "%s!SmbTraceStop: Terminated Event is set.\n", ID(ComponentName) ));
    ExAcquireResourceExclusive( ID(StateInterlock), TRUE );

    ID(TraceState) = TraceStopped;

    ExReleaseResource( ID(StateInterlock) );

    TrPrint(( "%s!SmbTraceStop: SmbTrace stopped.\n", ID(ComponentName) ));

    MmUnlockPagableImageSection(SmbTraceDiscardableCodeHandle);

    SmbTraceDiscardableCodeHandle = NULL;

    MmUnlockPagableImageSection(SmbTraceDiscardableDataHandle);

    SmbTraceDiscardableDataHandle = NULL;

    return STATUS_SUCCESS;

} // SmbTraceStop


VOID
SmbTraceCompleteSrv (
    IN PMDL SmbMdl,
    IN PVOID Smb,
    IN CLONG SmbLength
    )

/*++

Routine Description:

    Server version.

    Snapshot an SMB and export it to the SmbTrace application.  How
    this happens is determined by which mode (fast or slow) SmbTracing
    was requested in.  In the server, it is easy to guarantee that when
    tracing, a thread is always executing in the Fsp.

    Fast mode: the SMB is copied into shared memory and an entry for it
    is queued to the server SmbTrace thread, which asynchronously
    passes SMBs to the app.  If there is insufficient memory
    for anything (SMB, queue entry, etc.) the SMB is lost.

    Slow mode: identical to Fast mode except that this thread waits
    until the server SmbTrace thread signals that the app has finished
    processing the SMB.  Because each thread waits until its SMB has
    been completely processed, there is much less chance of running
    out of any resources.

    The SMB is either contained in SmbMdl, or at address Smb with length
    SmbLength.

Arguments:

    SmbMdl - an Mdl containing the SMB.

    Smb - a pointer to the SMB.

    SmbLength - the length of the SMB.

Return Value:

    None

--*/

{
    PSMBTRACE_QUEUE_ENTRY  queueEntry;
    PVOID  buffer;
    SMBTRACE_COMPONENT Component = SMBTRACE_SERVER;
    KEVENT WaitEvent;

    PAGED_CODE();

    //
    // This routine is server specific.
    //

    ASSERT( ID(TraceState) == TraceRunning );
    ASSERT( SmbTraceActive[SMBTRACE_SERVER] );

    //
    // We want either an Mdl, or a pointer and a length, or occasionally,
    // a completely NULL response.
    //

    ASSERT( ( SmbMdl == NULL  &&  Smb != NULL  &&  SmbLength != 0 )
         || ( SmbMdl != NULL  &&  Smb == NULL  &&  SmbLength == 0 )
         || ( SmbMdl == NULL  &&  Smb == NULL  &&  SmbLength == 0 ) );

    //
    // We've taken pains not to be at DPC level and to be in
    // the Fsp context too, for that matter.
    //

    ASSERT( KeGetCurrentIrql() < DISPATCH_LEVEL);
    ASSERT( PsGetCurrentProcess() == ID(FspProcess) );

    //
    // Ensure that SmbTrace really is still active and hence, the
    // shared memory is still around.
    //

    if ( SmbTraceReferenceHeap( Component ) == FALSE ) {
        return;
    }

    //
    // If the SMB is currently in an MDL, we don't yet have the length,
    // which we need, to know how much memory to allocate.
    //

    if ( SmbMdl != NULL ) {
        SmbLength = SmbTraceMdlLength(SmbMdl);
    }

    //
    // If we are in slow mode, then we wait after queuing the SMB
    // to the SmbTrace thread.  If we are set for fast mode we
    // garbage collect in case of no memory.
    //

    if ( ID(SingleSmbMode) ) {
        KeInitializeEvent( &WaitEvent, NotificationEvent, FALSE );
    }

    queueEntry = ExAllocatePoolWithTag( NonPagedPool,
                                        sizeof(SMBTRACE_QUEUE_ENTRY),
                                        'tbmS'
                                        );

    if ( queueEntry == NULL ) {
        // No free memory, this SMB is lost.  Record its loss.
        LOCK_INC_ID(SmbsLost);
        SmbTraceDereferenceHeap( Component );
        return;
    }

    //
    // Allocate the required amount of memory in our heap
    // in the shared memory.
    //

    buffer = RtlAllocateHeap( ID(PortMemoryHeap), 0, SmbLength );

    if ( buffer == NULL ) {
        // No free memory, this SMB is lost.  Record its loss.
        // Very unlikely in slow mode.
        LOCK_INC_ID(SmbsLost);
        ExFreePool( queueEntry );

        if ( !ID(SingleSmbMode) ) {
            //
            // Encourage some garbage collection.
            //
            KeSetEvent( &ID(NeedMemoryEvent), 0, FALSE );
        }

        SmbTraceDereferenceHeap( Component );
        return;
    }

    //
    // Copy the SMB to shared memory pointed to by the queue entry,
    // keeping in mind whether it's in an Mdl or contiguous to begin
    // with, and also preserving the address of the real SMB...
    //

    if ( SmbMdl != NULL ) {
        SmbTraceCopyMdlContiguous( buffer, SmbMdl, SmbLength );
        queueEntry->SmbAddress = SmbMdl;
    } else {
        RtlCopyMemory( buffer, Smb, SmbLength );
        queueEntry->SmbAddress = Smb;
    }

    queueEntry->SmbLength = SmbLength;
    queueEntry->Buffer = buffer;
    queueEntry->BufferNonPaged = FALSE;

    //
    // In slow mode, we want to wait until the SMB has been eaten,
    // in fast mode, we don't want to pass the address of the real
    // SMB along, since the SMB is long gone by the time it gets
    // decoded and printed.
    //

    if ( ID(SingleSmbMode) ) {
        queueEntry->WaitEvent = &WaitEvent;
    } else {
        queueEntry->WaitEvent = NULL;
        queueEntry->SmbAddress = NULL;
    }

    //
    // ...queue the entry to the SmbTrace thread...
    //

    ExInterlockedInsertTailList(
            &ID(Queue),
            &queueEntry->ListEntry,
            &ID(QueueInterlock)
            );

    KeReleaseSemaphore(
            &ID(QueueSemaphore),
            SEMAPHORE_INCREMENT,
            1,
            FALSE
            );

    //
    // ...and wait for the SMB to be eaten, in slow mode.
    //

    if ( ID(SingleSmbMode) ) {
        TrPrint(( "%s!SmbTraceCompleteSrv: Slow mode wait\n", ID(ComponentName) ));
        KeWaitForSingleObject(
            &WaitEvent,
            UserRequest,
            KernelMode,
            FALSE,
            NULL
            );
        TrPrint(( "%s!SmbTraceCompleteSrv: Slow mode wait done\n", ID(ComponentName) ));
    }

    SmbTraceDereferenceHeap( Component );

    return;

} // SmbTraceCompleteSrv


VOID
SmbTraceCompleteRdr (
    IN PMDL SmbMdl,
    IN PVOID Smb,
    IN CLONG SmbLength
    )

/*++

Routine Description:

    Redirector version

    Snapshot an SMB and export it to the SmbTrace application.  How
    this happens is determined by which mode (fast or slow) SmbTracing
    was requested in, and which context (DPC, Fsp or Fsd) the current
    thread is executing in.

    Fast mode: the SMB is copied into shared memory and an entry for it
    is queued to the redirector SmbTrace thread, which asynchronously
    passes SMBs to the app.  (When in DPC, the SMB is copied to non-paged
    pool instead of shared memory, and the SmbTrace thread deals with
    moving it to shared memory later.)  If there is insufficient memory
    for anything (SMB, queue entry, etc.) the SMB is lost.

    Slow mode: identical to Fast mode except that this thread waits
    until the server SmbTrace thread signals that the app has finished
    processing the SMB.  Because each thread waits until its SMB has
    been completely processed, there is much less chance of running
    out of any resources. If at DPC level, we behave exactly as in the
    fast mode case, because it would be a Bad Thing to block this thread
    at DPC level.

    The SMB is either contained in SmbMdl, or at address Smb with length
    SmbLength.

Arguments:

    SmbMdl - an Mdl containing the SMB.

    Smb - a pointer to the SMB.

    SmbLength - the length of the SMB.

Return Value:

    None

--*/

{
    PSMBTRACE_QUEUE_ENTRY  queueEntry;
    PVOID  buffer;
    BOOLEAN ProcessAttached = FALSE;
    BOOLEAN AtDpcLevel;
    SMBTRACE_COMPONENT Component = SMBTRACE_REDIRECTOR;
    KEVENT WaitEvent;

    //
    // This routine is redirector specific.
    //

    ASSERT( ID(TraceState) == TraceRunning );
    ASSERT( SmbTraceActive[SMBTRACE_REDIRECTOR] );

    //
    // We want either an Mdl, or a pointer and a length, or occasionally,
    // a completely NULL response
    //

    ASSERT( ( SmbMdl == NULL  &&  Smb != NULL  &&  SmbLength != 0 )
         || ( SmbMdl != NULL  &&  Smb == NULL  &&  SmbLength == 0 )
         || ( SmbMdl == NULL  &&  Smb == NULL  &&  SmbLength == 0 ) );

    //
    // Ensure that SmbTrace really is still active and hence, the
    // shared memory is still around.
    //

    if ( SmbTraceReferenceHeap( Component ) == FALSE ) {
        return;
    }

    //
    // To avoid multiple system calls, we find out once and for all.
    //

    AtDpcLevel = (BOOLEAN)(KeGetCurrentIrql() >= DISPATCH_LEVEL);

    //
    // If the SMB is currently in an MDL, we don't yet have the length,
    // which we need to know how much memory to allocate.
    //

    if ( SmbMdl != NULL ) {
        SmbLength = SmbTraceMdlLength(SmbMdl);
    }

    //
    // If we are in slow mode, then we wait after queuing the SMB
    // to the SmbTrace thread.  If we are set for fast mode we
    // garbage collect in case of no memory.  If we're at DPC level,
    // we store the SMB in non-paged pool.
    //

    if ( ID(SingleSmbMode) ) {
        KeInitializeEvent( &WaitEvent, NotificationEvent, FALSE );
    }

    //
    // allocate queue entry
    //

    queueEntry = ExAllocatePoolWithTag(
                     NonPagedPool,
                     sizeof(SMBTRACE_QUEUE_ENTRY),
                     'tbmS'
                     );

    if ( queueEntry == NULL ) {
        // No free memory, this SMB is lost.  Record its loss.
        LOCK_INC_ID(SmbsLost);
        SmbTraceDereferenceHeap( Component );
        return;
    }

    //
    // allocate buffer for SMB, in non-paged pool or shared heap as
    // appropriate
    //

    if ( AtDpcLevel ) {

        buffer = ExAllocatePoolWithTag( NonPagedPool, SmbLength, 'tbmS' );
        queueEntry->BufferNonPaged = TRUE;

    } else {

        if ( PsGetCurrentProcess() != ID(FspProcess) ) {
            KeAttachProcess(ID(FspProcess));
            ProcessAttached = TRUE;
        }

        buffer = RtlAllocateHeap( ID(PortMemoryHeap), 0, SmbLength );
        queueEntry->BufferNonPaged = FALSE;

    }

    if ( buffer == NULL ) {

        if ( ProcessAttached ) {
            KeDetachProcess();
        }

        // No free memory, this SMB is lost.  Record its loss.
        LOCK_INC_ID(SmbsLost);

        if (!ID(SingleSmbMode)) {

            //
            // If it was shared memory we ran out of, encourage
            // some garbage collection.
            //
            if ( !queueEntry->BufferNonPaged ) {
                KeSetEvent( &ID(NeedMemoryEvent), 0, FALSE );
            }
        }

        ExFreePool( queueEntry );
        SmbTraceDereferenceHeap( Component );
        return;
    }

    //
    // Copy the SMB to shared or non-paged memory pointed to by the
    // queue entry, keeping in mind whether it's in an Mdl or contiguous
    // to begin with, and also preserving the address of the real SMB...
    //

    if ( SmbMdl != NULL ) {
        SmbTraceCopyMdlContiguous( buffer, SmbMdl, SmbLength );
        queueEntry->SmbAddress = SmbMdl;
    } else {
        RtlCopyMemory( buffer, Smb, SmbLength );
        queueEntry->SmbAddress = Smb;
    }

    if ( ProcessAttached ) {
        KeDetachProcess();
    }

    queueEntry->SmbLength = SmbLength;
    queueEntry->Buffer = buffer;

    //
    // In slow mode, we want to wait until the SMB has been eaten,
    // in fast mode, we don't want to pass the address of the real
    // SMB along, since the SMB is long gone by the time it gets
    // decoded and printed.
    //

    if ( ID(SingleSmbMode) && !AtDpcLevel ) {
        queueEntry->WaitEvent = &WaitEvent;
    } else {
        queueEntry->WaitEvent = NULL;
        queueEntry->SmbAddress = NULL;
    }

    //
    // ...queue the entry to the SmbTrace thread...
    //

    ExInterlockedInsertTailList(
            &ID(Queue),
            &queueEntry->ListEntry,
            &ID(QueueInterlock)
            );

    KeReleaseSemaphore(
            &ID(QueueSemaphore),
            SEMAPHORE_INCREMENT,
            1,
            FALSE
            );

    //
    // ...and wait for the SMB to be eaten, in slow mode.
    //

    if ( ID(SingleSmbMode) && !AtDpcLevel ) {
        TrPrint(( "%s!SmbTraceCompleteRdr: Slow mode wait\n", ID(ComponentName) ));
        KeWaitForSingleObject(
            &WaitEvent,
            UserRequest,
            KernelMode,
            FALSE,
            NULL
            );
        TrPrint(( "%s!SmbTraceCompleteRdr: Slow mode wait done\n", ID(ComponentName) ));
    }

    SmbTraceDereferenceHeap( Component );

    return;

} // SmbTraceCompleteRdr


//
// Internal routines
//


BOOLEAN
SmbTraceReferenceHeap(
    IN SMBTRACE_COMPONENT Component
    )

/*++

Routine Description:

    This routine references the SmbTrace shared memory heap,
    ensuring it isn't disposed of while caller is using it.

Arguments:

    Component - Context from which we're called: server or redirector

Return Value:

    BOOLEAN - TRUE if SmbTrace is still active, and hence
              heap exists and was successfully referenced.
              FALSE otherwise.

--*/

{
    BOOLEAN retval = TRUE;  // assume we'll get it
    KIRQL OldIrql;

    ACQUIRE_SPIN_LOCK( &ID(HeapReferenceCountLock), &OldIrql );

    if ( ID(TraceState) != TraceRunning ) {
        retval = FALSE;
    } else {
        ASSERT( ID(HeapReferenceCount) > 0 );
        ID(HeapReferenceCount)++;
        TrPrint(( "%s!SmbTraceReferenceHeap: Count now %lx\n",
            ID(ComponentName),
            ID(HeapReferenceCount) ));
    }

    RELEASE_SPIN_LOCK( &ID(HeapReferenceCountLock), OldIrql );

    return retval;

} // SmbTraceReferenceHeap

typedef struct _TRACE_DEREFERENCE_ITEM {
    WORK_QUEUE_ITEM WorkItem;
    SMBTRACE_COMPONENT Component;
} TRACE_DEREFERENCE_ITEM, *PTRACE_DEREFERENCE_ITEM;

VOID
SmbTraceDeferredDereferenceHeap(
    IN PVOID Context
    )
/*++

Routine Description:

    If a caller dereferences a heap to 0 from DPC_LEVEL, this routine will
    be called in a system thread to complete the dereference at task time.

Arguments:

    Component - Context from which we're called: server or redirector

Return Value:

    None

--*/

{
    PTRACE_DEREFERENCE_ITEM WorkItem = Context;
    SMBTRACE_COMPONENT Component = WorkItem->Component;

    PAGED_CODE();

    ExFreePool(WorkItem);

    SmbTraceDereferenceHeap(Component);

}


VOID
SmbTraceDereferenceHeap(
    IN SMBTRACE_COMPONENT Component
    )

/*++

Routine Description:

    This routine dereferences the SmbTrace shared memory heap,
    disposing of it when the reference count is zero.

Arguments:

    Component - Context from which we're called: server or redirector

Return Value:

    None

--*/

{
    ULONG oldCount;
    KIRQL OldIrql;

    ACQUIRE_SPIN_LOCK( &ID(HeapReferenceCountLock), &OldIrql );

    if (ID(HeapReferenceCount) > 1) {
        ID(HeapReferenceCount) --;

        TrPrint(( "%s!SmbTraceDereferenceHeap: Count now %lx\n",
            ID(ComponentName),
            ID(HeapReferenceCount) ));

        RELEASE_SPIN_LOCK( &ID(HeapReferenceCountLock), OldIrql );

        return;
    }

    RELEASE_SPIN_LOCK( &ID(HeapReferenceCountLock), OldIrql );

    //
    //  If we are executing at DPC_LEVEL, we cannot dereference the heap
    //  to 0.
    //

    if (KeGetCurrentIrql() >= DISPATCH_LEVEL) {
        PTRACE_DEREFERENCE_ITEM WorkItem;

        WorkItem = ExAllocatePoolWithTag(NonPagedPoolMustSucceed, sizeof(TRACE_DEREFERENCE_ITEM), 'tbmS');

        ExInitializeWorkItem(&WorkItem->WorkItem, SmbTraceDeferredDereferenceHeap, WorkItem);
        WorkItem->Component = Component;

        ExQueueWorkItem(&WorkItem->WorkItem, DelayedWorkQueue);

        return;

    }

    ACQUIRE_SPIN_LOCK( &ID(HeapReferenceCountLock), &OldIrql );

    oldCount = ID(HeapReferenceCount)--;

    TrPrint(( "%s!SmbTraceDereferenceHeap: Count now %lx\n",
        ID(ComponentName),
        ID(HeapReferenceCount) ));

    RELEASE_SPIN_LOCK( &ID(HeapReferenceCountLock), OldIrql );

    if ( oldCount == 1 ) {

        //
        // Free the section, release the handles and such.
        //

        SmbTraceDisconnect( Component );
    }

    return;

} // SmbTraceDereferenceHeap


VOID
SmbTraceDisconnect (
    IN SMBTRACE_COMPONENT Component
    )

/*++

Routine Description:

    This routine reverses all the effects of SmbTraceStart. Mostly,
    it just needs to close certain handles to do this.

Arguments:

    Component - Context from which we're called: server or redirector

Return Value:

    None - always works

--*/

{
    BOOLEAN ProcessAttached = FALSE;

    PAGED_CODE();

    if (PsGetCurrentProcess() != ID(FspProcess)) {
        KeAttachProcess(ID(FspProcess));
        ProcessAttached = TRUE;

    }


    if ( ID(DoneSmbEvent) != NULL ) {
        // Worker thread may be blocked on this, so we set it first
        TrPrint(( "%s!SmbTraceDisconnect: Signal DoneSmbEvent, handle %x, process %x.\n",
                    ID(ComponentName), ID(DoneSmbEvent), PsGetCurrentProcess()));
        ZwSetEvent( ID(DoneSmbEvent), NULL );

        TrPrint(( "%s!SmbTraceDisconnect: Close DoneSmbEvent, handle %x, process %x.\n",
                    ID(ComponentName), ID(DoneSmbEvent), PsGetCurrentProcess()));
        ZwClose( ID(DoneSmbEvent) );
        ID(DoneSmbEvent) = NULL;
    }

    if ( ID(NewSmbEvent) != NULL ) {
        ZwClose( ID(NewSmbEvent) );
        ID(NewSmbEvent) = NULL;
    }

    if ( ID(PortMemoryHeap) != NULL ) {
        RtlDestroyHeap( ID(PortMemoryHeap) );
        ID(PortMemoryHeap) = NULL;
    }

    if ( ID(SectionHandle) != NULL ) {
        ZwClose( ID(SectionHandle) );
        ID(SectionHandle) = NULL;
    }

    if (ProcessAttached) {
        KeDetachProcess();
    }

    return;

} // SmbTraceDisconnect


VOID
SmbTraceEmptyQueue (
    IN SMBTRACE_COMPONENT Component
    )

/*++

Routine Description:

    This routine empties the queue of unprocessed SMBs.

Arguments:

    Component - Context from which we're called: server or redirector

Return Value:

    None - always works

--*/

{
    PLIST_ENTRY            listEntry;
    PSMBTRACE_QUEUE_ENTRY  queueEntry;

    PAGED_CODE();

    while ( ( listEntry = ExInterlockedRemoveHeadList(
                              &ID(Queue),
                              &ID(QueueInterlock)
                              )
            ) != NULL
    ) {
        queueEntry = CONTAINING_RECORD(
                          listEntry,
                          SMBTRACE_QUEUE_ENTRY,
                          ListEntry
                          );

        //
        // If data for this entry is in non-paged pool, free it too.
        // This only ever happens in the redirector.
        //

        if ( queueEntry->BufferNonPaged ) {

            ASSERT( Component == SMBTRACE_REDIRECTOR );

            ExFreePool( queueEntry->Buffer );
        }

        //
        // If a worker thread is waiting on this event, let it go.
        // This only ever happens in slow mode.
        //

        if ( queueEntry->WaitEvent != NULL ) {

            ASSERT( ID(SingleSmbMode) == TRUE );

            KeSetEvent( queueEntry->WaitEvent, 0, FALSE );
        }

        ExFreePool( queueEntry );
    }

    return;

} // SmbTraceEmptyQueue


VOID
SmbTraceThreadEntry (
    IN PVOID Context
    )

/*++

Routine Description:

    This routine is the entry point of the SmbTrace thread for the server/
    redirector.  It is started by SmbTraceStart. This thread loops
    continuously until the client SmbTrace dies or another SmbTrace sends
    an FsCtl to stop the trace.

Arguments:

    Context - pointer to context block containing component from which
              we're called: server or redirector

Return Value:

    None

--*/

// we wait for termination, work-to-do and need-memory events
#define NUMBER_OF_BLOCKING_OBJECTS 4

// keep these definitions in sync

#define INDEX_WAIT_TERMINATIONEVENT     0
#define INDEX_WAIT_APPTERMINATIONEVENT  1
#define INDEX_WAIT_NEEDMEMORYEVENT      2
#define INDEX_WAIT_QUEUESEMAPHORE       3

#define STATUS_WAIT_TERMINATIONEVENT    STATUS_WAIT_0
#define STATUS_WAIT_APPTERMINATIONEVENT STATUS_WAIT_1
#define STATUS_WAIT_NEEDMEMORYEVENT     STATUS_WAIT_2
#define STATUS_WAIT_QUEUESEMAPHORE      STATUS_WAIT_3

{
    NTSTATUS status;
    PLIST_ENTRY listEntry;
    PSMBTRACE_QUEUE_ENTRY    queueEntry;
    PVOID buffer;
    PVOID waitObjects[NUMBER_OF_BLOCKING_OBJECTS];
    SMBTRACE_COMPONENT Component;
    BOOLEAN Looping;

#if NUMBER_OF_BLOCKING_OBJECTS > THREAD_WAIT_OBJECTS
    //
    // If we try to wait on too many objects, we need to allocate
    // our own wait blocks.
    //

    KWAIT_BLOCK waitBlocks[NUMBER_OF_BLOCKING_OBJECTS];
#endif

    PAGED_CODE();

    //
    // Context is really just the component
    //
    Component = (SMBTRACE_COMPONENT)Context;

    //
    // Initialize the queue.
    //

    InitializeListHead(    &ID(Queue) );
    KeInitializeSpinLock(  &ID(QueueInterlock) );
    KeInitializeSemaphore( &ID(QueueSemaphore), 0, 0x7FFFFFFF );

    //
    // Set up the array of objects to wait on.  We wait (in order)
    // for our termination event, the appliction termination event,
    // a no shared memory event or an SMB request to show up in the
    // SmbTrace queue.
    //

    waitObjects[INDEX_WAIT_TERMINATIONEVENT]    = &ID(TerminationEvent);
    waitObjects[INDEX_WAIT_APPTERMINATIONEVENT] = &ID(AppTerminationEvent);
    waitObjects[INDEX_WAIT_NEEDMEMORYEVENT]     = &ID(NeedMemoryEvent);
    waitObjects[INDEX_WAIT_QUEUESEMAPHORE]      = &ID(QueueSemaphore);

    //
    // No SMBs have been lost yet, and this thread is the first user
    // of the shared memory.  It's also a special user in that it gets
    // access before TraceState == TraceRunning, a requirement for all
    // subsequent referencers.
    //

    ID(SmbsLost) = 0L;
    ID(HeapReferenceCount) = 1;

    //
    // Signal to the FSP that we are ready to start capturing SMBs.
    //

    KeSetEvent( &ID(ActiveEvent), 0, FALSE );

    //
    // Main loop, executed until the thread is terminated.
    //

    TrPrint(( "%s!SmbTraceThread: Tracing started.\n", ID(ComponentName) ));

    Looping = TRUE;
    while( Looping ) {

        TrPrint(( "%s!SmbTraceThread: WaitForMultiple.\n", ID(ComponentName) ));
        status = KeWaitForMultipleObjects(
                    NUMBER_OF_BLOCKING_OBJECTS,
                    &waitObjects[0],
                    WaitAny,
                    UserRequest,
                    KernelMode,
                    FALSE,
                    NULL,
#if NUMBER_OF_BLOCKING_OBJECTS > THREAD_WAIT_OBJECTS
                    &waitBlocks[0]
#else
                    NULL
#endif
                    );

        if ( !NT_SUCCESS(status) ) {
            TrPrint((
                "%s!SmbTraceThreadEntry: KeWaitForMultipleObjectsfailed: %X\n",
                ID(ComponentName), status ));
        } else {
            TrPrint((
                "%s!SmbTraceThreadEntry: %lx\n",
                ID(ComponentName), status ));
        }

        switch( status ) {

        case STATUS_WAIT_TERMINATIONEVENT:

            //
            // Stop looping, and then proceed to clean up and die.
            //

            Looping = FALSE;
            break;

        case STATUS_WAIT_APPTERMINATIONEVENT:

            //  Turn off the event so we don't go in a tight loop
            KeResetEvent(&ID(AppTerminationEvent));

            //
            // Inform the app that it is time to die.  The NULL SMB
            // sent here may not be the next to be processed by the
            // app, but the ApplicationStop bit will be detected
            // immediately.
            //

            ID(TableHeader)->ApplicationStop = TRUE;
            SmbTraceToClient( NULL, 0, NULL, Component );

            break;

        case STATUS_WAIT_NEEDMEMORYEVENT:

            //  Turn off the event so we don't go in a loop.
            KeResetEvent(&ID(NeedMemoryEvent));
            //
            // Do a garbage collection, freeing all memory that is
            // allocated in the shared memory but that has been read
            // by the client.
            //

            SmbTraceFreeMemory( Component );

            break;

        case STATUS_WAIT_QUEUESEMAPHORE:

            //
            // If any get through once we've gone into AppWaiting
            // state, don't bother sending them on, they're not
            // going to get processed.
            //

            if ( ID(TraceState) == TraceAppWaiting ) {
                SmbTraceEmptyQueue( Component );
                break;
            }

            //
            // Remove the first element in the our queue.  A
            // work item is represented by our header followed by
            // an SMB. We must free the entry after we are done
            // with it.
            //

            listEntry = ExInterlockedRemoveHeadList(
                            &ID(Queue),
                            &ID(QueueInterlock)
                            );

            if ( listEntry != NULL ) {

                //
                // Get the address of the queue entry.
                //

                queueEntry = CONTAINING_RECORD(
                                  listEntry,
                                  SMBTRACE_QUEUE_ENTRY,
                                  ListEntry
                                  );

                //
                // If the data is in non-paged pool, move it to shared
                // memory and free the non-paged pool before passing
                // the SMB to the client.  Note that in this case,
                // there's no need to signal anyone.  They ain't waiting.
                //

                if ( queueEntry->BufferNonPaged ) {

                    //
                    // Server never uses non-paged pool.
                    //

                    ASSERT( Component != SMBTRACE_SERVER );

                    buffer = RtlAllocateHeap( ID(PortMemoryHeap), 0,
                                              queueEntry->SmbLength );

                    if ( buffer == NULL ) {

                        LOCK_INC_ID(SmbsLost);

                        ExFreePool( queueEntry->Buffer );
                        ExFreePool( queueEntry );

                        break;

                    }

                    RtlCopyMemory( buffer, queueEntry->Buffer,
                                   queueEntry->SmbLength );

                    ExFreePool( queueEntry->Buffer );

                    //
                    // Send it off.  Because the original SMB is long
                    // dead, we don't pass its real address along (not
                    // that we have it, anyway.)
                    //

                    ASSERT( queueEntry->SmbAddress == NULL );

                    SmbTraceToClient(
                            buffer,
                            queueEntry->SmbLength,
                            NULL,
                            Component
                            );

                } else {

                    //
                    // Enter the SMB into the table and send it to the
                    // client. Can block in slow mode.  When it does so, we'll
                    // signal the applicable thread.
                    //

                    SmbTraceToClient(
                            queueEntry->Buffer,
                            queueEntry->SmbLength,
                            queueEntry->SmbAddress,
                            Component
                            );

                    if ( queueEntry->WaitEvent != NULL ) {
                        KeSetEvent( queueEntry->WaitEvent, 0, FALSE );
                    }
                }

                //
                // Now, we must free the queue entry.
                //

                ExFreePool( queueEntry );

            }

            break;

        default:
            break;
        }

    }

    //
    // Clean up!
    //
    TrPrint(( "%s!SmbTraceThread: Tracing clean up.\n", ID(ComponentName) ));

    SmbTraceDereferenceHeap( Component );

    SmbTraceEmptyQueue( Component );

    //
    // Signal to SmbTraceStop that we're dying.
    //

    TrPrint(( "%s!SmbTraceThread: Tracing terminated.\n", ID(ComponentName) ));

    KeSetEvent( &ID(TerminatedEvent), 0, FALSE );

    //
    // Kill this thread.
    //

    status = PsTerminateSystemThread( STATUS_SUCCESS );

    // Shouldn't get here
    TrPrint((
        "%s!SmbTraceThreadEntry: PsTerminateSystemThread() failed: %X\n",
        ID(ComponentName), status ));

} // SmbTraceThreadEntry

// constant only of interest while constructing waitObject arrays
// in SmbTraceThreadEntry
#undef NUMBER_OF_BLOCKING_OBJECTS


NTSTATUS
SmbTraceFreeMemory (
    IN SMBTRACE_COMPONENT Component
    )

/*++

Routine Description:

    This procedure frees any memory that may have been allocated to an
    SMB that the client has already consumed. It does not alter table
    entries, except to record that the memory buffer has been cleared.
    This routinue is not espectally fast, it should not be called often,
    only when needed.

Arguments:

    Component - Context from which we're called: server or redirector

Return Value:

    NTSTATUS - result of operation.

--*/

{
    PVOID    buffer;
    PSMBTRACE_TABLE_ENTRY    tableEntry;
    ULONG    tableIndex;

    PAGED_CODE();

    TrPrint(( "%s!SmbTraceFreeMemory: Called for garbage collection.\n",
              ID(ComponentName) ));

    //
    // No free memory in the heap, perhaps we can free some by freeing
    // memory in old table entries. This is expensive for time.
    //

    tableIndex = ID(TableHeader)->NextFree;

    while( tableIndex != ID(TableHeader)->HighestConsumed ) {

        tableEntry = ID(Table) + tableIndex;

        //
        // Check if this table entry has been used but its memory has not
        // been freed yet. If so, free it.
        //

        if ( tableEntry->BufferOffset != 0L ) {

            buffer = (PVOID)( (ULONG)tableEntry->BufferOffset
                        + (ULONG)ID(PortMemoryBase) );

            RtlFreeHeap( ID(PortMemoryHeap), 0, buffer);

            tableEntry->BufferOffset = 0L;
        }


        tableIndex = (tableIndex + 1) % ID(TableSize);
    }

    return( STATUS_SUCCESS );

} // SmbTraceFreeMemory


VOID
SmbTraceToClient(
    IN PVOID Smb,
    IN CLONG SmbLength,
    IN PVOID SmbAddress,
    IN SMBTRACE_COMPONENT Component
    )

/*++

Routine Description:

    Enter an SMB already found in shared memory into the table.  Set
    an event for the client.  If there is no table space, the SMB is
    not saved.  If in slow mode, wait for the client to finish with
    and then free the memory occupied by the SMB.

Arguments:

    Smb - a pointer to the SMB (which is ALREADY in shared memory).
          Can be NULL, indicating no new SMB is to be added, but the
          application is to be signalled anyway.

    SmbLength - the length of the SMB.

    SmbAddress - the address of the real SMB, not in shared memory.

    Component - Context from which we're called: server or redirector

Return Value:

    None

--*/

{
    NTSTATUS status;
    PVOID    buffer;
    PSMBTRACE_TABLE_ENTRY    tableEntry;
    ULONG    tableIndex;

    PAGED_CODE();

    //
    //  Reset DoneSmbEvent so we can determine when the request has been processed
    //

    if ( ID(SingleSmbMode) ) {
        PKEVENT DoneEvent;

        TrPrint(( "%s!SmbTraceToClient: Reset DoneSmbEvent, handle %x, process %x.\n",
                    ID(ComponentName), ID(DoneSmbEvent), PsGetCurrentProcess()));

        status = ObReferenceObjectByHandle( ID(DoneSmbEvent),
                                            EVENT_MODIFY_STATE,
                                            NULL,
                                            KernelMode,
                                            (PVOID *)&DoneEvent,
                                            NULL
                                            );

        ASSERT ( NT_SUCCESS(status) );

        KeResetEvent(DoneEvent);

        ObDereferenceObject(DoneEvent);
    }

    if (Smb != NULL) {

        //
        // See if there is room in the table for a pointer to our SMB.
        //

        if ( ID(TableHeader)->NextFree == ID(TableHeader)->HighestConsumed ) {
            // Tough luck. No memory in the table, this SMB is lost.
            LOCK_INC_ID( SmbsLost );
            RtlFreeHeap( ID(PortMemoryHeap), 0, Smb );
            return;
        }

        tableIndex = ID(TableHeader)->NextFree;

        tableEntry = ID(Table) + tableIndex;

        //
        // Record the number of SMBs that were lost before this one and
        // (maybe) zero the count for the next one.
        //

        tableEntry->NumberMissed = ID(SmbsLost);

        if ( tableEntry->NumberMissed != 0 ) {
            LOCK_ZERO_ID(SmbsLost);
        }

        //
        // Check if this table entry has been used but its memory has not
        // been freed yet. If so, free it.
        //
        if ( tableEntry->BufferOffset != 0L ) {

            buffer = (PVOID)( (ULONG)tableEntry->BufferOffset
                        + (ULONG)ID(PortMemoryBase) );

            RtlFreeHeap( ID(PortMemoryHeap), 0, buffer);
            tableEntry->BufferOffset = 0L;
        }

        //
        // Record the location and size of this SMB in the table.
        //

        tableEntry->BufferOffset = (ULONG)Smb - (ULONG)ID(PortMemoryBase);
        tableEntry->SmbLength = SmbLength;

        //
        // Record the real address of the actual SMB (i.e. not the shared
        // memory copy) if it's available.
        //

        tableEntry->SmbAddress = SmbAddress;

        //
        // Increment the Next Free counter.
        //

        ID(TableHeader)->NextFree = (tableIndex + 1) % ID(TableSize);

    }


    //
    // Unlock the client so it will process this new SMB.
    //

    TrPrint(( "%s!SmbTraceToClient: Set NewSmbEvent.\n", ID(ComponentName) ));
    status = ZwSetEvent( ID(NewSmbEvent), NULL );

    //
    //  When stopping the trace we set TraceState to TraceStopping and then
    //  DoneSmbEvent. This prevents this routine from blocking indefinitely
    //  because it Resets DoneSmbEvent processes the Smb and then checks TraceState
    //  before blocking.
    //
    if (( ID(SingleSmbMode) ) &&
        ( ID(TraceState) == TraceRunning )) {

        //
        // Wait for the app to acknowledge that the SMB has been
        // processed.
        //

        TrPrint(( "%s!SmbTraceToClient: Waiting for DoneSmbEvent, handle %x, process %x.\n",
                    ID(ComponentName), ID(DoneSmbEvent), PsGetCurrentProcess()));
        status = ZwWaitForSingleObject(
                    ID(DoneSmbEvent),
                    FALSE,
                    NULL
                    );

        TrPrint(( "%s!SmbTraceToClient: DoneSmbEvent is set, handle %x, process %x.\n",
                    ID(ComponentName), ID(DoneSmbEvent), PsGetCurrentProcess()));
        ASSERT( NT_SUCCESS(status) );

        if (Smb != NULL) {

            tableEntry->BufferOffset = 0L;
            RtlFreeHeap( ID(PortMemoryHeap), 0, Smb);
        }

    }

    return;

} // SmbTraceToClient


ULONG
SmbTraceMdlLength(
    IN PMDL Mdl
    )

/*++

Routine Description:

    Determine the total number of bytes of data found in an Mdl.

Arguments:

    Mdl - a pointer to an Mdl whose length is to be calculated

Return Value:

    ULONG - total number of data bytes in Mdl

--*/

{
    ULONG Bytes = 0;

    while (Mdl != NULL) {
        Bytes += MmGetMdlByteCount(Mdl);
        Mdl = Mdl->Next;
    }

    return Bytes;
} // SmbTraceMdlLength


VOID
SmbTraceCopyMdlContiguous(
    OUT PVOID Destination,
    IN  PMDL Mdl,
    IN  ULONG Length
    )

/*++

Routine Description:

    Copy the data stored in Mdl into the contiguous memory at
    Destination.  Length is present to keep the same interface
    as RtlCopyMemory.

Arguments:

    Destination - a pointer to previously allocated memory into which
                  the Mdl is to be copied.

    Mdl - a pointer to an Mdl which is to be copied to Destination

    Length - number of data bytes expected in Mdl

Return Value:

    None

--*/

{
    PCHAR Dest = Destination;

    UNREFERENCED_PARAMETER(Length);

    while (Mdl != NULL) {

        RtlCopyMemory(
            Dest,
            MmGetSystemAddressForMdl(Mdl),
            MmGetMdlByteCount(Mdl)
            );

        Dest += MmGetMdlByteCount(Mdl);
        Mdl = Mdl->Next;
    }

    ASSERT((ULONG)(Dest - (PCHAR)Destination) == Length);

    return;

} // SmbTraceCopyMdlContiguous