summaryrefslogtreecommitdiff
path: root/src/VBox/HostDrivers/VBoxNetFlt/win/drv/VBoxNetFltRt-win.cpp
blob: 728f3e541603495a1bd5d93aa19b175eb403ddc4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
/* $Id$ */
/** @file
 * VBoxNetFltRt-win.cpp - Bridged Networking Driver, Windows Specific Runtime Code.
 */

/*
 * Copyright (C) 2011-2016 Oracle Corporation
 *
 * This file is part of VirtualBox Open Source Edition (OSE), as
 * available from http://www.virtualbox.org. This file is free software;
 * you can redistribute it and/or modify it under the terms of the GNU
 * General Public License (GPL) as published by the Free Software
 * Foundation, in version 2 as it comes in the "COPYING" file of the
 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
 *
 * The contents of this file may alternatively be used under the terms
 * of the Common Development and Distribution License Version 1.0
 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the
 * VirtualBox OSE distribution, in which case the provisions of the
 * CDDL are applicable instead of those of the GPL.
 *
 * You may elect to license modified versions of this file under the
 * terms and conditions of either the GPL or the CDDL or both.
 */


/*********************************************************************************************************************************
*   Header Files                                                                                                                 *
*********************************************************************************************************************************/
#include "VBoxNetFltCmn-win.h"
#include <VBox/intnetinline.h>
#include <iprt/thread.h>

#include <iprt/nt/tdikrnl.h>
#include <mstcpip.h>


/*********************************************************************************************************************************
*   Structures and Typedefs                                                                                                      *
*********************************************************************************************************************************/
/** represents the job element of the job queue
 * see comments for VBOXNETFLT_JOB_QUEUE */
typedef struct VBOXNETFLT_JOB
{
    /** link in the job queue */
    LIST_ENTRY ListEntry;
    /** job function to be executed */
    PFNVBOXNETFLT_JOB_ROUTINE pfnRoutine;
    /** parameter to be passed to the job function */
    PVOID pContext;
    /** event that will be fired on job completion */
    KEVENT CompletionEvent;
    /** true if the job manager should use the completion even for completion indication, false-otherwise*/
    bool bUseCompletionEvent;
} VBOXNETFLT_JOB, *PVBOXNETFLT_JOB;

/**
 * represents the queue of jobs processed by the worker thread
 *
 * we use the thread to process tasks which are required to be done at passive level
 * our callbacks may be called at APC level by IntNet, there are some tasks that we can not create at APC,
 * e.g. thread creation. This is why we schedule such jobs to the worker thread working at passive level
 */
typedef struct VBOXNETFLT_JOB_QUEUE
{
    /* jobs */
    LIST_ENTRY Jobs;
    /* we are using ExInterlocked..List functions to access the jobs list */
    KSPIN_LOCK Lock;
    /** this event is used to initiate a job worker thread kill */
    KEVENT KillEvent;
    /** this event is used to notify a worker thread that jobs are added to the queue */
    KEVENT NotifyEvent;
    /** worker thread */
    PKTHREAD pThread;
} VBOXNETFLT_JOB_QUEUE, *PVBOXNETFLT_JOB_QUEUE;

typedef struct _CREATE_INSTANCE_CONTEXT
{
#ifndef VBOXNETADP
    PNDIS_STRING pOurName;
    PNDIS_STRING pBindToName;
#else
    NDIS_HANDLE hMiniportAdapter;
    NDIS_HANDLE hWrapperConfigurationContext;
#endif
    NDIS_STATUS Status;
} CREATE_INSTANCE_CONTEXT, *PCREATE_INSTANCE_CONTEXT;

/*contexts used for our jobs */
/* Attach context */
typedef struct _ATTACH_INFO
{
    PVBOXNETFLTINS pNetFltIf;
    PCREATE_INSTANCE_CONTEXT pCreateContext;
    bool fRediscovery;
    int Status;
} ATTACH_INFO, *PATTACH_INFO;

/* general worker context */
typedef struct _WORKER_INFO
{
    PVBOXNETFLTINS pNetFltIf;
    int Status;
} WORKER_INFO, *PWORKER_INFO;

/* idc initialization */
typedef struct _INIT_IDC_INFO
{
    VBOXNETFLT_JOB Job;
    bool bInitialized;
    volatile bool bStop;
    volatile int rc;
    KEVENT hCompletionEvent;
} INIT_IDC_INFO, *PINIT_IDC_INFO;


/*********************************************************************************************************************************
*   Global Variables                                                                                                             *
*********************************************************************************************************************************/
/** global job queue. some operations are required to be done at passive level, e.g. thread creation, adapter bind/unbind initiation,
 * while IntNet typically calls us APC_LEVEL, so we just create a system thread in our DriverEntry and enqueue the jobs to that thread */
static VBOXNETFLT_JOB_QUEUE g_VBoxJobQueue;
volatile static bool g_bVBoxIdcInitialized;
INIT_IDC_INFO g_VBoxInitIdcInfo;

/**
 * The (common) global data.
 */
static VBOXNETFLTGLOBALS g_VBoxNetFltGlobals;
/* win-specific global data */
VBOXNETFLTGLOBALS_WIN g_VBoxNetFltGlobalsWin = {0};


/*********************************************************************************************************************************
*   Defined Constants And Macros                                                                                                 *
*********************************************************************************************************************************/
#define LIST_ENTRY_2_JOB(pListEntry) \
    ( (PVBOXNETFLT_JOB)((uint8_t *)(pListEntry) - RT_OFFSETOF(VBOXNETFLT_JOB, ListEntry)) )


/*********************************************************************************************************************************
*   Internal Functions                                                                                                           *
*********************************************************************************************************************************/
static int vboxNetFltWinAttachToInterface(PVBOXNETFLTINS pThis, void * pContext, bool fRediscovery);
static int vboxNetFltWinConnectIt(PVBOXNETFLTINS pThis);
static int vboxNetFltWinFiniIdc();
static void vboxNetFltWinFiniNetFltBase();
static int vboxNetFltWinInitNetFltBase();
static int vboxNetFltWinFiniNetFlt();
static int vboxNetFltWinStartInitIdcProbing();
static int vboxNetFltWinStopInitIdcProbing();



/** makes the current thread to sleep for the given number of miliseconds */
DECLHIDDEN(void) vboxNetFltWinSleep(ULONG milis)
{
    RTThreadSleep(milis);
}

/** wait for the given device to be dereferenced */
DECLHIDDEN(void) vboxNetFltWinWaitDereference(PVBOXNETFLT_WINIF_DEVICE pState)
{
#ifdef DEBUG
    uint64_t StartNanoTS = RTTimeSystemNanoTS();
    uint64_t CurNanoTS;
#endif
    Assert(KeGetCurrentIrql() < DISPATCH_LEVEL);

    while (ASMAtomicUoReadU32((volatile uint32_t *)&pState->cReferences))
    {
        vboxNetFltWinSleep(2);
#ifdef DEBUG
        CurNanoTS = RTTimeSystemNanoTS();
        if (CurNanoTS - StartNanoTS > 20000000)
        {
            LogRel(("device not idle"));
            AssertFailed();
//            break;
        }
#endif
    }
}

/**
 * mem functions
 */
/* allocates and zeroes the nonpaged memory of a given size */
DECLHIDDEN(NDIS_STATUS) vboxNetFltWinMemAlloc(PVOID *ppvMemBuf, UINT cbLength)
{
#ifdef DEBUG_NETFLT_USE_EXALLOC
    *ppvMemBuf = ExAllocatePoolWithTag(NonPagedPool, cbLength, VBOXNETFLT_MEM_TAG);
    if (*ppvMemBuf)
    {
        NdisZeroMemory(*ppvMemBuf, cbLength);
        return NDIS_STATUS_SUCCESS;
    }
    return NDIS_STATUS_FAILURE;
#else
    NDIS_STATUS fStatus = NdisAllocateMemoryWithTag(ppvMemBuf, cbLength, VBOXNETFLT_MEM_TAG);
    if (fStatus == NDIS_STATUS_SUCCESS)
        NdisZeroMemory(*ppvMemBuf, cbLength);
    return fStatus;
#endif
}

/* frees memory allocated with vboxNetFltWinMemAlloc */
DECLHIDDEN(void) vboxNetFltWinMemFree(PVOID pvMemBuf)
{
#ifdef DEBUG_NETFLT_USE_EXALLOC
    ExFreePool(pvMemBuf);
#else
    NdisFreeMemory(pvMemBuf, 0, 0);
#endif
}

#ifndef VBOXNETFLT_NO_PACKET_QUEUE

/* initializes packet info pool and allocates the cSize packet infos for the pool */
static NDIS_STATUS vboxNetFltWinPpAllocatePacketInfoPool(PVBOXNETFLT_PACKET_INFO_POOL pPool, UINT cSize)
{
    UINT cbBufSize = sizeof(PACKET_INFO)*cSize;
    PACKET_INFO * pPacketInfos;
    NDIS_STATUS fStatus;
    UINT i;

    Assert(cSize > 0);

    INIT_INTERLOCKED_PACKET_QUEUE(&pPool->Queue);

    fStatus = vboxNetFltWinMemAlloc((PVOID*)&pPacketInfos, cbBufSize);

    if (fStatus == NDIS_STATUS_SUCCESS)
    {
        PVBOXNETFLTPACKET_INFO pInfo;
        pPool->pBuffer = pPacketInfos;

        for (i = 0; i < cSize; i++)
        {
            pInfo = &pPacketInfos[i];
            vboxNetFltWinQuEnqueueTail(&pPool->Queue.Queue, pInfo);
            pInfo->pPool = pPool;
        }
    }
    else
    {
        AssertFailed();
    }

    return fStatus;
}

/* frees the packet info pool */
VOID vboxNetFltWinPpFreePacketInfoPool(PVBOXNETFLT_PACKET_INFO_POOL pPool)
{
    vboxNetFltWinMemFree(pPool->pBuffer);

    FINI_INTERLOCKED_PACKET_QUEUE(&pPool->Queue)
}

#endif

/**
 * copies one string to another. in case the destination string size is not enough to hold the complete source string
 * does nothing and returns NDIS_STATUS_RESOURCES .
 */
DECLHIDDEN(NDIS_STATUS) vboxNetFltWinCopyString(PNDIS_STRING pDst, PNDIS_STRING pSrc)
{
    NDIS_STATUS Status = NDIS_STATUS_SUCCESS;

    if (pDst != pSrc)
    {
        if (pDst->MaximumLength < pSrc->Length)
        {
            AssertFailed();
            Status = NDIS_STATUS_RESOURCES;
        }
        else
        {
            pDst->Length = pSrc->Length;

            if (pDst->Buffer != pSrc->Buffer)
            {
                NdisMoveMemory(pDst->Buffer, pSrc->Buffer, pSrc->Length);
            }
        }
    }
    return Status;
}

/************************************************************************************
 * PINTNETSG pSG manipulation functions
 ************************************************************************************/

/* moves the contents of the given NDIS_BUFFER and all other buffers chained to it to the PINTNETSG
 * the PINTNETSG is expected to contain one segment whose bugger is large enough to maintain
 * the contents of the given NDIS_BUFFER and all other buffers chained to it */
static NDIS_STATUS vboxNetFltWinNdisBufferMoveToSG0(PNDIS_BUFFER pBuffer, PINTNETSG pSG)
{
    PINTNETSEG paSeg;
    uint8_t * ptr;
    PVOID pVirtualAddress;
    UINT cbCurrentLength;
    NDIS_STATUS fStatus = NDIS_STATUS_SUCCESS;

    Assert(pSG->cSegsAlloc == 1);

    paSeg = pSG->aSegs;
    ptr = (uint8_t*)paSeg->pv;
    paSeg->cb = 0;
    paSeg->Phys = NIL_RTHCPHYS;
    pSG->cbTotal = 0;

    Assert(paSeg->pv);

    while (pBuffer)
    {
        NdisQueryBufferSafe(pBuffer, &pVirtualAddress, &cbCurrentLength, NormalPagePriority);

        if (!pVirtualAddress)
        {
            fStatus = NDIS_STATUS_FAILURE;
            break;
        }

        pSG->cbTotal += cbCurrentLength;
        paSeg->cb += cbCurrentLength;
        NdisMoveMemory(ptr, pVirtualAddress, cbCurrentLength);
        ptr += cbCurrentLength;

        NdisGetNextBuffer(pBuffer, &pBuffer);
    }

    if (fStatus == NDIS_STATUS_SUCCESS)
    {
        pSG->cSegsUsed = 1;
        Assert(pSG->cbTotal == paSeg->cb);
    }
    return fStatus;
}

/* converts the PNDIS_BUFFER to PINTNETSG by making the PINTNETSG segments to point to the memory buffers the
 * ndis buffer(s) point to (as opposed to vboxNetFltWinNdisBufferMoveToSG0 which copies the memory from ndis buffers(s) to PINTNETSG) */
static NDIS_STATUS vboxNetFltWinNdisBuffersToSG(PNDIS_BUFFER pBuffer, PINTNETSG pSG)
{
    UINT cSegs = 0;
    NDIS_STATUS Status = NDIS_STATUS_SUCCESS;
    PVOID pVirtualAddress;
    UINT cbCurrentLength;

    while (pBuffer)
    {
        NdisQueryBufferSafe(pBuffer, &pVirtualAddress, &cbCurrentLength, NormalPagePriority);

        if (!pVirtualAddress)
        {
            Status = NDIS_STATUS_FAILURE;
            break;
        }

        pSG->cbTotal += cbCurrentLength;
        pSG->aSegs[cSegs].cb = cbCurrentLength;
        pSG->aSegs[cSegs].pv = pVirtualAddress;
        pSG->aSegs[cSegs].Phys = NIL_RTHCPHYS;
        cSegs++;

        NdisGetNextBuffer(pBuffer, &pBuffer);
    }

    AssertFatal(cSegs <= pSG->cSegsAlloc);

    if (Status == NDIS_STATUS_SUCCESS)
    {
        pSG->cSegsUsed = cSegs;
    }

    return Status;
}

static void vboxNetFltWinDeleteSG(PINTNETSG pSG)
{
    vboxNetFltWinMemFree(pSG);
}

static PINTNETSG vboxNetFltWinCreateSG(uint32_t cSegs)
{
    PINTNETSG pSG;
    NTSTATUS Status = vboxNetFltWinMemAlloc((PVOID*)&pSG, RT_OFFSETOF(INTNETSG, aSegs[cSegs]));
    if (Status == STATUS_SUCCESS)
    {
        IntNetSgInitTempSegs(pSG, 0 /*cbTotal*/, cSegs, 0 /*cSegsUsed*/);
        return pSG;
    }

    return NULL;
}

/************************************************************************************
 * packet queue functions
 ************************************************************************************/
#ifndef VBOXNETFLT_NO_PACKET_QUEUE
#if !defined(VBOXNETADP)
static NDIS_STATUS vboxNetFltWinQuPostPacket(PVBOXNETFLTINS pNetFlt, PNDIS_PACKET pPacket, PINTNETSG pSG, uint32_t fFlags
# ifdef DEBUG_NETFLT_PACKETS
        , PNDIS_PACKET pTmpPacket
# endif
        )
{
    NDIS_STATUS Status;
    PNDIS_PACKET pMyPacket;
    bool bSrcHost = fFlags & PACKET_SRC_HOST;

    LogFlow(("posting packet back to driver stack..\n"));

    if (!pPacket)
    {
        /* INTNETSG was in the packet queue, create a new NdisPacket from INTNETSG*/
        pMyPacket = vboxNetFltWinNdisPacketFromSG(pNetFlt,
                pSG, /* PINTNETSG */
                pSG, /* PVOID pBufToFree */
                bSrcHost, /* bool bToWire */
                false); /* bool bCopyMemory */

        Assert(pMyPacket);

        NDIS_SET_PACKET_STATUS(pMyPacket, NDIS_STATUS_SUCCESS);

        DBG_CHECK_PACKET_AND_SG(pMyPacket, pSG);

#ifdef DEBUG_NETFLT_PACKETS
        Assert(pTmpPacket);

        DBG_CHECK_PACKET_AND_SG(pTmpPacket, pSG);

        DBG_CHECK_PACKETS(pTmpPacket, pMyPacket);
#endif

        LogFlow(("non-ndis packet info, packet created (%p)\n", pMyPacket));
    }
    else
    {
        /* NDIS_PACKET was in the packet queue */
        DBG_CHECK_PACKET_AND_SG(pPacket, pSG);

        if (!(fFlags & PACKET_MINE))
        {
            /* the packet is the one that was passed to us in send/receive callback
             * According to the DDK, we can not post it further,
             * instead we should allocate our own packet.
             * So, allocate our own packet (pMyPacket) and copy the packet info there */
            if (bSrcHost)
            {
                Status = vboxNetFltWinPrepareSendPacket(pNetFlt, pPacket, &pMyPacket/*, true*/);
                LogFlow(("packet from wire, packet created (%p)\n", pMyPacket));
            }
            else
            {
                Status = vboxNetFltWinPrepareRecvPacket(pNetFlt, pPacket, &pMyPacket, false);
                LogFlow(("packet from wire, packet created (%p)\n", pMyPacket));
            }
        }
        else
        {
            /* the packet enqueued is ours, simply assign pMyPacket and zero pPacket */
            pMyPacket = pPacket;
            pPacket = NULL;
        }
        Assert(pMyPacket);
    }

    if (pMyPacket)
    {
        /* we have successfully initialized our packet, post it to the host or to the wire */
        if (bSrcHost)
        {
#if defined(DEBUG_NETFLT_PACKETS) || !defined(VBOX_LOOPBACK_USEFLAGS)
            vboxNetFltWinLbPutSendPacket(pNetFlt, pMyPacket, false /* bFromIntNet */);
#endif
            NdisSend(&Status, pNetFlt->u.s.hBinding, pMyPacket);

            if (Status != NDIS_STATUS_PENDING)
            {
#if defined(DEBUG_NETFLT_PACKETS) || !defined(VBOX_LOOPBACK_USEFLAGS)
                /* the status is NOT pending, complete the packet */
                bool bTmp = vboxNetFltWinLbRemoveSendPacket(pNetFlt, pMyPacket);
                Assert(bTmp);
#endif
                if (pPacket)
                {
                    LogFlow(("status is not pending, completing packet (%p)\n", pPacket));

                    NdisIMCopySendCompletePerPacketInfo (pPacket, pMyPacket);

                    NdisFreePacket(pMyPacket);
                }
                else
                {
                    /* should never be here since the PINTNETSG is stored only when the underlying miniport
                     * indicates NDIS_STATUS_RESOURCES, we should never have this when processing
                     * the "from-host" packets */
                    AssertFailed();
                    LogFlow(("status is not pending, freeing myPacket (%p)\n", pMyPacket));
                    vboxNetFltWinFreeSGNdisPacket(pMyPacket, false);
                }
            }
        }
        else
        {
            NdisMIndicateReceivePacket(pNetFlt->u.s.hMiniport, &pMyPacket, 1);

            Status = NDIS_STATUS_PENDING;
            /* the packet receive completion is always indicated via MiniportReturnPacket */
        }
    }
    else
    {
        /*we failed to create our packet */
        AssertFailed();
        Status = NDIS_STATUS_FAILURE;
    }

    return Status;
}
#endif

static bool vboxNetFltWinQuProcessInfo(PVBOXNETFLTINS pNetFltIf, PPACKET_QUEUE_WORKER pWorker, PVOID pvPacket, const UINT fFlags)
#else
DECLHIDDEN(bool) vboxNetFltWinPostIntnet(PVBOXNETFLTINS pNetFltIf, PVOID pvPacket, const UINT fFlags)
#endif
{
    PNDIS_PACKET pPacket = NULL;
    PINTNETSG pSG = NULL;
    NDIS_STATUS Status;
#ifndef VBOXNETADP
    bool bSrcHost;
    bool bDropIt;
# ifndef VBOXNETFLT_NO_PACKET_QUEUE
    bool bPending;
# endif
#endif
#ifdef VBOXNETFLT_NO_PACKET_QUEUE
    bool bDeleteSG = false;
#endif
#ifdef DEBUG_NETFLT_PACKETS
    /* packet used for matching */
    PNDIS_PACKET pTmpPacket = NULL;
#endif

#ifndef VBOXNETADP
    bSrcHost = (fFlags & VBOXNETFLT_PACKET_SRC_HOST) != 0;
#endif

    /* we first need to obtain the INTNETSG to be passed to intnet */

    /* the queue may contain two "types" of packets:
     * the NDIS_PACKET and the INTNETSG.
     * I.e. on send/receive we typically enqueue the NDIS_PACKET passed to us by ndis,
     * however in case our ProtocolReceive is called or the packet's status is set to NDIS_STSTUS_RESOURCES
     * in ProtocolReceivePacket, we must return the packet immediately on ProtocolReceive*** exit
     * In this case we allocate the INTNETSG, copy the ndis packet data there and enqueue it.
     * In this case the packet info flags has the VBOXNETFLT_PACKET_SG fag set
     *
     * Besides that the NDIS_PACKET contained in the queue could be either the one passed to us in our send/receive callback
     * or the one created by us. The latter is possible in case our ProtocolReceive callback is called and we call NdisTransferData
     * in this case we need to allocate the packet the data to be transferred to.
     * If the enqueued packet is the one allocated by us the VBOXNETFLT_PACKET_MINE flag is set
     * */
    if ((fFlags & VBOXNETFLT_PACKET_SG) == 0)
    {
        /* we have NDIS_PACKET enqueued, we need to convert it to INTNETSG to be passed to intnet */
        PNDIS_BUFFER pCurrentBuffer = NULL;
        UINT cBufferCount;
        UINT cbPacketLength;

        pPacket = (PNDIS_PACKET)pvPacket;

        LogFlow(("ndis packet info, packet (%p)\n", pPacket));

        LogFlow(("preparing pSG"));
        NdisQueryPacket(pPacket, NULL, &cBufferCount, &pCurrentBuffer, &cbPacketLength);
        Assert(cBufferCount);

#ifdef VBOXNETFLT_NO_PACKET_QUEUE
        pSG = vboxNetFltWinCreateSG(cBufferCount);
#else
        /* we can not allocate the INTNETSG on stack since in this case we may get stack overflow
         * somewhere outside of our driver (3 pages of system thread stack does not seem to be enough)
         *
         * since we have a "serialized" packet processing, i.e. all packets are being processed and passed
         * to intnet by this thread, we just use one previously allocated INTNETSG which is stored in PVBOXNETFLTINS */
        pSG = pWorker->pSG;

        if (cBufferCount > pSG->cSegsAlloc)
        {
            pSG = vboxNetFltWinCreateSG(cBufferCount + 2);
            if (pSG)
            {
                vboxNetFltWinDeleteSG(pWorker->pSG);
                pWorker->pSG = pSG;
            }
            else
            {
                LogRel(("Failed to reallocate the pSG\n"));
            }
        }
#endif

        if (pSG)
        {
#ifdef VBOXNETFLT_NO_PACKET_QUEUE
            bDeleteSG = true;
#endif
            /* reinitialize */
            IntNetSgInitTempSegs(pSG, 0 /*cbTotal*/, pSG->cSegsAlloc, 0 /*cSegsUsed*/);

            /* convert the ndis buffers to INTNETSG */
            Status = vboxNetFltWinNdisBuffersToSG(pCurrentBuffer, pSG);
            if (Status != NDIS_STATUS_SUCCESS)
            {
                pSG = NULL;
            }
            else
            {
                DBG_CHECK_PACKET_AND_SG(pPacket, pSG);
            }
        }
    }
    else
    {
        /* we have the INTNETSG enqueued. (see the above comment explaining why/when this may happen)
         * just use the INTNETSG to pass it to intnet */
#ifndef VBOXNETADP
        /* the PINTNETSG is stored only when the underlying miniport
         * indicates NDIS_STATUS_RESOURCES, we should never have this when processing
         * the "from-host" packedts */
        Assert(!bSrcHost);
#endif
        pSG = (PINTNETSG)pvPacket;

        LogFlow(("not ndis packet info, pSG (%p)\n", pSG));
    }

#ifdef DEBUG_NETFLT_PACKETS
    if (!pPacket && !pTmpPacket)
    {
        /* create tmp packet that woud be used for matching */
        pTmpPacket = vboxNetFltWinNdisPacketFromSG(pNetFltIf,
                    pSG, /* PINTNETSG */
                    pSG, /* PVOID pBufToFree */
                    bSrcHost, /* bool bToWire */
                    true); /* bool bCopyMemory */

        NDIS_SET_PACKET_STATUS(pTmpPacket, NDIS_STATUS_SUCCESS);

        DBG_CHECK_PACKET_AND_SG(pTmpPacket, pSG);

        Assert(pTmpPacket);
    }
#endif
    do
    {
#ifndef VBOXNETADP
        /* the pSG was successfully initialized, post it to the netFlt*/
        bDropIt = pSG ? pNetFltIf->pSwitchPort->pfnRecv(pNetFltIf->pSwitchPort, NULL /* pvIf */, pSG,
                    bSrcHost ? INTNETTRUNKDIR_HOST : INTNETTRUNKDIR_WIRE
                            )
              : false;
#else
        if (pSG)
        {
            pNetFltIf->pSwitchPort->pfnRecv(pNetFltIf->pSwitchPort, NULL /* pvIf */, pSG, INTNETTRUNKDIR_HOST);
            STATISTIC_INCREASE(pNetFltIf->u.s.WinIf.cTxSuccess);
        }
        else
        {
            STATISTIC_INCREASE(pNetFltIf->u.s.WinIf.cTxError);
        }
#endif

#ifndef VBOXNETFLT_NO_PACKET_QUEUE

# if !defined(VBOXNETADP)
        if (!bDropIt)
        {
            Status = vboxNetFltWinQuPostPacket(pNetFltIf, pPacket, pSG, fFlags
#  ifdef DEBUG_NETFLT_PACKETS
                               , pTmpPacket
#  endif
            );

            if (Status == NDIS_STATUS_PENDING)
            {
                /* we will process packet completion in the completion routine */
                bPending = true;
                break;
            }
        }
        else
# endif
        {
            Status = NDIS_STATUS_SUCCESS;
        }

        /* drop it */
        if (pPacket)
        {
            if (!(fFlags & PACKET_MINE))
            {
# if !defined(VBOXNETADP)
                /* complete the packets */
                if (fFlags & PACKET_SRC_HOST)
                {
# endif
/*                    NDIS_SET_PACKET_STATUS(pPacket, Status); */
                    NdisMSendComplete(pNetFltIf->u.s.hMiniport, pPacket, Status);
# if !defined(VBOXNETADP)
                }
                else
                {
# endif
# ifndef VBOXNETADP
                    NdisReturnPackets(&pPacket, 1);
# endif
# if !defined(VBOXNETADP)
                }
# endif
            }
            else
            {
                Assert(!(fFlags & PACKET_SRC_HOST));
                vboxNetFltWinFreeSGNdisPacket(pPacket, true);
            }
        }
        else
        {
            Assert(pSG);
            vboxNetFltWinMemFree(pSG);
        }
# ifndef VBOXNETADP
        bPending = false;
# endif
    } while (0);

#ifdef DEBUG_NETFLT_PACKETS
    if (pTmpPacket)
    {
        vboxNetFltWinFreeSGNdisPacket(pTmpPacket, true);
    }
#endif

#ifndef VBOXNETADP
    return bPending;
#else
    return false;
#endif
#else /* #ifdef VBOXNETFLT_NO_PACKET_QUEUE */
    } while (0);

    if (bDeleteSG)
        vboxNetFltWinMemFree(pSG);

# ifndef VBOXNETADP
    return bDropIt;
# else
    return true;
# endif
#endif
}
#ifndef VBOXNETFLT_NO_PACKET_QUEUE
/*
 * thread start function for the thread which processes the packets enqueued in our send and receive callbacks called by ndis
 *
 * ndis calls us at DISPATCH_LEVEL, while IntNet is using kernel functions which require Irql<DISPATCH_LEVEL
 * this is why we can not immediately post packets to IntNet from our sen/receive callbacks
 * instead we put the incoming packets to the queue and maintain the system thread running at passive level
 * which processes the queue and posts the packets to IntNet, and further to the host or to the wire.
 */
static VOID vboxNetFltWinQuPacketQueueWorkerThreadProc(PVBOXNETFLTINS pNetFltIf)
{
    bool fResume = true;
    NTSTATUS fStatus;
    PPACKET_QUEUE_WORKER pWorker = &pNetFltIf->u.s.PacketQueueWorker;

    PVOID apEvents[] = {
        (PVOID)&pWorker->KillEvent,
        (PVOID)&pWorker->NotifyEvent
    };

    while (fResume)
    {
        uint32_t cNumProcessed;
        uint32_t cNumPostedToHostWire;

        fStatus = KeWaitForMultipleObjects(RT_ELEMENTS(apEvents), apEvents, WaitAny, Executive, KernelMode, FALSE, NULL, NULL);
        if (!NT_SUCCESS(fStatus) || fStatus == STATUS_WAIT_0)
        {
            /* "kill" event was set
             * will process queued packets and exit */
            fResume = false;
        }

        LogFlow(("processing vboxNetFltWinQuPacketQueueWorkerThreadProc\n"));

        cNumProcessed = 0;
        cNumPostedToHostWire = 0;

        do
        {
            PVBOXNETFLTPACKET_INFO pInfo;

#ifdef DEBUG_NETFLT_PACKETS
            /* packet used for matching */
            PNDIS_PACKET pTmpPacket = NULL;
#endif

            /** @todo FIXME: !!! the better approach for performance would be to dequeue all packets at once
             * and then go through all dequeued packets
             * the same should be done for enqueue !!! */
            pInfo = vboxNetFltWinQuInterlockedDequeueHead(&pWorker->PacketQueue);

            if (!pInfo)
            {
                break;
            }

            LogFlow(("found info (0x%p)\n", pInfo));

            if (vboxNetFltWinQuProcessInfo(pNetFltIf, pWorker, pInfo->pPacket, pInfo->fFlags))
            {
                cNumPostedToHostWire++;
            }

            vboxNetFltWinPpFreePacketInfo(pInfo);

            cNumProcessed++;
        } while (TRUE);

        if (cNumProcessed)
        {
            vboxNetFltWinDecReferenceNetFlt(pNetFltIf, cNumProcessed);

            Assert(cNumProcessed >= cNumPostedToHostWire);

            if (cNumProcessed != cNumPostedToHostWire)
            {
                vboxNetFltWinDecReferenceWinIf(pNetFltIf, cNumProcessed - cNumPostedToHostWire);
            }
        }
    }

    PsTerminateSystemThread(STATUS_SUCCESS);
}
#endif
/**
 * thread start function for the job processing thread
 *
 * see comments for PVBOXNETFLT_JOB_QUEUE
 */
static VOID vboxNetFltWinJobWorkerThreadProc(PVBOXNETFLT_JOB_QUEUE pQueue)
{
    bool fResume = true;
    NTSTATUS Status;

    PVOID apEvents[] = {
        (PVOID)&pQueue->KillEvent,
        (PVOID)&pQueue->NotifyEvent,
    };

    do
    {
        Status = KeWaitForMultipleObjects(RT_ELEMENTS(apEvents), apEvents, WaitAny, Executive, KernelMode, FALSE, NULL, NULL);
        Assert(NT_SUCCESS(Status));
        if (!NT_SUCCESS(Status) || Status == STATUS_WAIT_0)
        {
            /* will process queued jobs and exit */
            Assert(Status == STATUS_WAIT_0);
            fResume = false;
        }

        do
        {
            PLIST_ENTRY pJobEntry = ExInterlockedRemoveHeadList(&pQueue->Jobs, &pQueue->Lock);
            PVBOXNETFLT_JOB pJob;

            if (!pJobEntry)
                break;

            pJob = LIST_ENTRY_2_JOB(pJobEntry);

            Assert(KeGetCurrentIrql() == PASSIVE_LEVEL);
            pJob->pfnRoutine(pJob->pContext);
            Assert(KeGetCurrentIrql() == PASSIVE_LEVEL);

            if (pJob->bUseCompletionEvent)
            {
                KeSetEvent(&pJob->CompletionEvent, 1, FALSE);
            }
        } while (TRUE);
    } while (fResume);

    Assert(Status == STATUS_WAIT_0);

    PsTerminateSystemThread(STATUS_SUCCESS);
}

/**
 * enqueues the job to the job queue to be processed by the job worker thread
 * see comments for PVBOXNETFLT_JOB_QUEUE
 */
static VOID vboxNetFltWinJobEnqueueJob(PVBOXNETFLT_JOB_QUEUE pQueue, PVBOXNETFLT_JOB pJob, bool bEnqueueHead)
{
    if (bEnqueueHead)
    {
        ExInterlockedInsertHeadList(&pQueue->Jobs, &pJob->ListEntry, &pQueue->Lock);
    }
    else
    {
        ExInterlockedInsertTailList(&pQueue->Jobs, &pJob->ListEntry, &pQueue->Lock);
    }

    KeSetEvent(&pQueue->NotifyEvent, 1, FALSE);
}

DECLINLINE(VOID) vboxNetFltWinJobInit(PVBOXNETFLT_JOB pJob, PFNVBOXNETFLT_JOB_ROUTINE pfnRoutine, PVOID pContext, bool bUseEvent)
{
    pJob->pfnRoutine = pfnRoutine;
    pJob->pContext = pContext;
    pJob->bUseCompletionEvent = bUseEvent;
    if (bUseEvent)
        KeInitializeEvent(&pJob->CompletionEvent, NotificationEvent, FALSE);
}

/**
 * enqueues the job to the job queue to be processed by the job worker thread and
 * blocks until the job is done
 * see comments for PVBOXNETFLT_JOB_QUEUE
 */
static VOID vboxNetFltWinJobSynchExec(PVBOXNETFLT_JOB_QUEUE pQueue, PFNVBOXNETFLT_JOB_ROUTINE pfnRoutine, PVOID pContext)
{
    VBOXNETFLT_JOB Job;

    Assert(KeGetCurrentIrql() < DISPATCH_LEVEL);

    vboxNetFltWinJobInit(&Job, pfnRoutine, pContext, true);

    vboxNetFltWinJobEnqueueJob(pQueue, &Job, false);

    KeWaitForSingleObject(&Job.CompletionEvent, Executive, KernelMode, FALSE, NULL);
}

/**
 * enqueues the job to be processed by the job worker thread at passive level and
 * blocks until the job is done
 */
DECLHIDDEN(VOID) vboxNetFltWinJobSynchExecAtPassive(PFNVBOXNETFLT_JOB_ROUTINE pfnRoutine, PVOID pContext)
{
    vboxNetFltWinJobSynchExec(&g_VBoxJobQueue, pfnRoutine, pContext);
}

/**
 * helper function used for system thread creation
 */
static NTSTATUS vboxNetFltWinQuCreateSystemThread(PKTHREAD *ppThread, PKSTART_ROUTINE pfnStartRoutine, PVOID pvStartContext)
{
    OBJECT_ATTRIBUTES ObjectAttributes;
    Assert(KeGetCurrentIrql() == PASSIVE_LEVEL);

    InitializeObjectAttributes(&ObjectAttributes, NULL, OBJ_KERNEL_HANDLE, NULL, NULL);

    HANDLE hThread;
    NTSTATUS Status = PsCreateSystemThread(&hThread, THREAD_ALL_ACCESS, &ObjectAttributes, NULL, NULL, (PKSTART_ROUTINE)pfnStartRoutine, pvStartContext);
    Assert(Status == STATUS_SUCCESS);
    if (Status == STATUS_SUCCESS)
    {
        Status = ObReferenceObjectByHandle(hThread, THREAD_ALL_ACCESS, NULL, KernelMode, (PVOID*)ppThread, NULL);
        Assert(Status == STATUS_SUCCESS);
        ZwClose(hThread);
        if (Status == STATUS_SUCCESS)
        {
            return STATUS_SUCCESS;
        }

        /** @todo how would we fail in this case ?*/
    }
    return Status;
}

/**
 * initialize the job queue
 * see comments for PVBOXNETFLT_JOB_QUEUE
 */
static NTSTATUS vboxNetFltWinJobInitQueue(PVBOXNETFLT_JOB_QUEUE pQueue)
{
    NTSTATUS fStatus;

    Assert(KeGetCurrentIrql() == PASSIVE_LEVEL);

    NdisZeroMemory(pQueue, sizeof(VBOXNETFLT_JOB_QUEUE));

    KeInitializeEvent(&pQueue->KillEvent, NotificationEvent, FALSE);

    KeInitializeEvent(&pQueue->NotifyEvent, SynchronizationEvent, FALSE);

    InitializeListHead(&pQueue->Jobs);

    fStatus = vboxNetFltWinQuCreateSystemThread(&pQueue->pThread, (PKSTART_ROUTINE)vboxNetFltWinJobWorkerThreadProc, pQueue);
    if (fStatus != STATUS_SUCCESS)
    {
        pQueue->pThread = NULL;
    }
    else
    {
        Assert(pQueue->pThread);
    }

    return fStatus;
}

/**
 * deinitialize the job queue
 * see comments for PVBOXNETFLT_JOB_QUEUE
 */
static void vboxNetFltWinJobFiniQueue(PVBOXNETFLT_JOB_QUEUE pQueue)
{
    Assert(KeGetCurrentIrql() == PASSIVE_LEVEL);

    if (pQueue->pThread)
    {
        KeSetEvent(&pQueue->KillEvent, 0, FALSE);

        KeWaitForSingleObject(pQueue->pThread, Executive,
                            KernelMode, FALSE, NULL);
    }
}

#ifndef VBOXNETFLT_NO_PACKET_QUEUE

/**
 * initializes the packet queue
 * */
DECLHIDDEN(NTSTATUS) vboxNetFltWinQuInitPacketQueue(PVBOXNETFLTINS pInstance)
{
    NTSTATUS Status;
    PPACKET_QUEUE_WORKER pWorker = &pInstance->u.s.PacketQueueWorker;

    AssertFatal(!pWorker->pSG);

    Assert(KeGetCurrentIrql() == PASSIVE_LEVEL);

    KeInitializeEvent(&pWorker->KillEvent, NotificationEvent, FALSE);

    KeInitializeEvent(&pWorker->NotifyEvent, SynchronizationEvent, FALSE);

    INIT_INTERLOCKED_PACKET_QUEUE(&pWorker->PacketQueue);

    do
    {
    Status = vboxNetFltWinPpAllocatePacketInfoPool(&pWorker->PacketInfoPool, VBOXNETFLT_PACKET_INFO_POOL_SIZE);

    if (Status == NDIS_STATUS_SUCCESS)
    {
        pWorker->pSG = vboxNetFltWinCreateSG(PACKET_QUEUE_SG_SEGS_ALLOC);
        if (!pWorker->pSG)
        {
            Status = STATUS_INSUFFICIENT_RESOURCES;
            break;
        }

        Status = vboxNetFltWinQuCreateSystemThread(&pWorker->pThread, (PKSTART_ROUTINE)vboxNetFltWinQuPacketQueueWorkerThreadProc, pInstance);
        if (Status != STATUS_SUCCESS)
        {
            vboxNetFltWinPpFreePacketInfoPool(&pWorker->PacketInfoPool);
            vboxNetFltWinMemFree(pWorker->pSG);
            pWorker->pSG = NULL;
            break;
        }
    }

    } while (0);

    return Status;
}

/*
 * deletes the packet queue
 */
DECLHIDDEN(void) vboxNetFltWinQuFiniPacketQueue(PVBOXNETFLTINS pInstance)
{
    PINTNETSG pSG;
    PPACKET_QUEUE_WORKER pWorker = &pInstance->u.s.PacketQueueWorker;
    Assert(KeGetCurrentIrql() < DISPATCH_LEVEL);

    /* using the pPacketQueueSG as an indicator that the packet queue is initialized */
    RTSpinlockAcquire((pInstance)->hSpinlock);
    if (pWorker->pSG)
    {
        pSG = pWorker->pSG;
        pWorker->pSG = NULL;
        RTSpinlockRelease((pInstance)->hSpinlock);
        KeSetEvent(&pWorker->KillEvent, 0, FALSE);

        KeWaitForSingleObject(pWorker->pThread, Executive,
                            KernelMode, FALSE, NULL);

        vboxNetFltWinPpFreePacketInfoPool(&pWorker->PacketInfoPool);

        vboxNetFltWinDeleteSG(pSG);

        FINI_INTERLOCKED_PACKET_QUEUE(&pWorker->PacketQueue);
    }
    else
    {
        RTSpinlockRelease((pInstance)->hSpinlock);
    }
}

#endif

/*
 * creates the INTNETSG containing one segment pointing to the buffer of size cbBufSize
 * the INTNETSG created should be cleaned with vboxNetFltWinMemFree
 */
DECLHIDDEN(NDIS_STATUS) vboxNetFltWinAllocSG(UINT cbPacket, PINTNETSG *ppSG)
{
    NDIS_STATUS Status;
    PINTNETSG pSG;

    /* allocation:
     * 1. SG_PACKET - with one aSegs pointing to
     * 2. buffer of cbPacket containing the entire packet */
    AssertCompileSizeAlignment(INTNETSG, sizeof(PVOID));
    Status = vboxNetFltWinMemAlloc((PVOID*)&pSG, cbPacket + sizeof(INTNETSG));
    if (Status == NDIS_STATUS_SUCCESS)
    {
        IntNetSgInitTemp(pSG, pSG + 1, cbPacket);
        LogFlow(("pSG created (%p)\n", pSG));
        *ppSG = pSG;
    }
    return Status;
}

#ifndef VBOXNETFLT_NO_PACKET_QUEUE
/**
 * put the packet info to the queue
 */
DECLINLINE(void) vboxNetFltWinQuEnqueueInfo(PVBOXNETFLTPACKET_QUEUE_WORKER pWorker, PVBOXNETFLTPACKET_INFO pInfo)
{
    vboxNetFltWinQuInterlockedEnqueueTail(&pWorker->PacketQueue, pInfo);

    KeSetEvent(&pWorker->NotifyEvent, IO_NETWORK_INCREMENT, FALSE);
}

/**
 * puts the packet to the queue
 *
 * @return NDIST_STATUS_SUCCESS iff the packet was enqueued successfully
 * and error status otherwise.
 * NOTE: that the success status does NOT mean that the packet processing is completed, but only that it was enqueued successfully
 * the packet can be returned to the caller protocol/moniport only in case the bReleasePacket was set to true (in this case the copy of the packet was enqueued)
 * or if vboxNetFltWinQuEnqueuePacket failed, i.e. the packet was NOT enqueued
 */
DECLHIDDEN(NDIS_STATUS) vboxNetFltWinQuEnqueuePacket(PVBOXNETFLTINS pInstance, PVOID pPacket, const UINT fPacketFlags)
{
    PVBOXNETFLT_PACKET_INFO pInfo;
    PVBOXNETFLT_PACKET_QUEUE_WORKER pWorker = &pInstance->u.s.PacketQueueWorker;
    NDIS_STATUS fStatus = NDIS_STATUS_SUCCESS;

    do
    {
        if (fPacketFlags & PACKET_COPY)
        {
            PNDIS_BUFFER pBuffer = NULL;
            UINT cBufferCount;
            UINT uBytesCopied = 0;
            UINT cbPacketLength;
            PINTNETSG pSG;

            /* the packet is Ndis packet */
            Assert(!(fPacketFlags & PACKET_SG));
            Assert(!(fPacketFlags & PACKET_MINE));

            NdisQueryPacket((PNDIS_PACKET)pPacket,
                    NULL,
                    &cBufferCount,
                    &pBuffer,
                    &cbPacketLength);


            Assert(cBufferCount);

            fStatus = vboxNetFltWinAllocSG(cbPacketLength, &pSG);
            if (fStatus != NDIS_STATUS_SUCCESS)
            {
                AssertFailed();
                break;
            }

            pInfo = vboxNetFltWinPpAllocPacketInfo(&pWorker->PacketInfoPool);

            if (!pInfo)
            {
                AssertFailed();
                /** @todo what status to set? */
                fStatus = NDIS_STATUS_FAILURE;
                vboxNetFltWinMemFree(pSG);
                break;
            }

            Assert(pInfo->pPool);

            /* the packet we are queueing is SG, add PACKET_SG to flags */
            SET_FLAGS_TO_INFO(pInfo, fPacketFlags | PACKET_SG);
            SET_PACKET_TO_INFO(pInfo, pSG);

            fStatus = vboxNetFltWinNdisBufferMoveToSG0(pBuffer, pSG);
            if (fStatus != NDIS_STATUS_SUCCESS)
            {
                AssertFailed();
                vboxNetFltWinPpFreePacketInfo(pInfo);
                vboxNetFltWinMemFree(pSG);
                break;
            }

            DBG_CHECK_PACKET_AND_SG((PNDIS_PACKET)pPacket, pSG);
        }
        else
        {
            pInfo = vboxNetFltWinPpAllocPacketInfo(&pWorker->PacketInfoPool);

            if (!pInfo)
            {
                AssertFailed();
                /** @todo what status to set? */
                fStatus = NDIS_STATUS_FAILURE;
                break;
            }

            Assert(pInfo->pPool);

            SET_FLAGS_TO_INFO(pInfo, fPacketFlags);
            SET_PACKET_TO_INFO(pInfo, pPacket);
        }

        vboxNetFltWinQuEnqueueInfo(pWorker, pInfo);

    } while (0);

    return fStatus;
}
#endif


/*
 * netflt
 */
#ifndef VBOXNETADP
static NDIS_STATUS vboxNetFltWinSynchNdisRequest(PVBOXNETFLTINS pNetFlt, PNDIS_REQUEST pRequest)
{
    int rc;

    Assert(KeGetCurrentIrql() < DISPATCH_LEVEL);

    /* 1. serialize */
    rc = RTSemFastMutexRequest(pNetFlt->u.s.WinIf.hSynchRequestMutex); AssertRC(rc);
    if (RT_SUCCESS(rc))
    {
        NDIS_STATUS fRequestStatus = NDIS_STATUS_SUCCESS;

        /* 2. set pNetFlt->u.s.pSynchRequest */
        Assert(!pNetFlt->u.s.WinIf.pSynchRequest);
        pNetFlt->u.s.WinIf.pSynchRequest = pRequest;

        /* 3. call NdisRequest */
        NdisRequest(&fRequestStatus, pNetFlt->u.s.WinIf.hBinding, pRequest);

        if (fRequestStatus == NDIS_STATUS_PENDING)
        {
        /* 3.1 if pending wait and assign the resulting status */
            KeWaitForSingleObject(&pNetFlt->u.s.WinIf.hSynchCompletionEvent, Executive,
                            KernelMode, FALSE, NULL);

            fRequestStatus = pNetFlt->u.s.WinIf.SynchCompletionStatus;
        }

        /* 4. clear the pNetFlt->u.s.pSynchRequest */
        pNetFlt->u.s.WinIf.pSynchRequest = NULL;

        RTSemFastMutexRelease(pNetFlt->u.s.WinIf.hSynchRequestMutex); AssertRC(rc);
        return fRequestStatus;
    }
    return NDIS_STATUS_FAILURE;
}


DECLHIDDEN(NDIS_STATUS) vboxNetFltWinGetMacAddress(PVBOXNETFLTINS pNetFlt, PRTMAC pMac)
{
    NDIS_REQUEST request;
    NDIS_STATUS status;
    request.RequestType = NdisRequestQueryInformation;
    request.DATA.QUERY_INFORMATION.InformationBuffer = pMac;
    request.DATA.QUERY_INFORMATION.InformationBufferLength = sizeof(RTMAC);
    request.DATA.QUERY_INFORMATION.Oid = OID_802_3_CURRENT_ADDRESS;
    status = vboxNetFltWinSynchNdisRequest(pNetFlt, &request);
    if (status != NDIS_STATUS_SUCCESS)
    {
        /** @todo */
        AssertFailed();
    }

    return status;

}

DECLHIDDEN(NDIS_STATUS) vboxNetFltWinQueryPhysicalMedium(PVBOXNETFLTINS pNetFlt, NDIS_PHYSICAL_MEDIUM * pMedium)
{
    NDIS_REQUEST Request;
    NDIS_STATUS Status;
    Request.RequestType = NdisRequestQueryInformation;
    Request.DATA.QUERY_INFORMATION.InformationBuffer = pMedium;
    Request.DATA.QUERY_INFORMATION.InformationBufferLength = sizeof(NDIS_PHYSICAL_MEDIUM);
    Request.DATA.QUERY_INFORMATION.Oid = OID_GEN_PHYSICAL_MEDIUM;
    Status = vboxNetFltWinSynchNdisRequest(pNetFlt, &Request);
    if (Status != NDIS_STATUS_SUCCESS)
    {
        if (Status == NDIS_STATUS_NOT_SUPPORTED || Status == NDIS_STATUS_NOT_RECOGNIZED || Status == NDIS_STATUS_INVALID_OID)
        {
            Status = NDIS_STATUS_NOT_SUPPORTED;
        }
        else
        {
            LogRel(("OID_GEN_PHYSICAL_MEDIUM failed: Status (0x%x)", Status));
            AssertFailed();
        }
    }
    return Status;
}

DECLHIDDEN(bool) vboxNetFltWinIsPromiscuous(PVBOXNETFLTINS pNetFlt)
{
    /** @todo r=bird: This is too slow and is probably returning the wrong
     *        information. What we're interested in is whether someone besides us
     *        has put the interface into promiscuous mode. */
    NDIS_REQUEST request;
    NDIS_STATUS status;
    ULONG filter;
    Assert(VBOXNETFLT_PROMISCUOUS_SUPPORTED(pNetFlt));
    request.RequestType = NdisRequestQueryInformation;
    request.DATA.QUERY_INFORMATION.InformationBuffer = &filter;
    request.DATA.QUERY_INFORMATION.InformationBufferLength = sizeof(filter);
    request.DATA.QUERY_INFORMATION.Oid = OID_GEN_CURRENT_PACKET_FILTER;
    status = vboxNetFltWinSynchNdisRequest(pNetFlt, &request);
    if (status != NDIS_STATUS_SUCCESS)
    {
        /** @todo */
        AssertFailed();
        return false;
    }
    return (filter & NDIS_PACKET_TYPE_PROMISCUOUS) != 0;
}

DECLHIDDEN(NDIS_STATUS) vboxNetFltWinSetPromiscuous(PVBOXNETFLTINS pNetFlt, bool bYes)
{
/** @todo Need to report changes to the switch via:
 *  pThis->pSwitchPort->pfnReportPromiscuousMode(pThis->pSwitchPort, fPromisc);
 */
    Assert(VBOXNETFLT_PROMISCUOUS_SUPPORTED(pNetFlt));
    if (VBOXNETFLT_PROMISCUOUS_SUPPORTED(pNetFlt))
    {
        NDIS_REQUEST Request;
        NDIS_STATUS fStatus;
        ULONG fFilter;
        ULONG fExpectedFilter;
        ULONG fOurFilter;
        Request.RequestType = NdisRequestQueryInformation;
        Request.DATA.QUERY_INFORMATION.InformationBuffer = &fFilter;
        Request.DATA.QUERY_INFORMATION.InformationBufferLength = sizeof(fFilter);
        Request.DATA.QUERY_INFORMATION.Oid = OID_GEN_CURRENT_PACKET_FILTER;
        fStatus = vboxNetFltWinSynchNdisRequest(pNetFlt, &Request);
        if (fStatus != NDIS_STATUS_SUCCESS)
        {
            /** @todo */
            AssertFailed();
            return fStatus;
        }

        if (!pNetFlt->u.s.WinIf.StateFlags.fUpperProtSetFilterInitialized)
        {
            /* the cache was not initialized yet, initiate it with the current filter value */
            pNetFlt->u.s.WinIf.fUpperProtocolSetFilter = fFilter;
            pNetFlt->u.s.WinIf.StateFlags.fUpperProtSetFilterInitialized = TRUE;
        }


        if (bYes)
        {
            fExpectedFilter = NDIS_PACKET_TYPE_PROMISCUOUS;
            fOurFilter = NDIS_PACKET_TYPE_PROMISCUOUS;
        }
        else
        {
            fExpectedFilter = pNetFlt->u.s.WinIf.fUpperProtocolSetFilter;
            fOurFilter = 0;
        }

        if (fExpectedFilter != fFilter)
        {
            Request.RequestType = NdisRequestSetInformation;
            Request.DATA.SET_INFORMATION.InformationBuffer = &fExpectedFilter;
            Request.DATA.SET_INFORMATION.InformationBufferLength = sizeof(fExpectedFilter);
            Request.DATA.SET_INFORMATION.Oid = OID_GEN_CURRENT_PACKET_FILTER;
            fStatus = vboxNetFltWinSynchNdisRequest(pNetFlt, &Request);
            if (fStatus != NDIS_STATUS_SUCCESS)
            {
                /** @todo */
                AssertFailed();
                return fStatus;
            }
        }
        pNetFlt->u.s.WinIf.fOurSetFilter = fOurFilter;
        return fStatus;
    }
    return NDIS_STATUS_NOT_SUPPORTED;
}

#else /* VBOXNETADP */

/**
 *  Generates a new unique MAC address based on our vendor ID
 */
DECLHIDDEN(void) vboxNetFltWinGenerateMACAddress(RTMAC *pMac)
{
    /* temporary use a time info */
    uint64_t NanoTS = RTTimeSystemNanoTS();
    pMac->au8[0] = (uint8_t)((VBOXNETADP_VENDOR_ID >> 16) & 0xff);
    pMac->au8[1] = (uint8_t)((VBOXNETADP_VENDOR_ID >> 8) & 0xff);
    pMac->au8[2] = (uint8_t)(VBOXNETADP_VENDOR_ID & 0xff);
    pMac->au8[3] = (uint8_t)(NanoTS & 0xff0000);
    pMac->au16[2] = (uint16_t)(NanoTS & 0xffff);
}

DECLHIDDEN(int) vboxNetFltWinMAC2NdisString(RTMAC *pMac, PNDIS_STRING pNdisString)
{
    static const char s_achDigits[17] = "0123456789abcdef";
    PWSTR pString;

    /* validate parameters */
    AssertPtrReturn(pMac, VERR_INVALID_PARAMETER);
    AssertPtrReturn(pNdisString, VERR_INVALID_PARAMETER);
    AssertReturn(pNdisString->MaximumLength >= 13*sizeof(pNdisString->Buffer[0]), VERR_INVALID_PARAMETER);

    pString = pNdisString->Buffer;

    for (int i = 0; i < 6; i++)
    {
        uint8_t u8 = pMac->au8[i];
        pString[0] = s_achDigits[(u8 >>  4) & 0xf];
        pString[1] = s_achDigits[(u8/*>>0*/)& 0xf];
        pString += 2;
    }

    pNdisString->Length = 12*sizeof(pNdisString->Buffer[0]);

    *pString = L'\0';

    return VINF_SUCCESS;
}

static int vboxNetFltWinWchar2Byte(WCHAR c, uint8_t *pb)
{
    if (c >= L'A' && c <= L'F')
        *pb = (c - L'A') + 10;
    else if (c >= L'a' && c <= L'f')
        *pb = (c - L'a') + 10;
    else if (c >= L'0' && c <= L'9')
        *pb = (c - L'0');
    else
        return VERR_INVALID_PARAMETER;
    return VINF_SUCCESS;
}

DECLHIDDEN(int) vboxNetFltWinMACFromNdisString(RTMAC *pMac, PNDIS_STRING pNdisString)
{

    /* validate parameters */
    AssertPtrReturn(pMac, VERR_INVALID_PARAMETER);
    AssertPtrReturn(pNdisString, VERR_INVALID_PARAMETER);
    AssertReturn(pNdisString->Length >= 12*sizeof(pNdisString->Buffer[0]), VERR_INVALID_PARAMETER);

    int rc = VINF_SUCCESS;
    PWSTR pString = pNdisString->Buffer;
    for (int i = 0; i < 6; i++)
    {
        uint8_t v1, v2;
        rc = vboxNetFltWinWchar2Byte(pString[0], &v1);
        if (RT_FAILURE(rc))
            break;

        rc = vboxNetFltWinWchar2Byte(pString[1], &v2);
        if (RT_FAILURE(rc))
            break;

        pMac->au8[i] = (v1 << 4) | v2;

        pString += 2;
    }

    return rc;
}

#endif /* VBOXNETADP */

/**
 * creates a NDIS_PACKET from the PINTNETSG
 */
DECLHIDDEN(PNDIS_PACKET) vboxNetFltWinNdisPacketFromSG(PVBOXNETFLTINS pNetFlt, PINTNETSG pSG, PVOID pBufToFree, bool bToWire, bool bCopyMemory)
{
    NDIS_STATUS fStatus;
    PNDIS_PACKET pPacket;

    Assert(pSG->aSegs[0].pv);
    Assert(pSG->cbTotal >= VBOXNETFLT_PACKET_ETHEADER_SIZE);

/** @todo Hrmpf, how can we fix this assumption?  I fear this'll cause data
 *        corruption and maybe even BSODs ... */
    AssertReturn(pSG->cSegsUsed == 1 || bCopyMemory, NULL);

#ifdef VBOXNETADP
    NdisAllocatePacket(&fStatus, &pPacket, pNetFlt->u.s.WinIf.hRecvPacketPool);
#else
    NdisAllocatePacket(&fStatus, &pPacket, bToWire ? pNetFlt->u.s.WinIf.hSendPacketPool : pNetFlt->u.s.WinIf.hRecvPacketPool);
#endif
    if (fStatus == NDIS_STATUS_SUCCESS)
    {
        PNDIS_BUFFER pBuffer;
        PVOID pvMemBuf;

        /** @todo generally we do not always need to zero-initialize the complete OOB data here, reinitialize only when/what we need,
         * however we DO need to reset the status for the packets we indicate via NdisMIndicateReceivePacket to avoid packet loss
         * in case the status contains NDIS_STATUS_RESOURCES */
        VBOXNETFLT_OOB_INIT(pPacket);

        if (bCopyMemory)
        {
            fStatus = vboxNetFltWinMemAlloc(&pvMemBuf, pSG->cbTotal);
            Assert(fStatus == NDIS_STATUS_SUCCESS);
            if (fStatus == NDIS_STATUS_SUCCESS)
                IntNetSgRead(pSG, pvMemBuf);
        }
        else
        {
            pvMemBuf = pSG->aSegs[0].pv;
        }
        if (fStatus == NDIS_STATUS_SUCCESS)
        {
#ifdef VBOXNETADP
            NdisAllocateBuffer(&fStatus, &pBuffer,
                    pNetFlt->u.s.WinIf.hRecvBufferPool,
                    pvMemBuf,
                    pSG->cbTotal);
#else
            NdisAllocateBuffer(&fStatus, &pBuffer,
                    bToWire ? pNetFlt->u.s.WinIf.hSendBufferPool : pNetFlt->u.s.WinIf.hRecvBufferPool,
                    pvMemBuf,
                    pSG->cbTotal);
#endif

            if (fStatus == NDIS_STATUS_SUCCESS)
            {
                NdisChainBufferAtBack(pPacket, pBuffer);

                if (bToWire)
                {
                    PVBOXNETFLT_PKTRSVD_PT pSendInfo = (PVBOXNETFLT_PKTRSVD_PT)pPacket->ProtocolReserved;
                    pSendInfo->pOrigPacket = NULL;
                    pSendInfo->pBufToFree = pBufToFree;
#ifdef VBOX_LOOPBACK_USEFLAGS
                    /* set "don't loopback" flags */
                    NdisGetPacketFlags(pPacket) = g_VBoxNetFltGlobalsWin.fPacketDontLoopBack;
#else
                    NdisGetPacketFlags(pPacket) = 0;
#endif
                }
                else
                {
                    PVBOXNETFLT_PKTRSVD_MP pRecvInfo = (PVBOXNETFLT_PKTRSVD_MP)pPacket->MiniportReserved;
                    pRecvInfo->pOrigPacket = NULL;
                    pRecvInfo->pBufToFree = pBufToFree;

                    /* we must set the header size on receive */
                    NDIS_SET_PACKET_HEADER_SIZE(pPacket, VBOXNETFLT_PACKET_ETHEADER_SIZE);
                    /* NdisAllocatePacket zero-initializes the OOB data,
                     * but keeps the packet flags, clean them here */
                    NdisGetPacketFlags(pPacket) = 0;
                }
                /** @todo set out of bound data */
            }
            else
            {
                AssertFailed();
                if (bCopyMemory)
                {
                    vboxNetFltWinMemFree(pvMemBuf);
                }
                NdisFreePacket(pPacket);
                pPacket = NULL;
            }
        }
        else
        {
            AssertFailed();
            NdisFreePacket(pPacket);
            pPacket = NULL;
        }
    }
    else
    {
        pPacket = NULL;
    }

    DBG_CHECK_PACKET_AND_SG(pPacket, pSG);

    return pPacket;
}

/*
 * frees NDIS_PACKET created with vboxNetFltWinNdisPacketFromSG
 */
DECLHIDDEN(void) vboxNetFltWinFreeSGNdisPacket(PNDIS_PACKET pPacket, bool bFreeMem)
{
    UINT cBufCount;
    PNDIS_BUFFER pFirstBuffer;
    UINT uTotalPacketLength;
    PNDIS_BUFFER pBuffer;

    NdisQueryPacket(pPacket, NULL, &cBufCount, &pFirstBuffer, &uTotalPacketLength);

    Assert(cBufCount == 1);

    do
    {
        NdisUnchainBufferAtBack(pPacket, &pBuffer);
        if (pBuffer != NULL)
        {
            PVOID pvMemBuf;
            UINT cbLength;

            NdisQueryBufferSafe(pBuffer, &pvMemBuf, &cbLength, NormalPagePriority);
            NdisFreeBuffer(pBuffer);
            if (bFreeMem)
            {
                vboxNetFltWinMemFree(pvMemBuf);
            }
        }
        else
        {
            break;
        }
    } while (true);

    NdisFreePacket(pPacket);
}

#if !defined(VBOXNETADP)
static void vboxNetFltWinAssociateMiniportProtocol(PVBOXNETFLTGLOBALS_WIN pGlobalsWin)
{
    NdisIMAssociateMiniport(pGlobalsWin->Mp.hMiniport, pGlobalsWin->Pt.hProtocol);
}
#endif

/*
 * NetFlt driver unload function
 */
DECLHIDDEN(VOID) vboxNetFltWinUnload(IN PDRIVER_OBJECT DriverObject)
{
    int rc;
    UNREFERENCED_PARAMETER(DriverObject);

    LogFlowFunc(("ENTER: DO (0x%x)\n", DriverObject));

    rc = vboxNetFltWinFiniIdc();
    if (RT_FAILURE(rc))
    {
        /** @todo we can not prevent driver unload here */
        AssertFailed();

        LogFlowFunc(("vboxNetFltWinFiniIdc - failed, busy.\n"));
    }

    vboxNetFltWinJobFiniQueue(&g_VBoxJobQueue);
#ifndef VBOXNETADP
    vboxNetFltWinPtDeregister(&g_VBoxNetFltGlobalsWin.Pt);
#endif

    vboxNetFltWinMpDeregister(&g_VBoxNetFltGlobalsWin.Mp);

#ifndef VBOXNETADP
    NdisFreeSpinLock(&g_VBoxNetFltGlobalsWin.lockFilters);
#endif /* VBOXNETADP */

    LogFlow(("LEAVE: DO (0x%x)\n", DriverObject));

    vboxNetFltWinFiniNetFltBase();
    /* don't use logging or any RT after de-init */
}

RT_C_DECLS_BEGIN

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

RT_C_DECLS_END

NTSTATUS DriverEntry(IN PDRIVER_OBJECT DriverObject, IN PUNICODE_STRING RegistryPath)
{
    NDIS_STATUS Status = NDIS_STATUS_SUCCESS;
    int rc;

    /* the idc registration is initiated via IOCTL since our driver
     * can be loaded when the VBoxDrv is not in case we are a Ndis IM driver */
    rc = vboxNetFltWinInitNetFltBase();
    AssertRC(rc);
    if (RT_SUCCESS(rc))
    {
        Status = vboxNetFltWinJobInitQueue(&g_VBoxJobQueue);
        Assert(Status == STATUS_SUCCESS);
        if (Status == STATUS_SUCCESS)
        {
            ULONG MjVersion;
            ULONG MnVersion;

            /* note: we do it after we initialize the Job Queue */
            vboxNetFltWinStartInitIdcProbing();

            NdisZeroMemory(&g_VBoxNetFltGlobalsWin, sizeof (g_VBoxNetFltGlobalsWin));
            KeInitializeEvent(&g_VBoxNetFltGlobalsWin.SynchEvent, SynchronizationEvent, TRUE /* signalled*/);

            PsGetVersion(&MjVersion, &MnVersion,
              NULL, /* PULONG BuildNumber OPTIONAL */
              NULL /* PUNICODE_STRING CSDVersion OPTIONAL */
              );

            g_VBoxNetFltGlobalsWin.fPacketDontLoopBack = NDIS_FLAGS_DONT_LOOPBACK;

            if (MjVersion == 5 && MnVersion == 0)
            {
                /* this is Win2k, we don't support it actually, but just in case */
                g_VBoxNetFltGlobalsWin.fPacketDontLoopBack |= NDIS_FLAGS_SKIP_LOOPBACK_W2K;
            }

            g_VBoxNetFltGlobalsWin.fPacketIsLoopedBack = NDIS_FLAGS_IS_LOOPBACK_PACKET;

#ifndef VBOXNETADP
            RTListInit(&g_VBoxNetFltGlobalsWin.listFilters);
            NdisAllocateSpinLock(&g_VBoxNetFltGlobalsWin.lockFilters);
#endif

            Status = vboxNetFltWinMpRegister(&g_VBoxNetFltGlobalsWin.Mp, DriverObject, RegistryPath);
            Assert(Status == STATUS_SUCCESS);
            if (Status == NDIS_STATUS_SUCCESS)
            {
#ifndef VBOXNETADP
                Status = vboxNetFltWinPtRegister(&g_VBoxNetFltGlobalsWin.Pt, DriverObject, RegistryPath);
                Assert(Status == STATUS_SUCCESS);
                if (Status == NDIS_STATUS_SUCCESS)
#endif
                {
#ifndef VBOXNETADP
                    vboxNetFltWinAssociateMiniportProtocol(&g_VBoxNetFltGlobalsWin);
#endif
                    return STATUS_SUCCESS;

//#ifndef VBOXNETADP
//                vboxNetFltWinPtDeregister(&g_VBoxNetFltGlobalsWin.Pt);
//#endif
                }
#ifndef VBOXNETADP /* unreachable for VBOXNETADP because of the above return */
                vboxNetFltWinMpDeregister(&g_VBoxNetFltGlobalsWin.Mp);
# ifndef VBOXNETADP
                NdisFreeSpinLock(&g_VBoxNetFltGlobalsWin.lockFilters);
# endif
#endif
            }
            vboxNetFltWinJobFiniQueue(&g_VBoxJobQueue);
        }
        vboxNetFltWinFiniNetFlt();
    }
    else
    {
        Status = NDIS_STATUS_FAILURE;
    }

    return Status;
}

#ifndef VBOXNETADP
/**
 * creates and initializes the packet to be sent to the underlying miniport given a packet posted to our miniport edge
 * according to DDK docs we must create our own packet rather than posting the one passed to us
 */
DECLHIDDEN(NDIS_STATUS) vboxNetFltWinPrepareSendPacket(PVBOXNETFLTINS pNetFlt, PNDIS_PACKET pPacket, PNDIS_PACKET *ppMyPacket)
{
    NDIS_STATUS Status;

    NdisAllocatePacket(&Status, ppMyPacket, pNetFlt->u.s.WinIf.hSendPacketPool);

    if (Status == NDIS_STATUS_SUCCESS)
    {
        PVBOXNETFLT_PKTRSVD_PT pSendInfo = (PVBOXNETFLT_PKTRSVD_PT)((*ppMyPacket)->ProtocolReserved);
        pSendInfo->pOrigPacket = pPacket;
        pSendInfo->pBufToFree = NULL;
        /* the rest will be filled on send */

        vboxNetFltWinCopyPacketInfoOnSend(*ppMyPacket, pPacket);

#ifdef VBOX_LOOPBACK_USEFLAGS
        NdisGetPacketFlags(*ppMyPacket) |= g_VBoxNetFltGlobalsWin.fPacketDontLoopBack;
#endif
    }
    else
    {
        *ppMyPacket = NULL;
    }

    return Status;
}

/**
 * creates and initializes the packet to be sent to the upperlying protocol given a packet indicated to our protocol edge
 * according to DDK docs we must create our own packet rather than posting the one passed to us
 */
DECLHIDDEN(NDIS_STATUS) vboxNetFltWinPrepareRecvPacket(PVBOXNETFLTINS pNetFlt, PNDIS_PACKET pPacket, PNDIS_PACKET *ppMyPacket, bool bDpr)
{
    NDIS_STATUS Status;

    if (bDpr)
    {
        Assert(KeGetCurrentIrql() == DISPATCH_LEVEL);
        NdisDprAllocatePacket(&Status, ppMyPacket, pNetFlt->u.s.WinIf.hRecvPacketPool);
    }
    else
    {
        NdisAllocatePacket(&Status, ppMyPacket, pNetFlt->u.s.WinIf.hRecvPacketPool);
    }

    if (Status == NDIS_STATUS_SUCCESS)
    {
        PVBOXNETFLT_PKTRSVD_MP pRecvInfo = (PVBOXNETFLT_PKTRSVD_MP)((*ppMyPacket)->MiniportReserved);
        pRecvInfo->pOrigPacket = pPacket;
        pRecvInfo->pBufToFree = NULL;

        Status = vboxNetFltWinCopyPacketInfoOnRecv(*ppMyPacket, pPacket, false);
    }
    else
    {
        *ppMyPacket = NULL;
    }
    return Status;
}
#endif
/**
 * initializes the VBOXNETFLTINS (our context structure) and binds to the given adapter
 */
#if defined(VBOXNETADP)
DECLHIDDEN(NDIS_STATUS) vboxNetFltWinPtInitBind(PVBOXNETFLTINS *ppNetFlt, NDIS_HANDLE hMiniportAdapter, PNDIS_STRING pBindToMiniportName /* actually this is our miniport name*/, NDIS_HANDLE hWrapperConfigurationContext)
#else
DECLHIDDEN(NDIS_STATUS) vboxNetFltWinPtInitBind(PVBOXNETFLTINS *ppNetFlt, PNDIS_STRING pOurMiniportName, PNDIS_STRING pBindToMiniportName)
#endif
{
    NDIS_STATUS Status;
    do
    {
        ANSI_STRING AnsiString;
        int rc;
        PVBOXNETFLTINS pInstance;
        USHORT cbAnsiName = pBindToMiniportName->Length;/* the length is is bytes ; *2 ;RtlUnicodeStringToAnsiSize(pBindToMiniportName)*/
        CREATE_INSTANCE_CONTEXT Context;

# ifndef VBOXNETADP
        Context.pOurName = pOurMiniportName;
        Context.pBindToName = pBindToMiniportName;
# else
        Context.hMiniportAdapter = hMiniportAdapter;
        Context.hWrapperConfigurationContext = hWrapperConfigurationContext;
# endif
        Context.Status = NDIS_STATUS_SUCCESS;

        AnsiString.Buffer = 0; /* will be allocated by RtlUnicodeStringToAnsiString */
        AnsiString.Length = 0;
        AnsiString.MaximumLength = cbAnsiName;

        Assert(KeGetCurrentIrql() == PASSIVE_LEVEL);

        Status = RtlUnicodeStringToAnsiString(&AnsiString, pBindToMiniportName, true);

        if (Status != STATUS_SUCCESS)
        {
            break;
        }

        rc = vboxNetFltSearchCreateInstance(&g_VBoxNetFltGlobals, AnsiString.Buffer, &pInstance, &Context);
        RtlFreeAnsiString(&AnsiString);
        if (RT_FAILURE(rc))
        {
            AssertFailed();
            Status = Context.Status != NDIS_STATUS_SUCCESS ? Context.Status : NDIS_STATUS_FAILURE;
            break;
        }

        Assert(pInstance);

        if (rc == VINF_ALREADY_INITIALIZED)
        {
            /* the case when our adapter was unbound while IntNet was connected to it */
            /* the instance remains valid until IntNet disconnects from it, we simply search and re-use it*/
            rc = vboxNetFltWinAttachToInterface(pInstance, &Context, true);
            if (RT_FAILURE(rc))
            {
                AssertFailed();
                Status = Context.Status != NDIS_STATUS_SUCCESS ? Context.Status : NDIS_STATUS_FAILURE;
                /* release netflt */
                vboxNetFltRelease(pInstance, false);

                break;
            }
        }

        *ppNetFlt = pInstance;

    } while (FALSE);

    return Status;
}
/*
 * deinitializes the VBOXNETFLTWIN
 */
DECLHIDDEN(VOID) vboxNetFltWinPtFiniWinIf(PVBOXNETFLTWIN pWinIf)
{
#ifndef VBOXNETADP
    int rc;
#endif

    LogFlowFunc(("ENTER: pWinIf 0x%p\n", pWinIf));

    Assert(KeGetCurrentIrql() == PASSIVE_LEVEL);
#ifndef VBOXNETADP
    if (pWinIf->MpDeviceName.Buffer)
    {
        vboxNetFltWinMemFree(pWinIf->MpDeviceName.Buffer);
    }

    FINI_INTERLOCKED_SINGLE_LIST(&pWinIf->TransferDataList);
# if defined(DEBUG_NETFLT_LOOPBACK) || !defined(VBOX_LOOPBACK_USEFLAGS)
    FINI_INTERLOCKED_SINGLE_LIST(&pWinIf->SendPacketQueue);
# endif
    NdisFreeBufferPool(pWinIf->hSendBufferPool);
    NdisFreePacketPool(pWinIf->hSendPacketPool);
    rc = RTSemFastMutexDestroy(pWinIf->hSynchRequestMutex);  AssertRC(rc);
#endif

    /* NOTE: NULL is a valid handle */
    NdisFreeBufferPool(pWinIf->hRecvBufferPool);
    NdisFreePacketPool(pWinIf->hRecvPacketPool);

    LogFlowFunc(("LEAVE: pWinIf 0x%p\n", pWinIf));
}

#ifndef VBOXNETADP
DECLHIDDEN(NDIS_STATUS) vboxNetFltWinPtInitWinIf(PVBOXNETFLTWIN pWinIf, IN PNDIS_STRING pOurDeviceName)
#else
DECLHIDDEN(NDIS_STATUS) vboxNetFltWinPtInitWinIf(PVBOXNETFLTWIN pWinIf)
#endif
{
    NDIS_STATUS Status = NDIS_STATUS_SUCCESS;
#ifndef VBOXNETADP
    int rc;
#endif

    LogFlowFunc(("ENTER: pWinIf 0x%p\n", pWinIf));

    Assert(KeGetCurrentIrql() == PASSIVE_LEVEL);

    NdisZeroMemory(pWinIf, sizeof (VBOXNETFLTWIN));
    NdisAllocatePacketPoolEx(&Status, &pWinIf->hRecvPacketPool,
                               VBOXNETFLT_PACKET_POOL_SIZE_NORMAL,
                               VBOXNETFLT_PACKET_POOL_SIZE_OVERFLOW,
                               PROTOCOL_RESERVED_SIZE_IN_PACKET);
    Assert(Status == NDIS_STATUS_SUCCESS);
    if (Status == NDIS_STATUS_SUCCESS)
    {
        /* NOTE: NULL is a valid handle !!! */
        NdisAllocateBufferPool(&Status, &pWinIf->hRecvBufferPool, VBOXNETFLT_BUFFER_POOL_SIZE_RX);
        Assert(Status == NDIS_STATUS_SUCCESS);
        if (Status == NDIS_STATUS_SUCCESS)
        {
            pWinIf->MpState.PowerState = NdisDeviceStateD3;
            vboxNetFltWinSetOpState(&pWinIf->MpState, kVBoxNetDevOpState_Deinitialized);
#ifndef VBOXNETADP
            pWinIf->PtState.PowerState = NdisDeviceStateD3;
            vboxNetFltWinSetOpState(&pWinIf->PtState, kVBoxNetDevOpState_Deinitialized);

            NdisAllocateBufferPool(&Status,
                    &pWinIf->hSendBufferPool,
                    VBOXNETFLT_BUFFER_POOL_SIZE_TX);
            Assert(Status == NDIS_STATUS_SUCCESS);
            if (Status == NDIS_STATUS_SUCCESS)
            {
                INIT_INTERLOCKED_SINGLE_LIST(&pWinIf->TransferDataList);

# if defined(DEBUG_NETFLT_LOOPBACK) || !defined(VBOX_LOOPBACK_USEFLAGS)
                INIT_INTERLOCKED_SINGLE_LIST(&pWinIf->SendPacketQueue);
# endif
                NdisInitializeEvent(&pWinIf->OpenCloseEvent);

                KeInitializeEvent(&pWinIf->hSynchCompletionEvent, SynchronizationEvent, FALSE);

                NdisInitializeEvent(&pWinIf->MpInitCompleteEvent);

                NdisAllocatePacketPoolEx(&Status, &pWinIf->hSendPacketPool,
                                           VBOXNETFLT_PACKET_POOL_SIZE_NORMAL,
                                           VBOXNETFLT_PACKET_POOL_SIZE_OVERFLOW,
                                           sizeof (PVBOXNETFLT_PKTRSVD_PT));
                Assert(Status == NDIS_STATUS_SUCCESS);
                if (Status == NDIS_STATUS_SUCCESS)
                {
                    rc = RTSemFastMutexCreate(&pWinIf->hSynchRequestMutex);
                    AssertRC(rc);
                    if (RT_SUCCESS(rc))
                    {
                        Status = vboxNetFltWinMemAlloc((PVOID*)&pWinIf->MpDeviceName.Buffer, pOurDeviceName->Length);
                        Assert(Status == NDIS_STATUS_SUCCESS);
                        if (Status == NDIS_STATUS_SUCCESS)
                        {
                            pWinIf->MpDeviceName.MaximumLength = pOurDeviceName->Length;
                            pWinIf->MpDeviceName.Length = 0;
                            Status = vboxNetFltWinCopyString(&pWinIf->MpDeviceName, pOurDeviceName);
#endif
                            return NDIS_STATUS_SUCCESS;
#ifndef VBOXNETADP
                            // unreachable: vboxNetFltWinMemFree(pWinIf->MpDeviceName.Buffer);
                        }
                        RTSemFastMutexDestroy(pWinIf->hSynchRequestMutex);
                    }
                    else
                        Status = NDIS_STATUS_FAILURE;
                    NdisFreePacketPool(pWinIf->hSendPacketPool);
                }
                NdisFreeBufferPool(pWinIf->hSendBufferPool);
            }
            NdisFreeBufferPool(pWinIf->hRecvBufferPool);
#endif
        }
        NdisFreePacketPool(pWinIf->hRecvPacketPool);
    }

    LogFlowFunc(("LEAVE: pWinIf 0x%p, Status 0x%x\n", pWinIf, Status));

    return Status;
}

/**
 * match packets
 */
#define NEXT_LIST_ENTRY(_Entry) ((_Entry)->Flink)
#define PREV_LIST_ENTRY(_Entry) ((_Entry)->Blink)
#define FIRST_LIST_ENTRY NEXT_LIST_ENTRY
#define LAST_LIST_ENTRY PREV_LIST_ENTRY

#define MIN(_a, _b) ((_a) < (_b) ? (_a) : (_b))

#ifndef VBOXNETADP

#ifdef DEBUG_misha

RTMAC g_vboxNetFltWinVerifyMACBroadcast = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
RTMAC g_vboxNetFltWinVerifyMACGuest = {0x08, 0x00, 0x27, 0x01, 0x02, 0x03};

DECLHIDDEN(PRTNETETHERHDR) vboxNetFltWinGetEthHdr(PNDIS_PACKET pPacket)
{
    UINT cBufCount1;
    PNDIS_BUFFER pBuffer1;
    UINT uTotalPacketLength1;
    RTNETETHERHDR* pEth;
    UINT cbLength1 = 0;
    UINT i = 0;

    NdisQueryPacket(pPacket, NULL, &cBufCount1, &pBuffer1, &uTotalPacketLength1);

    Assert(pBuffer1);
    Assert(uTotalPacketLength1 >= VBOXNETFLT_PACKET_ETHEADER_SIZE);
    if (uTotalPacketLength1 < VBOXNETFLT_PACKET_ETHEADER_SIZE)
        return NULL;

    NdisQueryBufferSafe(pBuffer1, &pEth, &cbLength1, NormalPagePriority);
    Assert(cbLength1 >= VBOXNETFLT_PACKET_ETHEADER_SIZE);
    if (cbLength1 < VBOXNETFLT_PACKET_ETHEADER_SIZE)
        return NULL;

    return pEth;
}

DECLHIDDEN(PRTNETETHERHDR) vboxNetFltWinGetEthHdrSG(PINTNETSG pSG)
{
    Assert(pSG->cSegsUsed);
    Assert(pSG->cSegsAlloc >= pSG->cSegsUsed);
    Assert(pSG->aSegs[0].cb >= VBOXNETFLT_PACKET_ETHEADER_SIZE);

    if (!pSG->cSegsUsed)
        return NULL;

    if (pSG->aSegs[0].cb < VBOXNETFLT_PACKET_ETHEADER_SIZE)
        return NULL;

    return (PRTNETETHERHDR)pSG->aSegs[0].pv;
}

DECLHIDDEN(bool) vboxNetFltWinCheckMACs(PNDIS_PACKET pPacket, PRTMAC pDst, PRTMAC pSrc)
{
    PRTNETETHERHDR pHdr = vboxNetFltWinGetEthHdr(pPacket);
    Assert(pHdr);

    if (!pHdr)
        return false;

    if (pDst && memcmp(pDst, &pHdr->DstMac, sizeof(RTMAC)))
        return false;

    if (pSrc && memcmp(pSrc, &pHdr->SrcMac, sizeof(RTMAC)))
        return false;

    return true;
}

DECLHIDDEN(bool) vboxNetFltWinCheckMACsSG(PINTNETSG pSG, PRTMAC pDst, PRTMAC pSrc)
{
    PRTNETETHERHDR pHdr = vboxNetFltWinGetEthHdrSG(pSG);
    Assert(pHdr);

    if (!pHdr)
        return false;

    if (pDst && memcmp(pDst, &pHdr->DstMac, sizeof(RTMAC)))
        return false;

    if (pSrc && memcmp(pSrc, &pHdr->SrcMac, sizeof(RTMAC)))
        return false;

    return true;
}
#endif

# if !defined(VBOX_LOOPBACK_USEFLAGS) || defined(DEBUG_NETFLT_PACKETS)
/*
 * answers whether the two given packets match based on the packet length and the first cbMatch bytes of the packets
 * if cbMatch < 0 matches complete packets.
 */
DECLHIDDEN(bool) vboxNetFltWinMatchPackets(PNDIS_PACKET pPacket1, PNDIS_PACKET pPacket2, const INT cbMatch)
{
    UINT cBufCount1;
    PNDIS_BUFFER pBuffer1;
    UINT uTotalPacketLength1;
    uint8_t *pbMemBuf1 = NULL;
    UINT cbLength1 = 0;

    UINT cBufCount2;
    PNDIS_BUFFER pBuffer2;
    UINT uTotalPacketLength2;
    uint8_t *pbMemBuf2 = NULL;
    UINT cbLength2 = 0;
    bool bMatch = true;

#ifdef DEBUG_NETFLT_PACKETS
    bool bCompleteMatch = false;
#endif

    NdisQueryPacket(pPacket1, NULL, &cBufCount1, &pBuffer1, &uTotalPacketLength1);
    NdisQueryPacket(pPacket2, NULL, &cBufCount2, &pBuffer2, &uTotalPacketLength2);

    Assert(pBuffer1);
    Assert(pBuffer2);

    if (uTotalPacketLength1 != uTotalPacketLength2)
    {
        bMatch = false;
    }
    else
    {
        UINT ucbLength2Match = 0;
        UINT ucbMatch;
        if (cbMatch < 0 || (UINT)cbMatch > uTotalPacketLength1)
        {
            /* NOTE: assuming uTotalPacketLength1 == uTotalPacketLength2*/
            ucbMatch = uTotalPacketLength1;
#ifdef DEBUG_NETFLT_PACKETS
            bCompleteMatch = true;
#endif
        }
        else
        {
            ucbMatch = (UINT)cbMatch;
        }

        for (;;)
        {
            if (!cbLength1)
            {
                NdisQueryBufferSafe(pBuffer1, &pbMemBuf1, &cbLength1, NormalPagePriority);
                NdisGetNextBuffer(pBuffer1, &pBuffer1);
            }
            else
            {
                Assert(pbMemBuf1);
                Assert(ucbLength2Match);
                pbMemBuf1 += ucbLength2Match;
            }

            if (!cbLength2)
            {
                NdisQueryBufferSafe(pBuffer2, &pbMemBuf2, &cbLength2, NormalPagePriority);
                NdisGetNextBuffer(pBuffer2, &pBuffer2);
            }
            else
            {
                Assert(pbMemBuf2);
                Assert(ucbLength2Match);
                pbMemBuf2 += ucbLength2Match;
            }

            ucbLength2Match = MIN(ucbMatch, cbLength1);
            ucbLength2Match = MIN(ucbLength2Match, cbLength2);

            if (memcmp(pbMemBuf1, pbMemBuf2, ucbLength2Match))
            {
                bMatch = false;
                break;
            }

            ucbMatch -= ucbLength2Match;
            if (!ucbMatch)
                break;

            cbLength1 -= ucbLength2Match;
            cbLength2 -= ucbLength2Match;
        }
    }

#ifdef DEBUG_NETFLT_PACKETS
    if (bMatch && !bCompleteMatch)
    {
        /* check that the packets fully match */
        DBG_CHECK_PACKETS(pPacket1, pPacket2);
    }
#endif

    return bMatch;
}

/*
 * answers whether the ndis packet and PINTNETSG match based on the packet length and the first cbMatch bytes of the packet and PINTNETSG
 * if cbMatch < 0 matches complete packets.
 */
DECLHIDDEN(bool) vboxNetFltWinMatchPacketAndSG(PNDIS_PACKET pPacket, PINTNETSG pSG, const INT cbMatch)
{
    UINT cBufCount1;
    PNDIS_BUFFER pBuffer1;
    UINT uTotalPacketLength1;
    uint8_t *pbMemBuf1 = NULL;
    UINT cbLength1 = 0;
    UINT uTotalPacketLength2 = pSG->cbTotal;
    uint8_t *pbMemBuf2 = NULL;
    UINT cbLength2 = 0;
    bool bMatch = true;
    bool bCompleteMatch = false;
    UINT i = 0;

    NdisQueryPacket(pPacket, NULL, &cBufCount1, &pBuffer1, &uTotalPacketLength1);

    Assert(pBuffer1);
    Assert(pSG->cSegsUsed);
    Assert(pSG->cSegsAlloc >= pSG->cSegsUsed);

    if (uTotalPacketLength1 != uTotalPacketLength2)
    {
        AssertFailed();
        bMatch = false;
    }
    else
    {
        UINT ucbLength2Match = 0;
        UINT ucbMatch;

        if (cbMatch < 0 || (UINT)cbMatch > uTotalPacketLength1)
        {
            /* NOTE: assuming uTotalPacketLength1 == uTotalPacketLength2*/
            ucbMatch = uTotalPacketLength1;
            bCompleteMatch = true;
        }
        else
        {
            ucbMatch = (UINT)cbMatch;
        }

        for (;;)
        {
            if (!cbLength1)
            {
                NdisQueryBufferSafe(pBuffer1, &pbMemBuf1, &cbLength1, NormalPagePriority);
                NdisGetNextBuffer(pBuffer1, &pBuffer1);
            }
            else
            {
                Assert(pbMemBuf1);
                Assert(ucbLength2Match);
                pbMemBuf1 += ucbLength2Match;
            }

            if (!cbLength2)
            {
                Assert(i < pSG->cSegsUsed);
                pbMemBuf2 = (uint8_t*)pSG->aSegs[i].pv;
                cbLength2 = pSG->aSegs[i].cb;
                i++;
            }
            else
            {
                Assert(pbMemBuf2);
                Assert(ucbLength2Match);
                pbMemBuf2 += ucbLength2Match;
            }

            ucbLength2Match = MIN(ucbMatch, cbLength1);
            ucbLength2Match = MIN(ucbLength2Match, cbLength2);

            if (memcmp(pbMemBuf1, pbMemBuf2, ucbLength2Match))
            {
                bMatch = false;
                AssertFailed();
                break;
            }

            ucbMatch -= ucbLength2Match;
            if (!ucbMatch)
                break;

            cbLength1 -= ucbLength2Match;
            cbLength2 -= ucbLength2Match;
        }
    }

    if (bMatch && !bCompleteMatch)
    {
        /* check that the packets fully match */
        DBG_CHECK_PACKET_AND_SG(pPacket, pSG);
    }
    return bMatch;
}

#  if 0
/*
 * answers whether the two PINTNETSGs match based on the packet length and the first cbMatch bytes of the PINTNETSG
 * if cbMatch < 0 matches complete packets.
 */
static bool vboxNetFltWinMatchSGs(PINTNETSG pSG1, PINTNETSG pSG2, const INT cbMatch)
{
    UINT uTotalPacketLength1 = pSG1->cbTotal;
    PVOID pbMemBuf1 = NULL;
    UINT cbLength1 = 0;
    UINT i1 = 0;
    UINT uTotalPacketLength2 = pSG2->cbTotal;
    PVOID pbMemBuf2 = NULL;
    UINT cbLength2 = 0;

    bool bMatch = true;
    bool bCompleteMatch = false;
    UINT i2 = 0;

    Assert(pSG1->cSegsUsed);
    Assert(pSG2->cSegsUsed);
    Assert(pSG1->cSegsAlloc >= pSG1->cSegsUsed);
    Assert(pSG2->cSegsAlloc >= pSG2->cSegsUsed);

    if (uTotalPacketLength1 != uTotalPacketLength2)
    {
        AssertFailed();
        bMatch = false;
    }
    else
    {
        UINT ucbMatch;
        if (cbMatch < 0 || (UINT)cbMatch > uTotalPacketLength1)
        {
            /* NOTE: assuming uTotalPacketLength1 == uTotalPacketLength2*/
            ucbMatch = uTotalPacketLength1;
            bCompleteMatch = true;
        }
        else
        {
            ucbMatch = (UINT)cbMatch;
        }

        do
        {
            UINT ucbLength2Match;
            if (!cbLength1)
            {
                Assert(i1 < pSG1->cSegsUsed);
                pbMemBuf1 = pSG1->aSegs[i1].pv;
                cbLength1 = pSG1->aSegs[i1].cb;
                i1++;
            }

            if (!cbLength2)
            {
                Assert(i2 < pSG2->cSegsUsed);
                pbMemBuf2 = pSG2->aSegs[i2].pv;
                cbLength2 = pSG2->aSegs[i2].cb;
                i2++;
            }

            ucbLength2Match = MIN(ucbMatch, cbLength1);
            ucbLength2Match = MIN(ucbLength2Match, cbLength2);

            if (memcmp(pbMemBuf1, pbMemBuf2, ucbLength2Match))
            {
                bMatch = false;
                AssertFailed();
                break;
            }
            ucbMatch -= ucbLength2Match;
            cbLength1 -= ucbLength2Match;
            cbLength2 -= ucbLength2Match;
        } while (ucbMatch);
    }

    if (bMatch && !bCompleteMatch)
    {
        /* check that the packets fully match */
        DBG_CHECK_SGS(pSG1, pSG2);
    }
    return bMatch;
}
#  endif
# endif
#endif

static void vboxNetFltWinFiniNetFltBase()
{
    do
    {
        vboxNetFltDeleteGlobals(&g_VBoxNetFltGlobals);

        /*
         * Undo the work done during start (in reverse order).
         */
        memset(&g_VBoxNetFltGlobals, 0, sizeof(g_VBoxNetFltGlobals));

        RTLogDestroy(RTLogRelSetDefaultInstance(NULL));
        RTLogDestroy(RTLogSetDefaultInstance(NULL));

        RTR0Term();
    } while (0);
}

/*
 * Defines max timeout for waiting for driver unloading
 * (3000 * 100 ms = 5 minutes)
 */
#define MAX_UNLOAD_PROBES 3000

static int vboxNetFltWinFiniIdc()
{
    int rc;
    int i;

    vboxNetFltWinStopInitIdcProbing();

    if (g_bVBoxIdcInitialized)
    {
         for (i = 0; (rc = vboxNetFltTryDeleteIdc(&g_VBoxNetFltGlobals)) == VERR_WRONG_ORDER
            && i < MAX_UNLOAD_PROBES; i++)
        {
            RTThreadSleep(100);
        }
        if (i == MAX_UNLOAD_PROBES)
        {
            // seems something hungs in driver
            LogFlow(("vboxNetFltWinFiniIdc - Can't delete Idc. pInH=%p cFRefs=%d fIDcOpen=%s",
                        g_VBoxNetFltGlobals.pInstanceHead, g_VBoxNetFltGlobals.cFactoryRefs,
                        g_VBoxNetFltGlobals.fIDCOpen ? "true" : "false"));
            LogFlow(("vboxNetFltWinFiniIdc g_VBoxNetFltGlobalsWin cDvRefs=%d hDev=%x pDev=%p Mp=%x \n",
                        g_VBoxNetFltGlobalsWin.cDeviceRefs, g_VBoxNetFltGlobalsWin.hDevice,
                        g_VBoxNetFltGlobalsWin.pDevObj, g_VBoxNetFltGlobalsWin.Mp.hMiniport));
            Assert(i == MAX_UNLOAD_PROBES);
            return VERR_WRONG_ORDER;
        }

        if (RT_SUCCESS(rc))
        {
            g_bVBoxIdcInitialized = false;
        }
    }
    else
    {
        rc = VINF_SUCCESS;
    }
    return rc;

}

static int vboxNetFltWinFiniNetFlt()
{
    int rc = vboxNetFltWinFiniIdc();
    if (RT_SUCCESS(rc))
    {
        vboxNetFltWinFiniNetFltBase();
    }
    return rc;
}

/**
 * base netflt initialization
 */
static int vboxNetFltWinInitNetFltBase()
{
    int rc;

    do
    {
        Assert(!g_bVBoxIdcInitialized);

        rc = RTR0Init(0);
        if (!RT_SUCCESS(rc))
        {
            break;
        }

        memset(&g_VBoxNetFltGlobals, 0, sizeof(g_VBoxNetFltGlobals));
        rc = vboxNetFltInitGlobals(&g_VBoxNetFltGlobals);
        if (!RT_SUCCESS(rc))
        {
            RTR0Term();
            break;
        }
    }while (0);

    return rc;
}

/**
 * initialize IDC
 */
static int vboxNetFltWinInitIdc()
{
    int rc;

    do
    {
        if (g_bVBoxIdcInitialized)
        {
            rc = VINF_ALREADY_INITIALIZED;
            break;
        }

        /*
         * connect to the support driver.
         *
         * This will call back vboxNetFltOsOpenSupDrv (and maybe vboxNetFltOsCloseSupDrv)
         * for establishing the connect to the support driver.
         */
        rc = vboxNetFltInitIdc(&g_VBoxNetFltGlobals);
        if (!RT_SUCCESS(rc))
        {
            break;
        }

        g_bVBoxIdcInitialized = true;
    } while (0);

    return rc;
}

static VOID vboxNetFltWinInitIdcProbingWorker(PVOID pvContext)
{
    PINIT_IDC_INFO pInitIdcInfo = (PINIT_IDC_INFO)pvContext;
    int rc = vboxNetFltWinInitIdc();
    if (RT_FAILURE(rc))
    {
        bool bInterupted = ASMAtomicUoReadBool(&pInitIdcInfo->bStop);
        if (!bInterupted)
        {
            RTThreadSleep(1000); /* 1 s */
            bInterupted = ASMAtomicUoReadBool(&pInitIdcInfo->bStop);
            if (!bInterupted)
            {
                vboxNetFltWinJobEnqueueJob(&g_VBoxJobQueue, &pInitIdcInfo->Job, false);
                return;
            }
        }

        /* it's interrupted */
        rc = VERR_INTERRUPTED;
    }

    ASMAtomicUoWriteS32(&pInitIdcInfo->rc, rc);
    KeSetEvent(&pInitIdcInfo->hCompletionEvent, 0, FALSE);
}

static int vboxNetFltWinStopInitIdcProbing()
{
    if (!g_VBoxInitIdcInfo.bInitialized)
        return VERR_INVALID_STATE;

    ASMAtomicUoWriteBool(&g_VBoxInitIdcInfo.bStop, true);
    KeWaitForSingleObject(&g_VBoxInitIdcInfo.hCompletionEvent, Executive, KernelMode, FALSE, NULL);

    return g_VBoxInitIdcInfo.rc;
}

static int vboxNetFltWinStartInitIdcProbing()
{
    Assert(!g_bVBoxIdcInitialized);
    KeInitializeEvent(&g_VBoxInitIdcInfo.hCompletionEvent, NotificationEvent, FALSE);
    g_VBoxInitIdcInfo.bStop = false;
    g_VBoxInitIdcInfo.bInitialized = true;
    vboxNetFltWinJobInit(&g_VBoxInitIdcInfo.Job, vboxNetFltWinInitIdcProbingWorker, &g_VBoxInitIdcInfo, false);
    vboxNetFltWinJobEnqueueJob(&g_VBoxJobQueue, &g_VBoxInitIdcInfo.Job, false);
    return VINF_SUCCESS;
}

static int vboxNetFltWinInitNetFlt()
{
    int rc;

    do
    {
        rc = vboxNetFltWinInitNetFltBase();
        if (RT_FAILURE(rc))
        {
            AssertFailed();
            break;
        }

        /*
         * connect to the support driver.
         *
         * This will call back vboxNetFltOsOpenSupDrv (and maybe vboxNetFltOsCloseSupDrv)
         * for establishing the connect to the support driver.
         */
        rc = vboxNetFltWinInitIdc();
        if (RT_FAILURE(rc))
        {
            AssertFailed();
            vboxNetFltWinFiniNetFltBase();
            break;
        }
    } while (0);

    return rc;
}

/* detach*/
static int vboxNetFltWinDeleteInstance(PVBOXNETFLTINS pThis)
{
    LogFlow(("vboxNetFltWinDeleteInstance: pThis=0x%p \n", pThis));

    Assert(KeGetCurrentIrql() < DISPATCH_LEVEL);
    Assert(pThis);
    Assert(pThis->fDisconnectedFromHost);
    Assert(!pThis->fRediscoveryPending);
    Assert(pThis->enmTrunkState != INTNETTRUNKIFSTATE_ACTIVE);
#ifndef VBOXNETADP
    Assert(pThis->u.s.WinIf.PtState.OpState == kVBoxNetDevOpState_Deinitialized);
    Assert(!pThis->u.s.WinIf.hBinding);
#endif
    Assert(pThis->u.s.WinIf.MpState.OpState == kVBoxNetDevOpState_Deinitialized);
#ifndef VBOXNETFLT_NO_PACKET_QUEUE
    Assert(!pThis->u.s.PacketQueueWorker.pSG);
#endif

    RTSemMutexDestroy(pThis->u.s.hWinIfMutex);

    vboxNetFltWinDrvDereference();

    return VINF_SUCCESS;
}

static NDIS_STATUS vboxNetFltWinDisconnectIt(PVBOXNETFLTINS pInstance)
{
#ifndef VBOXNETFLT_NO_PACKET_QUEUE
    vboxNetFltWinQuFiniPacketQueue(pInstance);
#else
    RT_NOREF1(pInstance);
#endif
    return NDIS_STATUS_SUCCESS;
}

/* detach*/
DECLHIDDEN(NDIS_STATUS) vboxNetFltWinDetachFromInterface(PVBOXNETFLTINS pNetFlt, bool bOnUnbind)
{
    NDIS_STATUS Status;
    int rc;
    LogFlowFunc(("ENTER: pThis=%0xp\n", pNetFlt));

    Assert(KeGetCurrentIrql() < DISPATCH_LEVEL);
    Assert(pNetFlt);

    /* paranoia to ensure the instance is not removed while we're waiting on the mutex
     * in case ndis does something unpredictable, e.g. calls our miniport halt independently
     * from protocol unbind and concurrently with it*/
    vboxNetFltRetain(pNetFlt, false);

    rc = RTSemMutexRequest(pNetFlt->u.s.hWinIfMutex, RT_INDEFINITE_WAIT);
    if (RT_SUCCESS(rc))
    {
        Assert(vboxNetFltWinGetWinIfState(pNetFlt) == kVBoxWinIfState_Connected);
        Assert(vboxNetFltWinGetOpState(&pNetFlt->u.s.WinIf.MpState) == kVBoxNetDevOpState_Initialized);
#ifndef VBOXNETADP
        Assert(vboxNetFltWinGetOpState(&pNetFlt->u.s.WinIf.PtState) == kVBoxNetDevOpState_Initialized);
#endif
        if (vboxNetFltWinGetWinIfState(pNetFlt) == kVBoxWinIfState_Connected)
        {
            vboxNetFltWinSetWinIfState(pNetFlt, kVBoxWinIfState_Disconnecting);
#ifndef VBOXNETADP
            Status = vboxNetFltWinPtDoUnbinding(pNetFlt, bOnUnbind);
#else
            Status = vboxNetFltWinMpDoDeinitialization(pNetFlt);
#endif
            Assert(Status == NDIS_STATUS_SUCCESS);

            vboxNetFltWinSetWinIfState(pNetFlt, kVBoxWinIfState_Disconnected);
            Assert(vboxNetFltWinGetOpState(&pNetFlt->u.s.WinIf.MpState) == kVBoxNetDevOpState_Deinitialized);
#ifndef VBOXNETADP
            Assert(vboxNetFltWinGetOpState(&pNetFlt->u.s.WinIf.PtState) == kVBoxNetDevOpState_Deinitialized);
#endif
            vboxNetFltWinPtFiniWinIf(&pNetFlt->u.s.WinIf);

            /* we're unbinding, make an unbind-related release */
            vboxNetFltRelease(pNetFlt, false);
        }
        else
        {
            AssertBreakpoint();
#ifndef VBOXNETADP
            pNetFlt->u.s.WinIf.OpenCloseStatus = NDIS_STATUS_FAILURE;
#endif
            if (!bOnUnbind)
            {
                vboxNetFltWinSetOpState(&pNetFlt->u.s.WinIf.MpState, kVBoxNetDevOpState_Deinitialized);
            }
            Status = NDIS_STATUS_FAILURE;
        }
        RTSemMutexRelease(pNetFlt->u.s.hWinIfMutex);
    }
    else
    {
        AssertBreakpoint();
        Status = NDIS_STATUS_FAILURE;
    }

    /* release for the retain we made before waining on the mutex */
    vboxNetFltRelease(pNetFlt, false);

    LogFlowFunc(("LEAVE: Status 0x%x\n", Status));

    return Status;
}


/**
 * Checks if the host (not us) has put the adapter in promiscuous mode.
 *
 * @returns true if promiscuous, false if not.
 * @param   pThis               The instance.
 */
static bool vboxNetFltWinIsPromiscuous2(PVBOXNETFLTINS pThis)
{
#ifndef VBOXNETADP
    if (VBOXNETFLT_PROMISCUOUS_SUPPORTED(pThis))
    {
        bool bPromiscuous;
        if (!vboxNetFltWinReferenceWinIf(pThis))
            return false;

        bPromiscuous = (pThis->u.s.WinIf.fUpperProtocolSetFilter & NDIS_PACKET_TYPE_PROMISCUOUS) == NDIS_PACKET_TYPE_PROMISCUOUS;
            /*vboxNetFltWinIsPromiscuous(pAdapt);*/

        vboxNetFltWinDereferenceWinIf(pThis);
        return bPromiscuous;
    }
    return false;
#else
    RT_NOREF1(pThis);
    return true;
#endif
}


/**
 * Report the MAC address, promiscuous mode setting, GSO capabilities and
 * no-preempt destinations to the internal network.
 *
 * Does nothing if we're not currently connected to an internal network.
 *
 * @param   pThis           The instance data.
 */
static void vboxNetFltWinReportStuff(PVBOXNETFLTINS pThis)
{
    /** @todo Keep these up to date, esp. the promiscuous mode bit. */
    if (pThis->pSwitchPort
        && vboxNetFltTryRetainBusyNotDisconnected(pThis))
    {
        pThis->pSwitchPort->pfnReportMacAddress(pThis->pSwitchPort, &pThis->u.s.MacAddr);
        pThis->pSwitchPort->pfnReportPromiscuousMode(pThis->pSwitchPort,
                                                     vboxNetFltWinIsPromiscuous2(pThis));
        pThis->pSwitchPort->pfnReportGsoCapabilities(pThis->pSwitchPort, 0,
                                                     INTNETTRUNKDIR_WIRE | INTNETTRUNKDIR_HOST);
        /** @todo We should be able to do pfnXmit at DISPATCH_LEVEL... */
        pThis->pSwitchPort->pfnReportNoPreemptDsts(pThis->pSwitchPort, 0 /* none */);
        vboxNetFltRelease(pThis, true /*fBusy*/);
    }
}

/**
 * Worker for vboxNetFltWinAttachToInterface.
 *
 * @param   pAttachInfo     Structure for communicating with
 *                          vboxNetFltWinAttachToInterface.
 */
static void vboxNetFltWinAttachToInterfaceWorker(PATTACH_INFO pAttachInfo)
{
    PVBOXNETFLTINS pThis = pAttachInfo->pNetFltIf;
    NDIS_STATUS Status = NDIS_STATUS_SUCCESS;
    int rc;

    Assert(KeGetCurrentIrql() == PASSIVE_LEVEL);

    /* to ensure we're not removed while we're here */
    vboxNetFltRetain(pThis, false);

    rc = RTSemMutexRequest(pThis->u.s.hWinIfMutex, RT_INDEFINITE_WAIT);
    if (RT_SUCCESS(rc))
    {
        Assert(vboxNetFltWinGetWinIfState(pThis) == kVBoxWinIfState_Disconnected);
        Assert(vboxNetFltWinGetOpState(&pThis->u.s.WinIf.MpState) == kVBoxNetDevOpState_Deinitialized);
#ifndef VBOXNETADP
        Assert(vboxNetFltWinGetOpState(&pThis->u.s.WinIf.PtState) == kVBoxNetDevOpState_Deinitialized);
#endif
        if (vboxNetFltWinGetWinIfState(pThis) == kVBoxWinIfState_Disconnected)
        {
            if (pAttachInfo->fRediscovery)
            {
                /* rediscovery means adaptor bind is performed while intnet is already using it
                 * i.e. adaptor was unbound while being used by intnet and now being bound back again */
                Assert(   ((VBOXNETFTLINSSTATE)ASMAtomicUoReadU32((uint32_t volatile *)&pThis->enmState))
                       == kVBoxNetFltInsState_Connected);
            }
#ifndef VBOXNETADP
            Status = vboxNetFltWinPtInitWinIf(&pThis->u.s.WinIf, pAttachInfo->pCreateContext->pOurName);
#else
            Status = vboxNetFltWinPtInitWinIf(&pThis->u.s.WinIf);
#endif
            if (Status == NDIS_STATUS_SUCCESS)
            {
                vboxNetFltWinSetWinIfState(pThis, kVBoxWinIfState_Connecting);

#ifndef VBOXNETADP
                Status = vboxNetFltWinPtDoBinding(pThis, pAttachInfo->pCreateContext->pOurName, pAttachInfo->pCreateContext->pBindToName);
#else
                Status = vboxNetFltWinMpDoInitialization(pThis, pAttachInfo->pCreateContext->hMiniportAdapter, pAttachInfo->pCreateContext->hWrapperConfigurationContext);
#endif
                if (Status == NDIS_STATUS_SUCCESS)
                {
                    if (!pAttachInfo->fRediscovery)
                        vboxNetFltWinDrvReference();
#ifndef VBOXNETADP
                    if (pThis->u.s.WinIf.OpenCloseStatus == NDIS_STATUS_SUCCESS)
#endif
                    {
                        vboxNetFltWinSetWinIfState(pThis, kVBoxWinIfState_Connected);
#ifndef VBOXNETADP
                        Assert(vboxNetFltWinGetOpState(&pThis->u.s.WinIf.PtState) == kVBoxNetDevOpState_Initialized);
#endif
                        /* 4. mark as connected */
                        RTSpinlockAcquire(pThis->hSpinlock);
                        ASMAtomicUoWriteBool(&pThis->fDisconnectedFromHost, false);
                        RTSpinlockRelease(pThis->hSpinlock);

                        pAttachInfo->Status = VINF_SUCCESS;
                        pAttachInfo->pCreateContext->Status = NDIS_STATUS_SUCCESS;

                        RTSemMutexRelease(pThis->u.s.hWinIfMutex);

                        vboxNetFltRelease(pThis, false);

                        /* 5. Report MAC address, promiscuousness and GSO capabilities. */
                        vboxNetFltWinReportStuff(pThis);

                        return;
                    }
#ifndef VBOXNETADP /* unreachable for VBOXNETADP because of the return above */
                    AssertBreakpoint();

                    if (!pAttachInfo->fRediscovery)
                    {
                        vboxNetFltWinDrvDereference();
                    }
# ifndef VBOXNETADP
                    vboxNetFltWinPtDoUnbinding(pThis, true);
/*# else - unreachable
                    vboxNetFltWinMpDoDeinitialization(pThis); */
# endif
#endif
                }
                AssertBreakpoint();
                vboxNetFltWinPtFiniWinIf(&pThis->u.s.WinIf);
            }
            AssertBreakpoint();
            vboxNetFltWinSetWinIfState(pThis, kVBoxWinIfState_Disconnected);
            Assert(vboxNetFltWinGetOpState(&pThis->u.s.WinIf.MpState) == kVBoxNetDevOpState_Deinitialized);
#ifndef VBOXNETADP
            Assert(vboxNetFltWinGetOpState(&pThis->u.s.WinIf.PtState) == kVBoxNetDevOpState_Deinitialized);
#endif
        }
        AssertBreakpoint();

        pAttachInfo->Status = VERR_GENERAL_FAILURE;
        pAttachInfo->pCreateContext->Status = Status;
        RTSemMutexRelease(pThis->u.s.hWinIfMutex);
    }
    else
    {
        AssertBreakpoint();
        pAttachInfo->Status = rc;
    }

    vboxNetFltRelease(pThis, false);

    return;
}

/**
 * Common code for vboxNetFltOsInitInstance and
 * vboxNetFltOsMaybeRediscovered.
 *
 * @returns IPRT status code.
 * @param   pThis           The instance.
 * @param   fRediscovery    True if vboxNetFltOsMaybeRediscovered is calling,
 *                          false if it's vboxNetFltOsInitInstance.
 */
static int vboxNetFltWinAttachToInterface(PVBOXNETFLTINS pThis, void * pContext, bool fRediscovery)
{
    ATTACH_INFO Info;
    Info.pNetFltIf = pThis;
    Info.fRediscovery = fRediscovery;
    Info.pCreateContext = (PCREATE_INSTANCE_CONTEXT)pContext;

    vboxNetFltWinAttachToInterfaceWorker(&Info);

    return Info.Status;
}
static NTSTATUS vboxNetFltWinPtDevDispatch(IN PDEVICE_OBJECT pDevObj, IN PIRP pIrp)
{
    RT_NOREF1(pDevObj);
    PIO_STACK_LOCATION pIrpSl = IoGetCurrentIrpStackLocation(pIrp);;
    NTSTATUS Status = STATUS_SUCCESS;

    switch (pIrpSl->MajorFunction)
    {
        case IRP_MJ_DEVICE_CONTROL:
            Status = STATUS_NOT_SUPPORTED;
            break;
        case IRP_MJ_CREATE:
        case IRP_MJ_CLEANUP:
        case IRP_MJ_CLOSE:
            break;
        default:
            AssertFailed();
            break;
    }

    pIrp->IoStatus.Status = Status;
    IoCompleteRequest(pIrp, IO_NO_INCREMENT);

    return Status;
}

static NDIS_STATUS vboxNetFltWinDevCreate(PVBOXNETFLTGLOBALS_WIN pGlobals)
{
    NDIS_STRING DevName, LinkName;
    PDRIVER_DISPATCH aMajorFunctions[IRP_MJ_MAXIMUM_FUNCTION+1];
    NdisInitUnicodeString(&DevName, VBOXNETFLT_NAME_DEVICE);
    NdisInitUnicodeString(&LinkName, VBOXNETFLT_NAME_LINK);

    Assert(!pGlobals->hDevice);
    Assert(!pGlobals->pDevObj);
    NdisZeroMemory(aMajorFunctions, sizeof (aMajorFunctions));
    aMajorFunctions[IRP_MJ_CREATE] = vboxNetFltWinPtDevDispatch;
    aMajorFunctions[IRP_MJ_CLEANUP] = vboxNetFltWinPtDevDispatch;
    aMajorFunctions[IRP_MJ_CLOSE] = vboxNetFltWinPtDevDispatch;
    aMajorFunctions[IRP_MJ_DEVICE_CONTROL] = vboxNetFltWinPtDevDispatch;

    NDIS_STATUS Status = NdisMRegisterDevice(pGlobals->Mp.hNdisWrapper,
              &DevName, &LinkName,
              aMajorFunctions,
              &pGlobals->pDevObj,
              &pGlobals->hDevice);
    Assert(Status == NDIS_STATUS_SUCCESS);
    return Status;
}

static NDIS_STATUS vboxNetFltWinDevDestroy(PVBOXNETFLTGLOBALS_WIN pGlobals)
{
    Assert(pGlobals->hDevice);
    Assert(pGlobals->pDevObj);
    NDIS_STATUS Status = NdisMDeregisterDevice(pGlobals->hDevice);
    Assert(Status == NDIS_STATUS_SUCCESS);
    if (Status == NDIS_STATUS_SUCCESS)
    {
        pGlobals->hDevice = NULL;
        pGlobals->pDevObj = NULL;
    }
    return Status;
}

static NDIS_STATUS vboxNetFltWinDevCreateReference(PVBOXNETFLTGLOBALS_WIN pGlobals)
{
    Assert(KeGetCurrentIrql() == PASSIVE_LEVEL);
    NDIS_STATUS Status = KeWaitForSingleObject(&pGlobals->SynchEvent, Executive, KernelMode, FALSE, NULL);
    Assert(Status == STATUS_SUCCESS);
    if (Status == STATUS_SUCCESS)
    {
        Assert(pGlobals->cDeviceRefs >= 0);
        if (++pGlobals->cDeviceRefs == 1)
        {
            Status = vboxNetFltWinDevCreate(pGlobals);
            if (Status == NDIS_STATUS_SUCCESS)
            {
                ObReferenceObject(pGlobals->pDevObj);
            }
        }
        else
        {
            Status = NDIS_STATUS_SUCCESS;
        }
        KeSetEvent(&pGlobals->SynchEvent, 0, FALSE);
    }
    else
    {
        /* should never happen actually */
        AssertFailed();
        Status = NDIS_STATUS_FAILURE;
    }
    return Status;
}

static NDIS_STATUS vboxNetFltWinDevDereference(PVBOXNETFLTGLOBALS_WIN pGlobals)
{
    Assert(KeGetCurrentIrql() == PASSIVE_LEVEL);
    NDIS_STATUS Status = KeWaitForSingleObject(&pGlobals->SynchEvent, Executive, KernelMode, FALSE, NULL);
    Assert(Status == STATUS_SUCCESS);
    if (Status == STATUS_SUCCESS)
    {
        Assert(pGlobals->cDeviceRefs > 0);
        if (!(--pGlobals->cDeviceRefs))
        {
            ObDereferenceObject(pGlobals->pDevObj);
            Status = vboxNetFltWinDevDestroy(pGlobals);
        }
        else
        {
            Status = NDIS_STATUS_SUCCESS;
        }
        KeSetEvent(&pGlobals->SynchEvent, 0, FALSE);
    }
    else
    {
        /* should never happen actually */
        AssertFailed();
        Status = NDIS_STATUS_FAILURE;
    }
    return Status;
}

/* reference the driver module to prevent driver unload */
DECLHIDDEN(void) vboxNetFltWinDrvReference()
{
    vboxNetFltWinDevCreateReference(&g_VBoxNetFltGlobalsWin);
}

/* dereference the driver module to prevent driver unload */
DECLHIDDEN(void) vboxNetFltWinDrvDereference()
{
    vboxNetFltWinDevDereference(&g_VBoxNetFltGlobalsWin);
}

/*
 *
 * The OS specific interface definition
 *
 */


bool vboxNetFltOsMaybeRediscovered(PVBOXNETFLTINS pThis)
{
    /* AttachToInterface true if disconnected */
    return !ASMAtomicUoReadBool(&pThis->fDisconnectedFromHost);
}

int vboxNetFltPortOsXmit(PVBOXNETFLTINS pThis, void *pvIfData, PINTNETSG pSG, uint32_t fDst)
{
    RT_NOREF1(pvIfData);
    int rc = VINF_SUCCESS;
    uint32_t cRefs = 0;
#ifndef VBOXNETADP
    if (fDst & INTNETTRUNKDIR_WIRE)
        cRefs++;
    if (fDst & INTNETTRUNKDIR_HOST)
        cRefs++;
#else
    if ((fDst & INTNETTRUNKDIR_WIRE) || (fDst & INTNETTRUNKDIR_HOST))
        cRefs = 1;
#endif

    AssertReturn(cRefs, VINF_SUCCESS);

    if (!vboxNetFltWinIncReferenceWinIf(pThis, cRefs))
    {
        return VERR_GENERAL_FAILURE;
    }
#ifndef VBOXNETADP
    if (fDst & INTNETTRUNKDIR_WIRE)
    {
        PNDIS_PACKET pPacket;

        pPacket = vboxNetFltWinNdisPacketFromSG(pThis, pSG, NULL /*pBufToFree*/,
                                                true /*fToWire*/, true /*fCopyMemory*/);

        if (pPacket)
        {
            NDIS_STATUS fStatus;

#ifndef VBOX_LOOPBACK_USEFLAGS
            /* force "don't loopback" flags to prevent loopback branch invocation in any case
             * to avoid ndis misbehave */
            NdisGetPacketFlags(pPacket) |= g_VBoxNetFltGlobalsWin.fPacketDontLoopBack;
#else
            /* this is done by default in vboxNetFltWinNdisPacketFromSG */
#endif

#if defined(DEBUG_NETFLT_PACKETS) || !defined(VBOX_LOOPBACK_USEFLAGS)
            vboxNetFltWinLbPutSendPacket(pThis, pPacket, true /* bFromIntNet */);
#endif
            NdisSend(&fStatus, pThis->u.s.WinIf.hBinding, pPacket);
            if (fStatus != NDIS_STATUS_PENDING)
            {
#if defined(DEBUG_NETFLT_PACKETS) || !defined(VBOX_LOOPBACK_USEFLAGS)
                /* the status is NOT pending, complete the packet */
                bool fTmp = vboxNetFltWinLbRemoveSendPacket(pThis, pPacket);
                Assert(fTmp); NOREF(fTmp);
#endif
                if (!NT_SUCCESS(fStatus))
                    rc = VERR_GENERAL_FAILURE; /** @todo convert status to VERR_xxx */

                vboxNetFltWinFreeSGNdisPacket(pPacket, true);
            }
            else
            {
                /* pending, dereference on packet complete */
                cRefs--;
            }
        }
        else
        {
            AssertFailed();
            rc = VERR_NO_MEMORY;
        }
    }
#endif

#ifndef VBOXNETADP
    if (fDst & INTNETTRUNKDIR_HOST)
#else
    if (cRefs)
#endif
    {
        PNDIS_PACKET pPacket = vboxNetFltWinNdisPacketFromSG(pThis, pSG, NULL /*pBufToFree*/,
                                                             false /*fToWire*/, true /*fCopyMemory*/);
        if (pPacket)
        {
            NdisMIndicateReceivePacket(pThis->u.s.WinIf.hMiniport, &pPacket, 1);
            cRefs--;
#ifdef VBOXNETADP
            STATISTIC_INCREASE(pThis->u.s.WinIf.cRxSuccess);
#endif
        }
        else
        {
            AssertFailed();
#ifdef VBOXNETADP
            STATISTIC_INCREASE(pThis->u.s.WinIf.cRxError);
#endif
            rc = VERR_NO_MEMORY;
        }
    }

    Assert(cRefs <= 2);

    if (cRefs)
    {
        vboxNetFltWinDecReferenceWinIf(pThis, cRefs);
    }

    return rc;
}

void vboxNetFltPortOsSetActive(PVBOXNETFLTINS pThis, bool fActive)
{
#ifndef VBOXNETADP
    NDIS_STATUS Status;
#endif
    /* we first wait for all pending ops to complete
     * this might include all packets queued for processing */
    for (;;)
    {
        if (fActive)
        {
            if (!pThis->u.s.cModePassThruRefs)
            {
                break;
            }
        }
        else
        {
            if (!pThis->u.s.cModeNetFltRefs)
            {
                break;
            }
        }
        vboxNetFltWinSleep(2);
    }

    if (!vboxNetFltWinReferenceWinIf(pThis))
        return;
#ifndef VBOXNETADP

    if (fActive)
    {
#ifdef DEBUG_misha
        NDIS_PHYSICAL_MEDIUM PhMedium;
        bool bPromiscSupported;

        Status = vboxNetFltWinQueryPhysicalMedium(pThis, &PhMedium);
        if (Status != NDIS_STATUS_SUCCESS)
        {

            LogRel(("vboxNetFltWinQueryPhysicalMedium failed, Status (0x%x), setting medium to NdisPhysicalMediumUnspecified\n", Status));
            Assert(Status == NDIS_STATUS_NOT_SUPPORTED);
            if (Status != NDIS_STATUS_NOT_SUPPORTED)
            {
                LogRel(("vboxNetFltWinQueryPhysicalMedium failed, Status (0x%x), setting medium to NdisPhysicalMediumUnspecified\n", Status));
            }
            PhMedium = NdisPhysicalMediumUnspecified;
        }
        else
        {
            LogRel(("(SUCCESS) vboxNetFltWinQueryPhysicalMedium SUCCESS\n"));
        }

        bPromiscSupported = (!(PhMedium == NdisPhysicalMediumWirelessWan
                        || PhMedium == NdisPhysicalMediumWirelessLan
                        || PhMedium == NdisPhysicalMediumNative802_11
                        || PhMedium == NdisPhysicalMediumBluetooth
                        /*|| PhMedium == NdisPhysicalMediumWiMax */
                        ));

        Assert(bPromiscSupported == VBOXNETFLT_PROMISCUOUS_SUPPORTED(pThis));
#endif
    }

    if (VBOXNETFLT_PROMISCUOUS_SUPPORTED(pThis))
    {
        Status = vboxNetFltWinSetPromiscuous(pThis, fActive);
        if (Status != NDIS_STATUS_SUCCESS)
        {
            LogRel(("vboxNetFltWinSetPromiscuous failed, Status (0x%x), fActive (%d)\n", Status, fActive));
            AssertFailed();
        }
    }
#else
# ifdef VBOXNETADP_REPORT_DISCONNECTED
    if (fActive)
    {
        NdisMIndicateStatus(pThis->u.s.WinIf.hMiniport,
                                 NDIS_STATUS_MEDIA_CONNECT,
                                 (PVOID)NULL,
                                 0);
    }
    else
    {
        NdisMIndicateStatus(pThis->u.s.WinIf.hMiniport,
                                 NDIS_STATUS_MEDIA_DISCONNECT,
                                 (PVOID)NULL,
                                 0);
    }
#else
    if (fActive)
    {
        /* indicate status change to make the ip settings be re-picked for dhcp */
        NdisMIndicateStatus(pThis->u.s.WinIf.hMiniport,
                                 NDIS_STATUS_MEDIA_DISCONNECT,
                                 (PVOID)NULL,
                                 0);

        NdisMIndicateStatus(pThis->u.s.WinIf.hMiniport,
                                 NDIS_STATUS_MEDIA_CONNECT,
                                 (PVOID)NULL,
                                 0);
    }
# endif
#endif
    vboxNetFltWinDereferenceWinIf(pThis);

    return;
}

#ifndef VBOXNETADP

DECLINLINE(bool) vboxNetFltWinIsAddrLinkLocal4(PCRTNETADDRIPV4 pAddr)
{
    return (pAddr->s.Lo == 0xfea9); /* 169.254 */
}

DECLINLINE(bool) vboxNetFltWinIsAddrLinkLocal6(PCRTNETADDRIPV6 pAddr)
{
    return ((pAddr->au8[0] == 0xfe) && ((pAddr->au8[1] & 0xc0) == 0x80));
}

void vboxNetFltWinNotifyHostAddress(PTA_ADDRESS pAddress, bool fAdded)
{
    void *pvAddr = NULL;
    INTNETADDRTYPE enmAddrType = kIntNetAddrType_Invalid;

    LogFlow(("==>vboxNetFltWinNotifyHostAddress: AddrType=%d %s\n",
             pAddress->AddressType, fAdded ? "added" : "deleted"));
    if (pAddress->AddressType == TDI_ADDRESS_TYPE_IP)
    {
        PTDI_ADDRESS_IP pTdiAddrIp = (PTDI_ADDRESS_IP)pAddress->Address;
        /*
         * Note that we do not get loopback addresses here. If we did we should
         * have checked and ignored them too.
         */
        if (!vboxNetFltWinIsAddrLinkLocal4((PCRTNETADDRIPV4)(&pTdiAddrIp->in_addr)))
        {
            pvAddr = &pTdiAddrIp->in_addr;
            enmAddrType = kIntNetAddrType_IPv4;
        }
        else
            Log2(("vboxNetFltWinNotifyHostAddress: ignoring link-local address %RTnaipv4\n",
                  pTdiAddrIp->in_addr));
    }
    else if (pAddress->AddressType == TDI_ADDRESS_TYPE_IP6)
    {
        PTDI_ADDRESS_IP6 pTdiAddrIp6 = (PTDI_ADDRESS_IP6)pAddress->Address;
        if (!vboxNetFltWinIsAddrLinkLocal6((PCRTNETADDRIPV6)(pTdiAddrIp6->sin6_addr)))
        {
            pvAddr = pTdiAddrIp6->sin6_addr;
            enmAddrType = kIntNetAddrType_IPv6;
        }
        else
            Log2(("vboxNetFltWinNotifyHostAddress: ignoring link-local address %RTnaipv6\n",
                  pTdiAddrIp6->sin6_addr));
    }
    else
    {
        Log2(("vboxNetFltWinNotifyHostAddress: ignoring irrelevant address type %d\n",
              pAddress->AddressType));
        LogFlow(("<==vboxNetFltWinNotifyHostAddress\n"));
        return;
    }
    if (pvAddr)
    {
        NdisAcquireSpinLock(&g_VBoxNetFltGlobalsWin.lockFilters);
        /* At this point the list must contain at least one element. */
        PVBOXNETFLTINS pInstance = NULL;
        PVBOXNETFLTWIN pFilter;
        RTListForEach(&g_VBoxNetFltGlobalsWin.listFilters, pFilter, VBOXNETFLTWIN, node)
        {
            pInstance = RT_FROM_MEMBER(pFilter, VBOXNETFLTINS, u.s.WinIf);
            if (vboxNetFltWinReferenceWinIf(pInstance))
            {
                if (pInstance->pSwitchPort && pInstance->pSwitchPort->pfnNotifyHostAddress)
                    break;
                vboxNetFltWinDereferenceWinIf(pInstance);
            }
            else
                Log2(("vboxNetFltWinNotifyHostAddress: failed to retain filter instance %p\n", pInstance));
            pInstance = NULL;
        }
        NdisReleaseSpinLock(&g_VBoxNetFltGlobalsWin.lockFilters);
        if (pInstance)
        {
            if (enmAddrType == kIntNetAddrType_IPv4)
                Log2(("vboxNetFltWin%sAddressHandler: %RTnaipv4\n",
                      fAdded ? "Add" : "Del", *(PCRTNETADDRIPV4)pvAddr));
            else
                Log2(("vboxNetFltWin%sAddressHandler: %RTnaipv6\n",
                      fAdded ? "Add" : "Del", pvAddr));
            pInstance->pSwitchPort->pfnNotifyHostAddress(pInstance->pSwitchPort, fAdded,
                                                         enmAddrType, pvAddr);
            vboxNetFltWinDereferenceWinIf(pInstance);
        }
        else
            Log2(("vboxNetFltWinNotifyHostAddress: no filters require notification\n"));
    }
    LogFlow(("<==vboxNetFltWinNotifyHostAddress\n"));
}

void vboxNetFltWinAddAddressHandler(PTA_ADDRESS Address,
                                    PUNICODE_STRING DeviceName,
                                    PTDI_PNP_CONTEXT Context)
{
    RT_NOREF2(DeviceName, Context);
    vboxNetFltWinNotifyHostAddress(Address, true);
}

void vboxNetFltWinDelAddressHandler(PTA_ADDRESS Address,
                                    PUNICODE_STRING DeviceName,
                                    PTDI_PNP_CONTEXT Context)
{
    RT_NOREF2(DeviceName, Context);
    vboxNetFltWinNotifyHostAddress(Address, false);
}

void vboxNetFltWinRegisterIpAddrNotifier(PVBOXNETFLTINS pThis)
{
    LogFlow(("==>vboxNetFltWinRegisterIpAddrNotifier: instance=%p pThis->pSwitchPort=%p pThis->pSwitchPort->pfnNotifyHostAddress=%p\n",
             pThis, pThis->pSwitchPort, pThis->pSwitchPort ? pThis->pSwitchPort->pfnNotifyHostAddress : NULL));
    if (pThis->pSwitchPort && pThis->pSwitchPort->pfnNotifyHostAddress)
    {
        NdisAcquireSpinLock(&g_VBoxNetFltGlobalsWin.lockFilters);
        bool fRegisterHandlers = RTListIsEmpty(&g_VBoxNetFltGlobalsWin.listFilters);
        RTListPrepend(&g_VBoxNetFltGlobalsWin.listFilters, &pThis->u.s.WinIf.node);
        NdisReleaseSpinLock(&g_VBoxNetFltGlobalsWin.lockFilters);

        if (fRegisterHandlers)
        {
            TDI_CLIENT_INTERFACE_INFO Info;
            UNICODE_STRING ClientName = RTL_CONSTANT_STRING(L"VBoxNetFlt");
            memset(&Info, 0, sizeof(Info));
            Info.MajorTdiVersion = 2;
            Info.MinorTdiVersion = 0;
            Info.ClientName = &ClientName;
            Info.AddAddressHandlerV2 = vboxNetFltWinAddAddressHandler;
            Info.DelAddressHandlerV2 = vboxNetFltWinDelAddressHandler;
            Assert(!g_VBoxNetFltGlobalsWin.hNotifier);
            NTSTATUS Status = TdiRegisterPnPHandlers(&Info, sizeof(Info), &g_VBoxNetFltGlobalsWin.hNotifier);
            Log2(("vboxNetFltWinRegisterIpAddrNotifier: TdiRegisterPnPHandlers returned %d\n", Status)); NOREF(Status);
        }
        else
            Log2(("vboxNetFltWinRegisterIpAddrNotifier: already registed\n"));
    }
    else
        Log2(("vboxNetFltWinRegisterIpAddrNotifier: this instance does not require notifications, ignoring...\n"));
    LogFlow(("<==vboxNetFltWinRegisterIpAddrNotifier: notifier=%p\n", g_VBoxNetFltGlobalsWin.hNotifier));
}

void vboxNetFltWinUnregisterIpAddrNotifier(PVBOXNETFLTINS pThis)
{
    LogFlow(("==>vboxNetFltWinUnregisterIpAddrNotifier: notifier=%p\n", g_VBoxNetFltGlobalsWin.hNotifier));
    if (pThis->pSwitchPort && pThis->pSwitchPort->pfnNotifyHostAddress)
    {
        NdisAcquireSpinLock(&g_VBoxNetFltGlobalsWin.lockFilters);
        /* At this point the list must contain at least one element. */
        Assert(!RTListIsEmpty(&g_VBoxNetFltGlobalsWin.listFilters));
        RTListNodeRemove(&pThis->u.s.WinIf.node);
        HANDLE hNotifier = NULL;
        if (RTListIsEmpty(&g_VBoxNetFltGlobalsWin.listFilters))
        {
            /*
             * The list has become empty, so we need to deregister handlers. We
             * grab hNotifier and reset it while still holding the lock. This
             * guaranties that we won't interfere with setting it in
             * vboxNetFltWinRegisterIpAddrNotifier(). It is inconceivable that
             * vboxNetFltWinUnregisterIpAddrNotifier() will be called for the
             * same filter instance while it is still being processed by
             * vboxNetFltWinRegisterIpAddrNotifier(). This would require trunk
             * destruction in the middle of its creation. It is possible that
             * vboxNetFltWinUnregisterIpAddrNotifier() is called for another
             * filter instance, but in such case we won't even get here as the
             * list won't be empty.
             */
            hNotifier = g_VBoxNetFltGlobalsWin.hNotifier;
            g_VBoxNetFltGlobalsWin.hNotifier = NULL;
        }
        NdisReleaseSpinLock(&g_VBoxNetFltGlobalsWin.lockFilters);
        if (hNotifier)
        {
            NTSTATUS Status = TdiDeregisterPnPHandlers(hNotifier);
            Log2(("vboxNetFltWinUnregisterIpAddrNotifier: TdiDeregisterPnPHandlers(%p) returned %d\n",
                  hNotifier, Status)); NOREF(Status);
        }
        else
            Log2(("vboxNetFltWinUnregisterIpAddrNotifier: filters remain, do not deregister handlers yet\n"));
    }
    else
        Log2(("vboxNetFltWinUnregisterIpAddrNotifier: this instance did not require notifications, ignoring...\n"));
    LogFlow(("<==vboxNetFltWinUnregisterIpAddrNotifier\n"));
}
#else /* VBOXNETADP */
#define vboxNetFltWinRegisterIpAddrNotifier(x)
#define vboxNetFltWinUnregisterIpAddrNotifier(x)
#endif /* VBOXNETADP */

int vboxNetFltOsDisconnectIt(PVBOXNETFLTINS pThis)
{
    NDIS_STATUS Status = vboxNetFltWinDisconnectIt(pThis);
    Log2(("vboxNetFltOsDisconnectIt: pThis=%p pThis->pSwitchPort=%p pThis->pSwitchPort->pfnNotifyHostAddress=%p\n",
          pThis, pThis->pSwitchPort, pThis->pSwitchPort ? pThis->pSwitchPort->pfnNotifyHostAddress : NULL));
    vboxNetFltWinUnregisterIpAddrNotifier(pThis);
    return Status == NDIS_STATUS_SUCCESS ? VINF_SUCCESS : VERR_GENERAL_FAILURE;
}

static void vboxNetFltWinConnectItWorker(PVOID pvContext)
{
    PWORKER_INFO pInfo = (PWORKER_INFO)pvContext;
#if !defined(VBOXNETADP) || !defined(VBOXNETFLT_NO_PACKET_QUEUE)
    NDIS_STATUS Status;
#endif
    PVBOXNETFLTINS pInstance = pInfo->pNetFltIf;

    Assert(KeGetCurrentIrql() == PASSIVE_LEVEL);

    /* this is not a rediscovery, initialize Mac cache */
    if (vboxNetFltWinReferenceWinIf(pInstance))
    {
#ifndef VBOXNETADP
        Status = vboxNetFltWinGetMacAddress(pInstance, &pInstance->u.s.MacAddr);
        if (Status == NDIS_STATUS_SUCCESS)
#endif
        {
#ifdef VBOXNETFLT_NO_PACKET_QUEUE
            pInfo->Status = VINF_SUCCESS;
#else
            Status = vboxNetFltWinQuInitPacketQueue(pInstance);
            if (Status == NDIS_STATUS_SUCCESS)
            {
                pInfo->Status = VINF_SUCCESS;
            }
            else
            {
                pInfo->Status = VERR_GENERAL_FAILURE;
            }
#endif
        }
#ifndef VBOXNETADP
        else
        {
            pInfo->Status = VERR_INTNET_FLT_IF_FAILED;
        }
#endif

        vboxNetFltWinDereferenceWinIf(pInstance);
    }
    else
    {
        pInfo->Status = VERR_INTNET_FLT_IF_NOT_FOUND;
    }
}

static int vboxNetFltWinConnectIt(PVBOXNETFLTINS pThis)
{
    WORKER_INFO Info;
    Info.pNetFltIf = pThis;

    vboxNetFltWinJobSynchExecAtPassive(vboxNetFltWinConnectItWorker, &Info);

    if (RT_SUCCESS(Info.Status))
        vboxNetFltWinReportStuff(pThis);

    return Info.Status;
}

int vboxNetFltOsConnectIt(PVBOXNETFLTINS pThis)
{
    Log2(("vboxNetFltOsConnectIt: pThis=%p pThis->pSwitchPort=%p pThis->pSwitchPort->pfnNotifyHostAddress=%p\n",
          pThis, pThis->pSwitchPort, pThis->pSwitchPort ? pThis->pSwitchPort->pfnNotifyHostAddress : NULL));
    vboxNetFltWinRegisterIpAddrNotifier(pThis);
    return vboxNetFltWinConnectIt(pThis);
}

void vboxNetFltOsDeleteInstance(PVBOXNETFLTINS pThis)
{
    vboxNetFltWinDeleteInstance(pThis);
}

int vboxNetFltOsInitInstance(PVBOXNETFLTINS pThis, void *pvContext)
{
    int rc = RTSemMutexCreate(&pThis->u.s.hWinIfMutex);
    if (RT_SUCCESS(rc))
    {
        rc = vboxNetFltWinAttachToInterface(pThis, pvContext, false /*fRediscovery*/ );
        if (RT_SUCCESS(rc))
        {
            return rc;
        }
        RTSemMutexDestroy(pThis->u.s.hWinIfMutex);
    }
    return rc;
}

int vboxNetFltOsPreInitInstance(PVBOXNETFLTINS pThis)
{
    pThis->u.s.cModeNetFltRefs = 0;
    pThis->u.s.cModePassThruRefs = 0;
    vboxNetFltWinSetWinIfState(pThis, kVBoxWinIfState_Disconnected);
    vboxNetFltWinSetOpState(&pThis->u.s.WinIf.MpState, kVBoxNetDevOpState_Deinitialized);
#ifndef VBOXNETADP
    vboxNetFltWinSetOpState(&pThis->u.s.WinIf.PtState, kVBoxNetDevOpState_Deinitialized);
#endif
    return VINF_SUCCESS;
}

void vboxNetFltPortOsNotifyMacAddress(PVBOXNETFLTINS pThis, void *pvIfData, PCRTMAC pMac)
{
    RT_NOREF3(pThis, pvIfData, pMac);
}

int vboxNetFltPortOsConnectInterface(PVBOXNETFLTINS pThis, void *pvIf, void **ppvIfData)
{
    /* Nothing to do */
    RT_NOREF3(pThis, pvIf, ppvIfData);
    return VINF_SUCCESS;
}

int vboxNetFltPortOsDisconnectInterface(PVBOXNETFLTINS pThis, void *pvIfData)
{
    /* Nothing to do */
    RT_NOREF2(pThis, pvIfData);
    return VINF_SUCCESS;
}