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

Copyright (c) 1999 - 2002  Microsoft Corporation

Module Name:

    cancelSafe.c

Abstract:

    This is the main module of the cancelSafe miniFilter driver.

Environment:

    Kernel mode

--*/

#include <fltKernel.h>
#include <dontuse.h>
#include <suppress.h>


//
//  Debug flags and helper functions
//

#define CSQ_TRACE_ERROR                     0x00000001
#define CSQ_TRACE_LOAD_UNLOAD               0x00000002
#define CSQ_TRACE_INSTANCE_CALLBACK         0x00000004
#define CSQ_TRACE_CONTEXT_CALLBACK          0x00000008
#define CSQ_TRACE_CBDQ_CALLBACK             0x00000010
#define CSQ_TRACE_PRE_READ                  0x00000020
#define CSQ_TRACE_ALL                       0xFFFFFFFF

#define DebugTrace(Level, Data)               \
    if ((Level) & Globals.DebugLevel) {       \
        DbgPrint Data;                        \
    }

//
//  Memory Pool Tags
//

#define INSTANCE_CONTEXT_TAG              'IqsC'
#define QUEUE_CONTEXT_TAG                 'QqsC'
#define CSQ_REG_TAG                       'RqsC'
#define CSQ_STRING_TAG                    'SqsC'

//
// Registry value names and default values
//

#define CSQ_DEFAULT_TIME_DELAY            150000000
#define CSQ_DEFAULT_MAPPING_PATH          L"\\"
#define CSQ_KEY_NAME_DELAY                L"OperatingDelay"
#define CSQ_KEY_NAME_PATH                 L"OperatingPath"
#define CSQ_KEY_NAME_DEBUG_LEVEL          L"DebugLevel"
#define CSQ_MAX_PATH_LENGTH               256


//
//  Prototypes
//

//
//  Queue context data structure
//

typedef struct _QUEUE_CONTEXT {

    FLT_CALLBACK_DATA_QUEUE_IO_CONTEXT CbdqIoContext;

} QUEUE_CONTEXT, *PQUEUE_CONTEXT;

//
//  Instance context data structure
//

typedef struct _INSTANCE_CONTEXT {

    //
    //  Instance for this context.
    //

    PFLT_INSTANCE Instance;

    //
    //  Cancel safe queue members
    //

    FLT_CALLBACK_DATA_QUEUE Cbdq;
    LIST_ENTRY QueueHead;
    FAST_MUTEX Lock;

    //
    //  Flag to control the life/death of the work item thread
    //

    volatile LONG WorkerThreadFlag;

    //
    //  Notify the worker thread that the instance is being torndown
    //

    KEVENT TeardownEvent;

} INSTANCE_CONTEXT, *PINSTANCE_CONTEXT;


typedef struct _CSQ_GLOBAL_DATA {

    ULONG  DebugLevel;

    PFLT_FILTER  FilterHandle;

    NPAGED_LOOKASIDE_LIST QueueContextLookaside;

    UNICODE_STRING MappingPath;

    PWSTR PathBuffer;

    LONGLONG TimeDelay;

} CSQ_GLOBAL_DATA;



//
//  Global variables
//

CSQ_GLOBAL_DATA Globals;


//
//  Local function prototypes
//

DRIVER_INITIALIZE DriverEntry;
NTSTATUS
DriverEntry (
    _In_ PDRIVER_OBJECT DriverObject,
    _In_ PUNICODE_STRING RegistryPath
    );

VOID
FreeGlobals(
    );

NTSTATUS
Unload (
    _In_ FLT_FILTER_UNLOAD_FLAGS Flags
    );

VOID
ContextCleanup (
    _In_ PFLT_CONTEXT Context,
    _In_ FLT_CONTEXT_TYPE ContextType
    );

NTSTATUS
InstanceSetup (
    _In_ PCFLT_RELATED_OBJECTS FltObjects,
    _In_ FLT_INSTANCE_SETUP_FLAGS Flags,
    _In_ DEVICE_TYPE VolumeDeviceType,
    _In_ FLT_FILESYSTEM_TYPE VolumeFilesystemType
    );

NTSTATUS
InstanceQueryTeardown (
    _In_ PCFLT_RELATED_OBJECTS FltObjects,
    _In_ FLT_INSTANCE_QUERY_TEARDOWN_FLAGS Flags
    );

VOID
InstanceTeardownStart (
    _In_ PCFLT_RELATED_OBJECTS FltObjects,
    _In_ FLT_INSTANCE_TEARDOWN_FLAGS Flags
    );

VOID
InstanceTeardownComplete (
    _In_ PCFLT_RELATED_OBJECTS FltObjects,
    _In_ FLT_INSTANCE_TEARDOWN_FLAGS Flags
    );

typedef
NTSTATUS
(*PFN_IoOpenDriverRegistryKey) (
    PDRIVER_OBJECT     DriverObject,
    DRIVER_REGKEY_TYPE RegKeyType,
    ACCESS_MASK        DesiredAccess,
    ULONG              Flags,
    PHANDLE            DriverRegKey
    );

PFN_IoOpenDriverRegistryKey
GetIoOpenDriverRegistryKey (
    VOID
    );

NTSTATUS
OpenServiceParametersKey (
    _In_ PDRIVER_OBJECT DriverObject,
    _In_ PUNICODE_STRING ServiceRegistryPath,
    _Out_ PHANDLE ServiceParametersKey
    );

NTSTATUS
SetConfiguration (
    _In_ PDRIVER_OBJECT DriverObject,
    _In_ PUNICODE_STRING RegistryPath
    );

VOID
_IRQL_requires_max_(APC_LEVEL)
_IRQL_raises_(APC_LEVEL)
_Requires_lock_not_held_((CONTAINING_RECORD( DataQueue, INSTANCE_CONTEXT, Cbdq ))->Lock)
_Acquires_lock_((CONTAINING_RECORD( DataQueue, INSTANCE_CONTEXT, Cbdq ))->Lock)
CsqAcquire(
    _In_ PFLT_CALLBACK_DATA_QUEUE DataQueue,
    _Out_ PKIRQL Irql
    );

VOID
_IRQL_requires_max_(APC_LEVEL)
_IRQL_requires_min_(APC_LEVEL)
_IRQL_raises_(PASSIVE_LEVEL)
_Requires_lock_held_((CONTAINING_RECORD( DataQueue, INSTANCE_CONTEXT, Cbdq ))->Lock)
_Releases_lock_((CONTAINING_RECORD( DataQueue, INSTANCE_CONTEXT, Cbdq ))->Lock)
CsqRelease(
    _In_ PFLT_CALLBACK_DATA_QUEUE DataQueue,
    _In_ KIRQL Irql
    );

NTSTATUS
CsqInsertIo(
    _In_ PFLT_CALLBACK_DATA_QUEUE DataQueue,
    _In_ PFLT_CALLBACK_DATA Data,
    _In_opt_ PVOID Context
    );
VOID
CsqRemoveIo(
    _In_ PFLT_CALLBACK_DATA_QUEUE DataQueue,
    _In_ PFLT_CALLBACK_DATA Data
    );
PFLT_CALLBACK_DATA
CsqPeekNextIo(
    _In_ PFLT_CALLBACK_DATA_QUEUE DataQueue,
    _In_opt_ PFLT_CALLBACK_DATA Data,
    _In_opt_ PVOID PeekContext
    );
VOID
CsqCompleteCanceledIo(
    _In_ PFLT_CALLBACK_DATA_QUEUE DataQueue,
    _Inout_ PFLT_CALLBACK_DATA Data
    );

FLT_PREOP_CALLBACK_STATUS
PreRead (
    _Inout_ PFLT_CALLBACK_DATA Data,
    _In_ PCFLT_RELATED_OBJECTS FltObjects,
    _Flt_CompletionContext_Outptr_ PVOID *CompletionContext
    );

VOID
PreReadWorkItemRoutine(
    _In_ PFLT_GENERIC_WORKITEM WorkItem,
    _In_ PFLT_FILTER Filter,
    _In_ PVOID Context
    );

NTSTATUS
PreReadPendIo(
    _In_ PINSTANCE_CONTEXT InstanceContext
    );

NTSTATUS
PreReadProcessIo(
    _Inout_ PFLT_CALLBACK_DATA Data
    );

VOID
PreReadEmptyQueueAndComplete(
    _In_ PINSTANCE_CONTEXT InstanceContext
    );

//
//  Assign text sections for each routine.
//

#ifdef ALLOC_PRAGMA
#pragma alloc_text(INIT, DriverEntry)
#pragma alloc_text(INIT, GetIoOpenDriverRegistryKey)
#pragma alloc_text(INIT, OpenServiceParametersKey)
#pragma alloc_text(INIT, SetConfiguration)
#pragma alloc_text(PAGE, Unload)
#pragma alloc_text(PAGE, FreeGlobals)
#pragma alloc_text(PAGE, ContextCleanup)
#pragma alloc_text(PAGE, InstanceSetup)
#pragma alloc_text(PAGE, InstanceQueryTeardown)
#pragma alloc_text(PAGE, InstanceTeardownStart)
#pragma alloc_text(PAGE, InstanceTeardownComplete)

#endif

//
//  Filters callback routines
//

FLT_OPERATION_REGISTRATION Callbacks[] = {
    { IRP_MJ_READ,
      FLTFL_OPERATION_REGISTRATION_SKIP_PAGING_IO,
      PreRead,
      NULL },

    { IRP_MJ_OPERATION_END }
};

//
// Filters context registration data structure
//

const FLT_CONTEXT_REGISTRATION ContextRegistration[] = {

    { FLT_INSTANCE_CONTEXT,
        0,
        ContextCleanup,
        sizeof( INSTANCE_CONTEXT ),
        INSTANCE_CONTEXT_TAG },

    { FLT_CONTEXT_END }
};

//
// Filters registration data structure
//

FLT_REGISTRATION FilterRegistration = {

    sizeof( FLT_REGISTRATION ),             //  Size
    FLT_REGISTRATION_VERSION,               //  Version
    0,                                      //  Flags
    ContextRegistration,                    //  Context
    Callbacks,                              //  Operation callbacks
    Unload,                                 //  Filters unload routine
    InstanceSetup,                          //  InstanceSetup routine
    InstanceQueryTeardown,                  //  InstanceQueryTeardown routine
    InstanceTeardownStart,                  //  InstanceTeardownStart routine
    InstanceTeardownComplete,               //  InstanceTeardownComplete routine
    NULL, NULL, NULL                        //  Unused naming support callbacks
};

//
//  Filter driver initialization and unload routines
//

NTSTATUS
DriverEntry (
    _In_ PDRIVER_OBJECT DriverObject,
    _In_ PUNICODE_STRING RegistryPath
    )
/*++

Routine Description:

    This is the initialization routine for this filter driver. It registers
    itself with the filter manager and initializes all its global data structures.

Arguments:

    DriverObject - Pointer to driver object created by the system to
        represent this driver.

    RegistryPath - Unicode string identifying where the parameters for this
        driver are located in the registry.

Return Value:

    Returns STATUS_SUCCESS.

--*/
{
    NTSTATUS Status;

    //
    //  Default to NonPagedPoolNx for non paged pool allocations where supported.
    //

    ExInitializeDriverRuntime( DrvRtPoolNxOptIn );

    //
    //  Initialize global lookaside list
    //

    ExInitializeNPagedLookasideList( &Globals.QueueContextLookaside,
                                     NULL,
                                     NULL,
                                     0,
                                     sizeof( QUEUE_CONTEXT ),
                                     QUEUE_CONTEXT_TAG,
                                     0 );

    //
    //  Initialize the configuration to default values
    //

    Globals.DebugLevel = CSQ_TRACE_ERROR;

    Globals.TimeDelay = CSQ_DEFAULT_TIME_DELAY;

    Globals.PathBuffer = NULL;

    RtlInitUnicodeString( &Globals.MappingPath, CSQ_DEFAULT_MAPPING_PATH );


    //
    //  Modify the configuration based on values in the registry
    //

    Status = SetConfiguration( DriverObject, RegistryPath );

    if (!NT_SUCCESS( Status )) {

        goto DriverEntryCleanup;
    }

    DebugTrace( CSQ_TRACE_LOAD_UNLOAD,
                ("[Csq]: CancelSafe!DriverEntry\n") );



    //
    //  Register with the filter manager
    //

    Status = FltRegisterFilter( DriverObject,
                                &FilterRegistration,
                                &Globals.FilterHandle );

    if (!NT_SUCCESS( Status )) {

        DebugTrace( CSQ_TRACE_LOAD_UNLOAD | CSQ_TRACE_ERROR,
                    ("[Csq]: Failed to register filter (Status = 0x%x)\n",
                    Status) );

        goto DriverEntryCleanup;

    }

    //
    //  Start filtering I/O
    //

    Status = FltStartFiltering( Globals.FilterHandle );

    if (!NT_SUCCESS( Status )) {

        DebugTrace( CSQ_TRACE_LOAD_UNLOAD | CSQ_TRACE_ERROR,
                    ("[Csq]: Failed to start filtering (Status = 0x%x)\n",
                    Status) );

        FltUnregisterFilter( Globals.FilterHandle );

        goto DriverEntryCleanup;

    }


    DebugTrace( CSQ_TRACE_LOAD_UNLOAD,
                ("[Csq]: Driver loaded complete\n") );

DriverEntryCleanup:

    if (!NT_SUCCESS( Status )) {

        FreeGlobals();
    }

    return Status;
}

PFN_IoOpenDriverRegistryKey
GetIoOpenDriverRegistryKey (
    VOID
    )
{
    static PFN_IoOpenDriverRegistryKey pIoOpenDriverRegistryKey = NULL;
    UNICODE_STRING FunctionName = {0};

    if (pIoOpenDriverRegistryKey == NULL) {

        RtlInitUnicodeString(&FunctionName, L"IoOpenDriverRegistryKey");

        pIoOpenDriverRegistryKey = (PFN_IoOpenDriverRegistryKey)MmGetSystemRoutineAddress(&FunctionName);
    }

    return pIoOpenDriverRegistryKey;
}

NTSTATUS
OpenServiceParametersKey (
    _In_ PDRIVER_OBJECT DriverObject,
    _In_ PUNICODE_STRING ServiceRegistryPath,
    _Out_ PHANDLE ServiceParametersKey
    )
/*++

Routine Description:

    This routine opens the service parameters key, using the isolation-compliant
    APIs when possible.

Arguments:

    DriverObject - Pointer to driver object created by the system to
        represent this driver.

    RegistryPath - The path key passed to the driver during DriverEntry.

    ServiceParametersKey - Returns a handle to the service parameters subkey.

Return Value:

    STATUS_SUCCESS if the function completes successfully.  Otherwise a valid
    NTSTATUS code is returned.

--*/
{
    NTSTATUS Status;
    PFN_IoOpenDriverRegistryKey pIoOpenDriverRegistryKey;
    UNICODE_STRING Subkey;
    HANDLE ParametersKey = NULL;
    HANDLE ServiceRegKey = NULL;
    OBJECT_ATTRIBUTES Attributes;

    //
    //  Open the parameters key to read values from the INF, using the API to
    //  open the key if possible.
    //

    pIoOpenDriverRegistryKey = GetIoOpenDriverRegistryKey();

    if (pIoOpenDriverRegistryKey != NULL) {

        //
        //  Open the parameters key using the API.
        //

        Status = pIoOpenDriverRegistryKey( DriverObject,
                                           DriverRegKeyParameters,
                                           KEY_READ,
                                           0,
                                           &ParametersKey );

        if (!NT_SUCCESS( Status )) {

            goto OpenServiceParametersKeyCleanup;
        }

    } else {

        //
        //  Open specified service root key.
        //

        InitializeObjectAttributes( &Attributes,
                                    ServiceRegistryPath,
                                    OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE,
                                    NULL,
                                    NULL );

        Status = ZwOpenKey( &ServiceRegKey,
                            KEY_READ,
                            &Attributes );

        if (!NT_SUCCESS( Status )) {

            goto OpenServiceParametersKeyCleanup;
        }

        //
        //  Open the parameters key relative to service key path.
        //

        RtlInitUnicodeString( &Subkey, L"Parameters" );

        InitializeObjectAttributes( &Attributes,
                                    &Subkey,
                                    OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE,
                                    ServiceRegKey,
                                    NULL );

        Status = ZwOpenKey( &ParametersKey,
                            KEY_READ,
                            &Attributes );

        if (!NT_SUCCESS( Status )) {

            goto OpenServiceParametersKeyCleanup;
        }
    }

    //
    //  Return value to caller.
    //

    *ServiceParametersKey = ParametersKey;

OpenServiceParametersKeyCleanup:

    if (ServiceRegKey != NULL) {

        ZwClose( ServiceRegKey );
    }

    return Status;

}

NTSTATUS
SetConfiguration (
    _In_ PDRIVER_OBJECT DriverObject,
    _In_ PUNICODE_STRING RegistryPath
    )
/*++

Routine Description:

    This routine tries to configure the debuglevel, mapping path and
    queue delay based on values in the registry.

Arguments:

    DriverObject - Pointer to driver object created by the system to
        represent this driver.

    RegistryPath - The path key passed to the driver during DriverEntry.

Return Value:

    STATUS_SUCCESS if the function completes successfully.  Otherwise a valid
    NTSTATUS code is returned.

--*/
{
    NTSTATUS Status;
    HANDLE DriverRegKey = NULL;
    UNICODE_STRING ValueName;
    UCHAR Buffer[sizeof(KEY_VALUE_PARTIAL_INFORMATION) + CSQ_MAX_PATH_LENGTH  * sizeof(WCHAR)];
    PKEY_VALUE_PARTIAL_INFORMATION Value = (PKEY_VALUE_PARTIAL_INFORMATION)Buffer;
    ULONG ValueLength = sizeof(Buffer);
    ULONG ResultLength;
    ULONG Length;

    //
    //  Open service parameters key to query values from.
    //

    Status = OpenServiceParametersKey( DriverObject,
                                       RegistryPath,
                                       &DriverRegKey );

    if (!NT_SUCCESS( Status )) {

        DriverRegKey = NULL;
        goto SetConfigurationCleanup;
    }

    //
    //  Query the debug level.
    //

    RtlInitUnicodeString( &ValueName, CSQ_KEY_NAME_DEBUG_LEVEL );

    Status = ZwQueryValueKey( DriverRegKey,
                              &ValueName,
                              KeyValuePartialInformation,
                              Value,
                              ValueLength,
                              &ResultLength );

    if (NT_SUCCESS( Status )) {

        Globals.DebugLevel = *(PULONG)(Value->Data);
    }

    //
    //  Query the queue time delay.
    //

    RtlInitUnicodeString( &ValueName, CSQ_KEY_NAME_DELAY );

    Status = ZwQueryValueKey( DriverRegKey,
                              &ValueName,
                              KeyValuePartialInformation,
                              Value,
                              ValueLength,
                              &ResultLength );

    if (NT_SUCCESS( Status )) {

        if (Value->Type != REG_DWORD) {

            Status = STATUS_INVALID_PARAMETER;
            goto SetConfigurationCleanup;
        }

        Globals.TimeDelay = (LONGLONG)(*(PULONG)(Value->Data));

    }

    //
    //  Query the mapping path.
    //

    RtlInitUnicodeString( &ValueName, CSQ_KEY_NAME_PATH );

    //
    //  For simplicity of this sample, the length of the mapping path
    //  allowed in the registry is limited to CSQ_MAX_PATH_LENGTH
    //  characters. If this size is exceeded the default mapping path
    //  will be used.
    //

    Status = ZwQueryValueKey( DriverRegKey,
                              &ValueName,
                              KeyValuePartialInformation,
                              Value,
                              ValueLength,
                              &ValueLength );

    if (NT_SUCCESS( Status )) {

        //
        //  Set up the mapping and ensure the mapping string format is "\a\...\".
        //  If the mapping path doesn't begin with '\' fail, if it doesn't end
        //  with a '\' append one.
        //

        if (*(PWCHAR)(Value->Data) != L'\\') {

            Status = STATUS_INVALID_PARAMETER;
            goto SetConfigurationCleanup;
        }

        //
        //  Allocate enough space for an extra character in case a trailing '\'
        //  is missing and needs to be added.
        //

        Length = Value->DataLength + sizeof(WCHAR),

        Globals.PathBuffer = ExAllocatePoolZero( NonPagedPool, Length, CSQ_STRING_TAG );

        if (Globals.PathBuffer == NULL) {

            Status = STATUS_INSUFFICIENT_RESOURCES;
            goto SetConfigurationCleanup;
        }

        RtlCopyMemory( Globals.PathBuffer, Value->Data, Value->DataLength );

        Globals.PathBuffer[Length / sizeof(WCHAR) - 1] = L'\0';

        //
        //  Add a trailing '\' if one is missing.
        //

        if (Globals.PathBuffer[Length/sizeof(WCHAR) - 3] != L'\\') {

            Globals.PathBuffer[Length/sizeof(WCHAR) - 2] = L'\\';

        }

        RtlInitUnicodeString(&Globals.MappingPath, Globals.PathBuffer);

    }

    //
    //  Ignore errors when looking for values in the registry.
    //  Default values will be used.
    //

    Status = STATUS_SUCCESS;

SetConfigurationCleanup:

    if (DriverRegKey != NULL) {

        ZwClose( DriverRegKey );
    }

    return Status;

}


VOID
FreeGlobals(
    )
/*++

Routine Descrition:

    This routine cleans up the global buffers on both
    teardown and initialization failure.

Arguments:

Return Value:

    None.

--*/
{
    PAGED_CODE();

    Globals.FilterHandle = NULL;

    ExDeleteNPagedLookasideList( &Globals.QueueContextLookaside );

    if (Globals.PathBuffer != NULL) {

        ExFreePoolWithTag( Globals.PathBuffer, CSQ_STRING_TAG );
        Globals.PathBuffer = NULL;
    }

    RtlInitUnicodeString( &Globals.MappingPath, NULL );
}


NTSTATUS
Unload (
    _In_ FLT_FILTER_UNLOAD_FLAGS Flags
    )
/*++

Routine Description:

    This is the unload routine for this filter driver. This is called
    when the minifilter is about to be unloaded. We can fail this unload
    request if this is not a mandatory unloaded indicated by the Flags
    parameter.

Arguments:

    Flags - Indicating if this is a mandatory unload.

Return Value:

    Returns the final status of this operation.

--*/
{
    UNREFERENCED_PARAMETER( Flags );

    PAGED_CODE();

    DebugTrace( CSQ_TRACE_LOAD_UNLOAD,
                ("[Csq]: CancelSafe!Unload\n") );

    FltUnregisterFilter( Globals.FilterHandle );

    FreeGlobals();

    return STATUS_SUCCESS;
}


//
//  Context cleanup routine.
//

VOID
ContextCleanup (
    _In_ PFLT_CONTEXT Context,
    _In_ FLT_CONTEXT_TYPE ContextType
    )
/*++

Routine Description:

    FltMgr calls this routine immediately before it deletes the context.

Arguments:

    Context - Pointer to the minifilter driver's portion of the context.

    ContextType - Type of context. Must be one of the following values:
        FLT_FILE_CONTEXT (Microsoft Windows Vista and later only.),
        FLT_INSTANCE_CONTEXT, FLT_STREAM_CONTEXT, FLT_STREAMHANDLE_CONTEXT,
        FLT_TRANSACTION_CONTEXT (Windows Vista and later only.), and
        FLT_VOLUME_CONTEXT

Return Value:

    None.

--*/
{
    UNREFERENCED_PARAMETER( Context );
    UNREFERENCED_PARAMETER( ContextType );

    PAGED_CODE();

    DebugTrace( CSQ_TRACE_CONTEXT_CALLBACK,
                ("[Csq]: CancelSafe!ContextCleanup\n") );
}

//
//  Instance setup/teardown routines.
//

NTSTATUS
InstanceSetup (
    _In_ PCFLT_RELATED_OBJECTS FltObjects,
    _In_ FLT_INSTANCE_SETUP_FLAGS Flags,
    _In_ DEVICE_TYPE VolumeDeviceType,
    _In_ FLT_FILESYSTEM_TYPE VolumeFilesystemType
    )
/*++

Routine Description:

    This routine is called whenever a new instance is created on a volume. This
    gives us a chance to decide if we need to attach to this volume or not.

Arguments:

    FltObjects - Pointer to the FLT_RELATED_OBJECTS data structure containing
        opaque handles to this filter, instance and its associated volume.

    Flags - Flags describing the reason for this attach request.

    VolumeDeviceType - Device type of the file system volume.
        Must be one of the following: FILE_DEVICE_CD_ROM_FILE_SYSTEM,
        FILE_DEVICE_DISK_FILE_SYSTEM, and FILE_DEVICE_NETWORK_FILE_SYSTEM.

    VolumeFilesystemType - File system type of the volume.

Return Value:

    STATUS_SUCCESS - attach
    STATUS_FLT_DO_NOT_ATTACH - do not attach

--*/
{
    PINSTANCE_CONTEXT InstCtx = NULL;
    NTSTATUS Status = STATUS_SUCCESS;

    UNREFERENCED_PARAMETER( Flags );
    UNREFERENCED_PARAMETER( VolumeDeviceType );
    UNREFERENCED_PARAMETER( VolumeFilesystemType );

    PAGED_CODE();

    DebugTrace( CSQ_TRACE_INSTANCE_CALLBACK,
                ("[Csq]: CancelSafe!InstanceSetup\n") );

    //
    //  Allocate and initialize the instance context.
    //

    Status = FltAllocateContext( FltObjects->Filter,
                                 FLT_INSTANCE_CONTEXT,
                                 sizeof( INSTANCE_CONTEXT ),
                                 NonPagedPool,
                                 &InstCtx );

    if (!NT_SUCCESS( Status )) {

        DebugTrace( CSQ_TRACE_INSTANCE_CALLBACK | CSQ_TRACE_ERROR,
                    ("[Csq]: Failed to allocate instance context (Volume = %p, Instance = %p, Status = 0x%x)\n",
                    FltObjects->Volume,
                    FltObjects->Instance,
                    Status) );

        goto InstanceSetupCleanup;
    }

    Status = FltCbdqInitialize( FltObjects->Instance,
                                &InstCtx->Cbdq,
                                CsqInsertIo,
                                CsqRemoveIo,
                                CsqPeekNextIo,
                                CsqAcquire,
                                CsqRelease,
                                CsqCompleteCanceledIo );

    if (!NT_SUCCESS( Status )) {

        DebugTrace( CSQ_TRACE_INSTANCE_CALLBACK | CSQ_TRACE_ERROR,
                    ("[Csq]: Failed to initialize callback data queue (Volume = %p, Instance = %p, Status = 0x%x)\n",
                    FltObjects->Volume,
                    FltObjects->Instance,
                    Status) );

        goto InstanceSetupCleanup;
    }

    //
    //  Initialize the internal queue head and lock of the cancel safe queue.
    //

    InitializeListHead( &InstCtx->QueueHead );

    ExInitializeFastMutex( &InstCtx->Lock );

    //
    //  Initialize other members of the instance context.
    //

    InstCtx->Instance = FltObjects->Instance;

    InstCtx->WorkerThreadFlag = 0;

    KeInitializeEvent( &InstCtx->TeardownEvent, NotificationEvent, FALSE );

    //
    //  Set the instance context.
    //

    Status = FltSetInstanceContext( FltObjects->Instance,
                                    FLT_SET_CONTEXT_KEEP_IF_EXISTS,
                                    InstCtx,
                                    NULL );

    if (!NT_SUCCESS( Status )) {

        DebugTrace( CSQ_TRACE_INSTANCE_CALLBACK | CSQ_TRACE_ERROR,
                    ("[Csq]: Failed to set instance context (Volume = %p, Instance = %p, Status = 0x%x)\n",
                    FltObjects->Volume,
                    FltObjects->Instance,
                    Status) );

        goto InstanceSetupCleanup;
    }


InstanceSetupCleanup:

    if (InstCtx != NULL) {

        FltReleaseContext( InstCtx );
    }

    return Status;
}


NTSTATUS
InstanceQueryTeardown (
    _In_ PCFLT_RELATED_OBJECTS FltObjects,
    _In_ FLT_INSTANCE_QUERY_TEARDOWN_FLAGS Flags
    )
/*++

Routine Description:

    This is called when an instance is being manually deleted by a
    call to FltDetachVolume or FilterDetach thereby giving us a
    chance to fail that detach request.

Arguments:

    FltObjects - Pointer to the FLT_RELATED_OBJECTS data structure containing
        opaque handles to this filter, instance and its associated volume.

    Flags - Indicating where this detach request came from.

Return Value:

    Returns the status of this operation.

--*/
{
    UNREFERENCED_PARAMETER( FltObjects );
    UNREFERENCED_PARAMETER( Flags );

    PAGED_CODE();

    DebugTrace( CSQ_TRACE_INSTANCE_CALLBACK,
                ("[Csq]: CancelSafe!InstanceQueryTeardown\n") );

    return STATUS_SUCCESS;
}


VOID
InstanceTeardownStart (
    _In_ PCFLT_RELATED_OBJECTS FltObjects,
    _In_ FLT_INSTANCE_TEARDOWN_FLAGS Flags
    )
/*++

Routine Description:

    This routine is called at the start of instance teardown.

Arguments:

    FltObjects - Pointer to the FLT_RELATED_OBJECTS data structure containing
        opaque handles to this filter, instance and its associated volume.

    Flags - Reason why this instance is been deleted.

Return Value:

    None.

--*/
{
    PINSTANCE_CONTEXT InstCtx = 0;
    NTSTATUS Status;

    UNREFERENCED_PARAMETER( FltObjects );
    UNREFERENCED_PARAMETER( Flags );

    PAGED_CODE();

    DebugTrace( CSQ_TRACE_INSTANCE_CALLBACK,
                ("[Csq]: CancelSafe!InstanceTeardownStart\n") );

    //
    //  Get a pointer to the instance context.
    //

    Status = FltGetInstanceContext( FltObjects->Instance,
                                    &InstCtx );

    if (!NT_SUCCESS( Status ))
    {
        FLT_ASSERT( !"Instance Context is missing" );
        return;
    }

    //
    //  Disable the insert to the cancel safe queue.
    //

    FltCbdqDisable( &InstCtx->Cbdq );

    //
    //  Remove all callback data from the queue and complete them.
    //

    PreReadEmptyQueueAndComplete( InstCtx );

    //
    //  Signal the worker thread if it is pended.
    //

    KeSetEvent( &InstCtx->TeardownEvent, 0, FALSE );

    //
    //  Cleanup
    //

    FltReleaseContext( InstCtx );
}


VOID
InstanceTeardownComplete (
    _In_ PCFLT_RELATED_OBJECTS FltObjects,
    _In_ FLT_INSTANCE_TEARDOWN_FLAGS Flags
    )
/*++

Routine Description:

    This routine is called at the end of instance teardown.

Arguments:

    FltObjects - Pointer to the FLT_RELATED_OBJECTS data structure containing
        opaque handles to this filter, instance and its associated volume.

    Flags - Reason why this instance is been deleted.

Return Value:

    None.

--*/
{
    UNREFERENCED_PARAMETER( FltObjects );
    UNREFERENCED_PARAMETER( Flags );

    DebugTrace( CSQ_TRACE_INSTANCE_CALLBACK,
                ("[Csq]: CancelSafe!InstanceTeardownComplete\n") );

    PAGED_CODE();
}


//
//  Cbdq callback routines.
//

VOID
_IRQL_requires_max_(APC_LEVEL)
_IRQL_raises_(APC_LEVEL)
_Requires_lock_not_held_((CONTAINING_RECORD( DataQueue, INSTANCE_CONTEXT, Cbdq ))->Lock)
_Acquires_lock_((CONTAINING_RECORD( DataQueue, INSTANCE_CONTEXT, Cbdq ))->Lock)
CsqAcquire(
    _In_ PFLT_CALLBACK_DATA_QUEUE DataQueue,
    _Out_ PKIRQL Irql
    )
/*++

Routine Description:

    FltMgr calls this routine to acquire the lock protecting the queue.

Arguments:

    DataQueue - Supplies a pointer to the queue itself.

    Irql - Returns the previous IRQL if a spinlock is acquired.  We do not use
           any spinlocks, so we ignore this.

Return Value:

    None.

--*/
{
    PINSTANCE_CONTEXT InstCtx;

    DebugTrace( CSQ_TRACE_CBDQ_CALLBACK,
                ("[Csq]: CancelSafe!CsqAcquire\n") );

    //
    //  Get a pointer to the instance context.
    //

    InstCtx = CONTAINING_RECORD( DataQueue, INSTANCE_CONTEXT, Cbdq );

    //
    //  Acquire the lock.
    //

    ExAcquireFastMutex( &InstCtx->Lock );

    *Irql = 0;
}


VOID
_IRQL_requires_max_(APC_LEVEL)
_IRQL_requires_min_(APC_LEVEL)
_IRQL_raises_(PASSIVE_LEVEL)
_Requires_lock_held_((CONTAINING_RECORD( DataQueue, INSTANCE_CONTEXT, Cbdq ))->Lock)
_Releases_lock_((CONTAINING_RECORD( DataQueue, INSTANCE_CONTEXT, Cbdq ))->Lock)
CsqRelease(
    _In_ PFLT_CALLBACK_DATA_QUEUE DataQueue,
    _In_ KIRQL Irql
    )
/*++

Routine Description:

    FltMgr calls this routine to release the lock protecting the queue.

Arguments:

    DataQueue - Supplies a pointer to the queue itself.

    Irql - Supplies the previous IRQL if a spinlock is acquired.  We do not use
           any spinlocks, so we ignore this.

Return Value:

    None.

--*/
{
    PINSTANCE_CONTEXT InstCtx;

    UNREFERENCED_PARAMETER( Irql );

    DebugTrace( CSQ_TRACE_CBDQ_CALLBACK,
                ("[Csq]: CancelSafe!CsqRelease\n") );

    //
    //  Get a pointer to the instance context.
    //

    InstCtx = CONTAINING_RECORD( DataQueue, INSTANCE_CONTEXT, Cbdq );

    //
    //  Release the lock.
    //

    ExReleaseFastMutex( &InstCtx->Lock );
}


NTSTATUS
CsqInsertIo(
    _In_ PFLT_CALLBACK_DATA_QUEUE DataQueue,
    _In_ PFLT_CALLBACK_DATA Data,
    _In_opt_ PVOID Context
    )
/*++

Routine Description:

    FltMgr calls this routine to insert an entry into our pending I/O queue.
    The queue is already locked before this routine is called.

Arguments:

    DataQueue - Supplies a pointer to the queue itself.

    Data - Supplies the callback data for the operation that is being
           inserted into the queue.

    Context - Supplies user-defined context information.

Return Value:

    STATUS_SUCCESS if the function completes successfully.  Otherwise a valid
    NTSTATUS code is returned.

--*/
{
    PINSTANCE_CONTEXT InstCtx;
    PFLT_GENERIC_WORKITEM WorkItem = NULL;
    NTSTATUS Status = STATUS_SUCCESS;
    BOOLEAN WasQueueEmpty;

    UNREFERENCED_PARAMETER( Context );

    DebugTrace( CSQ_TRACE_CBDQ_CALLBACK,
                ("[Csq]: CancelSafe!CsqInsertIo\n") );

    //
    //  Get a pointer to the instance context.
    //

    InstCtx = CONTAINING_RECORD( DataQueue, INSTANCE_CONTEXT, Cbdq );

    //
    //  Save the queue state before inserting to it.
    //

    WasQueueEmpty = IsListEmpty( &InstCtx->QueueHead );

    //
    //  Insert the callback data entry into the queue.
    //

    InsertTailList( &InstCtx->QueueHead,
                    &Data->QueueLinks );

    //
    //  Queue a work item if no worker thread present.
    //

    if (WasQueueEmpty &&
        InterlockedIncrement( &InstCtx->WorkerThreadFlag ) == 1) {

        WorkItem = FltAllocateGenericWorkItem();

        if (WorkItem) {

            Status = FltQueueGenericWorkItem( WorkItem,
                                              InstCtx->Instance,
                                              PreReadWorkItemRoutine,
                                              DelayedWorkQueue,
                                              InstCtx->Instance );

            if (!NT_SUCCESS( Status )) {

                DebugTrace( CSQ_TRACE_CBDQ_CALLBACK | CSQ_TRACE_ERROR,
                            ("[Csq]: Failed to queue the work item (Status = 0x%x)\n",
                            Status) );

                FltFreeGenericWorkItem( WorkItem );
            }

        } else {

            Status = STATUS_INSUFFICIENT_RESOURCES;
        }

        if (!NT_SUCCESS( Status )) {

            //
            //  If we failed to queue a workitem we need to
            //  decrement the worker thread flag. If we did
            //  not decrement it future queue insertions would
            //  not trigger a workitem and requests added to
            //  the queue would be orphaned. We can safely
            //  decrement the flag here because we are
            //  guaranteed that no worker routine is currently
            //  running and that the queue is currently locked.
            //

            InterlockedDecrement( &InstCtx->WorkerThreadFlag );
            NT_ASSERT( InstCtx->WorkerThreadFlag == 0 );

            //
            //  Remove the callback data that was inserted into the queue.
            //

            RemoveTailList( &InstCtx->QueueHead );
        }
    }

    return Status;
}


VOID
CsqRemoveIo(
    _In_ PFLT_CALLBACK_DATA_QUEUE DataQueue,
    _In_ PFLT_CALLBACK_DATA Data
    )
/*++

Routine Description:

    FltMgr calls this routine to remove an entry from our pending I/O queue.
    The queue is already locked before this routine is called.

Arguments:

    DataQueue - Supplies a pointer to the queue itself.

    Data - Supplies the callback data that is to be removed.

Return Value:

    None.

--*/
{
    UNREFERENCED_PARAMETER( DataQueue );

    DebugTrace( CSQ_TRACE_CBDQ_CALLBACK,
                ("[Csq]: CancelSafe!CsqRemoveIo\n") );

    //
    //  Remove the callback data entry from the queue.
    //

    RemoveEntryList( &Data->QueueLinks );
}


PFLT_CALLBACK_DATA
CsqPeekNextIo(
    _In_ PFLT_CALLBACK_DATA_QUEUE DataQueue,
    _In_opt_ PFLT_CALLBACK_DATA Data,
    _In_opt_ PVOID PeekContext
    )
/*++

Routine Description:

    FltMgr calls this routine to look for an entry on our pending I/O queue.
    The queue is already locked before this routine is called.

Arguments:

    DataQueue - Supplies a pointer to the queue itself.

    Data - Supplies the callback data we should start our search from.
           If this is NULL, we start at the beginning of the list.

    PeekContext - Supplies user-defined context information.

Return Value:

    A pointer to the next callback data structure, or NULL.

--*/
{
    PINSTANCE_CONTEXT InstCtx;
    PLIST_ENTRY NextEntry;
    PFLT_CALLBACK_DATA NextData;

    UNREFERENCED_PARAMETER( PeekContext );

    DebugTrace( CSQ_TRACE_CBDQ_CALLBACK,
                ("[Csq]: CancelSafe!CsqPeekNextIo\n") );

    //
    //  Get a pointer to the instance context.
    //

    InstCtx = CONTAINING_RECORD( DataQueue, INSTANCE_CONTEXT, Cbdq );

    //
    //  If the supplied callback "Data" is NULL, the "NextIo" is the first entry
    //  in the queue; or it is the next list entry in the queue.
    //

    if (Data == NULL) {

        NextEntry = InstCtx->QueueHead.Flink;

    } else {

        NextEntry =  Data->QueueLinks.Flink;
    }

    //
    //  Return NULL if we hit the end of the queue or the queue is empty.
    //

    if (NextEntry == &InstCtx->QueueHead) {

        return NULL;
    }

    NextData = CONTAINING_RECORD( NextEntry, FLT_CALLBACK_DATA, QueueLinks );

    return NextData;
}


VOID
CsqCompleteCanceledIo(
    _In_ PFLT_CALLBACK_DATA_QUEUE DataQueue,
    _Inout_ PFLT_CALLBACK_DATA Data
    )
/*++

Routine Description:

    FltMgr calls this routine to complete an operation as cancelled that was
    previously pended. The queue is already locked before this routine is called.

Arguments:

    DataQueue - Supplies a pointer to the queue itself.

    Data - Supplies the callback data that is to be canceled.

Return Value:

    None.

--*/
{
    PQUEUE_CONTEXT QueueCtx;

    UNREFERENCED_PARAMETER( DataQueue );

    DebugTrace( CSQ_TRACE_CBDQ_CALLBACK,
                ("[Csq]: CancelSafe!CsqCompleteCanceledIo\n") );

    QueueCtx = (PQUEUE_CONTEXT) Data->QueueContext[0];

    //
    //  Just complete the operation as canceled.
    //

    Data->IoStatus.Status = STATUS_CANCELLED;
    Data->IoStatus.Information = 0;

    FltCompletePendedPreOperation( Data,
                                   FLT_PREOP_COMPLETE,
                                   0 );

    //
    //  Free the extra storage that was allocated for this canceled I/O.
    //

    ExFreeToNPagedLookasideList( &Globals.QueueContextLookaside,
                                 QueueCtx );
}


FLT_PREOP_CALLBACK_STATUS
PreRead (
    _Inout_ PFLT_CALLBACK_DATA Data,
    _In_ PCFLT_RELATED_OBJECTS FltObjects,
    _Flt_CompletionContext_Outptr_ PVOID *CompletionContext
    )
/*++

Routine Description:

    Handle pre-read.

Arguments:

    Data - Pointer to the filter callbackData that is passed to us.

    FltObjects - Pointer to the FLT_RELATED_OBJECTS data structure containing
        opaque handles to this filter, instance, its associated volume and
        file object.

    CompletionContext - The context for the completion routine for this
        operation.

Return Value:

    The return value is the status of the operation.

--*/
{

    PINSTANCE_CONTEXT InstCtx = NULL;
    PQUEUE_CONTEXT QueueCtx = NULL;
    PFLT_FILE_NAME_INFORMATION NameInfo = NULL;
    NTSTATUS CbStatus = FLT_PREOP_SUCCESS_NO_CALLBACK;
    NTSTATUS Status;

    UNREFERENCED_PARAMETER( CompletionContext );

    DebugTrace( CSQ_TRACE_PRE_READ,
                ("[Csq]: CancelSafe!PreRead\n") );

    //
    //  Skip IRP_PAGING_IO, IRP_SYNCHRONOUS_PAGING_IO and
    //  TopLevelIrp.
    //

    if ((Data->Iopb->IrpFlags & IRP_PAGING_IO) ||
        (Data->Iopb->IrpFlags & IRP_SYNCHRONOUS_PAGING_IO) ||
        IoGetTopLevelIrp()) {

        return FLT_PREOP_SUCCESS_NO_CALLBACK;
    }

    //
    //  Get and parse the file name
    //

    Status = FltGetFileNameInformation( Data,
                                        FLT_FILE_NAME_NORMALIZED
                                          | FLT_FILE_NAME_QUERY_DEFAULT,
                                        &NameInfo );

    if (!NT_SUCCESS( Status )) {

        DebugTrace( CSQ_TRACE_PRE_READ | CSQ_TRACE_ERROR,
                    ("[Csq]: Failed to get filename (Status = 0x%x)\n",
                    Status) );

        goto PreReadCleanup;
    }

    Status = FltParseFileNameInformation( NameInfo );

    if (!NT_SUCCESS( Status )) {

        DebugTrace( CSQ_TRACE_PRE_READ | CSQ_TRACE_ERROR,
                    ("[Csq]: Failed to parse filename (Name = %wZ, Status = 0x%x)\n",
                    &NameInfo->Name,
                    Status) );

        goto PreReadCleanup;
    }

    //
    //  Compare to see if this file I/O is to be pended.
    //

    if (!RtlPrefixUnicodeString( &Globals.MappingPath, &NameInfo->ParentDir, TRUE )) {

        goto PreReadCleanup;
    }

    //
    //  Since Fast I/O operations cannot be queued, we could return
    //  FLT_PREOP_SUCCESS_NO_CALLBACK at this point. In this sample,
    //  we disallow Fast I/O for this magic file in order to force an IRP
    //  to be sent to us again. The purpose of doing that is to demonstrate
    //  the cancel safe queue, which may not be true in the real world.
    //

    if (!FLT_IS_IRP_OPERATION( Data )) {

        CbStatus = FLT_PREOP_DISALLOW_FASTIO;
        goto PreReadCleanup;
    }

    //
    //  Allocate a context for each I/O to be inserted into the queue.
    //

    QueueCtx = ExAllocateFromNPagedLookasideList( &Globals.QueueContextLookaside );

    if (QueueCtx == NULL) {

        DebugTrace( CSQ_TRACE_PRE_READ | CSQ_TRACE_ERROR,
                    ("[Csq]: Failed to allocate from NPagedLookasideList (Status = 0x%x)\n",
                    Status) );

        goto PreReadCleanup;
    }

    RtlZeroMemory(QueueCtx, sizeof(QUEUE_CONTEXT));

    //
    //  Get the instance context.
    //

    Status = FltGetInstanceContext( FltObjects->Instance,
                                    &InstCtx );

    if (!NT_SUCCESS( Status )) {

        FLT_ASSERT( !"Instance context is missing" );
        goto PreReadCleanup;
    }

    //
    //  Set the queue context
    //

    Data->QueueContext[0] = (PVOID) QueueCtx;
    Data->QueueContext[1] = NULL;

    //
    //  Insert the callback data into the cancel safe queue
    //

    Status = FltCbdqInsertIo( &InstCtx->Cbdq,
                              Data,
                              &QueueCtx->CbdqIoContext,
                              0 );

    if (Status == STATUS_SUCCESS) {

        //
        //  In general, we can create a worker thread here as long as we can
        //  correctly handle the insert/remove race conditions b/w multi threads.
        //  In this sample, the worker thread creation is done in CsqInsertIo.
        //  This is a simpler solution because CsqInsertIo is atomic with
        //  respect to other CsqXxxIo callback routines.
        //

        CbStatus = FLT_PREOP_PENDING;

    } else {

        DebugTrace( CSQ_TRACE_PRE_READ | CSQ_TRACE_ERROR,
                    ("[Csq]: Failed to insert into cbdq (Status = 0x%x)\n",
                    Status) );
    }

PreReadCleanup:

    //
    //  Clean up
    //

    if (QueueCtx && CbStatus != FLT_PREOP_PENDING) {

        ExFreeToNPagedLookasideList( &Globals.QueueContextLookaside, QueueCtx );
    }

    if (NameInfo) {

        FltReleaseFileNameInformation( NameInfo );
    }

    if (InstCtx) {

        FltReleaseContext( InstCtx );
    }

    return CbStatus;
}


VOID
PreReadWorkItemRoutine(
    _In_ PFLT_GENERIC_WORKITEM WorkItem,
    _In_ PFLT_FILTER Filter,
    _In_ PVOID Context
    )
/*++

Routine Description:

    This WorkItem routine is called in the system thread context to process
    all the pended I/O in this mini filter's cancel safe queue. For each I/O
    in the queue, it completes the I/O after pending the operation for a
    period of time. The thread exits when the queue is empty.

Arguments:

    WorkItem - Unused.

    Filter - Unused.

    Context - Context information.

Return Value:

    None.

--*/
{
    PINSTANCE_CONTEXT InstCtx = NULL;
    PFLT_CALLBACK_DATA Data;
    PFLT_INSTANCE Instance = (PFLT_INSTANCE)Context;
    PQUEUE_CONTEXT QueueCtx;
    NTSTATUS Status;
    FLT_PREOP_CALLBACK_STATUS callbackStatus;

    UNREFERENCED_PARAMETER( WorkItem );
    UNREFERENCED_PARAMETER( Filter );

    DebugTrace( CSQ_TRACE_PRE_READ,
                ("[Csq]: CancelSafe!PreReadWorkItemRoutine\n") );

    //
    //  Get a pointer to the instance context.
    //

    Status = FltGetInstanceContext( Instance,
                                    &InstCtx );

    if (!NT_SUCCESS( Status ))
    {
        FLT_ASSERT( !"Instance Context is missing" );
        return;
    }

    //
    //  Process all the pended I/O in the cancel safe queue
    //

    for (;;) {

        callbackStatus = FLT_PREOP_SUCCESS_NO_CALLBACK;

        PreReadPendIo( InstCtx );

        //
        //  WorkerThreadFlag >= 1;
        //  Here we reduce it to 1.
        //

        InterlockedExchange( &InstCtx->WorkerThreadFlag, 1 );

        //
        //  Remove an I/O from the cancel safe queue.
        //

        Data = FltCbdqRemoveNextIo( &InstCtx->Cbdq,
                                    NULL);

        if (Data) {

            QueueCtx = (PQUEUE_CONTEXT) Data->QueueContext[0];

            PreReadProcessIo( Data );

            //
            //  Check to see if we need to lock the user buffer.
            //
            //  If the FLTFL_CALLBACK_DATA_SYSTEM_BUFFER flag is set we don't
            //  have to lock the buffer because its already a system buffer.
            //
            //  If the MdlAddress is NULL and the buffer is a user buffer,
            //  then we have to construct one in order to look at the buffer.
            //
            //  If the length of the buffer is zero there is nothing to read,
            //  so we cannot construct a MDL.
            //

            if (!FlagOn(Data->Flags, FLTFL_CALLBACK_DATA_SYSTEM_BUFFER) &&
                Data->Iopb->Parameters.Read.MdlAddress == NULL &&
                Data->Iopb->Parameters.Read.Length > 0) {

                Status = FltLockUserBuffer( Data );

                if (!NT_SUCCESS( Status )) {

                    //
                    //  If could not lock the user buffer we cannot
                    //  allow the IO to go below us. Because we are
                    //  in a different VA space and the buffer is a
                    //  user mode address, we will either fault or
                    //  corrpt data
                    //

                    DebugTrace( CSQ_TRACE_PRE_READ | CSQ_TRACE_ERROR,
                                ("[Csq]: Failed to lock user buffer (Status = 0x%x)\n",
                                Status) );

                    callbackStatus = FLT_PREOP_COMPLETE;
                    Data->IoStatus.Status = Status;
                }
            }

            //
            //  Complete the I/O
            //

            FltCompletePendedPreOperation( Data,
                                           callbackStatus,
                                           NULL );

            //
            //  Free the extra storage that was allocated for this I/O.
            //

            ExFreeToNPagedLookasideList( &Globals.QueueContextLookaside,
                                         QueueCtx );

        } else {

            //
            //  At this moment it is possible that a new IO is being inserted
            //  into the queue in the CsqInsertIo routine. Now that the queue is
            //  empty, CsqInsertIo needs to make a decision on whether to create
            //  a new worker thread. The decision is based on the race between
            //  the InterlockedIncrement in CsqInsertIo and the
            //  InterlockedDecrement as below. There are two situations:
            //
            //  (1) If the decrement executes earlier before the increment,
            //      the flag will be decremented to 0 so this worker thread
            //      will return. Then CsqInsertIo will increment the flag
            //      from 0 to 1, and therefore create a new worker thread.
            //  (2) If the increment executes earlier before the decrement,
            //      the flag will be first incremented to 2 in CsqInsertIo
            //      so a new worker thread will not be satisfied. Then the
            //      decrement as below will lower the flag down to 1, and
            //      therefore continue this worker thread.
            //

            if (InterlockedDecrement( &InstCtx->WorkerThreadFlag ) == 0) {

                break;
            }

        }
    }

    //
    //  Clean up
    //

    FltReleaseContext(InstCtx);

    FltFreeGenericWorkItem(WorkItem);
}


NTSTATUS
PreReadPendIo(
    _In_ PINSTANCE_CONTEXT InstanceContext
    )
/*++

Routine Description:

    This routine waits for a period of time or until the instance is
    torndown.

Arguments:

    InstanceContext - Supplies a pointer to the instance context.

Return Value:

    The return value is the status of the operation.

--*/
{
    LARGE_INTEGER DueTime;
    NTSTATUS Status;

    //
    //  Delay or get signaled if the instance is torndown.
    //

    DueTime.QuadPart = (LONGLONG) - Globals.TimeDelay;

    Status = KeWaitForSingleObject( &InstanceContext->TeardownEvent,
                                    Executive,
                                    KernelMode,
                                    FALSE,
                                    &DueTime );

    return Status;
}


NTSTATUS
PreReadProcessIo(
    _Inout_ PFLT_CALLBACK_DATA Data
    )
/*++

Routine Description:

    This routine process the I/O that was removed from the queue.

Arguments:

    Data - Supplies the callback data that was removed from the queue.

Return Value:

    The return value is the status of the operation.

--*/
{
    UNREFERENCED_PARAMETER( Data );

    return STATUS_SUCCESS;
}


VOID
PreReadEmptyQueueAndComplete(
    _In_ PINSTANCE_CONTEXT InstanceContext
    )
/*++

Routine Description:

    This routine empties the cancel safe queue and complete all the
    pended pre-read operations.

Arguments:

    InstanceContext - Supplies a pointer to the instance context.

Return Value:

    None.

--*/
{
    NTSTATUS Status;
    FLT_PREOP_CALLBACK_STATUS callbackStatus;
    PFLT_CALLBACK_DATA Data;
    PQUEUE_CONTEXT QueueCtx;

    do {

        callbackStatus = FLT_PREOP_SUCCESS_NO_CALLBACK;

        Data = FltCbdqRemoveNextIo( &InstanceContext->Cbdq,
                                    NULL );

        if (Data) {

            QueueCtx = (PQUEUE_CONTEXT) Data->QueueContext[0];

            //
            //  Check to see if we need to lock the user buffer.
            //
            //  If the FLTFL_CALLBACK_DATA_SYSTEM_BUFFER flag is set we don't
            //  have to lock the buffer because its already a system buffer.
            //
            //  If the MdlAddress is NULL and the buffer is a user buffer,
            //  then we have to construct one in order to look at the buffer.
            //
            //  If the length of the buffer is zero there is nothing to read,
            //  so we cannot construct a MDL.
            //

            if (!FlagOn(Data->Flags, FLTFL_CALLBACK_DATA_SYSTEM_BUFFER) &&
                Data->Iopb->Parameters.Read.MdlAddress == NULL &&
                Data->Iopb->Parameters.Read.Length > 0) {

                Status = FltLockUserBuffer( Data );

                if (!NT_SUCCESS( Status )) {

                    //
                    //  If could not lock the user buffer we cannot
                    //  allow the IO to go below us. Because we are
                    //  in a different VA space and the buffer is a
                    //  user mode address, we will either fault or
                    //  corrpt data
                    //

                    callbackStatus = FLT_PREOP_COMPLETE;
                    Data->IoStatus.Status = Status;
                }
            }

            FltCompletePendedPreOperation( Data,
                                           callbackStatus,
                                           NULL );

            ExFreeToNPagedLookasideList( &Globals.QueueContextLookaside,
                                         QueueCtx );
        }

    } while (Data);
}